Golang appengine-aetest.NewInstance类(方法)实例源码

下面列出了Golang appengine-aetest.NewInstance 类(方法)源码代码实例,从而了解它的用法。

作者:jimhop    项目:frederi   
func TestHomePage(t *testing.T) {
	inst, err := aetest.NewInstance(&aetest.Options{StronglyConsistentDatastore: true})
	if err != nil {
		t.Fatalf("Failed to create instance: %v", err)
	}
	defer inst.Close()

	req, err := inst.NewRequest("GET", "/", nil)
	if err != nil {
		t.Fatalf("Failed to create req1: %v", err)
	}

	aetest.Login(&user.User{Email: "[email protected]"}, req)

	w := httptest.NewRecorder()
	c := appengine.NewContext(req)
	addTestUser(c, "[email protected]", true)

	homepage(c, w, req)

	code := w.Code
	if code != http.StatusOK {
		t.Errorf("got code %v, want %v", code, http.StatusOK)
	}

	body := w.Body.Bytes()
	expected := []byte("[email protected]")
	if !bytes.Contains(body, expected) {
		t.Errorf("got body %v, did not contain %v", string(body), string(expected))
	}
	if !bytes.Contains(body, []byte("Logout")) {
		t.Errorf("got body %v, did not contain %v", body,
			[]byte("Logout"))
	}
}

作者:tSU-Roo    项目:Lyco   
func TestBuildPageHandler(t *testing.T) {
	opt := &aetest.Options{AppID: "unittest", StronglyConsistentDatastore: true}
	user := &user.User{Email: "[email protected]", Admin: true, ID: "1234567890"}
	inst, err := aetest.NewInstance(opt)
	if err != nil {
		t.Fatalf(err.Error())
	}
	defer inst.Close()
	request, err := inst.NewRequest("POST", "/build", strings.NewReader("Name=ABC&chip=true&fox=true&hour=3&minute=0"))
	if err != nil {
		t.Fatalf("Failed to create request: %v", err)
	}
	request.Header.Set("Content-Type", "application/x-www-form-urlencoded; param=value")
	aetest.Login(user, request)
	recoder := httptest.NewRecorder()
	buildPageHandler(recoder, request)
	if recoder.Code != 302 {
		b, _ := ioutil.ReadAll(recoder.Body)
		t.Fatalf("unexpected %d, expected 302, body=%s", recoder.Code, string(b))
	}
	context := appengine.NewContext(request)
	g := goon.FromContext(context)
	v := Village{No: 1}
	if err := g.Get(&v); err != nil {
		t.Fatalf("unexpected err, expected Get Village{No: 1}")
	}
	if v.Name != "ABC" || v.Chip == false || v.IncludeFox == false || v.UpdatetimeHour != 3 || v.UpdatetimeMinute != 0 {
		t.Fatalf("Failed: Cant't get correct Data from datastore")
	}
}

作者:alvaradopcesa    项目:gae-go-exampl   
func TestIndex(t *testing.T) {

	inst, err := aetest.NewInstance(nil)
	if err != nil {
		t.Error(err)
	}
	defer inst.Close()

	req, err := inst.NewRequest("GET", "/", nil)
	if err != nil {
		t.Error(err)
	}

	res := httptest.NewRecorder()

	Index(res, req)

	// response check
	data, err := ioutil.ReadAll(res.Body)
	if err != nil {
		t.Error(err)
	}
	h := string(data)
	//fmt.Println("html: ", h)

	re := regexp.MustCompile("Sign Guestbook")
	if matched := re.MatchString(h); !matched {
		t.Error("not matched")
	}
}

