コード例 #1
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())
	}
}
コード例 #2
0
ファイル: vodka_test.go プロジェクト: hiproz/vodka
func TestVodkaWebSocket(t *testing.T) {
	fmt.Println("TestVodkaWebSocket start")
	e := New()
	e.WebSocket("/ws", func(c *Context) error {
		fmt.Println("Got WebSocket Request!")
		c.socket.Write([]byte("test"))
		return nil
	})
	srv := httptest.NewServer(e)
	defer srv.Close()
	addr := srv.Listener.Addr().String()
	origin := "http://localhost"
	url := fmt.Sprintf("ws://%s/ws", addr)
	ws, err := websocket.Dial(url, "", origin)

	if assert.NoError(t, err) {
		ws.Write([]byte("test"))
		defer ws.Close()
		buf := new(bytes.Buffer)
		buf.ReadFrom(ws)
		assert.Equal(t, "test", buf.String())
		fmt.Println("Return buf.String():", buf.String())
	}

	fmt.Println("TestVodkaWebSocket end")
}
コード例 #3
0
ファイル: auth_test.go プロジェクト: hiproz/vodka
func TestBasicAuth(t *testing.T) {
	req, _ := http.NewRequest(vodka.GET, "/", nil)
	rec := httptest.NewRecorder()
	c := vodka.NewContext(req, vodka.NewResponse(rec), vodka.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(vodka.Authorization, auth)
	assert.NoError(t, ba(c))

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

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

	// Empty Authorization header
	req.Header.Set(vodka.Authorization, "")
	he = ba(c).(*vodka.HTTPError)
	assert.Equal(t, http.StatusUnauthorized, he.Code())
	assert.Equal(t, Basic+" realm=Restricted", rec.Header().Get(vodka.WWWAuthenticate))

	// Invalid Authorization header
	auth = base64.StdEncoding.EncodeToString([]byte("invalid"))
	req.Header.Set(vodka.Authorization, auth)
	he = ba(c).(*vodka.HTTPError)
	assert.Equal(t, http.StatusUnauthorized, he.Code())
	assert.Equal(t, Basic+" realm=Restricted", rec.Header().Get(vodka.WWWAuthenticate))

	// WebSocket
	c.Request().Header.Set(vodka.Upgrade, vodka.WebSocket)
	assert.NoError(t, ba(c))
}
コード例 #4
0
ファイル: response_test.go プロジェクト: hiproz/vodka
func TestResponse(t *testing.T) {
	w := httptest.NewRecorder()
	r := NewResponse(w)

	// SetWriter
	r.SetWriter(w)

	// Writer
	assert.Equal(t, w, r.Writer())

	// Header
	assert.NotNil(t, r.Header())

	// WriteHeader
	r.WriteHeader(http.StatusOK)
	assert.Equal(t, http.StatusOK, r.status)

	// Committed
	assert.True(t, r.committed)

	// Already committed
	r.WriteHeader(http.StatusTeapot)
	assert.NotEqual(t, http.StatusTeapot, r.Status())

	// Status
	r.status = http.StatusOK
	assert.Equal(t, http.StatusOK, r.Status())

	// Write
	s := "vodka"
	_, err := r.Write([]byte(s))
	assert.NoError(t, err)

	// Flush
	r.Flush()

	// Size
	assert.EqualValues(t, len(s), r.Size())

	// Committed
	assert.Equal(t, true, r.Committed())

	// Hijack
	assert.Panics(t, func() {
		r.Hijack()
	})

	// CloseNotify
	assert.Panics(t, func() {
		r.CloseNotify()
	})

	// reset
	r.reset(httptest.NewRecorder())
}
コード例 #5
0
ファイル: context_test.go プロジェクト: hiproz/vodka
func testBind(t *testing.T, c *Context, ct string) {
	c.request.Header.Set(ContentType, ct)
	u := new(user)
	err := c.Bind(u)
	if ct == "" {
		assert.Error(t, UnsupportedMediaType)
	} else if assert.NoError(t, err) {
		assert.Equal(t, "1", u.ID)
		assert.Equal(t, "Joe", u.Name)
	}
}
コード例 #6
0
ファイル: context_test.go プロジェクト: hiproz/vodka
func TestContextForm(t *testing.T) {
	f := make(url.Values)
	f.Set("name", "joe")
	f.Set("email", "*****@*****.**")

	req, err := http.NewRequest(POST, "/", strings.NewReader(f.Encode()))
	assert.NoError(t, err)
	req.Header.Add(ContentType, ApplicationForm)

	c := NewContext(req, nil, New())
	assert.Equal(t, "joe", c.Form("name"))
	assert.Equal(t, "*****@*****.**", c.Form("email"))
}
コード例 #7
0
ファイル: context_test.go プロジェクト: hiproz/vodka
func TestContextQuery(t *testing.T) {
	q := make(url.Values)
	q.Set("name", "joe")
	q.Set("email", "*****@*****.**")

	req, err := http.NewRequest(GET, "/", nil)
	assert.NoError(t, err)
	req.URL.RawQuery = q.Encode()

	c := NewContext(req, nil, New())
	assert.Equal(t, "joe", c.Query("name"))
	assert.Equal(t, "*****@*****.**", c.Query("email"))

}
コード例 #8
0
ファイル: context_test.go プロジェクト: hiproz/vodka
func TestContext(t *testing.T) {
	userJSON := `{"id":"1","name":"Joe"}`
	userXML := `<user><id>1</id><name>Joe</name></user>`

	req, _ := http.NewRequest(POST, "/", strings.NewReader(userJSON))
	rec := httptest.NewRecorder()
	c := NewContext(req, NewResponse(rec), New())

	// Request
	assert.NotNil(t, c.Request())

	// Response
	assert.NotNil(t, c.Response())

	// Socket
	assert.Nil(t, c.Socket())

	// Param by id
	c.pnames = []string{"id"}
	c.pvalues = []string{"1"}
	assert.Equal(t, "1", c.P(0))

	// Param by name
	assert.Equal(t, "1", c.Param("id"))

	// Store
	c.Set("user", "Joe")
	assert.Equal(t, "Joe", c.Get("user"))

	//------
	// Bind
	//------

	// JSON
	testBind(t, c, "application/json")

	// XML
	c.request, _ = http.NewRequest(POST, "/", strings.NewReader(userXML))
	testBind(t, c, ApplicationXML)

	// Unsupported
	testBind(t, c, "")

	//--------
	// Render
	//--------

	tpl := &Template{
		templates: template.Must(template.New("hello").Parse("Hello, {{.}}!")),
	}
	c.vodka.SetRenderer(tpl)
	err := c.Render(http.StatusOK, "hello", "Joe")
	if assert.NoError(t, err) {
		assert.Equal(t, http.StatusOK, rec.Code)
		assert.Equal(t, "Hello, Joe!", rec.Body.String())
	}

	c.vodka.renderer = nil
	err = c.Render(http.StatusOK, "hello", "Joe")
	assert.Error(t, err)

	// JSON
	rec = httptest.NewRecorder()
	c = NewContext(req, NewResponse(rec), New())
	err = c.JSON(http.StatusOK, user{"1", "Joe"})
	if assert.NoError(t, err) {
		assert.Equal(t, http.StatusOK, rec.Code)
		assert.Equal(t, ApplicationJSONCharsetUTF8, rec.Header().Get(ContentType))
		assert.Equal(t, userJSON+"\n", rec.Body.String())
	}

	// JSONP
	rec = httptest.NewRecorder()
	c = NewContext(req, NewResponse(rec), New())
	callback := "callback"
	err = c.JSONP(http.StatusOK, callback, user{"1", "Joe"})
	if assert.NoError(t, err) {
		assert.Equal(t, http.StatusOK, rec.Code)
		assert.Equal(t, ApplicationJavaScriptCharsetUTF8, rec.Header().Get(ContentType))
		assert.Equal(t, callback+"("+userJSON+"\n);", rec.Body.String())
	}

	// XML
	rec = httptest.NewRecorder()
	c = NewContext(req, NewResponse(rec), New())
	err = c.XML(http.StatusOK, user{"1", "Joe"})
	if assert.NoError(t, err) {
		assert.Equal(t, http.StatusOK, rec.Code)
		assert.Equal(t, ApplicationXMLCharsetUTF8, rec.Header().Get(ContentType))
		assert.Equal(t, xml.Header, xml.Header, rec.Body.String())
	}

	// String
	rec = httptest.NewRecorder()
	c = NewContext(req, NewResponse(rec), New())
	err = c.String(http.StatusOK, "Hello, World!")
	if assert.NoError(t, err) {
		assert.Equal(t, http.StatusOK, rec.Code)
		assert.Equal(t, TextPlain, rec.Header().Get(ContentType))
		assert.Equal(t, "Hello, World!", rec.Body.String())
	}

	// HTML
	rec = httptest.NewRecorder()
	c = NewContext(req, NewResponse(rec), New())
	err = c.HTML(http.StatusOK, "Hello, <strong>World!</strong>")
	if assert.NoError(t, err) {
		assert.Equal(t, http.StatusOK, rec.Code)
		assert.Equal(t, TextHTMLCharsetUTF8, rec.Header().Get(ContentType))
		assert.Equal(t, "Hello, <strong>World!</strong>", rec.Body.String())
	}

	// File
	rec = httptest.NewRecorder()
	c = NewContext(req, NewResponse(rec), New())
	err = c.File("test/fixture/walle.png", false)
	if assert.NoError(t, err) {
		assert.Equal(t, http.StatusOK, rec.Code)
		assert.Equal(t, 219885, rec.Body.Len())
	}

	// File as attachment
	rec = httptest.NewRecorder()
	c = NewContext(req, NewResponse(rec), New())
	err = c.File("test/fixture/walle.png", true)
	if assert.NoError(t, err) {
		assert.Equal(t, http.StatusOK, rec.Code)
		assert.Equal(t, rec.Header().Get(ContentDisposition), "attachment; filename=walle.png")
		assert.Equal(t, 219885, rec.Body.Len())
	}

	// Status
	rec = httptest.NewRecorder()
	c = NewContext(req, NewResponse(rec), New())
	c.Status(http.StatusOK)
	assert.Equal(t, http.StatusOK, c.response.status)

	// Redirect
	rec = httptest.NewRecorder()
	c = NewContext(req, NewResponse(rec), New())
	assert.Equal(t, nil, c.Redirect(http.StatusMovedPermanently, "http://github.com/insionng/vodka"))

	// Error
	rec = httptest.NewRecorder()
	c = NewContext(req, NewResponse(rec), New())
	c.Error(errors.New("error"))
	assert.Equal(t, http.StatusInternalServerError, c.response.status)

	// reset
	c.reset(req, NewResponse(httptest.NewRecorder()), New())
}