コード例 #1
0
ファイル: shortcut_test.go プロジェクト: crewjam/saml
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": "******"}`+"\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
0
// 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
0
ファイル: csrf_test.go プロジェクト: macaron-contrib/csrf
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
0
ファイル: main_test.go プロジェクト: yosukesuzuki/t2tapp
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)
	}
}
コード例 #5
0
ファイル: handler_test.go プロジェクト: quixoten/vault
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
0
ファイル: router_test.go プロジェクト: ksarch-saas/cc
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
0
ファイル: api_test.go プロジェクト: Workiva/go-rest
// 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
0
ファイル: csrf_test.go プロジェクト: rverton/csrf
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
0
ファイル: oauth2_test.go プロジェクト: cyberwolf88/oauth2
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
0
ファイル: csrf_test.go プロジェクト: rverton/csrf
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
0
ファイル: csrf_test.go プロジェクト: rverton/csrf
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
0
ファイル: compress_test.go プロジェクト: orktes/captainhub
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
0
ファイル: cors_test.go プロジェクト: joao-parana/csfw
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
0
ファイル: vertex_test.go プロジェクト: sguzwf/vertex
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
0
ファイル: router_test.go プロジェクト: coralproject/xenia
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)
	}
}
コード例 #16
0
ファイル: gzip_test.go プロジェクト: bsm/gziphandler
func TestGzipHandler(t *testing.T) {
	testBody := "aaabbbccc"

	// This just exists to provide something for GzipHandler to wrap.
	handler := newTestHandler(testBody)

	// requests without accept-encoding are passed along as-is

	req1, _ := http.NewRequest("GET", "/whatever", nil)
	res1 := httptest.NewRecorder()
	handler.ServeHTTP(res1, req1)

	assert.Equal(t, 200, res1.Code)
	assert.Equal(t, "", res1.Header().Get("Content-Encoding"))
	assert.Equal(t, "Accept-Encoding", res1.Header().Get("Vary"))
	assert.Equal(t, testBody, res1.Body.String())

	// but requests with accept-encoding:gzip are compressed if possible

	req2, _ := http.NewRequest("GET", "/whatever", nil)
	req2.Header.Set("Accept-Encoding", "gzip")
	res2 := httptest.NewRecorder()
	handler.ServeHTTP(res2, req2)

	assert.Equal(t, 200, res2.Code)
	assert.Equal(t, "gzip", res2.Header().Get("Content-Encoding"))
	assert.Equal(t, "Accept-Encoding", res2.Header().Get("Vary"))
	assert.Equal(t, gzipStr(testBody), res2.Body.Bytes())
}
コード例 #17
0
func TestSnapshot_BadMethods(t *testing.T) {
	httpTest(t, func(srv *HTTPServer) {
		body := bytes.NewBuffer(nil)
		req, err := http.NewRequest("POST", "/v1/snapshot", body)
		if err != nil {
			t.Fatalf("err: %v", err)
		}

		resp := httptest.NewRecorder()
		_, err = srv.Snapshot(resp, req)
		if err != nil {
			t.Fatalf("err: %v", err)
		}
		if resp.Code != 405 {
			t.Fatalf("bad code: %d", resp.Code)
		}
	})

	httpTest(t, func(srv *HTTPServer) {
		body := bytes.NewBuffer(nil)
		req, err := http.NewRequest("DELETE", "/v1/snapshot", body)
		if err != nil {
			t.Fatalf("err: %v", err)
		}

		resp := httptest.NewRecorder()
		_, err = srv.Snapshot(resp, req)
		if err != nil {
			t.Fatalf("err: %v", err)
		}
		if resp.Code != 405 {
			t.Fatalf("bad code: %d", resp.Code)
		}
	})
}
コード例 #18
0
ファイル: session_test.go プロジェクト: scozss/session
func Test_Flash(t *testing.T) {
	Convey("Test flash", t, func() {
		m := macaron.New()
		m.Use(Sessioner())
		m.Get("/set", func(f *Flash) string {
			f.Success("success")
			f.Error("error")
			f.Warning("warning")
			f.Info("info")
			return ""
		})
		m.Get("/get", func() {})

		resp := httptest.NewRecorder()
		req, err := http.NewRequest("GET", "/set", nil)
		So(err, ShouldBeNil)
		m.ServeHTTP(resp, req)

		resp = httptest.NewRecorder()
		req, err = http.NewRequest("GET", "/get", nil)
		So(err, ShouldBeNil)
		req.Header.Set("Cookie", "macaron_flash=error%3Derror%26info%3Dinfo%26success%3Dsuccess%26warning%3Dwarning; Path=/")
		m.ServeHTTP(resp, req)
	})
}
コード例 #19
0
ファイル: routes_test.go プロジェクト: rlizana/routes
// TestFilterParam tests the ability to apply middleware
// function to filter all routes with specified parameter
// in the REST url
func TestFilterParam(t *testing.T) {

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

	// first test that the param filter does not trigger
	handler := new(RouteMux)
	handler.Get("/", HandlerOk)
	handler.Get("/:id", HandlerOk)
	handler.FilterParam("id", FilterId)
	handler.ServeHTTP(w, r)

	if w.Code != http.StatusOK {
		t.Errorf("Code set to [%v]; want [%v]", w.Code, http.StatusOK)
	}

	// now test the param filter does trigger
	r, _ = http.NewRequest("GET", "/admin", nil)
	w = httptest.NewRecorder()
	handler.ServeHTTP(w, r)

	if w.Code != http.StatusUnauthorized {
		t.Errorf("Did not apply Param Filter. Code set to [%v]; want [%v]", w.Code, http.StatusUnauthorized)
	}

}
コード例 #20
0
ファイル: basic_test.go プロジェクト: vastbinderj/dmv
func Test_BasicAuth(t *testing.T) {
	res := httptest.NewRecorder()
	auth := "Basic " + base64.StdEncoding.EncodeToString([]byte("gopher:golf"))
	m := martini.Classic()
	m.Get("/protected", AuthBasic(), func(w http.ResponseWriter, req *http.Request, b *Basic) {
		fmt.Fprintf(w, "hi %s %s", b.Username, b.Password)
	})
	r, _ := http.NewRequest("GET", "/protected", nil)
	m.ServeHTTP(res, r)
	if res.Code != 401 {
		t.Error("Response not 401")
	}
	if strings.Contains(res.Body.String(), "hi") {
		t.Error("Auth block failed")
	}
	res = httptest.NewRecorder()
	r.Header.Set("Authorization", auth)
	m.ServeHTTP(res, r)
	if res.Code == 401 {
		t.Error("Response is 401")
	}
	if res.Body.String() != "hi gopher golf" {
		t.Error("Auth failed, got: ", res.Body.String())
	}
}
コード例 #21
0
ファイル: routing_test.go プロジェクト: mssola/todo
func TestUserLogged(t *testing.T) {
	initTestDB()
	defer closeTestDB()

	req, err := http.NewRequest("GET", "/", nil)
	if err != nil {
		t.Fatalf("Request was not successful: %v", err)
	}

	if val := userLogged(req, nil); val {
		t.Fatalf("Expected to be false: %v", val)
	}

	w := httptest.NewRecorder()
	lib.SetCookie(w, req, "userId", "1")

	if val := userLogged(req, nil); val {
		t.Fatalf("Expected to be false: %v", val)
	}

	u := &app.User{ID: uuid.Generate().String(), Name: "user", PasswordHash: "1234"}
	app.Db.Insert(u)

	var user app.User
	if err := app.Db.SelectOne(&user, "select * from users"); err != nil {
		t.Fatalf("Expected to be nil: %v", err)
	}

	w = httptest.NewRecorder()
	lib.SetCookie(w, req, "userId", user.ID)

	if val := userLogged(req, nil); !val {
		t.Fatalf("Expected to be true: %v", val)
	}
}
コード例 #22
0
ファイル: compress_test.go プロジェクト: hiproz/vodka
func TestGzip(t *testing.T) {
	req, _ := http.NewRequest(vodka.GET, "/", nil)
	rec := httptest.NewRecorder()
	c := vodka.NewContext(req, vodka.NewResponse(rec), vodka.New())
	h := func(c *vodka.Context) error {
		c.Response().Write([]byte("test")) // For Content-Type sniffing
		return nil
	}

	// Skip if no Accept-Encoding header
	Gzip()(h)(c)
	assert.Equal(t, http.StatusOK, rec.Code)
	assert.Equal(t, "test", rec.Body.String())

	req, _ = http.NewRequest(vodka.GET, "/", nil)
	req.Header.Set(vodka.AcceptEncoding, "gzip")
	rec = httptest.NewRecorder()
	c = vodka.NewContext(req, vodka.NewResponse(rec), vodka.New())

	// Gzip
	Gzip()(h)(c)
	assert.Equal(t, http.StatusOK, rec.Code)
	assert.Equal(t, "gzip", rec.Header().Get(vodka.ContentEncoding))
	assert.Contains(t, rec.Header().Get(vodka.ContentType), vodka.TextPlain)
	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())
	}
}
コード例 #23
0
ファイル: daemon_test.go プロジェクト: niemeyer/snapd
func (s *daemonSuite) TestCommandMethodDispatch(c *check.C) {
	cmd := &Command{d: newTestDaemon(c)}
	mck := &mockHandler{cmd: cmd}
	rf := mkRF(c, cmd, mck)
	cmd.GET = rf
	cmd.PUT = rf
	cmd.POST = rf
	cmd.DELETE = rf

	for _, method := range []string{"GET", "POST", "PUT", "DELETE"} {
		req, err := http.NewRequest(method, "", nil)
		c.Assert(err, check.IsNil)

		rec := httptest.NewRecorder()
		cmd.ServeHTTP(rec, req)
		c.Check(rec.Code, check.Equals, http.StatusUnauthorized, check.Commentf(method))

		rec = httptest.NewRecorder()
		req.RemoteAddr = "uid=0;" + req.RemoteAddr

		cmd.ServeHTTP(rec, req)
		c.Check(mck.lastMethod, check.Equals, method)
		c.Check(rec.Code, check.Equals, http.StatusOK)
	}

	req, err := http.NewRequest("POTATO", "", nil)
	c.Assert(err, check.IsNil)
	req.RemoteAddr = "uid=0;" + req.RemoteAddr

	rec := httptest.NewRecorder()
	cmd.ServeHTTP(rec, req)
	c.Check(rec.Code, check.Equals, http.StatusMethodNotAllowed)
}
コード例 #24
0
ファイル: pool_test.go プロジェクト: pedrosnk/tsuru
func (s *S) TestAddPool(c *check.C) {
	b := bytes.NewBufferString("name=pool1")
	req, err := http.NewRequest("POST", "/pools", b)
	c.Assert(err, check.IsNil)
	req.Header.Set("Authorization", "bearer "+s.token.GetValue())
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	rec := httptest.NewRecorder()
	defer provision.RemovePool("pool1")
	m := RunServer(true)
	m.ServeHTTP(rec, req)
	c.Assert(rec.Code, check.Equals, http.StatusCreated)
	c.Assert(err, check.IsNil)
	pools, err := provision.ListPools(bson.M{"_id": "pool1"})
	c.Assert(err, check.IsNil)
	c.Assert(pools, check.HasLen, 1)
	b = bytes.NewBufferString("name=pool2&public=true")
	req, err = http.NewRequest("POST", "/pools", b)
	c.Assert(err, check.IsNil)
	req.Header.Set("Authorization", "bearer "+s.token.GetValue())
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	rec = httptest.NewRecorder()
	defer provision.RemovePool("pool2")
	m.ServeHTTP(rec, req)
	c.Assert(rec.Code, check.Equals, http.StatusCreated)
	pools, err = provision.ListPools(bson.M{"_id": "pool2"})
	c.Assert(err, check.IsNil)
	c.Assert(pools[0].Public, check.Equals, true)
}
コード例 #25
0
ファイル: mux_test.go プロジェクト: FihlaTV/bridge-server
func TestIfItWorks(t *testing.T) {
	t.Parallel()

	m := New()
	ch := make(chan string, 1)

	m.Get("/hello/:name", func(c C, w http.ResponseWriter, r *http.Request) {
		greeting := "Hello "
		if c.Env != nil {
			if g, ok := c.Env["greeting"]; ok {
				greeting = g.(string)
			}
		}
		ch <- greeting + c.URLParams["name"]
	})

	r, _ := http.NewRequest("GET", "/hello/carl", nil)
	m.ServeHTTP(httptest.NewRecorder(), r)
	out := <-ch
	if out != "Hello carl" {
		t.Errorf(`Unexpected response %q, expected "Hello carl"`, out)
	}

	r, _ = http.NewRequest("GET", "/hello/bob", nil)
	env := map[interface{}]interface{}{"greeting": "Yo "}
	m.ServeHTTPC(C{Env: env}, httptest.NewRecorder(), r)
	out = <-ch
	if out != "Yo bob" {
		t.Errorf(`Unexpected response %q, expected "Yo bob"`, out)
	}
}
コード例 #26
0
func Test_LedisCacher(t *testing.T) {
	Convey("Test ledis cache adapter", t, func() {
		opt := cache.Options{
			Adapter:       "ledis",
			AdapterConfig: "data_dir=./tmp.db",
			Interval:      1,
		}

		Convey("Basic operations", func() {
			t := tango.New()
			t.Use(cache.New(opt))

			t.Get("/", new(CacheAction))

			resp := httptest.NewRecorder()
			req, err := http.NewRequest("GET", "/", nil)
			So(err, ShouldBeNil)
			t.ServeHTTP(resp, req)

			t.Get("/id", new(Cache2Action))

			resp = httptest.NewRecorder()
			req, err = http.NewRequest("GET", "/id", nil)
			So(err, ShouldBeNil)
			t.ServeHTTP(resp, req)
		})
	})
}
コード例 #27
0
// TestRouterFilterParam tests the Parameter filter, and ensures the
// filter is only executed when the specified Parameter exists.
func TestRouterFilterParam(t *testing.T) {
	// in the first test scenario, the Parameter filter should not
	// be triggered because the "codename" variab does not exist
	r, _ := http.NewRequest("GET", "/neo", nil)
	w := httptest.NewRecorder()

	mux := New()
	mux.Filter(HandlerSetVar)
	mux.FilterParam("codename", HandlerErr)
	mux.Get("/:nickname", 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, and should
	// halt the request
	w = httptest.NewRecorder()

	mux = New()
	mux.Filter(HandlerSetVar)
	mux.FilterParam("codename", HandlerErr)
	mux.Get("/:codename", 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)
	}
}
コード例 #28
0
ファイル: router_test.go プロジェクト: coralproject/xenia
func TestPanic(t *testing.T) {

	router := New()
	router.PanicHandler = SimplePanicHandler
	router.GET("/abc", panicHandler)
	r, _ := newRequest("GET", "/abc", nil)
	w := httptest.NewRecorder()

	router.ServeHTTP(w, r)

	if w.Code != http.StatusInternalServerError {
		t.Errorf("Expected code %d from default panic handler, saw %d",
			http.StatusInternalServerError, w.Code)
	}

	sawPanic := false
	router.PanicHandler = func(w http.ResponseWriter, r *http.Request, err interface{}) {
		sawPanic = true
	}

	router.ServeHTTP(w, r)
	if !sawPanic {
		t.Errorf("Custom panic handler was not called")
	}

	// Assume this does the right thing. Just a sanity test.
	router.PanicHandler = ShowErrorsPanicHandler
	w = httptest.NewRecorder()
	router.ServeHTTP(w, r)
	if w.Code != http.StatusInternalServerError {
		t.Errorf("Expected code %d from ShowErrorsPanicHandler, saw %d",
			http.StatusInternalServerError, w.Code)
	}
}
コード例 #29
0
ファイル: server_test.go プロジェクト: jgatkinsn/os
func TestPrepareMultiFailures(t *testing.T) {
	server := DockerServer{multiFailures: []map[string]string{}}
	server.buildMuxer()
	errorID := "multi error"
	server.PrepareMultiFailures(errorID, "containers/json")
	server.PrepareMultiFailures(errorID, "containers/json")
	recorder := httptest.NewRecorder()
	request, _ := http.NewRequest("GET", "/containers/json?all=1", nil)
	server.ServeHTTP(recorder, request)
	if recorder.Code != http.StatusBadRequest {
		t.Errorf("PrepareFailure: wrong status. Want %d. Got %d.", http.StatusBadRequest, recorder.Code)
	}
	if recorder.Body.String() != errorID+"\n" {
		t.Errorf("PrepareFailure: wrong message. Want %s. Got %s.", errorID, recorder.Body.String())
	}
	recorder = httptest.NewRecorder()
	request, _ = http.NewRequest("GET", "/containers/json?all=1", nil)
	server.ServeHTTP(recorder, request)
	if recorder.Code != http.StatusBadRequest {
		t.Errorf("PrepareFailure: wrong status. Want %d. Got %d.", http.StatusBadRequest, recorder.Code)
	}
	if recorder.Body.String() != errorID+"\n" {
		t.Errorf("PrepareFailure: wrong message. Want %s. Got %s.", errorID, recorder.Body.String())
	}
	recorder = httptest.NewRecorder()
	request, _ = http.NewRequest("GET", "/containers/json?all=1", nil)
	server.ServeHTTP(recorder, request)
	if recorder.Code != http.StatusOK {
		t.Errorf("PrepareFailure: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code)
	}
	if recorder.Body.String() == errorID+"\n" {
		t.Errorf("PrepareFailure: wrong message. Want %s. Got %s.", errorID, recorder.Body.String())
	}
}
コード例 #30
0
ファイル: rest_test.go プロジェクト: homburg/adhocrest
func TestPostBadData(t *testing.T) {
	handler := NewHandler("")

	req, _ := http.NewRequest("POST", "/", strings.NewReader("[]"))
	w := httptest.NewRecorder()
	handler.ServeHTTP(w, req)

	if http.StatusInternalServerError != w.Code {
		t.Errorf(
			"Expected internal server error on non-\"dict\" post, got response\n%s",
			w.Body.String(),
		)
	}

	req, _ = http.NewRequest("POST", "/", strings.NewReader("500"))
	w = httptest.NewRecorder()
	handler.ServeHTTP(w, req)

	if http.StatusInternalServerError != w.Code {
		t.Errorf(
			"Expected internal server error on non-\"dict\" post, got response\n%s",
			w.Body.String(),
		)
	}

	req, _ = http.NewRequest("POST", "/", strings.NewReader(`{"from":"reader"}`))
	w = httptest.NewRecorder()
	handler.ServeHTTP(w, req)

	if http.StatusCreated != w.Code {
		t.Errorf("Expected %d on valid \"dict\" data, got %d", http.StatusCreated, w.Code)
	}
}