作者:Gleason    项目:g   
// TestSuccessCodeAndInfo sends out a message to the pubnub channel
// The response is parsed and should match the 'sent' status.
// _publishSuccessMessage is defined in the common.go file
func TestSuccessCodeAndInfo(t *testing.T) {
	/*context, err := aetest.NewContext(nil)
	if err != nil {
		t.Fatal(err)
	}
	defer context.Close()*/
	inst, err := aetest.NewInstance(&aetest.Options{"", true})
	context := CreateContext(inst)

	if err != nil {
		t.Fatal(err)
	}
	defer inst.Close()

	uuid := ""
	w, req := InitAppEngineContext(t)

	pubnubInstance := messaging.New(context, uuid, w, req, PubKey, SubKey, "", "", false)
	//pubnubInstance := messaging.NewPubnub(PubKey, SubKey, "", "", false, "")
	channel := "testChannel"
	message := "Pubnub API Usage Example"
	returnChannel := make(chan []byte)
	errorChannel := make(chan []byte)
	responseChannel := make(chan string)
	waitChannel := make(chan string)

	//go pubnubInstance.Publish(channel, message, returnChannel, errorChannel)
	go pubnubInstance.Publish(context, w, req, channel, message, returnChannel, errorChannel)
	go ParsePublishResponse(returnChannel, channel, publishSuccessMessage, "SuccessCodeAndInfo", responseChannel)

	go ParseErrorResponse(errorChannel, responseChannel)
	go WaitForCompletion(responseChannel, waitChannel)
	ParseWaitResponse(waitChannel, t, "SuccessCodeAndInfo")
	time.Sleep(2 * time.Second)
}

作者:jimhop    项目:frederi   
func TestGetClientMissingParm(t *testing.T) {
	inst, err := aetest.NewInstance(&aetest.Options{StronglyConsistentDatastore: true})
	if err != nil {
		t.Fatalf("Failed to create instance: %v", err)
	}
	defer inst.Close()

	url := "/client/"
	req, err := inst.NewRequest("GET", url, nil)
	if err != nil {
		t.Fatalf("Failed to create req: %v", err)
	}

	aetest.Login(&user.User{Email: "[email protected]"}, req)

	w := httptest.NewRecorder()
	c := appengine.NewContext(req)
	addTestUser(c, "[email protected]", true)

	getclientpage(c, w, req)

	code := w.Code
	if code != http.StatusNotFound {
		t.Errorf("got code %v, want %v", code, http.StatusOK)
	}

	body := w.Body.Bytes()
	msg := []byte("client id missing in path")
	if !bytes.Contains(body, msg) {
		t.Errorf("got body %v, did not contain %v", string(body),
			string(msg))
	}
}

作者:jimhop    项目:frederi   
func TestListUsersPageNotAdmin(t *testing.T) {
	inst, err := aetest.NewInstance(&aetest.Options{StronglyConsistentDatastore: true})
	if err != nil {
		t.Fatalf("Failed to create instance: %v", err)
	}
	defer inst.Close()

	req, err := inst.NewRequest("GET", "/users", nil)
	if err != nil {
		t.Fatalf("Failed to create req: %v", err)
	}

	aetest.Login(&user.User{Email: "[email protected]"}, req)

	w := httptest.NewRecorder()
	c := appengine.NewContext(req)
	addTestUser(c, "[email protected]", false)

	edituserspage(c, w, req)

	code := w.Code
	if code != http.StatusForbidden {
		t.Errorf("got code %v, want %v", code, http.StatusForbidden)
	}

}

