func NewApp(instance wcg.Server) *server.App { app := server.NewApp("_debug") app.GET("/routes.txt", wcg.AnonymousHandler(func(res *wcg.Response, req *wcg.Request) { res.Header().Set("Content-Type", "text/plain") res.WriteString(fmt.Sprintf("%v", instance.Routes())) res.End() })) app.GET("/env.txt", middleware.Gate("debugger"), wcg.AnonymousHandler(func(res *wcg.Response, req *wcg.Request) { res.Header().Set("Content-Type", "text/plain") res.WriteString("[Environment Variable]\n") for _, v := range os.Environ() { res.WriteString(fmt.Sprintf(" %v\n", v)) } res.WriteString("\n") res.WriteString("[Http Header]\n") for k, vlist := range req.HTTPRequest().Header { for _, v := range vlist { res.WriteString(fmt.Sprintf(" %s=%s\n", k, v)) } } })) app.GET("/config.json", middleware.Gate("debugger"), wcg.AnonymousHandler(func(res *wcg.Response, req *wcg.Request) { res.WriteJSON(map[string]interface{}{ "wcg.DefaultLogConfig": wcg.DefaultLogConfig, }) })) return app }
func Test_ByHeader(t *testing.T) { assert := gaetest.NewAssert(t) assert.Nil(gaetest.ResetFixtureFromFile(ts.Context, "./fixtures/Test_HeaderAuth.json", nil), "fixture") router := wcg.NewRouter() handler := wcg.AnonymousHandler(func(res *wcg.Response, req *wcg.Request) { res.WriteString(req.User.ID()) }) byHeader(router, func() { router.GET("/api/foo", handler) router.GET("/cron/foo", handler) }) req := ts.GET("/api/foo") assert.EqStr("-", string(req.RouteTo(router).Body), "Guest") req = ts.GET("/api/foo") req.AddHeader(request.APITokenHeader, "2e489f08-3be9-4d28-af86-b14841b2181a") assert.EqStr("api:2e489f08-3be9-4d28-af86-b14841b2181a", string(req.RouteTo(router).Body), "APITokenUser") req = ts.GET("/api/foo") req.AddHeader(request.APITokenHeader, "invalidtoken") assert.EqStr("-", string(req.RouteTo(router).Body), "Guest") req = ts.GET("/api/foo") req.AddHeader(request.TaskQueueHeader, "true") assert.EqStr(fmt.Sprintf("api:%s", request.APITokenForTask), string(req.RouteTo(router).Body), "Guest") req = ts.GET("/cron/foo") req.AddHeader(request.CronHeader, "true") assert.EqStr(fmt.Sprintf("api:%s", request.APITokenForCron), string(req.RouteTo(router).Body), "CronUser") }
func Test_APITokenOnly(t *testing.T) { assert := gaetest.NewAssert(t) router := wcg.NewRouter() router.GET("/", APITokenOnly(), wcg.AnonymousHandler(func(res *wcg.Response, req *wcg.Request) { res.WriteString("OK") }), ) req := ts.GET("/") res := req.RouteTo(router) assert.HTTPStatus(401, res) req = ts.GET("/") req.Request.User = &request.APITokenUser{ &models.APIToken{ Token: "testuser", Description: "test api token user", CreatedAt: time.Now(), AlertOn: time.Duration(0), LastAccess: time.Now(), }, } res = req.RouteTo(router) assert.HTTPStatus(200, res) }
func Test_ParseForm(t *testing.T) { assert := gaetest.NewAssert(t) router := wcg.NewRouter() router.POST("/*", ParseForm(func(v *validators.FormValidator) { v.IntField("foo").Required() }), wcg.AnonymousHandler(func(res *wcg.Response, req *wcg.Request) { res.WriteString("OK") }), ) req := ts.POSTForm("/api/", nil) res := req.RouteTo(router) var got map[string]interface{} assert.HTTPStatus(400, res) assert.JSONResponse(&got, res) assert.OK(len(got["fields"].(map[string]interface{})) > 0, "'fields' field") req = ts.POSTForm("/api/", url.Values{ "foo": []string{"a"}, }) res = req.RouteTo(router) assert.HTTPStatus(200, res) }
// Handle to test handler func (r *TestRequest) Handle(funcs ...func(*wcg.Response, *wcg.Request)) *TestResponse { router := wcg.NewRouter() for _, fun := range funcs { router.All("/*", wcg.AnonymousHandler(fun)) } return r.RouteTo(router) }
func Test_Session(t *testing.T) { assert := gaetest.NewAssert(t) handler := wcg.AnonymousHandler(func(res *wcg.Response, req *wcg.Request) { if req.Session == nil { res.WriteString("No Session") } else { res.WriteString("Has Session") } }) router := wcg.NewRouter() Use(router, func() { router.GET("/api/foo", handler) router.GET("/static/foo", handler) router.GET("/cron/foo", handler) }) req := ts.GET("/api/foo") assert.EqStr("Has Session", string(req.RouteTo(router).Body), "Has Session") req = ts.GET("/api/foo") req.AddHeader(request.APITokenHeader, "FOO") assert.EqStr("No Session", string(req.RouteTo(router).Body), "No Session") req = ts.GET("/api/foo") req.AddHeader(request.TaskQueueHeader, "true") assert.EqStr("No Session", string(req.RouteTo(router).Body), "No Session") req = ts.GET("/static/foo") assert.EqStr("No Session", string(req.RouteTo(router).Body), "No Session") req = ts.GET("/cron/foo") req.AddHeader(request.CronHeader, "true") assert.EqStr("No Session", string(req.RouteTo(router).Body), "No Session") }
func Test_PageResponse_GetTemplates(t *testing.T) { assert := gaetest.NewAssert(t) router := wcg.NewRouter() router.GET("/*", wcg.AnonymousHandler(func(res *wcg.Response, req *wcg.Request) { pr := NewPageResponseWithStatus("test", 200) res.WriteString(pr.GetTemplates(req)[0]) res.Close() })) assert.EqStr("default.html", string(ts.GET("/foo").RouteTo(router).Body), "index.html") assert.EqStr("./testapp/a.html", string(ts.GET("/testapp/a.html").RouteTo(router).Body), "/testapp/a.html") }
func Test_CollectReadyNASSMART(t *testing.T) { assert := wcg.NewAssert(t) httptest.StartMockServer(func(mock *httptest.MockServer) { mock.Routes().GET("/*", wcg.AnonymousHandler(func(res *wcg.Response, req *wcg.Request) { http.ServeFile(res, req.HTTPRequest(), "./fixtures/SMART.xml") })) stats, err := CollectReadyNASSMART(mock.Addr(), "", "", 6) assert.Nil(err, "getReadyNASSMart should not return an error") assert.EqInt(6, len(stats), "len(stats)") for _, s := range stats { assert.EqInt(5, s.StartStopCount, "StartStopCount") } }) }
func Test_getReadyNASSMART(t *testing.T) { assert := wcg.NewAssert(t) httptest.StartMockServer(func(mock *httptest.MockServer) { mock.Routes().GET("/*", wcg.AnonymousHandler(func(res *wcg.Response, req *wcg.Request) { http.ServeFile(res, req.HTTPRequest(), "./fixtures/SMART.xml") })) s, err := getSMARTStatsFromReadyNAS(mock.BaseURL(), "", "") assert.Nil(err, "getReadyNASSMart should not return an error") assert.EqInt(1, s.SpinUpTime, "SpinUpTime") assert.EqInt(5, s.StartStopCount, "StartStopCount") assert.EqInt64(252668631068583, s.HeadFlyingHours, "HeadFlyingHours") assert.EqInt64(76931166535, s.TotalLBAsWritten, "TotalLBAsWritten") assert.EqInt64(186750896472, s.TotalLBAsRead, "TotalLBAsRead") }) }
func Test_IsUserOptIn(t *testing.T) { assert := gaetest.NewAssert(t) assert.Nil(gaetest.ResetFixtureFromFile(ts.Context, "./fixtures/Test_IsUserOptIn.json", nil), "fixture") router := wcg.NewRouter() router.GET("/test_is_user_opt_in", wcg.AnonymousHandler(func(res *wcg.Response, req *wcg.Request) { assert.OK(IsUserOptIn(req, "12345", "67890"), "IsUserOptIn should return true.") assert.OK(!IsUserOptIn(req, "aaaa", "aaaa"), "IsUserOptIn should return false.") res.WriteString("OK") })) req := ts.GET("/test_is_user_opt_in") res := req.RouteTo(router) assert.HTTPStatus(200, res) }
func Test_IsAPI(t *testing.T) { assert := gaetest.NewAssert(t) handler := wcg.AnonymousHandler(func(res *wcg.Response, req *wcg.Request) { if IsAPI(req) { res.WriteString("IsAPI") } else { res.WriteString("Not IsAPI") } }) router := wcg.NewRouter() router.GET("/api/foo", handler) router.GET("/foo", handler) assert.EqStr("IsAPI", string(ts.GET("/api/foo").RouteTo(router).Body), "IsAPI") assert.EqStr("Not IsAPI", string(ts.GET("/foo").RouteTo(router).Body), "Not IsAPI") }
func Test_Run(t *testing.T) { assert := wcg.NewAssert(t) httptest.StartMockServer(func(s *httptest.MockServer) { s.Routes().GET("/*", wcg.AnonymousHandler(func(res *wcg.Response, req *wcg.Request) { res.WriteString("OK") })) url := s.BaseURL() runner := &Runner{ Crawler: &testCrawlerImpl{url}, } result, err := runner.Run(url) assert.Nil(err) assert.EqStr("OK", result.Data.(string)) }) }
func Test_getReadyNASSMART_With_BasicAuth(t *testing.T) { assert := wcg.NewAssert(t) httptest.StartMockServer(func(mock *httptest.MockServer) { mock.Routes().GET("/*", wcg.AnonymousHandler(func(res *wcg.Response, req *wcg.Request) { username, password, _ := req.HTTPRequest().BasicAuth() if username == "testuser" && password == "passw0rd" { http.ServeFile(res, req.HTTPRequest(), "./fixtures/SMART.xml") } else { res.WriteHeader(401) } })) _, err := getSMARTStatsFromReadyNAS(mock.BaseURL(), "testuser", "passw0rd") assert.Nil(err, "getReadyNASSMart should not return an error") _, err = getSMARTStatsFromReadyNAS(mock.BaseURL(), "", "") assert.OK(err != nil, "getReadyNASSMart should return an error") }) }
func Test_Gate(t *testing.T) { assert := gaetest.NewAssert(t) router := wcg.NewRouter() router.GET("/", Gate("foo"), wcg.AnonymousHandler(func(res *wcg.Response, req *wcg.Request) { res.WriteString("OK") }), ) req := ts.GET("/") res := req.RouteTo(router) assert.HTTPStatus(401, res) req = ts.GET("/") testhelper.TemporaryAllow(req, "foo", func() { res := req.RouteTo(router) assert.HTTPStatus(200, res) }) }
func Test_RequireMessengerOptIn(t *testing.T) { assert := gaetest.NewAssert(t) router := wcg.NewRouter() router.GET("/", RequireMessengerOptIn(""), wcg.AnonymousHandler(func(res *wcg.Response, req *wcg.Request) { res.WriteString("OK") }), ) req := ts.GET("/") res := req.RouteTo(router) assert.HTTPStatus(403, res) configs.TemporarySetConfig(ts.GET("dummy").Request, "facebook_page_id", "1234", func() { messenger.TemporaryOptIn(ts.GET("dummy").Request, "1234", wcg.GuestUser.ID(), func() { req := ts.GET("/") res := req.RouteTo(router) assert.HTTPStatus(200, res) }) }) }
func Test_IsTask(t *testing.T) { assert := gaetest.NewAssert(t) handler := wcg.AnonymousHandler(func(res *wcg.Response, req *wcg.Request) { if IsTask(req) { res.WriteString("IsTask") } else { res.WriteString("Not IsTask") } }) router := wcg.NewRouter() router.GET("/api/foo", handler) router.GET("/cron/foo", handler) assert.EqStr("Not IsTask", string(ts.GET("/api/foo").RouteTo(router).Body), "Not IsTask") assert.EqStr("Not IsTask", string(ts.GET("/cron/foo").RouteTo(router).Body), "Not IsTask") req := ts.GET("/cron/foo") req.AddHeader(TaskQueueHeader, "true") assert.EqStr("IsTask", string(req.RouteTo(router).Body), "IsTask") req = ts.GET("/api/foo") assert.EqStr("Not IsTask", string(req.RouteTo(router).Body), "Not IsTask") }
func Test_URLCacher_(t *testing.T) { assert := wcg.NewAssert(t) assert.Nil(gaetest.CleanupDatastore(ts.Context, "hplink")) httptest.StartMockServer(func(mock *httptest.MockServer) { // preparation for dummy entry var count = 0 mock.Routes().GET("/*", wcg.AnonymousHandler(func(res *wcg.Response, req *wcg.Request) { if req.Header("if-none-match") == "etagvalue" { res.WriteHeader(304) res.Close() return } count++ res.Header().Set("Etag", "etagvalue") res.WriteString("FOO") })) textURL := fmt.Sprintf("%s%s", mock.BaseURL(), "/") client := NewURLCacheAwareClient(ts.GET("/").Request, urlCacheKind) resp, _ := client.Get(textURL) body, _ := ioutil.ReadAll(resp.Body) resp.Body.Close() assert.EqInt(200, resp.StatusCode) assert.EqStr("FOO", string(body)) _, v := urlCacheKind.Get().Key(textURL).MustOne(ts.GET("/").Request) assert.NotNil(v) resp, _ = client.Get(textURL) body, _ = ioutil.ReadAll(resp.Body) resp.Body.Close() assert.EqInt(304, resp.StatusCode) assert.EqStr("FOO", string(body)) }) }
func Test_Run_With_UserAgent(t *testing.T) { assert := wcg.NewAssert(t) httptest.StartMockServer(func(s *httptest.MockServer) { s.Routes().GET("/*", wcg.AnonymousHandler(func(res *wcg.Response, req *wcg.Request) { if req.UserAgent() == "Special UserAgent" { res.WriteHeader(403) res.WriteString("Forbidden") } res.WriteString("OK") })) url := s.BaseURL() runner := &Runner{ Crawler: &testCrawlerImpl{url}, } result, err := runner.Run(url) assert.Nil(err) assert.EqStr("OK", result.Data.(string)) runner.UserAgent = "Special UserAgent" _, err = runner.Run(url) assert.NotNil(err) }) }
func bySession(router *wcg.Router, configure func()) { fbconfig := facebook.NewAuthConfig("dummy", "dumyy", "") fbconfig.RedirectURL = "/login/facebook/callback" fbconfig.ContextFactory = func(res *wcg.Response, req *wcg.Request) context.Context { return gae.NewContext(req) } fbconfig.UnauthorizedHandler = wcg.AnonymousHandler(func(res *wcg.Response, req *wcg.Request) { res.TemplatesWithStatus(401, nil, "permrejected.html", "header.html", "footer.html") }) fbconfig.AuthorizedHandler = wcg.AnonymousHandler(func(res *wcg.Response, req *wcg.Request) { ref, _ := req.Session.Get("LoginRef") if ref != "" && strings.HasPrefix(ref, "/") { res.Redirect(wcg.AbsoluteURL(req, ref), http.StatusFound) } else { res.Redirect("/", http.StatusFound) } }) fbconfig.InvalidatedHandler = wcg.AnonymousHandler(func(res *wcg.Response, req *wcg.Request) { req.Logger.Debugf("Guest user access.") }) fbconfig.Scopes = []string{} fbauth, fbcallback, fbvalidates, fblogout := middleware.OAuth2(fbconfig) // set routes router.Before(wcg.NewNamedHandler("facebook.validate", func(res *wcg.Response, req *wcg.Request) { if !request.ByGuest(req) { // already authenticated return } if req.Session == nil { return } // Check the fbconfig from ServerConfig fbapp := configs.GetMultiValues( req, "facebook_app_id", "facebook_app_secret", "facebook_page_id", ) if fbapp[0] != "" && fbapp[1] != "" { fbconfig.ClientID = fbapp[0] fbconfig.ClientSecret = fbapp[1] fbvalidates.Process(res, req) } })) router.GET("/login/facebook", wcg.NewNamedHandler("facebook.login.auth", func(res *wcg.Response, req *wcg.Request) { if !isFBConfigured(fbconfig) { return } req.Session.Set("LoginRef", req.Query("ref")) fbauth.Process(res, req) })) router.GET("/login/facebook/callback", wcg.NewNamedHandler("facebook.login.callback", func(res *wcg.Response, req *wcg.Request) { if !isFBConfigured(fbconfig) { return } fbcallback.Process(res, req) })) router.POST("/logout/facebook", wcg.NewNamedHandler("facebook.logout", func(res *wcg.Response, req *wcg.Request) { if !isFBConfigured(fbconfig) { return } fblogout.Process(res, req) res.Redirect("/", http.StatusFound) })) configure() }