func TestIndexHandler(t *testing.T) { _, done, err := aetest.NewContext() if err != nil { t.Fatal(err) } defer done() inst, err := aetest.NewInstance(nil) if err != nil { t.Errorf("Failed to create instance: %v", err) } defer inst.Close() request, err := inst.NewRequest("GET", "/", nil) if err != nil { t.Errorf("Error creating new instance %v", err) } response := httptest.NewRecorder() IndexHandler(response, request) if response.Code != http.StatusFound { t.Errorf("Did not get StatusFound(302) got %v", response.Code) } if response.Header().Get("Location") != "/index.html" { t.Errorf("Expected Location: /index.html but instead got %v", response.Header().Get("Location")) } }
// 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") }
// 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 TestRedirect(t *testing.T) { ti, err := aetest.NewInstance(nil) if err != nil { t.Fatal(err) } defer ti.Close() const ( redirectTo = "https://www.example.com" code = http.StatusFound ) handler := redirectHandler(redirectTo, code) urls := []string{"/", "/page", "/page/", "/page?with=query"} for _, u := range urls { req, err := ti.NewRequest("GET", u, nil) if err != nil { t.Errorf("%s: %v", u, err) continue } req.Host = "example.org" res := httptest.NewRecorder() handler.ServeHTTP(res, req) if res.Code != code { t.Errorf("%s: res.Code = %d; want %d", u, res.Code, code) } redir := redirectTo + u if v := res.Header().Get("location"); v != redir { t.Errorf("%s: location = %q; want %q", u, v, redir) } } }
func TestGetSpot(t *testing.T) { opt := aetest.Options{AppID: "t2jp-2015", StronglyConsistentDatastore: true} inst, err := aetest.NewInstance(&opt) defer inst.Close() input, err := json.Marshal(Spot{SpotName: "foo", Body: "bar"}) req, err := inst.NewRequest("POST", "/edit/v1/spots", bytes.NewBuffer(input)) if err != nil { t.Fatalf("Failed to create req: %v", err) } loginUser := user.User{Email: "*****@*****.**", Admin: false, ID: "111111"} aetest.Login(&loginUser, req) // ctx := appengine.NewContext(req) res := httptest.NewRecorder() c := web.C{} spotCreateHandler(c, res, req) if res.Code != http.StatusCreated { t.Fatalf("Fail to request spots create, status code: %v", res.Code) } var getResponse GetResponse err = json.NewDecoder(res.Body).Decode(&getResponse) spotCode := getResponse.Item.SpotCode t.Logf("spot code: %v", strconv.FormatInt(spotCode, 10)) getReq, err := inst.NewRequest("GET", "/edit/v1/spots/"+strconv.FormatInt(spotCode, 10), nil) if err != nil { t.Fatalf("Failed to create req: %v", err) } getRes := httptest.NewRecorder() getC := web.C{URLParams: map[string]string{"spotCode": strconv.FormatInt(spotCode, 10)}} spotGetHandler(getC, getRes, getReq) if getRes.Code != http.StatusOK { t.Fatalf("Fail to request spot get, status code: %v", getRes.Code) } }
func TestIndexPage(t *testing.T) { inst, err := aetest.NewInstance(nil) 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 request: %v", err) } w := httptest.NewRecorder() var vars map[string]string var settings Settings file, err := ioutil.ReadFile("./settings_test.json") if err == nil { json.Unmarshal(file, &settings) } ctx, _, _ := aetest.NewContext() index(&Context{ AE: ctx, Request: req, Response: w, Settings: &settings, Vars: vars, }) if w.Code != 200 { t.Errorf("Index did not return 200. Returned type was %d", w.Code) } }
func TestApi1ExpoCurrentHandlerNoExpo(t *testing.T) { inst, err := aetest.NewInstance(nil) if err != nil { t.Errorf("Failed to create instance: %v", err) } defer inst.Close() request, err := inst.NewRequest("GET", "/api/1/expo/current", nil) if err != nil { t.Errorf("Error creating new instance %v", err) } response := httptest.NewRecorder() Api1ExpoCurrentHandler(response, request) if response.Code != http.StatusOK { t.Errorf("Did not get StatusOK got %v", response.Code) } data, err := ioutil.ReadAll(response.Body) if err != nil { t.Errorf("Error reading body %v", err) } expected := "{ \"NumTeams\": 0, \"NumRegistered\": 0 }" if string(data) != expected { t.Errorf("Expected %s got %v", expected, string(data)) } }
func TestApi1UserProfileHandler(t *testing.T) { inst, err := aetest.NewInstance(nil) if err != nil { t.Errorf("Failed to create instance: %v", err) } defer inst.Close() request, err := inst.NewRequest("GET", "/api/1/user/profile", nil) if err != nil { t.Errorf("Error creating new instance %v", err) } response := httptest.NewRecorder() Api1UserProfileHandler(response, request) if response.Code != http.StatusOK { t.Errorf("Did not get StatusOK got %v", response.Code) } data, err := ioutil.ReadAll(response.Body) if err != nil { t.Errorf("Error reading body %v", err) } prefix := `{"Name":"","Email":"","LogoutUrl":"","LoginUrl":"/_ah/login?continue=` if !strings.HasPrefix(string(data), prefix) { t.Errorf("Expected %s got %v", prefix, string(data)) } }
func TestHook(t *testing.T) { ti, err := aetest.NewInstance(nil) if err != nil { t.Fatal(err) } defer ti.Close() body := `{"bucket": "dummy", "name": "path/obj"}` req, _ := ti.NewRequest("POST", "/-/hook/gcs", strings.NewReader(body)) const cacheKey = "dummy/path/obj" ctx := appengine.NewContext(req) item := &memcache.Item{Key: cacheKey, Value: []byte("ignored")} if err := memcache.Set(ctx, item); err != nil { t.Fatal(err) } // must remove cached item res := httptest.NewRecorder() http.DefaultServeMux.ServeHTTP(res, req) if res.Code != http.StatusOK { t.Errorf("res.Code = %d; want %d", res.Code, http.StatusOK) } if _, err := memcache.Get(ctx, cacheKey); err != memcache.ErrCacheMiss { t.Fatalf("memcache.Get(%q): %v; want ErrCacheMiss", cacheKey, err) } // cache misses must not respond with an error code req, _ = ti.NewRequest("POST", "/-/hook/gcs", strings.NewReader(body)) res = httptest.NewRecorder() http.DefaultServeMux.ServeHTTP(res, req) if res.Code != http.StatusOK { t.Errorf("res.Code = %d; want %d", res.Code, http.StatusOK) } }
func TestAddLocationTestify(t *testing.T) { inst, err := aetest.NewInstance( &aetest.Options{StronglyConsistentDatastore: true}) require.Nil(t, err, "Error creating aetest instance: %v", err) defer inst.Close() rt := initRouter() loc, err := json.Marshal(&Location{ Name: "Cambridge Fresh Pond", Lat: 42.5, Lng: -71.5, }) assert.Nil(t, err, "Error marshalling Location into JSON: %v", err) req, err := inst.NewRequest("POST", "/add-location", ioutil.NopCloser(bytes.NewBuffer(loc))) require.Nil(t, err, "Error preparing request: %v", err) rec := httptest.NewRecorder() rt.ServeHTTP(rec, req) const expectedResponse = `{"addLocation":"success"}` assert.Equal(t, expectedResponse, string(rec.Body.Bytes()), "Expected response to be %s, got %s", expectedResponse, string(rec.Body.Bytes())) dbReq, err := inst.NewRequest("GET", "/", nil) require.Nil(t, err, "Error preparing request: %v", err) ctx := appengine.NewContext(dbReq) q := datastore.NewQuery("Location") numLocs, err := q.Count(ctx) require.Nil(t, err, "Error preparing request: %v", err) assert.Equal(t, 1, numLocs, "Expected number of locations to be 1, got %d", numLocs) }
func (s *TestSuite) SetupSuite() { var err error s.inst, err = aetest.NewInstance( &aetest.Options{StronglyConsistentDatastore: true}) require.Nil(s.T(), err, "Error creating aetest instance: %v", err) s.rt = initRouter() }
func setUp() { server = NewServer() opt := aetest.Options{AppID: "auth", StronglyConsistentDatastore: true} var err error inst, err = aetest.NewInstance(&opt) if err != nil || inst == nil { log.Printf("ERROR: %v", fmt.Errorf("Failed to created aetest instance, %v", err)) inst.Close() } r, err := inst.NewRequest("GET", "/", nil) if err != nil { log.Panicf("Failed to create request: %v", err) inst.Close() } c := appengine.NewContext(r) _, err = setupFakeClient(c) if err != nil { log.Panicf("Failed to create fake client: %v", err) inst.Close() } userKey, err := setupFakeUser(c) if err != nil { log.Panicf("Failed to create fake user: %v", err) inst.Close() } _, err = setupFakeAccessToken(c, userKey) if err != nil { log.Panicf("Failed to create fake access token: %v", err) inst.Close() } }
func TestMain(m *testing.M) { oauth1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte(`{"access_token": "oauth1-token"}`)) })) config.Dir = "app" config.Env = "dev" config.Prefix = "/myprefix" config.Google.Auth.Client = "test-client-id" config.Google.ServiceAccount.Key = "" config.Twitter.TokenURL = oauth1.URL + "/" config.SyncToken = "sync-token" config.Schedule.Start = time.Date(2015, 5, 28, 9, 0, 0, 0, time.UTC) config.Schedule.Timezone = "America/Los_Angeles" var err error config.Schedule.Location, err = time.LoadLocation(config.Schedule.Timezone) if err != nil { fmt.Fprintf(os.Stderr, "Could not load location %q", config.Schedule.Location) os.Exit(1) } // a test instance shared across multiple tests if aetestInstance, err = aetest.NewInstance(nil); err != nil { panic(fmt.Sprintf("aetestInstance: %v", err)) } // run all tests code := m.Run() // cleanup oauth1.Close() aetestInstance.Close() cleanupTests() os.Exit(code) }
func TestCreateSpot(t *testing.T) { opt := aetest.Options{AppID: "t2jp-2015", StronglyConsistentDatastore: true} inst, err := aetest.NewInstance(&opt) defer inst.Close() input, err := json.Marshal(Spot{SpotName: "foo", Body: "bar"}) req, err := inst.NewRequest("POST", "/edit/v1/spots", bytes.NewBuffer(input)) if err != nil { t.Fatalf("Failed to create req: %v", err) } loginUser := user.User{Email: "*****@*****.**", Admin: false, ID: "111111"} aetest.Login(&loginUser, req) ctx := appengine.NewContext(req) res := httptest.NewRecorder() c := web.C{} spotCreateHandler(c, res, req) if res.Code != http.StatusCreated { t.Fatalf("Fail to request spots create, status code: %v", res.Code) } spots := []Spot{} _, err = datastore.NewQuery("Spot").Order("-UpdatedAt").GetAll(ctx, &spots) for i := 0; i < len(spots); i++ { t.Logf("SpotCode:%v", spots[i].SpotCode) t.Logf("SpotName:%v", spots[i].SpotName) } if spots[0].SpotName != "foo" { t.Fatalf("not expected value! :%v", spots[0].SpotName) } }
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 TestMain(m *testing.M) { var err error instance, err = aetest.NewInstance(nil) if err != nil { panic(err) } defer instance.Close() os.Exit(m.Run()) }
func TestGoonKind(t *testing.T) { opts := &aetest.Options{ StronglyConsistentDatastore: true, } inst, err := aetest.NewInstance(opts) if err != nil { t.Fatal(err) } defer inst.Close() req, err := inst.NewRequest("GET", "/", nil) if err != nil { t.Fatal(err) } c := appengine.NewContext(req) g := goon.FromContext(c) entity1 := &Sample{ Foo: "foo1", } key1, err := g.Put(entity1) if err != nil { t.Fatal(err) } t.Logf("key1: %s", key1.String()) entity2 := &Sample{ Kind: "sample_specified", Foo: "foo1", } key2, err := g.Put(entity2) if err != nil { t.Fatal(err) } t.Logf("key2: %s", key2.String()) cnt1, err := NewSampleQueryBuilder().Query().Count(c) if err != nil { t.Fatal(err) } if cnt1 != 1 { t.Errorf("unexpected: %v", cnt1) } cnt2, err := NewSampleQueryBuilderWithKind(entity2.Kind).Query().Count(c) if err != nil { t.Fatal(err) } if cnt2 != 1 { t.Errorf("unexpected: %v", cnt2) } }
func TestIndex(t *testing.T) { inst, err := aetest.NewInstance(nil) if err != nil { t.Fatalf("Failed to create instance: %v", err) } defer inst.Close() _, err = inst.NewRequest("GET", "/", nil) if err != nil { t.Fatalf("Failed to create req1: %v", err) } }
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 TestMain(m *testing.M) { flag.Parse() var err error testInstance, err = aetest.NewInstance(nil) if err != nil { log.Fatal(err) } code := m.Run() testInstance.Close() os.Exit(code) }
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 TestServe_Memcache(t *testing.T) { ti, err := aetest.NewInstance(nil) if err != nil { t.Fatal(err) } defer ti.Close() const ( bucket = "default-bucket" reqFile = "/index.html" realFile = bucket + "/index.html" contentType = "text/html" contents = "cached file" cacheControl = "public,max-age=10" ) req, _ := ti.NewRequest("GET", reqFile, nil) ctx := appengine.NewContext(req) obj := &object{ Meta: map[string]string{ "content-type": contentType, "cache-control": cacheControl, }, Body: []byte(contents), } item := memcache.Item{Key: realFile, Object: obj} if err := memcache.Gob.Set(ctx, &item); err != nil { t.Fatal(err) } // make sure we don't hit real GCS gcsBase = "invalid" // overwrite global config config.Buckets = map[string]string{"default": bucket} res := httptest.NewRecorder() http.DefaultServeMux.ServeHTTP(res, req) if res.Code != http.StatusOK { t.Errorf("res.Code = %d; want %d", res.Code, http.StatusOK) } if v := res.Header().Get("cache-control"); v != cacheControl { t.Errorf("cache-control = %q; want %q", v, cacheControl) } if v := res.Header().Get("content-type"); v != contentType { t.Errorf("content-type = %q; want %q", v, contentType) } if s := res.Body.String(); s != contents { t.Errorf("res.Body = %q; want %q", s, contents) } }
// 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 TestUpdateSpot(t *testing.T) { opt := aetest.Options{AppID: "t2jp-2015", StronglyConsistentDatastore: true} inst, err := aetest.NewInstance(&opt) defer inst.Close() input, err := json.Marshal(Spot{SpotName: "foo", Body: "bar"}) req, err := inst.NewRequest("POST", "/edit/v1/spots", bytes.NewBuffer(input)) if err != nil { t.Fatalf("Failed to create req: %v", err) } loginUser := user.User{Email: "*****@*****.**", Admin: false, ID: "111111"} aetest.Login(&loginUser, req) // ctx := appengine.NewContext(req) res := httptest.NewRecorder() c := web.C{} spotCreateHandler(c, res, req) if res.Code != http.StatusCreated { t.Fatalf("Fail to request spots create, status code: %v", res.Code) } var getResponse GetResponse err = json.NewDecoder(res.Body).Decode(&getResponse) if getResponse.Item.Status != "draft" { t.Fatalf("not saved as draft on creation!") } spotCodeString := strconv.FormatInt(getResponse.Item.SpotCode, 10) t.Logf("spot code: %v", spotCodeString) patchInput, err := json.Marshal(Spot{SpotName: "foo2", Body: "barbar"}) patchReq, err := inst.NewRequest("PATCH", "/edit/v1/spots/"+spotCodeString, bytes.NewBuffer(patchInput)) aetest.Login(&loginUser, patchReq) if err != nil { t.Fatalf("Failed to create req: %v", err) } patchRes := httptest.NewRecorder() patchC := web.C{URLParams: map[string]string{"spotCode": spotCodeString}} spotUpdateHandler(patchC, patchRes, patchReq) if patchRes.Code != http.StatusOK { t.Fatalf("Fail to request spot patch, status code: %v", patchRes.Code) } var checkSpot Spot ctx := appengine.NewContext(patchReq) checkSpot.SpotCode = getResponse.Item.SpotCode err = datastore.Get(ctx, checkSpot.key(ctx), &checkSpot) if err != nil { t.Fatalf("Fail to get data from datastore: %v", err) } if checkSpot.RevisionNumber != 1 { t.Fatalf("RevisionNumber should be 1") } }
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 TestAddLocation(t *testing.T) { inst, err := aetest.NewInstance( &aetest.Options{StronglyConsistentDatastore: true}) if err != nil { t.Fatalf("Error creating aetest instance: %v", err) } defer inst.Close() // Make sure the aetest instance always closes rt := initRouter() // Get our router loc, err := json.Marshal(&Location{ Name: "Cambridge Fresh Pond", Lat: 42.385658, Lng: -71.149308, }) if err != nil { t.Errorf("Error marshalling Location into JSON: %v", err) } req, err := inst.NewRequest("POST", "/add-location", ioutil.NopCloser(bytes.NewBuffer(loc))) if err != nil { t.Fatalf("Error preparing request: %v", err) } rec := httptest.NewRecorder() rt.ServeHTTP(rec, req) const expectedResponse = `{"addLocation":"success"}` if string(rec.Body.Bytes()) != expectedResponse { t.Errorf("Expected response to be %s, got %s", expectedResponse, string(rec.Body.Bytes())) } dbReq, err := inst.NewRequest("GET", "/", nil) if err != nil { t.Fatalf("Error preparing request: %v", err) } ctx := appengine.NewContext(dbReq) q := datastore.NewQuery("Location") numLocs, err := q.Count(ctx) if err != nil { t.Fatalf("Error preparing request: %v", err) } if numLocs != 1 { t.Errorf("Expected number of locations to be 1, got %d", numLocs) } }
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 TestResponsePublic(t *testing.T) { instance, _ := aetest.NewInstance(nil) defer instance.Close() fakeR, _ := instance.NewRequest("GET", "/", nil) fakeW := httptest.NewRecorder() handler := Response(func(ctx context.Context, w http.ResponseWriter, r *http.Request) { w.Write([]byte("OK")) }, 10*time.Second) handler(appengine.NewContext(fakeR), fakeW, fakeR) if fakeW.Code != http.StatusOK { t.Errorf("Expected http.StatusOK, but got %d", fakeW.Code) } if fakeW.Header().Get("Cache-Control") != "public,max-age=10" { t.Errorf("Unexpected Cache-Control header: %s", fakeW.Header().Get("Cache-Control")) } if fakeW.Header().Get("Vary") != "" { t.Errorf("Unexpected Vary header: %s", fakeW.Header().Get("Vary")) } fakeCtx := appengine.NewContext(fakeR) fakeCtx = context.WithValue(fakeCtx, "__auth_check_ctx", "passed") fakeW = httptest.NewRecorder() handler(fakeCtx, fakeW, fakeR) if fakeW.Code != http.StatusOK { t.Errorf("Expected http.StatusOK, but got %d", fakeW.Code) } if fakeW.Header().Get("Cache-Control") != "private,max-age=10" { t.Errorf("Unexpected Cache-Control header: %s", fakeW.Header().Get("Cache-Control")) } if fakeW.Header().Get("Vary") != "Authorization" { t.Errorf("Unexpected Vary header: %s", fakeW.Header().Get("Vary")) } }
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") } }