作者:mswift4    项目:polytask   
func TestHandlers(t *testing.T) {
	_, err := aetest.NewContext(nil)
	if err != nil {
		t.Fatal(err)
	}
	resp := httptest.NewRecorder()
	uri := "/api/tasks/"
	var testjson1 = `{"summary" : "task1",
                "content" : ["taskcontent1"],
    "done": false}`
	instance, err := aetest.NewInstance(nil)
	if err != nil {
		t.Fatal(err)
	}
	req, err := instance.NewRequest("POST", uri, ioutil.NopCloser(strings.NewReader(testjson1)))
	http.DefaultServeMux.ServeHTTP(resp, req)
	if p, err := ioutil.ReadAll(resp.Body); err != nil {
		t.Fail()

	} else {
		if strings.Contains(string(p), "Error") {
			t.Errorf("header response shouldn't return error: %s: ", p)
		}
		if !strings.Contains(string(p), "task1") {
			t.Errorf("header response doesn't match: \n%s", p)
		}
	}

	getreq, err := instance.NewRequest("GET", uri, nil)
	if err != nil {
		t.Fatal(err)
	}
	http.DefaultServeMux.ServeHTTP(resp, getreq)
	if p, err := ioutil.ReadAll(resp.Body); err != nil {
		t.Fail()
	} else {
		if strings.Contains(string(p), "Error") {
			t.Errorf("header response shouldn't return erros: %s: ", p)
		}
		if !strings.Contains(string(p), "task1") {
			t.Errorf("header response doesn't match: \n%s", p)
		}
		if !strings.Contains(string(p), "taskcontent1") {
			t.Errorf("header reponse doesn't match: \n%s", p)
		}
	}
	uri = "/api/task/5629499534213120"
	delreq, err := instance.NewRequest("DELETE", uri, nil)
	if err != nil {
		t.Fatal(err)
	}
	http.DefaultServeMux.ServeHTTP(resp, delreq)
	if p, err := ioutil.ReadAll(resp.Body); err != nil {
		t.Fail()
	} else {
		if strings.Contains(string(p), "Error") {
			t.Errorf("header response shouldn't return error: %s: ", p)
		}
	}
}

作者:jimhop    项目:frederi   
func TestEditVisitPageMissingPathInfo(t *testing.T) {
	inst, err := aetest.NewInstance(&aetest.Options{StronglyConsistentDatastore: true})
	if err != nil {
		t.Fatalf("Failed to create instance: %v", err)
	}
	defer inst.Close()

	url := "/editvisit/"
	req, err := inst.NewRequest("GET", url, nil)
	if err != nil {
		t.Fatalf("Failed to create req: %v", err)
	}

	aetest.Login(&user.User{Email: "[email protected]"}, req)

	w := httptest.NewRecorder()
	c := appengine.NewContext(req)

	addTestUser(c, "[email protected]", true)

	editvisitpage(c, w, req)

	code := w.Code
	if code != http.StatusBadRequest {
		t.Errorf("got code %v, want %v", code, http.StatusBadRequest)
	}

	body := w.Body.Bytes()
	expected := []byte("id is missing in path for update request /editvisit/")
	if !bytes.Contains(body, expected) {
		t.Errorf("got body %v, did not contain %v", string(body),
			string(expected))
	}

	url += "12345"
	req, err = inst.NewRequest("GET", url, nil)
	if err != nil {
		t.Fatalf("Failed to create req: %v", err)
	}

	aetest.Login(&user.User{Email: "[email protected]"}, req)

	w = httptest.NewRecorder()
	c = appengine.NewContext(req)

	editvisitpage(c, w, req)

	code = w.Code
	if code != http.StatusBadRequest {
		t.Errorf("got code %v, want %v", code, http.StatusBadRequest)
	}

	body = w.Body.Bytes()
	expected = []byte("id is missing in path for update request /editvisit/")
	if !bytes.Contains(body, expected) {
		t.Errorf("got body %v, did not contain %v", string(body),
			string(expected))
	}

}

作者:Gleason    项目:g   
// TestServerTime calls the GetTime method of the messaging to test the time
func TestServerTime(t *testing.T) {
	/*context, err := aetest.NewContext(nil)
	if err != nil {
		t.Fatal(err)
	}
	defer context.Close()*/
	inst, err := aetest.NewInstance(&aetest.Options{"", true})
	context := CreateContext(inst)

	if err != nil {
		t.Fatal(err)
	}
	defer inst.Close()

	uuid := ""
	w, req := InitAppEngineContext(t)

	pubnubInstance := messaging.New(context, uuid, w, req, PubKey, SubKey, "", "", false)
	//pubnubInstance := messaging.NewPubnub(PubKey, SubKey, "", "", false, "")

	returnTimeChannel := make(chan []byte)
	errorChannel := make(chan []byte)
	responseChannel := make(chan string)
	waitChannel := make(chan string)

	//go pubnubInstance.GetTime(returnTimeChannel, errorChannel)
	go pubnubInstance.GetTime(context, w, req, returnTimeChannel, errorChannel)
	go ParseTimeResponse(returnTimeChannel, responseChannel)
	go ParseErrorResponse(errorChannel, responseChannel)
	go WaitForCompletion(responseChannel, waitChannel)
	ParseWaitResponse(waitChannel, t, "Time")
}

