Exemple #1
0
func TestAddTrailingSlash(t *testing.T) {
	e := echo.New()
	req := test.NewRequest(echo.GET, "/add-slash", nil)
	rec := test.NewResponseRecorder()
	c := e.NewContext(req, rec)
	h := AddTrailingSlash()(func(c echo.Context) error {
		return nil
	})
	h(c)
	assert.Equal(t, "/add-slash/", req.URL().Path())
	assert.Equal(t, "/add-slash/", req.URI())

	// With config
	req = test.NewRequest(echo.GET, "/add-slash?key=value", nil)
	rec = test.NewResponseRecorder()
	c = e.NewContext(req, rec)
	h = AddTrailingSlashWithConfig(TrailingSlashConfig{
		RedirectCode: http.StatusMovedPermanently,
	})(func(c echo.Context) error {
		return nil
	})
	h(c)
	assert.Equal(t, http.StatusMovedPermanently, rec.Status())
	assert.Equal(t, "/add-slash/?key=value", rec.Header().Get(echo.HeaderLocation))
}
Exemple #2
0
func TestCORS(t *testing.T) {
	e := echo.New()
	req := test.NewRequest(echo.GET, "/", nil)
	rec := test.NewResponseRecorder()
	c := e.NewContext(req, rec)
	cors := CORSWithConfig(CORSConfig{
		AllowCredentials: true,
	})
	h := cors(func(c echo.Context) error {
		return c.String(http.StatusOK, "test")
	})

	// No origin header
	h(c)
	assert.Equal(t, "", rec.Header().Get(echo.HeaderAccessControlAllowOrigin))

	// Empty origin header
	req = test.NewRequest(echo.GET, "/", nil)
	rec = test.NewResponseRecorder()
	c = e.NewContext(req, rec)
	req.Header().Set(echo.HeaderOrigin, "")
	h(c)
	assert.Equal(t, "*", rec.Header().Get(echo.HeaderAccessControlAllowOrigin))

	// Wildcard origin
	req = test.NewRequest(echo.GET, "/", nil)
	rec = test.NewResponseRecorder()
	c = e.NewContext(req, rec)
	req.Header().Set(echo.HeaderOrigin, "localhost")
	h(c)
	assert.Equal(t, "*", rec.Header().Get(echo.HeaderAccessControlAllowOrigin))

	// Simple request
	req = test.NewRequest(echo.GET, "/", nil)
	rec = test.NewResponseRecorder()
	c = e.NewContext(req, rec)
	req.Header().Set(echo.HeaderOrigin, "localhost")
	cors = CORSWithConfig(CORSConfig{
		AllowOrigins:     []string{"localhost"},
		AllowCredentials: true,
		MaxAge:           3600,
	})
	h = cors(func(c echo.Context) error {
		return c.String(http.StatusOK, "test")
	})
	h(c)
	assert.Equal(t, "localhost", rec.Header().Get(echo.HeaderAccessControlAllowOrigin))

	// Preflight request
	req = test.NewRequest(echo.OPTIONS, "/", nil)
	rec = test.NewResponseRecorder()
	c = e.NewContext(req, rec)
	req.Header().Set(echo.HeaderOrigin, "localhost")
	req.Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSON)
	h(c)
	assert.Equal(t, "localhost", rec.Header().Get(echo.HeaderAccessControlAllowOrigin))
	assert.NotEmpty(t, rec.Header().Get(echo.HeaderAccessControlAllowMethods))
	assert.Equal(t, "true", rec.Header().Get(echo.HeaderAccessControlAllowCredentials))
	assert.Equal(t, "3600", rec.Header().Get(echo.HeaderAccessControlMaxAge))
}
Exemple #3
0
func TestGzip(t *testing.T) {
	e := echo.New()
	req := test.NewRequest(echo.GET, "/", nil)
	rec := test.NewResponseRecorder()
	c := e.NewContext(req, rec)

	// Skip if no Accept-Encoding header
	h := Gzip()(func(c echo.Context) error {
		c.Response().Write([]byte("test")) // For Content-Type sniffing
		return nil
	})
	h(c)
	assert.Equal(t, "test", rec.Body.String())

	req = test.NewRequest(echo.GET, "/", nil)
	req.Header().Set(echo.HeaderAcceptEncoding, "gzip")
	rec = test.NewResponseRecorder()
	c = e.NewContext(req, rec)

	// Gzip
	h(c)
	assert.Equal(t, "gzip", rec.Header().Get(echo.HeaderContentEncoding))
	assert.Contains(t, rec.Header().Get(echo.HeaderContentType), echo.MIMETextPlain)
	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())
	}
}
Exemple #4
0
func TestContextServeContent(t *testing.T) {
	e := New()
	req := test.NewRequest(GET, "/", nil)
	rec := test.NewResponseRecorder()
	c := e.NewContext(req, rec)

	fs := http.Dir("_fixture/images")
	f, err := fs.Open("walle.png")
	if assert.NoError(t, err) {
		fi, err := f.Stat()
		if assert.NoError(t, err) {
			// Not cached
			if assert.NoError(t, c.ServeContent(f, fi.Name(), fi.ModTime())) {
				assert.Equal(t, http.StatusOK, rec.Status())
			}

			// Cached
			rec = test.NewResponseRecorder()
			c = e.NewContext(req, rec)
			req.Header().Set(HeaderIfModifiedSince, fi.ModTime().UTC().Format(http.TimeFormat))
			if assert.NoError(t, c.ServeContent(f, fi.Name(), fi.ModTime())) {
				assert.Equal(t, http.StatusNotModified, rec.Status())
			}
		}
	}
}
Exemple #5
0
func TestSecure(t *testing.T) {
	e := echo.New()
	req := test.NewRequest(echo.GET, "/", nil)
	rec := test.NewResponseRecorder()
	c := e.NewContext(req, rec)
	h := func(c echo.Context) error {
		return c.String(http.StatusOK, "test")
	}

	// Default
	Secure()(h)(c)
	assert.Equal(t, "1; mode=block", rec.Header().Get(echo.HeaderXXSSProtection))
	assert.Equal(t, "nosniff", rec.Header().Get(echo.HeaderXContentTypeOptions))
	assert.Equal(t, "SAMEORIGIN", rec.Header().Get(echo.HeaderXFrameOptions))
	assert.Equal(t, "", rec.Header().Get(echo.HeaderStrictTransportSecurity))
	assert.Equal(t, "", rec.Header().Get(echo.HeaderContentSecurityPolicy))

	// Custom
	req.Header().Set(echo.HeaderXForwardedProto, "https")
	rec = test.NewResponseRecorder()
	c = e.NewContext(req, rec)
	SecureWithConfig(SecureConfig{
		XSSProtection:         "",
		ContentTypeNosniff:    "",
		XFrameOptions:         "",
		HSTSMaxAge:            3600,
		ContentSecurityPolicy: "default-src 'self'",
	})(h)(c)
	assert.Equal(t, "", rec.Header().Get(echo.HeaderXXSSProtection))
	assert.Equal(t, "", rec.Header().Get(echo.HeaderXContentTypeOptions))
	assert.Equal(t, "", rec.Header().Get(echo.HeaderXFrameOptions))
	assert.Equal(t, "max-age=3600; includeSubdomains", rec.Header().Get(echo.HeaderStrictTransportSecurity))
	assert.Equal(t, "default-src 'self'", rec.Header().Get(echo.HeaderContentSecurityPolicy))
}
Exemple #6
0
func TestStatic(t *testing.T) {
	e := echo.New()
	req := test.NewRequest(echo.GET, "/", nil)
	rec := test.NewResponseRecorder()
	c := e.NewContext(req, rec)
	h := Static("../_fixture")(func(c echo.Context) error {
		return echo.ErrNotFound
	})

	// Directory
	if assert.NoError(t, h(c)) {
		assert.Contains(t, rec.Body.String(), "Echo")
	}

	// HTML5 mode
	req = test.NewRequest(echo.GET, "/client", nil)
	rec = test.NewResponseRecorder()
	c = e.NewContext(req, rec)
	static := StaticWithConfig(StaticConfig{
		Root:  "../_fixture",
		HTML5: true,
	})
	h = static(func(c echo.Context) error {
		return echo.ErrNotFound
	})
	if assert.NoError(t, h(c)) {
		assert.Equal(t, http.StatusOK, rec.Status())
	}

	// Browse
	req = test.NewRequest(echo.GET, "/", nil)
	rec = test.NewResponseRecorder()
	c = e.NewContext(req, rec)
	static = StaticWithConfig(StaticConfig{
		Root:   "../_fixture/images",
		Browse: true,
	})
	h = static(func(c echo.Context) error {
		return echo.ErrNotFound
	})
	if assert.NoError(t, h(c)) {
		assert.Contains(t, rec.Body.String(), "walle")
	}

	// Not found
	req = test.NewRequest(echo.GET, "/not-found", nil)
	rec = test.NewResponseRecorder()
	c = e.NewContext(req, rec)
	static = StaticWithConfig(StaticConfig{
		Root: "../_fixture/images",
	})
	h = static(func(c echo.Context) error {
		return echo.ErrNotFound
	})
	assert.Error(t, h(c))
}
Exemple #7
0
func TestLoggerIPAddress(t *testing.T) {
	e := echo.New()
	req := test.NewRequest(echo.GET, "/", nil)
	rec := test.NewResponseRecorder()
	c := e.NewContext(req, rec)
	buf := new(bytes.Buffer)
	e.Logger().SetOutput(buf)
	ip := "127.0.0.1"
	h := Logger()(func(c echo.Context) error {
		return c.String(http.StatusOK, "test")
	})

	// With X-Real-IP
	req.Header().Add(echo.HeaderXRealIP, ip)
	h(c)
	assert.Contains(t, ip, buf.String())

	// With X-Forwarded-For
	buf.Reset()
	req.Header().Del(echo.HeaderXRealIP)
	req.Header().Add(echo.HeaderXForwardedFor, ip)
	h(c)
	assert.Contains(t, ip, buf.String())

	buf.Reset()
	h(c)
	assert.Contains(t, ip, buf.String())
}
Exemple #8
0
func TestEchoNotFound(t *testing.T) {
	e := New()
	req := test.NewRequest(GET, "/files", nil)
	rec := test.NewResponseRecorder()
	e.ServeHTTP(req, rec)
	assert.Equal(t, http.StatusNotFound, rec.Status())
}
Exemple #9
0
func TestEcho(t *testing.T) {
	e := New()
	req := test.NewRequest(GET, "/", nil)
	rec := test.NewResponseRecorder()
	c := e.NewContext(req, rec)

	// Router
	assert.NotNil(t, e.Router())

	// Debug
	e.SetDebug(true)
	assert.True(t, e.Debug())

	// DefaultHTTPErrorHandler
	e.DefaultHTTPErrorHandler(errors.New("error"), c)
	assert.Equal(t, http.StatusInternalServerError, rec.Status())

	// Encoders
	_, err := e.Encoder("undefined")
	assert.Error(t, err)

	e.SetEncoder("custom", &testEncoder{})
	if enc, err := e.Encoder("custom"); assert.NoError(t, err) {
		encoded, _ := enc.Encode(nil)
		assert.Equal(t, []byte("encoded"), encoded)
	}
}
Exemple #10
0
func TestEchoMethodNotAllowed(t *testing.T) {
	e := New()
	e.GET("/", func(c Context) error {
		return c.String(http.StatusOK, "Echo!")
	})
	req := test.NewRequest(POST, "/", nil)
	rec := test.NewResponseRecorder()
	e.ServeHTTP(req, rec)
	assert.Equal(t, http.StatusMethodNotAllowed, rec.Status())
}
Exemple #11
0
func TestContextRedirect(t *testing.T) {
	e := New()
	req := test.NewRequest(GET, "/", nil)
	rec := test.NewResponseRecorder()
	c := e.NewContext(req, rec)
	assert.Equal(t, nil, c.Redirect(http.StatusMovedPermanently, "http://labstack.github.io/echo"))
	assert.Equal(t, http.StatusMovedPermanently, rec.Status())
	assert.Equal(t, "http://labstack.github.io/echo", rec.Header().Get(HeaderLocation))
	assert.Error(t, c.Redirect(310, "http://labstack.github.io/echo"))
}
Exemple #12
0
func TestNonWWWRedirect(t *testing.T) {
	e := echo.New()
	next := func(c echo.Context) (err error) {
		return c.NoContent(http.StatusOK)
	}
	req := test.NewRequest(echo.GET, "http://www.labstack.com", nil)
	res := test.NewResponseRecorder()
	c := e.NewContext(req, res)
	NonWWWRedirect()(next)(c)
	assert.Equal(t, http.StatusMovedPermanently, res.Status())
	assert.Equal(t, "http://labstack.com", res.Header().Get(echo.HeaderLocation))
}
Exemple #13
0
func TestBinderQueryParams(t *testing.T) {
	e := New()
	req := test.NewRequest(GET, "/?id=1&name=Jon Snow", nil)
	rec := test.NewResponseRecorder()
	c := e.NewContext(req, rec)
	u := new(user)
	err := c.Bind(u)
	if assert.NoError(t, err) {
		assert.Equal(t, 1, u.ID)
		assert.Equal(t, "Jon Snow", u.Name)
	}
}
Exemple #14
0
func TestBinderForm(t *testing.T) {
	testBinderOkay(t, strings.NewReader(userForm), MIMEApplicationForm)
	testBinderError(t, nil, MIMEApplicationForm)
	e := New()
	req := test.NewRequest(POST, "/", strings.NewReader(userForm))
	rec := test.NewResponseRecorder()
	c := e.NewContext(req, rec)
	req.Header().Set(HeaderContentType, MIMEApplicationForm)
	var obj = make([]struct{ Field string }, 0)
	err := c.Bind(&obj)
	assert.Error(t, err)
}
Exemple #15
0
func TestGzipErrorReturned(t *testing.T) {
	e := echo.New()
	e.Use(Gzip())
	e.GET("/", func(c echo.Context) error {
		return echo.NewHTTPError(http.StatusInternalServerError, "error")
	})
	req := test.NewRequest(echo.GET, "/", nil)
	rec := test.NewResponseRecorder()
	e.ServeHTTP(req, rec)
	assert.Empty(t, rec.Header().Get(echo.HeaderContentEncoding))
	assert.Equal(t, "error", rec.Body.String())
}
Exemple #16
0
func TestBodyLimit(t *testing.T) {
	e := echo.New()
	hw := []byte("Hello, World!")
	req := test.NewRequest(echo.POST, "/", bytes.NewReader(hw))
	rec := test.NewResponseRecorder()
	c := e.NewContext(req, rec)
	h := func(c echo.Context) error {
		body, err := ioutil.ReadAll(c.Request().Body())
		if err != nil {
			return err
		}
		return c.String(http.StatusOK, string(body))
	}

	// Based on content length (within limit)
	if assert.NoError(t, BodyLimit("2M")(h)(c)) {
		assert.Equal(t, http.StatusOK, rec.Status())
		assert.Equal(t, hw, rec.Body.Bytes())
	}

	// Based on content read (overlimit)
	he := BodyLimit("2B")(h)(c).(*echo.HTTPError)
	assert.Equal(t, http.StatusRequestEntityTooLarge, he.Code)

	// Based on content read (within limit)
	req = test.NewRequest(echo.POST, "/", bytes.NewReader(hw))
	rec = test.NewResponseRecorder()
	c = e.NewContext(req, rec)
	if assert.NoError(t, BodyLimit("2M")(h)(c)) {
		assert.Equal(t, http.StatusOK, rec.Status())
		assert.Equal(t, "Hello, World!", rec.Body.String())
	}

	// Based on content read (overlimit)
	req = test.NewRequest(echo.POST, "/", bytes.NewReader(hw))
	rec = test.NewResponseRecorder()
	c = e.NewContext(req, rec)
	he = BodyLimit("2B")(h)(c).(*echo.HTTPError)
	assert.Equal(t, http.StatusRequestEntityTooLarge, he.Code)
}
Exemple #17
0
func testBinderOkay(t *testing.T, r io.Reader, ctype string) {
	e := New()
	req := test.NewRequest(POST, "/", r)
	rec := test.NewResponseRecorder()
	c := e.NewContext(req, rec)
	req.Header().Set(HeaderContentType, ctype)
	u := new(user)
	err := c.Bind(u)
	if assert.NoError(t, err) {
		assert.Equal(t, 1, u.ID)
		assert.Equal(t, "Jon Snow", u.Name)
	}
}
Exemple #18
0
func TestCSRF(t *testing.T) {
	e := echo.New()
	req := test.NewRequest(echo.GET, "/", nil)
	rec := test.NewResponseRecorder()
	c := e.NewContext(req, rec)
	csrf := CSRFWithConfig(CSRFConfig{
		Secret:       []byte("secret"),
		CookiePath:   "/",
		CookieDomain: "labstack.com",
	})
	h := csrf(func(c echo.Context) error {
		return c.String(http.StatusOK, "test")
	})

	// No secret
	assert.Panics(t, func() {
		CSRF(nil)
	})

	// Generate CSRF token
	h(c)
	assert.Contains(t, rec.Header().Get(echo.HeaderSetCookie), "csrf")

	// Empty/invalid CSRF token
	req = test.NewRequest(echo.POST, "/", nil)
	rec = test.NewResponseRecorder()
	c = e.NewContext(req, rec)
	req.Header().Set(echo.HeaderXCSRFToken, "")
	he := h(c).(*echo.HTTPError)
	assert.Equal(t, http.StatusForbidden, he.Code)

	// Valid CSRF token
	salt, _ := generateSalt(8)
	token := generateCSRFToken([]byte("secret"), salt)
	req.Header().Set(echo.HeaderXCSRFToken, token)
	if assert.NoError(t, h(c)) {
		assert.Equal(t, http.StatusOK, rec.Status())
	}
}
Exemple #19
0
func TestLogger(t *testing.T) {
	// Note: Just for the test coverage, not a real test.
	e := echo.New()
	req := test.NewRequest(echo.GET, "/", nil)
	rec := test.NewResponseRecorder()
	c := e.NewContext(req, rec)
	h := Logger()(func(c echo.Context) error {
		return c.String(http.StatusOK, "test")
	})

	// Status 2xx
	h(c)

	// Status 3xx
	rec = test.NewResponseRecorder()
	c = e.NewContext(req, rec)
	h = Logger()(func(c echo.Context) error {
		return c.String(http.StatusTemporaryRedirect, "test")
	})
	h(c)

	// Status 4xx
	rec = test.NewResponseRecorder()
	c = e.NewContext(req, rec)
	h = Logger()(func(c echo.Context) error {
		return c.String(http.StatusNotFound, "test")
	})
	h(c)

	// Status 5xx with empty path
	req = test.NewRequest(echo.GET, "", nil)
	rec = test.NewResponseRecorder()
	c = e.NewContext(req, rec)
	h = Logger()(func(c echo.Context) error {
		return errors.New("error")
	})
	h(c)
}
Exemple #20
0
func TestRecover(t *testing.T) {
	e := echo.New()
	buf := new(bytes.Buffer)
	e.SetLogOutput(buf)
	rq := test.NewRequest(echo.GET, "/", nil)
	rc := test.NewResponseRecorder()
	c := e.NewContext(rq, rc)
	h := Recover()(echo.HandlerFunc(func(c echo.Context) error {
		panic("test")
	}))
	h(c)
	assert.Equal(t, http.StatusInternalServerError, rc.Status())
	assert.Contains(t, buf.String(), "PANIC RECOVER")
}
Exemple #21
0
func TestGzipNoContent(t *testing.T) {
	e := echo.New()
	req := test.NewRequest(echo.GET, "/", nil)
	rec := test.NewResponseRecorder()
	c := e.NewContext(req, rec)
	h := Gzip()(func(c echo.Context) error {
		return c.NoContent(http.StatusOK)
	})
	if assert.NoError(t, h(c)) {
		assert.Empty(t, rec.Header().Get(echo.HeaderContentEncoding))
		assert.Empty(t, rec.Header().Get(echo.HeaderContentType))
		assert.Equal(t, 0, len(rec.Body.Bytes()))
	}
}
Exemple #22
0
func TestCSRF(t *testing.T) {
	e := echo.New()
	req := test.NewRequest(echo.GET, "/", nil)
	rec := test.NewResponseRecorder()
	c := e.NewContext(req, rec)
	csrf := CSRFWithConfig(CSRFConfig{
		TokenLength: 16,
	})
	h := csrf(func(c echo.Context) error {
		return c.String(http.StatusOK, "test")
	})

	// Generate CSRF token
	h(c)
	assert.Contains(t, rec.Header().Get(echo.HeaderSetCookie), "_csrf")

	// Without CSRF cookie
	req = test.NewRequest(echo.POST, "/", nil)
	rec = test.NewResponseRecorder()
	c = e.NewContext(req, rec)
	assert.Error(t, h(c))

	// Empty/invalid CSRF token
	req = test.NewRequest(echo.POST, "/", nil)
	rec = test.NewResponseRecorder()
	c = e.NewContext(req, rec)
	req.Header().Set(echo.HeaderXCSRFToken, "")
	assert.Error(t, h(c))

	// Valid CSRF token
	token := random.String(16)
	req.Header().Set(echo.HeaderCookie, "_csrf="+token)
	req.Header().Set(echo.HeaderXCSRFToken, token)
	if assert.NoError(t, h(c)) {
		assert.Equal(t, http.StatusOK, rec.Status())
	}
}
func TestMethodOverride(t *testing.T) {
	e := echo.New()
	m := MethodOverride()
	h := func(c echo.Context) error {
		return c.String(http.StatusOK, "test")
	}

	// Override with http header
	req := test.NewRequest(echo.POST, "/", nil)
	rec := test.NewResponseRecorder()
	req.Header().Set(echo.HeaderXHTTPMethodOverride, echo.DELETE)
	c := e.NewContext(req, rec)
	m(h)(c)
	assert.Equal(t, echo.DELETE, req.Method())

	// Override with form parameter
	m = MethodOverrideWithConfig(MethodOverrideConfig{Getter: MethodFromForm("_method")})
	req = test.NewRequest(echo.POST, "/", bytes.NewReader([]byte("_method="+echo.DELETE)))
	rec = test.NewResponseRecorder()
	req.Header().Set(echo.HeaderContentType, echo.MIMEApplicationForm)
	c = e.NewContext(req, rec)
	m(h)(c)
	assert.Equal(t, echo.DELETE, req.Method())

	// Override with query paramter
	m = MethodOverrideWithConfig(MethodOverrideConfig{Getter: MethodFromQuery("_method")})
	req = test.NewRequest(echo.POST, "/?_method="+echo.DELETE, nil)
	rec = test.NewResponseRecorder()
	c = e.NewContext(req, rec)
	m(h)(c)
	assert.Equal(t, echo.DELETE, req.Method())

	// Ignore `GET`
	req = test.NewRequest(echo.GET, "/", nil)
	req.Header().Set(echo.HeaderXHTTPMethodOverride, echo.DELETE)
	assert.Equal(t, echo.GET, req.Method())
}
Exemple #24
0
func TestContextMultipartForm(t *testing.T) {
	e := New()
	buf := new(bytes.Buffer)
	mw := multipart.NewWriter(buf)
	mw.WriteField("name", "Jon Snow")
	mw.Close()
	req := test.NewRequest(POST, "/", buf)
	req.Header().Set(HeaderContentType, mw.FormDataContentType())
	rec := test.NewResponseRecorder()
	c := e.NewContext(req, rec)
	f, err := c.MultipartForm()
	if assert.NoError(t, err) {
		assert.NotNil(t, f)
	}
}
Exemple #25
0
func TestEcho(t *testing.T) {
	e := New()
	req := test.NewRequest(GET, "/", nil)
	rec := test.NewResponseRecorder()
	c := e.NewContext(req, rec)

	// Router
	assert.NotNil(t, e.Router())

	// Debug
	e.SetDebug(true)
	assert.True(t, e.debug)

	// DefaultHTTPErrorHandler
	e.DefaultHTTPErrorHandler(errors.New("error"), c)
	assert.Equal(t, http.StatusInternalServerError, rec.Status())
}
Exemple #26
0
func TestGzipNoContent(t *testing.T) {
	e := echo.New()
	rq := test.NewRequest(echo.GET, "/", nil)
	rc := test.NewResponseRecorder()
	c := e.NewContext(rq, rc)
	h := Gzip()(func(c echo.Context) error {
		return c.NoContent(http.StatusOK)
	})
	h(c)

	assert.Empty(t, rc.Header().Get(echo.HeaderContentEncoding))
	assert.Empty(t, rc.Header().Get(echo.HeaderContentType))
	b, err := ioutil.ReadAll(rc.Body)
	if assert.NoError(t, err) {
		assert.Equal(t, 0, len(b))
	}
}
Exemple #27
0
func TestJWT(t *testing.T) {
	e := echo.New()
	req := test.NewRequest(echo.GET, "/", nil)
	res := test.NewResponseRecorder()
	c := e.NewContext(req, res)
	handler := func(c echo.Context) error {
		return c.String(http.StatusOK, "test")
	}
	config := JWTConfig{}
	token := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ"

	// No signing key provided
	assert.Panics(t, func() {
		JWTWithConfig(config)
	})

	// Unexpected signing method
	config.SigningKey = []byte("secret")
	config.SigningMethod = "RS256"
	h := JWTWithConfig(config)(handler)
	he := h(c).(*echo.HTTPError)
	assert.Equal(t, http.StatusBadRequest, he.Code)

	// Invalid key
	auth := bearer + " " + token
	req.Header().Set(echo.HeaderAuthorization, auth)
	config.SigningKey = []byte("invalid-key")
	h = JWTWithConfig(config)(handler)
	he = h(c).(*echo.HTTPError)
	assert.Equal(t, http.StatusUnauthorized, he.Code)

	// Valid JWT
	h = JWT([]byte("secret"))(handler)
	if assert.NoError(t, h(c)) {
		user := c.Get("user").(*jwt.Token)
		claims := user.Claims.(jwt.MapClaims)
		assert.Equal(t, claims["name"], "John Doe")
	}

	// Invalid Authorization header
	req.Header().Set(echo.HeaderAuthorization, "invalid-auth")
	h = JWT([]byte("secret"))(handler)
	he = h(c).(*echo.HTTPError)
	assert.Equal(t, http.StatusBadRequest, he.Code)
}
Exemple #28
0
func TestContextFormFile(t *testing.T) {
	e := New()
	buf := new(bytes.Buffer)
	mr := multipart.NewWriter(buf)
	w, err := mr.CreateFormFile("file", "test")
	if assert.NoError(t, err) {
		w.Write([]byte("test"))
	}
	mr.Close()
	req := test.NewRequest(POST, "/", buf)
	req.Header().Set(HeaderContentType, mr.FormDataContentType())
	rec := test.NewResponseRecorder()
	c := e.NewContext(req, rec)
	f, err := c.FormFile("file")
	if assert.NoError(t, err) {
		assert.Equal(t, "test", f.Filename)
	}
}
Exemple #29
0
func TestContextCookie(t *testing.T) {
	e := New()
	req := test.NewRequest(GET, "/", nil)
	theme := "theme=light"
	user := "******"
	req.Header().Add(HeaderCookie, theme)
	req.Header().Add(HeaderCookie, user)
	rec := test.NewResponseRecorder()
	c := e.NewContext(req, rec).(*context)

	// Read single
	cookie, err := c.Cookie("theme")
	if assert.NoError(t, err) {
		assert.Equal(t, "theme", cookie.Name())
		assert.Equal(t, "light", cookie.Value())
	}

	// Read multiple
	for _, cookie := range c.Cookies() {
		switch cookie.Name() {
		case "theme":
			assert.Equal(t, "light", cookie.Value())
		case "user":
			assert.Equal(t, "Jon Snow", cookie.Value())
		}
	}

	// Write
	cookie = &test.Cookie{Cookie: &http.Cookie{
		Name:     "SSID",
		Value:    "Ap4PGTEq",
		Domain:   "labstack.com",
		Path:     "/",
		Expires:  time.Now(),
		Secure:   true,
		HttpOnly: true,
	}}
	c.SetCookie(cookie)
	assert.Contains(t, rec.Header().Get(HeaderSetCookie), "SSID")
	assert.Contains(t, rec.Header().Get(HeaderSetCookie), "Ap4PGTEq")
	assert.Contains(t, rec.Header().Get(HeaderSetCookie), "labstack.com")
	assert.Contains(t, rec.Header().Get(HeaderSetCookie), "Secure")
	assert.Contains(t, rec.Header().Get(HeaderSetCookie), "HttpOnly")
}
Exemple #30
0
func TestBasicAuth(t *testing.T) {
	e := echo.New()
	rq := test.NewRequest(echo.GET, "/", nil)
	rs := test.NewResponseRecorder()
	c := e.NewContext(rq, rs)
	f := func(u, p string) bool {
		if u == "joe" && p == "secret" {
			return true
		}
		return false
	}
	h := BasicAuth(f)(func(c echo.Context) error {
		return c.String(http.StatusOK, "test")
	})

	// Valid credentials
	auth := basic + " " + base64.StdEncoding.EncodeToString([]byte("joe:secret"))
	rq.Header().Set(echo.HeaderAuthorization, auth)
	assert.NoError(t, h(c))

	//---------------------
	// Invalid credentials
	//---------------------

	// Incorrect password
	auth = basic + " " + base64.StdEncoding.EncodeToString([]byte("joe:password"))
	rq.Header().Set(echo.HeaderAuthorization, auth)
	he := h(c).(*echo.HTTPError)
	assert.Equal(t, http.StatusUnauthorized, he.Code)
	assert.Equal(t, basic+" realm=Restricted", rs.Header().Get(echo.HeaderWWWAuthenticate))

	// Empty Authorization header
	rq.Header().Set(echo.HeaderAuthorization, "")
	he = h(c).(*echo.HTTPError)
	assert.Equal(t, http.StatusUnauthorized, he.Code)
	assert.Equal(t, basic+" realm=Restricted", rs.Header().Get(echo.HeaderWWWAuthenticate))

	// Invalid Authorization header
	auth = base64.StdEncoding.EncodeToString([]byte("invalid"))
	rq.Header().Set(echo.HeaderAuthorization, auth)
	he = h(c).(*echo.HTTPError)
	assert.Equal(t, http.StatusUnauthorized, he.Code)
	assert.Equal(t, basic+" realm=Restricted", rs.Header().Get(echo.HeaderWWWAuthenticate))
}