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: "*****@*****.**"}, req) w := httptest.NewRecorder() c := appengine.NewContext(req) addTestUser(c, "*****@*****.**", 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("*****@*****.**") 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")) } }
func TestBuildPageHandler(t *testing.T) { opt := &aetest.Options{AppID: "unittest", StronglyConsistentDatastore: true} user := &user.User{Email: "*****@*****.**", 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") } }
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") } }
// 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) }
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: "*****@*****.**"}, req) w := httptest.NewRecorder() c := appengine.NewContext(req) addTestUser(c, "*****@*****.**", 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)) } }
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: "*****@*****.**"}, req) w := httptest.NewRecorder() c := appengine.NewContext(req) addTestUser(c, "*****@*****.**", false) edituserspage(c, w, req) code := w.Code if code != http.StatusForbidden { t.Errorf("got code %v, want %v", code, http.StatusForbidden) } }
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) } } }
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: "*****@*****.**"}, req) w := httptest.NewRecorder() c := appengine.NewContext(req) addTestUser(c, "*****@*****.**", 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: "*****@*****.**"}, 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)) } }
// 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") }
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: "*****@*****.**"}, req) w := httptest.NewRecorder() c := appengine.NewContext(req) addTestUser(c, "*****@*****.**", 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)) } }
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: "*****@*****.**"}, 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) } } } }
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) } } }
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") } }
func init() { var err error log.Printf("init()") inst, err = aetest.NewInstance(nil) if err != nil { log.Fatalf("Failed to create instance: %v", err) } }
// 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) }
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: "*****@*****.**", IsAdmin: true}, {Email: "*****@*****.**", IsAdmin: false}, {Email: "*****@*****.**", 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: "*****@*****.**"}, req) w := httptest.NewRecorder() c := appengine.NewContext(req) addTestUser(c, "*****@*****.**", 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{"*****@*****.**", "*****@*****.**", "*****@*****.**", `<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]) } } }
// 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) }
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: "*****@*****.**"}, req) w := httptest.NewRecorder() c := appengine.NewContext(req) addTestUser(c, "*****@*****.**", 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]) } } }
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 }
// 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 }
func do(t *testing.T, method, path string, f func(*http.Request)) { i, err := aetest.NewInstance(nil) if err != nil { t.Fatal(err) } defer i.Close() r, err := i.NewRequest(method, path, nil) if err != nil { t.Fatal(err) } f(r) }
func TestHandles(t *testing.T) { instance, err := aetest.NewInstance(nil) inst = instance if err != nil { t.Fatalf("Failed to create instance: %v", err) } defer inst.Close() get(t, "/") get(t, "/auth") get(t, "/hashtag?hashtags=1,2,3") get(t, "/process") }
// DetailedHistoryFor10Messages is a common method used by both TestDetailedHistoryFor10EncryptedMessages // and TestDetailedHistoryFor10Messages to publish's 10 messages to a pubnub channel, and after that // call the history method of the messaging package to fetch last 10 messages. These received // messages are compared to the messages sent and if all match test is successful. func DetailedHistoryFor10Messages(t *testing.T, cipherKey string, testName string) { numberOfMessages := 10 startMessagesFrom := 0 /*context, err := aetest.NewContext(nil) if err != nil { t.Fatal(err) } defer context.Close() w := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/", nil)*/ //context, err := aetest.NewContext(nil) //req, _ := http.NewRequest("GET", "/", nil) inst, err := aetest.NewInstance(&aetest.Options{"", true}) context := CreateContext(inst) if err != nil { t.Fatal(err) } //defer context.Close() defer inst.Close() uuid := "" w, req := InitAppEngineContext(t) //pubnubInstance := messaging.NewPubnub(PubKey, SubKey, SecKey, cipherKey, false, "") pubnubInstance := messaging.New(context, uuid, w, req, PubKey, SubKey, SecKey, "", false) message := "Test Message " r := GenRandom() channel := fmt.Sprintf("testChannel_dh_%d", r.Intn(20)) messagesSent := PublishMessages(context, w, req, pubnubInstance, channel, t, startMessagesFrom, numberOfMessages, message) if messagesSent { returnHistoryChannel := make(chan []byte) errorChannel := make(chan []byte) responseChannel := make(chan string) waitChannel := make(chan string) //go pubnubInstance.History(channel, numberOfMessages, 0, 0, false, returnHistoryChannel, errorChannel) go pubnubInstance.History(context, w, req, channel, numberOfMessages, 0, 0, false, returnHistoryChannel, errorChannel) go ParseHistoryResponseForMultipleMessages(returnHistoryChannel, channel, message, testName, startMessagesFrom, numberOfMessages, cipherKey, responseChannel) go ParseErrorResponse(errorChannel, responseChannel) go WaitForCompletion(responseChannel, waitChannel) ParseWaitResponse(waitChannel, t, testName) } else { t.Error("Test '" + testName + "': failed.") } }
func TestInvalidAppRevision(t *testing.T) { inst, err := aetest.NewInstance(nil) if err != nil { t.Fatalf("Failed to create instance: %v", err) } defer inst.Close() backend := &BackendService{} r := newBackendHTTPRequest(inst, "GetApiConfigs", nil) req := &GetAPIConfigsRequest{AppRevision: "invalid"} if err := backend.GetApiConfigs(r, req, nil); err == nil { t.Errorf("GetApiConfigs(%#v) = nil; want error", req) } }
func makeRequestFromFn(method string, body M, fn func(appengine.Context, *http.Request)) Response { aeinstance, _ := aetest.NewInstance(nil) defer aeinstance.Close() bytes, _ := json.Marshal(body) reader := strings.NewReader(string(bytes)) req, _ := aeinstance.NewRequest(method, "/", reader) req.Header.Add("Content-type", "application/json") c := appengine.NewContext(req) fn(c, req) return send(req) }
func TestPatternThree(t *testing.T) { inst, err := aetest.NewInstance(nil) if err != nil { t.Fatalf("Failed to create instance: %v", err) } defer inst.Close() r, _ := inst.NewRequest("GET", "/admin/astaxie", nil) w := httptest.NewRecorder() handler := NewControllerRegister() handler.InsertFilter("/admin/:all", BeforeRouter, FilterAdminUser) handler.ServeHTTP(w, r) if w.Body.String() != "i am admin" { t.Errorf("filter /admin/astaxie can't run") } }
func TestListPoll(t *testing.T) { inst, err := aetest.NewInstance(nil) if err != nil { t.Fatalf("failed to create instance: %v", err) } defer inst.Close() r, err := inst.NewRequest("GET", "http://localhost:8080/_ah/api/sparck/v1/polls", nil) res, err := http.DefaultClient.Do(r) if err != nil { t.Error(err) } assert := assert.New(t) assert.Equal(res.StatusCode, http.StatusOK, "Bad request status !") }
func TestEditClientPage(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() newclient := client{Firstname: "frederic", Lastname: "ozanam"} id, err := addclienttodb(newclient, inst) if err != nil { t.Fatalf("unable to add client: %v", err) } sid := strconv.FormatInt(id, 10) url := "/editclient/" + sid req, err := inst.NewRequest("GET", url, nil) if err != nil { t.Fatalf("Failed to create req: %v", err) } aetest.Login(&user.User{Email: "*****@*****.**"}, req) w := httptest.NewRecorder() c := appengine.NewContext(req) addTestUser(c, "*****@*****.**", true) editclientpage(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{`value="frederic"`, `value="ozanam"`, `method: "PUT"`, `url: "/api/client/` + sid + `"`, } 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]) } } }
func TestRouterHandler(t *testing.T) { inst, err := aetest.NewInstance(nil) if err != nil { t.Fatalf("Failed to create instance: %v", err) } defer inst.Close() r, _ := inst.NewRequest("POST", "/sayhi", nil) w := httptest.NewRecorder() handler := NewControllerRegister() handler.Handler("/sayhi", http.HandlerFunc(sayhello)) handler.ServeHTTP(w, r) if w.Body.String() != "sayhello" { t.Errorf("TestRouterHandler can't run") } }
func TestFilter(t *testing.T) { inst, err := aetest.NewInstance(nil) if err != nil { t.Fatalf("Failed to create instance: %v", err) } defer inst.Close() r, _ := inst.NewRequest("GET", "/person/asta/Xie", nil) w := httptest.NewRecorder() handler := NewControllerRegister() handler.InsertFilter("/person/:last/:first", BeforeRouter, FilterUser) handler.Add("/person/:last/:first", &TestController{}) handler.ServeHTTP(w, r) if w.Body.String() != "i am astaXie" { t.Errorf("user define func can't run") } }