作者:jimhop    项目:frederi   
func TestAddVisitPageMissingClient(t *testing.T) {
	inst, err := aetest.NewInstance(&aetest.Options{StronglyConsistentDatastore: true})
	if err != nil {
		t.Fatalf("Failed to create instance: %v", err)
	}
	defer inst.Close()

	url := "/recordvisit/"
	req, err := inst.NewRequest("GET", url, nil)
	if err != nil {
		t.Fatalf("Failed to create req: %v", err)
	}

	aetest.Login(&user.User{Email: "[email protected]"}, req)

	w := httptest.NewRecorder()
	c := appengine.NewContext(req)

	addTestUser(c, "[email protected]", true)

	recordvisitpage(c, w, req)

	code := w.Code
	if code != http.StatusBadRequest {
		t.Errorf("got code %v, want %v", code, http.StatusNotFound)
	}

	body := w.Body.Bytes()
	expected := []byte("Invalid/missing client id")
	if !bytes.Contains(body, expected) {
		t.Errorf("got body %v, did not contain %v", string(body),
			string(expected))
	}
}

作者:jimhop    项目:frederi   
func TestEndpointsNotAuthorized(t *testing.T) {
	inst, err := aetest.NewInstance(nil)
	if err != nil {
		t.Fatalf("Failed to create instance: %v", err)
	}
	defer inst.Close()

	for i := 0; i < len(endpoints); i++ {
		req, err := inst.NewRequest("GET", endpoints[i].url, nil)
		if err != nil {
			t.Fatalf("Failed to create req1: %v", err)
		}
		w := httptest.NewRecorder()
		c := appengine.NewContext(req)

		aetest.Login(&user.User{Email: "[email protected]"}, req)
		endpoints[i].handler(c, w, req)

		code := w.Code
		if code != http.StatusForbidden {
			t.Errorf("got code %v for endpoint %v, want %v", code,
				endpoints[i].url, http.StatusForbidden)
		}
		if endpoints[i].humanReadable {
			body := w.Body.Bytes()
			notauth := `Sorry`
			if !bytes.Contains(body, []byte(notauth)) {
				t.Errorf("endpoint %v: got body %v, did not contain %v", endpoints[i].url, string(body), notauth)
			}
		}
	}
}

作者:callmegarru    项目:go-endpoint   
func TestTokeninfoContextCurrentOAuthClientID(t *testing.T) {
	rt := newTestRoundTripper()
	origTransport := httpTransportFactory
	defer func() { httpTransportFactory = origTransport }()
	httpTransportFactory = func(c appengine.Context) http.RoundTripper {
		return rt
	}

	inst, err := aetest.NewInstance(nil)
	if err != nil {
		t.Fatalf("failed to create instance: %v", err)
	}
	defer inst.Close()

	tts := []*struct {
		token, scope, clientID string
		httpStatus             int
		content                string
	}{
		// token, scope, clientID, httpStatus, content
		{"some_token0", "scope.one", "my-client-id", 200, tokeninfoValid},
		{"some_token1", "scope.two", "my-client-id", 200, tokeninfoValid},
		{"some_token2", "scope.one", "", 200, tokeninfoUnverified},
		{"some_token3", "scope.one", "", 200, tokeninfoInvalidEmail},
		{"some_token4", "scope.one", "", 401, tokeninfoError},
		{"some_token5", "invalid.scope", "", 200, tokeninfoValid},
		{"some_token6", "scope.one", "", 400, "{}"},
		{"some_token7", "scope.one", "", 200, ""},
		{"", "scope.one", "", 200, tokeninfoValid},
		{"some_token9", "scope.one", "", -1, ""},
	}

	for i, tt := range tts {
		r, err := inst.NewRequest("GET", "/", nil)
		if err != nil {
			t.Fatalf("Error creating a req: %v", err)
		}
		r.Header.Set("authorization", "bearer "+tt.token)
		if tt.token != "" && tt.httpStatus > 0 {
			rt.Add(&http.Response{
				Status:     fmt.Sprintf("%d", tt.httpStatus),
				StatusCode: tt.httpStatus,
				Body:       ioutil.NopCloser(strings.NewReader(tt.content)),
			})
		}
		c := tokeninfoContextFactory(r)
		id, err := c.CurrentOAuthClientID(tt.scope)
		switch {
		case err != nil && tt.clientID != "":
			t.Errorf("%d: CurrentOAuthClientID(%v) = %v; want %q",
				i, tt.scope, err, tt.clientID)
		case err == nil && tt.clientID == "":
			t.Errorf("%d: CurrentOAuthClientID(%v) = %v; want error",
				i, tt.scope, id)
		case err == nil && id != tt.clientID:
			t.Errorf("%d: CurrentOAuthClientID(%v) = %v; want %q",
				i, tt.scope, id, tt.clientID)
		}
	}
}

