Exemplo n.º 1
2
func TestIsAjax(t *testing.T) {
	e := echo.New()
	req, err := http.NewRequest("GET", "/", nil)
	if err != nil {
		t.Error(err)
	}
	res := httptest.NewRecorder()
	ctx := echo.NewContext(req, echo.NewResponse(res), e)

	if ok := IsAjax(ctx); ok {
		t.Errorf("expected false got %v", ok)
	}

	req1, err := http.NewRequest("GET", "/", nil)
	if err != nil {
		t.Error(err)
	}
	req1.Header.Set("X-Requested-With", "XMLHttpRequest")
	res1 := httptest.NewRecorder()
	ctx1 := echo.NewContext(req1, echo.NewResponse(res1), e)

	if ok := IsAjax(ctx1); !ok {
		t.Errorf("expected true got %v", ok)
	}
}
Exemplo n.º 2
0
func TestGzip(t *testing.T) {
	req, _ := http.NewRequest(echo.GET, "/", nil)
	rec := httptest.NewRecorder()
	c := echo.NewContext(req, echo.NewResponse(rec), echo.New())
	h := func(c *echo.Context) error {
		c.Response().Write([]byte("test")) // 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(echo.GET, "/", nil)
	req.Header.Set(echo.AcceptEncoding, "gzip")
	rec = httptest.NewRecorder()
	c = echo.NewContext(req, echo.NewResponse(rec), echo.New())

	// Gzip
	Gzip()(h)(c)
	assert.Equal(t, http.StatusOK, rec.Code)
	assert.Equal(t, "gzip", rec.Header().Get(echo.ContentEncoding))
	assert.Contains(t, rec.Header().Get(echo.ContentType), echo.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())
	}
}
Exemplo n.º 3
0
func TestLogger(t *testing.T) {
	// Note: Just for the test coverage, not a real test.
	e := echo.New()
	req, _ := http.NewRequest(echo.GET, "/", nil)
	rec := httptest.NewRecorder()
	c := echo.NewContext(req, echo.NewResponse(rec), e)

	// With X-Real-IP
	req.Header.Add(echo.XRealIP, "127.0.0.1")
	h := func(c *echo.Context) error {
		return c.String(http.StatusOK, "test")
	}
	Logger()(h)(c)

	// With X-Forwarded-For
	req.Header.Del(echo.XRealIP)
	req.Header.Add(echo.XForwardedFor, "127.0.0.1")
	h = func(c *echo.Context) error {
		return c.String(http.StatusOK, "test")
	}
	Logger()(h)(c)

	// Status 2xx
	h = func(c *echo.Context) error {
		return c.String(http.StatusOK, "test")
	}
	Logger()(h)(c)

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

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

	// Status 5xx with empty path
	req, _ = http.NewRequest(echo.GET, "", nil)
	rec = httptest.NewRecorder()
	c = echo.NewContext(req, echo.NewResponse(rec), e)
	h = func(c *echo.Context) error {
		return errors.New("error")
	}
	Logger()(h)(c)
}
Exemplo n.º 4
0
func TestStripTrailingSlash(t *testing.T) {
	req, _ := http.NewRequest(echo.GET, "/users/", nil)
	rec := httptest.NewRecorder()
	c := echo.NewContext(req, echo.NewResponse(rec), echo.New())
	StripTrailingSlash()(c)
	assert.Equal(t, "/users", c.Request().URL.Path)
}
Exemplo n.º 5
0
func TestListRegions(t *testing.T) {
	for _, test := range []struct {
		p    mockProvisioner
		err  error
		code int
		body string
	}{
		{
			createProvisioner([]provisioner.Region{}),
			nil,
			200,
			"[]",
		},
		{
			createProvisioner([]provisioner.Region{{"name", "description", "country"}}),
			nil,
			200,
			"[{\"name\":\"name\",\"description\":\"description\",\"country\":\"country\"}]",
		},
	} {
		s := &yovpnServer{test.p}

		e := echo.New()
		req := mustNewRequest("GET", "/regions", nil)
		w := httptest.NewRecorder()
		c := echo.NewContext(req, echo.NewResponse(w, e), e)
		err := s.getRegions(c)

		assert.Equal(t, test.err, err)
		assert.Equal(t, test.code, w.Code)
		assert.Equal(t, test.body, w.Body.String())
	}
}
Exemplo n.º 6
0
func TestLoggerIPAddress(t *testing.T) {
	e := echo.New()
	req, _ := http.NewRequest(echo.GET, "/", nil)
	rec := httptest.NewRecorder()
	c := echo.NewContext(req, echo.NewResponse(rec, e), e)
	buf := new(bytes.Buffer)
	e.Logger().SetOutput(buf)
	ip := "127.0.0.1"
	h := func(c *echo.Context) error {
		return c.String(http.StatusOK, "test")
	}

	mw := Logger()

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

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

	// with req.RemoteAddr
	buf.Reset()
	mw(h)(c)
	assert.Contains(t, buf.String(), ip)
}
Exemplo n.º 7
0
func TestRedirectToSlash(t *testing.T) {
	req, _ := http.NewRequest(echo.GET, "/users", nil)
	rec := httptest.NewRecorder()
	c := echo.NewContext(req, echo.NewResponse(rec), echo.New())
	RedirectToSlash(RedirectToSlashOptions{Code: http.StatusTemporaryRedirect})(c)
	assert.Equal(t, http.StatusTemporaryRedirect, rec.Code)
	assert.Equal(t, "/users/", c.Response().Header().Get("Location"))
}
Exemplo n.º 8
0
func TestSleep(t *testing.T) {
	req, _ := http.NewRequest(echo.POST, "/", nil)
	rec := httptest.NewRecorder()
	c := echo.NewContext(req, echo.NewResponse(rec), echo.New())
	start := time.Now()
	Sleep(1)(c)
	duration := time.Now().Sub(start)
	assert.True(t, duration > time.Second*1)

	req, _ = http.NewRequest(echo.GET, "/", nil)
	rec = httptest.NewRecorder()
	c = echo.NewContext(req, echo.NewResponse(rec), echo.New())
	start = time.Now()
	Sleep(1)(c)
	duration = time.Now().Sub(start)
	assert.True(t, duration < 1*time.Second)
}
Exemplo n.º 9
0
func TestData(t *testing.T) {
	sampleData := []struct {
		key string
		val interface{}
	}{
		{"one", 1},
		{"two", "two"},
		{"three", "three"},
	}
	e := echo.New()
	req, err := http.NewRequest("GET", "/", nil)
	if err != nil {
		t.Error(err)
	}
	res := httptest.NewRecorder()

	// Create the context on which we will be messing with
	ctx := echo.NewContext(req, echo.NewResponse(res), e)

	//
	//	SetData
	//
	for _, v := range sampleData {
		SetData(ctx, v.key, v.val)
	}

	//
	//	GetData
	//
	data, ok := GetData(ctx).(Data)
	if !ok {
		t.Error("kaboom")
	}

	// Check the Data methods
	d := data.Get(sampleData[0].key)
	if d == nil {
		t.Errorf("expected %v got nil instead", sampleData[0].val)
	}

	data.Set("hello", "world")
	if h := data.Get("hello"); h != nil {
		if h.(string) != "world" {
			t.Errorf("expected world got %v", h)
		}
	}

	//
	//	GetLang
	//
	SetData(ctx, settings.LangDataKey, "en")

	lang := GetLang(ctx)
	if lang != "en" {
		t.Errorf("expected en got %s", lang)
	}
}
Exemplo n.º 10
0
func TestHash(t *testing.T) {
	e := echo.New()
	req, _ := http.NewRequest(echo.POST, "/", strings.NewReader("password=angryMonkey"))
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded;")
	rec := httptest.NewRecorder()
	c := echo.NewContext(req, echo.NewResponse(rec), e)
	Hash(c)
	assert.Equal(t, http.StatusOK, rec.Code)
	assert.Equal(t, "ZEHhWB65gUlzdVwtDQArEyx+KVLzp/aTaRaPlBzYRIFj6vjFdqEb0Q5B8zVKCZ0vKbZPZklJz0Fd7su2A+gf7Q==", rec.Body.String())
}
Exemplo n.º 11
0
func TestJWTAuth(t *testing.T) {
	req, _ := http.NewRequest(echo.GET, "/", nil)
	rec := httptest.NewRecorder()
	c := echo.NewContext(req, echo.NewResponse(rec), echo.New())
	key := []byte("key")
	fn := func(kid string, method jwt.SigningMethod) ([]byte, error) {
		return key, nil
	}
	ja := JWTAuth(fn)
	token := jwt.New(jwt.SigningMethodHS256)
	token.Claims["foo"] = "bar"
	token.Claims["exp"] = time.Now().Add(time.Hour * 72).Unix()
	ts, err := token.SignedString(key)
	assert.NoError(t, err)

	// Valid credentials
	auth := Bearer + " " + ts
	req.Header.Set(echo.Authorization, auth)
	assert.NoError(t, ja(c))

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

	// Expired token
	token.Claims["exp"] = time.Now().Add(-time.Second).Unix()
	ts, err = token.SignedString(key)
	assert.NoError(t, err)
	auth = Bearer + " " + ts
	req.Header.Set(echo.Authorization, auth)
	he := ja(c).(*echo.HTTPError)
	assert.Equal(t, http.StatusUnauthorized, he.Code())

	// Empty Authorization header
	req.Header.Set(echo.Authorization, "")
	he = ja(c).(*echo.HTTPError)
	assert.Equal(t, http.StatusBadRequest, he.Code())

	// Invalid Authorization header
	auth = "token"
	req.Header.Set(echo.Authorization, auth)
	he = ja(c).(*echo.HTTPError)
	assert.Equal(t, http.StatusBadRequest, he.Code())

	// Invalid scheme
	auth = "Bear token"
	req.Header.Set(echo.Authorization, auth)
	he = ja(c).(*echo.HTTPError)
	assert.Equal(t, http.StatusBadRequest, he.Code())

	// WebSocket
	c.Request().Header.Set(echo.Upgrade, echo.WebSocket)
	assert.NoError(t, ja(c))
}
Exemplo n.º 12
0
func TestRecover(t *testing.T) {
	e := echo.New()
	e.SetDebug(true)
	req, _ := http.NewRequest(echo.GET, "/", nil)
	rec := httptest.NewRecorder()
	c := echo.NewContext(req, echo.NewResponse(rec), e)
	h := func(c *echo.Context) error {
		panic("test")
	}
	Recover()(h)(c)
	assert.Equal(t, http.StatusInternalServerError, rec.Code)
	assert.Contains(t, rec.Body.String(), "panic recover")
}
Exemplo n.º 13
0
func TestShutdown(t *testing.T) {
	sigchan := make(chan os.Signal, 1)
	signal.Notify(sigchan, os.Interrupt, os.Kill)
	e := echo.New()
	req, _ := http.NewRequest(echo.POST, "/", strings.NewReader("command=shutdown"))
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded;")
	rec := httptest.NewRecorder()
	c := echo.NewContext(req, echo.NewResponse(rec), e)
	Shutdown()(c)
	s := <-sigchan
	assert.Equal(t, os.Interrupt, s)

}
Exemplo n.º 14
0
func TestLogger(t *testing.T) {
	e := echo.New()
	req, _ := http.NewRequest(echo.GET, "/", nil)
	rec := httptest.NewRecorder()
	c := echo.NewContext(req, echo.NewResponse(rec), e)
	b := &bytes.Buffer{}

	// Status 2xx
	h := func(c *echo.Context) error {
		return c.String(http.StatusOK, "test")
	}
	Logger(b)(h)(c)

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

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

	// Status 5xx with empty path
	req, _ = http.NewRequest(echo.GET, "", nil)
	rec = httptest.NewRecorder()
	c = echo.NewContext(req, echo.NewResponse(rec), e)
	h = func(c *echo.Context) error {
		return errors.New("error")
	}
	Logger(b)(h)(c)
}
Exemplo n.º 15
0
func TestLogger(t *testing.T) {
	// Note: Just for the test coverage, not a real test.
	e := echo.New()
	req, _ := http.NewRequest(echo.GET, "/", nil)
	rec := httptest.NewRecorder()
	c := echo.NewContext(req, echo.NewResponse(rec, e), e)

	// Status 2xx
	h := func(c *echo.Context) error {
		return c.String(http.StatusOK, "test")
	}
	Logger()(h)(c)

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

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

	// Status 5xx with empty path
	req, _ = http.NewRequest(echo.GET, "", nil)
	rec = httptest.NewRecorder()
	c = echo.NewContext(req, echo.NewResponse(rec, e), e)
	h = func(c *echo.Context) error {
		return errors.New("error")
	}
	Logger()(h)(c)
}
Exemplo n.º 16
0
func TestBasicAuth(t *testing.T) {
	req, _ := http.NewRequest(echo.GET, "/", nil)
	rec := httptest.NewRecorder()
	c := echo.NewContext(req, echo.NewResponse(rec), echo.New())
	fn := func(u, p string) bool {
		if u == "joe" && p == "secret" {
			return true
		}
		return false
	}
	ba := BasicAuth(fn)

	// Valid credentials
	auth := Basic + " " + base64.StdEncoding.EncodeToString([]byte("joe:secret"))
	req.Header.Set(echo.Authorization, auth)
	assert.NoError(t, ba(c))

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

	// Incorrect password
	auth = Basic + " " + base64.StdEncoding.EncodeToString([]byte("joe:password"))
	req.Header.Set(echo.Authorization, auth)
	he := ba(c).(*echo.HTTPError)
	assert.Equal(t, http.StatusUnauthorized, he.Code())

	// Empty Authorization header
	req.Header.Set(echo.Authorization, "")
	he = ba(c).(*echo.HTTPError)
	assert.Equal(t, http.StatusBadRequest, he.Code())

	// Invalid Authorization header
	auth = base64.StdEncoding.EncodeToString([]byte(" :secret"))
	req.Header.Set(echo.Authorization, auth)
	he = ba(c).(*echo.HTTPError)
	assert.Equal(t, http.StatusBadRequest, he.Code())

	// Invalid scheme
	auth = "Base " + base64.StdEncoding.EncodeToString([]byte(" :secret"))
	req.Header.Set(echo.Authorization, auth)
	he = ba(c).(*echo.HTTPError)
	assert.Equal(t, http.StatusBadRequest, he.Code())

	// WebSocket
	c.Request().Header.Set(echo.Upgrade, echo.WebSocket)
	assert.NoError(t, ba(c))
}
Exemplo n.º 17
0
func TestBlank(t *testing.T) {
	e := echo.New()
	s := &yovpnServer{}
	req := mustNewRequest("GET", "/", nil)
	w := httptest.NewRecorder()

	c := echo.NewContext(req, echo.NewResponse(w, e), e)
	err := s.blank(c)

	if err != nil {
		t.Errorf("Expected no error, but got %s", err)
	}
	if w.Code != http.StatusOK {
		t.Errorf("Expected status 200, but got %v", w.Code)
	}
	if w.Body.Len() == 0 {
		t.Error("Expected body, but got none.")
	}
}
Exemplo n.º 18
0
func TestCreate(t *testing.T) {
	vars := url.Values{
		"resume_name": {"red dragon"},
	}
	req, err := http.NewRequest("POST", "/resume/create", strings.NewReader(vars.Encode()))
	if err != nil {
		t.Errorf("creating request %v", err)
	}
	req.Header.Set(echo.ContentType, echo.ApplicationForm)
	resp := httptest.NewRecorder()
	ctx := echo.NewContext(req, echo.NewResponse(resp), ts)
	ctx.Set("User", user)

	err = Create(ctx)
	if err != nil {
		t.Error(err)
	}
	if resp.Code != http.StatusFound {
		t.Errorf("expected  %d got %d", http.StatusFound, resp.Code)
	}
}
Exemplo n.º 19
0
func BenchmarkGzip(b *testing.B) {

	b.StopTimer()
	b.ReportAllocs()

	h := func(c *echo.Context) error {
		c.Response().Write([]byte("test")) // For Content-Type sniffing
		return nil
	}
	req, _ := http.NewRequest(echo.GET, "/", nil)
	req.Header.Set(echo.AcceptEncoding, "gzip")

	b.StartTimer()

	for i := 0; i < b.N; i++ {
		rec := httptest.NewRecorder()
		c := echo.NewContext(req, echo.NewResponse(rec), echo.New())
		Gzip()(h)(c)
	}

}
Exemplo n.º 20
0
import (
	"github.com/arbrix/go-test/app"
	"github.com/arbrix/go-test/model"
	"github.com/labstack/echo"
	"net/http"
	"net/http/httptest"
	"testing"
)

var (
	user      = model.User{ID: 1, Email: "*****@*****.**", Name: "testUser"}
	a         = app.NewApp(&app.TestConfig{}, &app.TestOrm{})
	tokenizer = Token{}
	req, _    = http.NewRequest(echo.GET, "/", nil)
	rec       = httptest.NewRecorder()
	c         = echo.NewContext(req, echo.NewResponse(rec), echo.New())
	token     interface{}
)

func TestCreate(t *testing.T) {
	_, err := tokenizer.Create(c, &a, &user)
	if err != nil {
		t.Error(err)
	}
	token = c.Get("jwt")
}

func TestParse(t *testing.T) {
	c.Request().Header.Set("Authorization", "Bearer "+token.(string))
	jwtParsed, err := tokenizer.Parse(c, &a)
	if err != nil {
Exemplo n.º 21
0
// Create dummy echo.Context with request for tests
// Note: echo makes it impossible to initialize the context response :(
func dummyContext() *echo.Context {
	req, _ := http.NewRequest("POST", "http://example.com", strings.NewReader("foo"))
	rec := httptest.NewRecorder()
	return echo.NewContext(req, echo.NewResponse(rec), echo.New())
}