本文整理汇总了Golang中net/http/httptest.NewRecorder函数的典型用法代码示例。如果您正苦于以下问题:Golang NewRecorder函数的具体用法?Golang NewRecorder怎么用?Golang NewRecorder使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewRecorder函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestShortcut
func (test *ServerTest) TestShortcut(c *C) {
w := httptest.NewRecorder()
r, _ := http.NewRequest("PUT", "https://idp.example.com/shortcuts/bob",
strings.NewReader("{\"url_suffix_as_relay_state\": true, \"service_provider\": \"https://sp.example.com/saml2/metadata\"}"))
test.Server.ServeHTTP(w, r)
c.Assert(w.Code, Equals, http.StatusNoContent)
w = httptest.NewRecorder()
r, _ = http.NewRequest("PUT", "https://idp.example.com/users/alice",
strings.NewReader(`{"name": "alice", "password": "hunter2"}`+"\n"))
test.Server.ServeHTTP(w, r)
c.Assert(w.Code, Equals, http.StatusNoContent)
w = httptest.NewRecorder()
r, _ = http.NewRequest("POST", "https://idp.example.com/login",
strings.NewReader("user=alice&password=hunter2"))
r.Header.Set("Content-type", "application/x-www-form-urlencoded")
test.Server.ServeHTTP(w, r)
c.Assert(w.Code, Equals, http.StatusOK)
w = httptest.NewRecorder()
r, _ = http.NewRequest("GET", "https://idp.example.com/login/bob/whoami", nil)
r.Header.Set("Cookie", "session=AAIEBggKDA4QEhQWGBocHiAiJCYoKiwuMDI0Njg6PD4=")
test.Server.ServeHTTP(w, r)
c.Assert(w.Code, Equals, http.StatusOK)
body := string(w.Body.Bytes())
c.Assert(strings.Contains(body, "<input type=\"hidden\" name=\"RelayState\" value=\"/whoami\" />"), Equals, true)
c.Assert(strings.Contains(body, "<script>document.getElementById('SAMLResponseForm').submit();</script>"), Equals, true)
}
示例2: TestRouterFilterPath
// TestRouterFilterPath tests the Path filter, and ensures the filter
// is only executed when the Request Path matches the filter Path.
func TestRouterFilterPath(t *testing.T) {
// in the first test scenario, the Path filter should not fire
// because it does not take the "first name" section of the URL
// into account, and should therefore not match
r, _ := http.NewRequest("GET", "/person/anderson/thomas", nil)
w := httptest.NewRecorder()
mux := New()
mux.FilterPath("/person/*/anderson", HandlerErr)
mux.Get("/person/:last/:first", HandlerOk)
mux.ServeHTTP(w, r)
if w.Body.String() != "hello world" {
t.Errorf("Body set to [%s]; want [%s]", w.Body.String(), "hello world")
}
// in this second scenario, the Parameter filter SHOULD fire because
// we are filtering on all "last names", and the pattern should match
// the first section of the URL (person) and the last section of the
// url (:first)
w = httptest.NewRecorder()
mux = New()
mux.FilterPath("/person/*/thomas", HandlerErr)
mux.Get("/person/:last/:first", HandlerOk)
mux.ServeHTTP(w, r)
if w.Body.String() == "hello world" {
t.Errorf("Body set to [%s]; want empty", w.Body.String())
}
if w.Code != 400 {
t.Errorf("Code set to [%s]; want [%s]", w.Code, http.StatusBadRequest)
}
}
示例3: Test_GenerateToken
func Test_GenerateToken(t *testing.T) {
Convey("Generate token", t, func() {
m := macaron.New()
m.Use(session.Sessioner())
m.Use(Csrfer())
// Simulate login.
m.Get("/login", func(sess session.Store, x CSRF) {
sess.Set("uid", "123456")
})
// Generate token.
m.Get("/private", func() {})
resp := httptest.NewRecorder()
req, err := http.NewRequest("GET", "/login", nil)
So(err, ShouldBeNil)
m.ServeHTTP(resp, req)
cookie := resp.Header().Get("Set-Cookie")
resp = httptest.NewRecorder()
req, err = http.NewRequest("GET", "/private", nil)
So(err, ShouldBeNil)
req.Header.Set("Cookie", cookie)
m.ServeHTTP(resp, req)
})
}
示例4: TestGetSpot
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: "[email protected]", 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)
}
}
示例5: TestHandler_error
func TestHandler_error(t *testing.T) {
w := httptest.NewRecorder()
respondError(w, 500, errors.New("Test Error"))
if w.Code != 500 {
t.Fatalf("expected 500, got %d", w.Code)
}
// The code inside of the error should override
// the argument to respondError
w2 := httptest.NewRecorder()
e := logical.CodedError(403, "error text")
respondError(w2, 500, e)
if w2.Code != 403 {
t.Fatalf("expected 403, got %d", w2.Code)
}
// vault.ErrSealed is a special case
w3 := httptest.NewRecorder()
respondError(w3, 400, vault.ErrSealed)
if w3.Code != 503 {
t.Fatalf("expected 503, got %d", w3.Code)
}
}
示例6: TestRouterNotAllowed
func TestRouterNotAllowed(t *testing.T) {
handlerFunc := func(_ http.ResponseWriter, _ *http.Request, _ Params) {}
router := New()
router.POST("/path", handlerFunc)
// Test not allowed
r, _ := http.NewRequest("GET", "/path", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, r)
if !(w.Code == http.StatusMethodNotAllowed) {
t.Errorf("NotAllowed handling failed: Code=%d, Header=%v", w.Code, w.Header())
}
w = httptest.NewRecorder()
responseText := "custom method"
router.MethodNotAllowed = func(w http.ResponseWriter, req *http.Request) {
w.WriteHeader(http.StatusTeapot)
w.Write([]byte(responseText))
}
router.ServeHTTP(w, r)
if got := w.Body.String(); !(got == responseText) {
t.Errorf("unexpected response got %q want %q", got, responseText)
}
if w.Code != http.StatusTeapot {
t.Errorf("unexpected response code %d want %d", w.Code, http.StatusTeapot)
}
}
示例7: TestVersionMiddleware
// Ensure that version validation middleware passes through request
// on a valid version, and returns a 400 on an invalid version.
func TestVersionMiddleware(t *testing.T) {
assert := assert.New(t)
api := NewAPI(&Configuration{})
handler := new(MockResourceHandler)
handler.On("Authenticate").Return(nil)
handler.On("ValidVersions").Return([]string{"1"})
handler.On("Rules").Return(&rules{})
handler.On("ResourceName").Return("widgets")
handler.On("ReadResourceList").Return([]Resource{"foo"}, "", nil)
api.RegisterResourceHandler(handler)
// Valid version
req, _ := http.NewRequest("GET", "http://example.com/api/v1/widgets", nil)
w := httptest.NewRecorder()
api.ServeHTTP(w, req)
assert.Equal(w.Code, 200)
assert.Contains(w.Body.String(), "foo")
// Invalid version
req, _ = http.NewRequest("GET", "http://example.com/api/v2/widgets", nil)
w = httptest.NewRecorder()
api.ServeHTTP(w, req)
assert.Equal(w.Code, http.StatusBadRequest)
assert.NotContains(w.Body.String(), "foo")
}
示例8: Test_GenerateCustomCookie
func Test_GenerateCustomCookie(t *testing.T) {
m := martini.Classic()
store := sessions.NewCookieStore([]byte("secret123"))
m.Use(sessions.Sessions("my_session", store))
m.Use(Generate(&Options{
Secret: "token123",
SessionKey: "userID",
SetCookie: true,
Cookie: "seesurf",
}))
// Simulate login.
m.Get("/login", func(s sessions.Session) string {
s.Set("userID", "123456")
return "OK"
})
// Generate cookie.
m.Get("/private", func(s sessions.Session, x CSRF) string {
return "OK"
})
res := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/login", nil)
m.ServeHTTP(res, req)
res2 := httptest.NewRecorder()
req2, _ := http.NewRequest("GET", "/private", nil)
req2.Header.Set("Cookie", res.Header().Get("Set-Cookie"))
m.ServeHTTP(res2, req2)
if !strings.Contains(res2.Header().Get("Set-Cookie"), "seesurf") {
t.Error("Failed to set custom csrf cookie")
}
}
示例9: Test_Logout
func Test_Logout(t *testing.T) {
recorder := httptest.NewRecorder()
s := sessions.NewCookieStore([]byte("secret123"))
m := martini.Classic()
m.Use(sessions.Sessions("my_session", s))
m.Use(Google(
&oauth2.Config{
ClientID: "client_id",
ClientSecret: "client_secret",
RedirectURL: "redirect_url",
},
))
m.Get("/", func(s sessions.Session) {
s.Set(keyToken, "dummy token")
})
m.Get("/get", func(s sessions.Session) {
if s.Get(keyToken) != nil {
t.Errorf("User credentials are still kept in the session.")
}
})
logout, _ := http.NewRequest("GET", "/logout", nil)
index, _ := http.NewRequest("GET", "/", nil)
m.ServeHTTP(httptest.NewRecorder(), index)
m.ServeHTTP(recorder, logout)
if recorder.Code != 302 {
t.Errorf("Not being redirected to the next page.")
}
}
示例10: Test_GenerateCustomHeader
func Test_GenerateCustomHeader(t *testing.T) {
m := martini.Classic()
store := sessions.NewCookieStore([]byte("secret123"))
m.Use(sessions.Sessions("my_session", store))
m.Use(Generate(&Options{
Secret: "token123",
SessionKey: "userID",
SetHeader: true,
Header: "X-SEESurfToken",
}))
// Simulate login.
m.Get("/login", func(s sessions.Session) string {
s.Set("userID", "123456")
return "OK"
})
// Generate HTTP header.
m.Get("/private", func(s sessions.Session, x CSRF) string {
return "OK"
})
res := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/login", nil)
m.ServeHTTP(res, req)
res2 := httptest.NewRecorder()
req2, _ := http.NewRequest("GET", "/private", nil)
req2.Header.Set("Cookie", res.Header().Get("Set-Cookie"))
m.ServeHTTP(res2, req2)
if res2.Header().Get("X-SEESurfToken") == "" {
t.Error("Failed to set X-SEESurfToken custom header")
}
}
示例11: Test_Validate
func Test_Validate(t *testing.T) {
m := martini.Classic()
store := sessions.NewCookieStore([]byte("secret123"))
m.Use(sessions.Sessions("my_session", store))
m.Use(Generate(&Options{
Secret: "token123",
SessionKey: "userID",
}))
// Simulate login.
m.Get("/login", func(s sessions.Session) string {
s.Set("userID", "123456")
return "OK"
})
// Generate token.
m.Get("/private", func(s sessions.Session, x CSRF) string {
return x.GetToken()
})
m.Post("/private", Validate, func(s sessions.Session) string {
return "OK"
})
// Login to set session.
res := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/login", nil)
m.ServeHTTP(res, req)
cookie := res.Header().Get("Set-Cookie")
// Get a new token.
res2 := httptest.NewRecorder()
req2, _ := http.NewRequest("GET", "/private", nil)
req2.Header.Set("Cookie", cookie)
m.ServeHTTP(res2, req2)
// Post using _csrf form value.
data := url.Values{}
data.Set("_csrf", res2.Body.String())
res3 := httptest.NewRecorder()
req3, _ := http.NewRequest("POST", "/private", bytes.NewBufferString(data.Encode()))
req3.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req3.Header.Set("Content-Length", strconv.Itoa(len(data.Encode())))
req3.Header.Set("Cookie", cookie)
m.ServeHTTP(res3, req3)
if res3.Code == 400 {
t.Error("Validation of _csrf form value failed")
}
// Post using X-CSRFToken HTTP header.
res4 := httptest.NewRecorder()
req4, _ := http.NewRequest("POST", "/private", nil)
req4.Header.Set("X-CSRFToken", res2.Body.String())
req4.Header.Set("Cookie", cookie)
m.ServeHTTP(res4, req4)
if res4.Code == 400 {
t.Error("Validation of X-CSRFToken failed")
}
}
示例12: TestGzip
func TestGzip(t *testing.T) {
// Empty Accept-Encoding header
req, _ := http.NewRequest(echo.GET, "/", nil)
rec := httptest.NewRecorder()
c := echo.NewContext(req, echo.NewResponse(rec), echo.New())
h := func(c *echo.Context) error {
return c.String(http.StatusOK, "test")
}
Gzip()(h)(c)
assert.Equal(t, http.StatusOK, rec.Code)
assert.Equal(t, "test", rec.Body.String())
// With Accept-Encoding header
req, _ = http.NewRequest(echo.GET, "/", nil)
req.Header.Set(echo.AcceptEncoding, "gzip")
rec = httptest.NewRecorder()
c = echo.NewContext(req, echo.NewResponse(rec), echo.New())
Gzip()(h)(c)
assert.Equal(t, http.StatusOK, rec.Code)
assert.Equal(t, "gzip", rec.Header().Get(echo.ContentEncoding))
r, err := gzip.NewReader(rec.Body)
defer r.Close()
if assert.NoError(t, err) {
buf := new(bytes.Buffer)
buf.ReadFrom(r)
assert.Equal(t, "test", buf.String())
}
}
示例13: TestAllowedOriginFunc
func TestAllowedOriginFunc(t *testing.T) {
r, _ := regexp.Compile("^http://foo")
s := ctxcors.New(
ctxcors.WithLogger(log.NewBlackHole()),
ctxcors.WithAllowOriginFunc(func(o string) bool {
return r.MatchString(o)
}),
)
req, _ := http.NewRequest("GET", "http://example.com/foo", nil)
res := httptest.NewRecorder()
req.Header.Set("Origin", "http://foobar.com")
s.WithCORS()(testHandler).ServeHTTPContext(context.Background(), res, req)
assertHeaders(t, res.Header(), map[string]string{
"Access-Control-Allow-Origin": "http://foobar.com",
})
res = httptest.NewRecorder()
req.Header.Set("Origin", "http://barfoo.com")
s.WithCORS()(testHandler).ServeHTTPContext(context.Background(), res, req)
assertHeaders(t, res.Header(), map[string]string{
"Access-Control-Allow-Origin": "",
})
}
示例14: TestRenderer
func TestRenderer(t *testing.T) {
//t.SkipNow()
r := RenderFunc(func(v interface{}, err error, w http.ResponseWriter, r *Request) error {
fmt.Fprintln(w, "testung")
return nil
}, "text/plain")
assert.EqualValues(t, r.ContentTypes(), []string{"text/plain"})
out := httptest.NewRecorder()
err := r.Render(nil, nil, out, nil)
if err != nil {
t.Error(err)
}
out.Flush()
assert.Equal(t, "testung\n", out.Body.String())
// test json renderer
jr := JSONRenderer{}
out = httptest.NewRecorder()
hr, _ := http.NewRequest("GET", "http://foo.bar?callback=foo", nil)
req := NewRequest(hr)
req.ParseForm()
assert.NoError(t, jr.Render("ello", nil, out, req))
assert.Equal(t, "foo(\"ello\");\n", out.Body.String())
out = httptest.NewRecorder()
writeError(out, "watwat")
assert.Equal(t, "watwat\n", out.Body.String())
}
示例15: TestSkipRedirect
func TestSkipRedirect(t *testing.T) {
router := New()
router.RedirectTrailingSlash = false
router.RedirectCleanPath = false
router.GET("/slash/", simpleHandler)
router.GET("/noslash", simpleHandler)
w := httptest.NewRecorder()
r, _ := newRequest("GET", "/slash", nil)
router.ServeHTTP(w, r)
if w.Code != http.StatusNotFound {
t.Errorf("/slash expected code 404, saw %d", w.Code)
}
r, _ = newRequest("GET", "/noslash/", nil)
w = httptest.NewRecorder()
router.ServeHTTP(w, r)
if w.Code != http.StatusNotFound {
t.Errorf("/noslash/ expected code 404, saw %d", w.Code)
}
r, _ = newRequest("GET", "//noslash", nil)
w = httptest.NewRecorder()
router.ServeHTTP(w, r)
if w.Code != http.StatusNotFound {
t.Errorf("//noslash expected code 404, saw %d", w.Code)
}
}