作者:killyEm    项目:beega   
func TestFlashHeader(t *testing.T) {
	// create fake GET request
	inst, err := aetest.NewInstance(nil)
	if err != nil {
		t.Fatalf("Failed to create instance: %v", err)
	}
	defer inst.Close()

	r, _ := inst.NewRequest("GET", "/", nil)
	w := httptest.NewRecorder()

	// setup the handler
	handler := NewControllerRegister()
	handler.Add("/", &TestFlashController{}, "get:TestWriteFlash")
	handler.ServeHTTP(w, r)

	// get the Set-Cookie value
	sc := w.Header().Get("Set-Cookie")
	// match for the expected header
	res := strings.Contains(sc, "BEEGO_FLASH=%00notice%23BEEGOFLASH%23TestFlashString%00")
	// validate the assertion
	if res != true {
		t.Errorf("TestFlashHeader() unable to validate flash message")
	}
}

作者:postfi    项目:panoptico   
func init() {
	var err error
	log.Printf("init()")
	inst, err = aetest.NewInstance(nil)
	if err != nil {
		log.Fatalf("Failed to create instance: %v", err)
	}
}

作者:flowl    项目:appengin   
// NewInstance launches a running instance of api_server.py which can be used
// for multiple test Contexts that delegate all App Engine API calls to that
// instance.
// If opts is nil the default values are used.
func NewInstance(opts *Options) (Instance, error) {
	aetest.PrepareDevAppserver = PrepareDevAppserver
	var aeOpts *aetest.Options
	if opts != nil {
		aeOpts = &aetest.Options{
			AppID: opts.AppID,
		}
	}
	return aetest.NewInstance(aeOpts)
}

作者:jimhop    项目:frederi   
func TestListUsersPage(t *testing.T) {
	inst, err := aetest.NewInstance(&aetest.Options{StronglyConsistentDatastore: true})
	if err != nil {
		t.Fatalf("Failed to create instance: %v", err)
	}
	defer inst.Close()

	newusers := []appuser{
		{Email: "[email protected]", IsAdmin: true},
		{Email: "[email protected]", IsAdmin: false},
		{Email: "[email protected]", IsAdmin: false},
	}

	req, err := inst.NewRequest("GET", "/users", nil)
	if err != nil {
		t.Fatalf("Failed to create req: %v", err)
	}

	aetest.Login(&user.User{Email: "[email protected]"}, req)

	w := httptest.NewRecorder()
	c := appengine.NewContext(req)
	addTestUser(c, "[email protected]", true)

	for i := range newusers {
		_, err := addTestUser(c, newusers[i].Email,
			newusers[i].IsAdmin)
		if err != nil {
			t.Fatalf("unable to add user: %v", err)
		}
	}

	edituserspage(c, w, req)

	code := w.Code
	if code != http.StatusOK {
		t.Errorf("got code %v, want %v", code, http.StatusOK)
	}

	body := w.Body.Bytes()
	rows := []string{"[email protected]",
		"[email protected]",
		"[email protected]",
		`<input type="checkbox" id="admin0" name="admin" checked="checked">`,
		`<input type="checkbox" id="admin1" name="admin">`,
		// [email protected] is user #3
		`<input type="checkbox" id="admin3" name="admin">`,
	}
	for i := range rows {
		if !bytes.Contains(body, []byte(rows[i])) {
			t.Errorf("got body %v, did not contain %v", string(body), rows[i])
		}
	}
}

作者:Celluliodi    项目:flanne   
// NewInstance launches a running instance of api_server.py which can be used
// for multiple test Contexts that delegate all App Engine API calls to that
// instance.
// If opts is nil the default values are used.
func NewInstance(opts *Options) (Instance, error) {
	aetest.PrepareDevAppserver = PrepareDevAppserver
	var aeOpts *aetest.Options
	if opts != nil {
		aeOpts = &aetest.Options{
			AppID: opts.AppID,
			StronglyConsistentDatastore: opts.StronglyConsistentDatastore,
		}
	}
	return aetest.NewInstance(aeOpts)
}

作者:jimhop    项目:frederi   
func TestListClientsPage(t *testing.T) {
	inst, err := aetest.NewInstance(&aetest.Options{StronglyConsistentDatastore: true})
	if err != nil {
		t.Fatalf("Failed to create instance: %v", err)
	}
	defer inst.Close()

	newclients := []client{
		{Firstname: "frederic", Lastname: "ozanam"},
		{Firstname: "John", Lastname: "Doe"},
		{Firstname: "Jane", Lastname: "Doe"},
	}
	ids := make(map[string]int64, len(newclients))
	for i := 0; i < len(newclients); i++ {
		id, err := addclienttodb(newclients[i], inst)
		if err != nil {
			t.Fatalf("unable to add client: %v", err)
		}
		ids[newclients[i].Lastname+`,`+newclients[i].Firstname] = id
	}
	req, err := inst.NewRequest("GET", "/listclients", nil)
	if err != nil {
		t.Fatalf("Failed to create req: %v", err)
	}

	aetest.Login(&user.User{Email: "[email protected]"}, req)

	w := httptest.NewRecorder()
	c := appengine.NewContext(req)
	addTestUser(c, "[email protected]", true)

	listclientspage(c, w, req)

	code := w.Code
	if code != http.StatusOK {
		t.Errorf("got code %v, want %v", code, http.StatusOK)
	}

	body := w.Body.Bytes()
	rows := []string{"<td>Clients</td>",
		"<a href=\"/client/" + strconv.FormatInt(ids["ozanam,frederic"], 10) +
			"\">ozanam, frederic</a>",
		"<a href=\"/client/" + strconv.FormatInt(ids["Doe,John"], 10) +
			"\">Doe, John</a>",
		"<a href=\"/client/" + strconv.FormatInt(ids["Doe,Jane"], 10) +
			"\">Doe, Jane</a>",
	}
	for i := 0; i < len(rows); i++ {
		if !bytes.Contains(body, []byte(rows[i])) {
			t.Errorf("got body %v, did not contain %v", string(body), rows[i])
		}
	}
}

作者:dennw    项目:cayle   
func createInstance() (aetest.Instance, graph.Options, error) {
	inst, err := aetest.NewInstance(&aetest.Options{"", true})
	if err != nil {
		return nil, nil, errors.New("Creation of new instance failed")
	}
	req1, err := inst.NewRequest("POST", "/api/v1/write", nil)
	if err != nil {
		return nil, nil, errors.New("Creation of new request failed")
	}
	opts := make(graph.Options)
	opts["HTTPRequest"] = req1
	return inst, opts, nil
}

作者:pathikdevan    项目:ioweb201   
// aetInstance returns an aetest.Instance associated with the test state t
// or creates a new one.
func aetInstance(t *testing.T) aetest.Instance {
	aetInstMu.Lock()
	defer aetInstMu.Unlock()
	if inst, ok := aetInst[t]; ok {
		return inst
	}
	inst, err := aetest.NewInstance(nil)
	if err != nil {
		t.Fatalf("aetest.NewInstance: %v", err)
	}
	aetInst[t] = inst
	return inst
}


问题


面经


文章

微信
公众号

扫码关注公众号