代码拉取完成,页面将自动刷新
package yasrpc
import (
"bytes"
"errors"
"mime/multipart"
"net/http"
"net/http/httptest"
"reflect"
"testing"
"time"
"git.yasdb.com/go/yasrpc/binding"
"git.yasdb.com/go/yasutil/assert"
)
func createMultipartRequest() *http.Request {
boundary := "--testboundary"
body := new(bytes.Buffer)
mw := multipart.NewWriter(body)
defer mw.Close()
must(mw.SetBoundary(boundary))
must(mw.WriteField("foo", "bar"))
must(mw.WriteField("bar", "10"))
must(mw.WriteField("bar", "foo2"))
must(mw.WriteField("array", "first"))
must(mw.WriteField("array", "second"))
must(mw.WriteField("id", ""))
must(mw.WriteField("time_local", "31/12/2016 14:55"))
must(mw.WriteField("time_utc", "31/12/2016 14:55"))
must(mw.WriteField("time_location", "31/12/2016 14:55"))
must(mw.WriteField("names[a]", "thinkerou"))
must(mw.WriteField("names[b]", "tianou"))
req, err := http.NewRequest("POST", "/", body)
must(err)
req.Header.Set("Content-Type", binding.MIMEMultipartPOSTForm+"; boundary="+boundary)
return req
}
func must(err error) {
if err != nil {
panic(err.Error())
}
}
// CreateTestContext returns a fresh engine and context for testing purposes
func CreateTestContext(w http.ResponseWriter) (c *Context, r *Engine) {
r = NewEngine()
c = r.allocateContext(0)
c.reset()
c.writermem.reset(w)
return
}
// CreateTestContextOnly returns a fresh context base on the engine for testing purposes
func CreateTestContextOnly(w http.ResponseWriter, r *Engine) (c *Context) {
c = r.allocateContext(r.maxParams)
c.reset()
c.writermem.reset(w)
return
}
func TestContextFormFile(t *testing.T) {
ast := assert.NewAssert(t)
buf := new(bytes.Buffer)
mw := multipart.NewWriter(buf)
w, err := mw.CreateFormFile("file", "test")
ast.Nil(err)
_, err = w.Write([]byte("test"))
ast.Nil(err)
mw.Close()
c, _ := CreateTestContext(httptest.NewRecorder())
c.Request, _ = http.NewRequest("POST", "/", buf)
c.Request.Header.Set("Content-Type", mw.FormDataContentType())
f, err := c.FormFile("file")
ast.Nil(err)
ast.Equal("test", f.Filename)
ast.Nil(c.SaveUploadedFile(f, "test"))
}
func TestContextMultipartForm(t *testing.T) {
ast := assert.NewAssert(t)
buf := new(bytes.Buffer)
mw := multipart.NewWriter(buf)
ast.Nil(mw.WriteField("foo", "bar"))
w, err := mw.CreateFormFile("file", "test")
ast.Nil(err)
_, err = w.Write([]byte("test"))
ast.Nil(err)
mw.Close()
c, _ := CreateTestContext(httptest.NewRecorder())
c.Request, _ = http.NewRequest("POST", "/", buf)
c.Request.Header.Set("Content-Type", mw.FormDataContentType())
f, err := c.MultipartForm()
ast.Nil(err)
ast.NotNil(f)
ast.Nil(c.SaveUploadedFile(f.File["file"][0], "test"))
}
func TestSaveUploadedOpenFailed(t *testing.T) {
ast := assert.NewAssert(t)
buf := new(bytes.Buffer)
mw := multipart.NewWriter(buf)
mw.Close()
c, _ := CreateTestContext(httptest.NewRecorder())
c.Request, _ = http.NewRequest("POST", "/", buf)
c.Request.Header.Set("Content-Type", mw.FormDataContentType())
f := &multipart.FileHeader{
Filename: "file",
}
ast.NotNil(c.SaveUploadedFile(f, "test"))
}
func TestSaveUploadedCreateFailed(t *testing.T) {
ast := assert.NewAssert(t)
buf := new(bytes.Buffer)
mw := multipart.NewWriter(buf)
w, err := mw.CreateFormFile("file", "test")
ast.Nil(err)
_, err = w.Write([]byte("test"))
ast.Nil(err)
mw.Close()
c, _ := CreateTestContext(httptest.NewRecorder())
c.Request, _ = http.NewRequest("POST", "/", buf)
c.Request.Header.Set("Content-Type", mw.FormDataContentType())
f, err := c.FormFile("file")
ast.Nil(err)
ast.Equal("test", f.Filename)
ast.NotNil(c.SaveUploadedFile(f, "/"))
}
func TestContextReset(t *testing.T) {
ast := assert.NewAssert(t)
router := NewEngine()
c := router.allocateContext(0)
ast.DeepEqual(c.engine, router)
c.index = 2
c.Writer = &responseWriter{ResponseWriter: httptest.NewRecorder()}
c.Params = Params{Param{}}
c.Error(errors.New("test")) //nolint: errcheck
c.Set("foo", "bar")
c.reset()
ast.False(c.IsAborted())
ast.Nil(c.Keys)
ast.Equal(len(c.Errors), 0)
ast.Equal(len(c.Errors.Errors()), 0)
ast.Equal(len(c.Errors.ByType(ErrorTypeAny)), 0)
ast.Equal(len(c.Params), 0)
ast.Equal(c.index, int8(-1))
ast.DeepEqual(c.Writer.(*responseWriter), &c.writermem)
}
func TestContextHandlers(t *testing.T) {
ast := assert.NewAssert(t)
c, _ := CreateTestContext(httptest.NewRecorder())
ast.Nil(c.handlers)
ast.Nil(c.handlers.Last())
c.handlers = HandlersChain{}
ast.NotNil(c.handlers)
ast.Nil(c.handlers.Last())
f := func(c *Context) {}
g := func(c *Context) {}
c.handlers = HandlersChain{f}
compareFunc(t, f, c.handlers.Last())
c.handlers = HandlersChain{f, g}
compareFunc(t, g, c.handlers.Last())
}
func TestContextSetGet(t *testing.T) {
ast := assert.NewAssert(t)
c, _ := CreateTestContext(httptest.NewRecorder())
c.Set("foo", "bar")
value, err := c.Get("foo")
ast.Equal("bar", value)
ast.True(err)
value, err = c.Get("foo2")
ast.Nil(value)
ast.False(err)
}
var handlerTest HandlerFunc = func(c *Context) {
}
func TestContextHandler(t *testing.T) {
ast := assert.NewAssert(t)
c, _ := CreateTestContext(httptest.NewRecorder())
c.handlers = HandlersChain{func(c *Context) {}, handlerTest}
ast.DeepEqual(reflect.ValueOf(handlerTest).Pointer(), reflect.ValueOf(c.Handler()).Pointer())
}
func TestContextQuery(t *testing.T) {
ast := assert.NewAssert(t)
c, _ := CreateTestContext(httptest.NewRecorder())
c.Request, _ = http.NewRequest("GET", "http://example.com/?foo=bar&page=10&id=", nil)
value, ok := c.GetQuery("foo")
ast.True(ok)
ast.Equal("bar", value)
ast.Equal("bar", c.DefaultQuery("foo", "none"))
ast.Equal("bar", c.Query("foo"))
value, ok = c.GetQuery("page")
ast.True(ok)
ast.Equal("10", value)
ast.Equal("10", c.DefaultQuery("page", "0"))
ast.Equal("10", c.Query("page"))
value, ok = c.GetQuery("id")
ast.True(ok)
ast.Equal(len(value), 0)
ast.Equal(len(c.DefaultQuery("id", "nada")), 0)
ast.Equal(len(c.Query("id")), 0)
value, ok = c.GetQuery("NoKey")
ast.False(ok)
ast.Equal(len(value), 0)
ast.Equal("nada", c.DefaultQuery("NoKey", "nada"))
ast.Equal(len(c.Query("NoKey")), 0)
// postform should not mess
value, ok = c.GetPostForm("page")
ast.False(ok)
ast.Equal(len(value), 0)
ast.Equal(len(c.PostForm("foo")), 0)
}
func TestContextQueryAndPostForm(t *testing.T) {
ast := assert.NewAssert(t)
c, _ := CreateTestContext(httptest.NewRecorder())
body := bytes.NewBufferString("foo=bar&page=11&both=&foo=second")
c.Request, _ = http.NewRequest("POST",
"/?both=GET&id=main&id=omit&array[]=first&array[]=second&ids[a]=hi&ids[b]=3.14", body)
c.Request.Header.Add("Content-Type", binding.MIMEPOSTForm)
ast.Equal("bar", c.DefaultPostForm("foo", "none"))
ast.Equal("bar", c.PostForm("foo"))
ast.Equal(len(c.Query("foo")), 0)
value, ok := c.GetPostForm("page")
ast.True(ok)
ast.Equal("11", value)
ast.Equal("11", c.DefaultPostForm("page", "0"))
ast.Equal("11", c.PostForm("page"))
ast.Equal(len(c.Query("page")), 0)
value, ok = c.GetPostForm("both")
ast.True(ok)
ast.Equal(len(value), 0)
ast.Equal(len(c.PostForm("both")), 0)
ast.Equal(len(c.DefaultPostForm("both", "nothing")), 0)
ast.Equal("GET", c.Query("both"))
value, ok = c.GetQuery("id")
ast.True(ok)
ast.Equal("main", value)
ast.Equal("000", c.DefaultPostForm("id", "000"))
ast.Equal("main", c.Query("id"))
ast.Equal(len(c.PostForm("id")), 0)
value, ok = c.GetQuery("NoKey")
ast.False(ok)
ast.Equal(len(value), 0)
value, ok = c.GetPostForm("NoKey")
ast.False(ok)
ast.Equal(len(value), 0)
ast.Equal("nada", c.DefaultPostForm("NoKey", "nada"))
ast.Equal("nothing", c.DefaultQuery("NoKey", "nothing"))
ast.Equal(len(c.PostForm("NoKey")), 0)
ast.Equal(len(c.Query("NoKey")), 0)
var obj struct {
Foo string `form:"foo"`
ID string `form:"id"`
Page int `form:"page"`
Both string `form:"both"`
Array []string `form:"array[]"`
}
ast.Nil(c.Bind(&obj))
ast.Equal("bar", obj.Foo)
ast.Equal("main", obj.ID)
ast.Equal(11, obj.Page)
ast.Equal(len(obj.Both), 0)
ast.DeepEqual([]string{"first", "second"}, obj.Array)
values, ok := c.GetQueryArray("array[]")
ast.True(ok)
ast.Equal("first", values[0])
ast.Equal("second", values[1])
values = c.QueryArray("array[]")
ast.Equal("first", values[0])
ast.Equal("second", values[1])
values = c.QueryArray("nokey")
ast.Equal(0, len(values))
values = c.QueryArray("both")
ast.Equal(1, len(values))
ast.Equal("GET", values[0])
dicts, ok := c.GetQueryMap("ids")
ast.True(ok)
ast.Equal("hi", dicts["a"])
ast.Equal("3.14", dicts["b"])
dicts, ok = c.GetQueryMap("nokey")
ast.False(ok)
ast.Equal(0, len(dicts))
dicts, ok = c.GetQueryMap("both")
ast.False(ok)
ast.Equal(0, len(dicts))
dicts, ok = c.GetQueryMap("array")
ast.False(ok)
ast.Equal(0, len(dicts))
dicts = c.QueryMap("ids")
ast.Equal("hi", dicts["a"])
ast.Equal("3.14", dicts["b"])
dicts = c.QueryMap("nokey")
ast.Equal(0, len(dicts))
}
func TestContextPostFormMultipart(t *testing.T) {
ast := assert.NewAssert(t)
c, _ := CreateTestContext(httptest.NewRecorder())
c.Request = createMultipartRequest()
var obj struct {
Foo string `form:"foo"`
Bar string `form:"bar"`
BarAsInt int `form:"bar"`
Array []string `form:"array"`
ID string `form:"id"`
TimeLocal time.Time `form:"time_local" time_format:"02/01/2006 15:04"`
TimeUTC time.Time `form:"time_utc" time_format:"02/01/2006 15:04" time_utc:"1"`
TimeLocation time.Time `form:"time_location" time_format:"02/01/2006 15:04" time_location:"Asia/Tokyo"`
BlankTime time.Time `form:"blank_time" time_format:"02/01/2006 15:04"`
}
ast.Nil(c.Bind(&obj))
ast.Equal("bar", obj.Foo)
ast.Equal("10", obj.Bar)
ast.Equal(10, obj.BarAsInt)
ast.DeepEqual([]string{"first", "second"}, obj.Array)
ast.Equal(len(obj.ID), 0)
ast.Equal("31/12/2016 14:55", obj.TimeLocal.Format("02/01/2006 15:04"))
ast.DeepEqual(time.Local, obj.TimeLocal.Location())
ast.Equal("31/12/2016 14:55", obj.TimeUTC.Format("02/01/2006 15:04"))
ast.DeepEqual(time.UTC, obj.TimeUTC.Location())
loc, _ := time.LoadLocation("Asia/Tokyo")
ast.Equal("31/12/2016 14:55", obj.TimeLocation.Format("02/01/2006 15:04"))
ast.DeepEqual(loc, obj.TimeLocation.Location())
ast.True(obj.BlankTime.IsZero())
value, ok := c.GetQuery("foo")
ast.False(ok)
ast.Equal(len(value), 0)
ast.Equal(len(c.Query("bar")), 0)
ast.Equal("nothing", c.DefaultQuery("id", "nothing"))
value, ok = c.GetPostForm("foo")
ast.True(ok)
ast.Equal("bar", value)
ast.Equal("bar", c.PostForm("foo"))
value, ok = c.GetPostForm("array")
ast.True(ok)
ast.Equal("first", value)
ast.Equal("first", c.PostForm("array"))
ast.Equal("10", c.DefaultPostForm("bar", "nothing"))
value, ok = c.GetPostForm("id")
ast.True(ok)
ast.Equal(len(value), 0)
ast.Equal(len(c.PostForm("id")), 0)
ast.Equal(len(c.DefaultPostForm("id", "nothing")), 0)
value, ok = c.GetPostForm("nokey")
ast.False(ok)
ast.Equal(len(value), 0)
ast.Equal("nothing", c.DefaultPostForm("nokey", "nothing"))
values, ok := c.GetPostFormArray("array")
ast.True(ok)
ast.Equal("first", values[0])
ast.Equal("second", values[1])
values = c.PostFormArray("array")
ast.Equal("first", values[0])
ast.Equal("second", values[1])
values = c.PostFormArray("nokey")
ast.Equal(0, len(values))
values = c.PostFormArray("foo")
ast.Equal(1, len(values))
ast.Equal("bar", values[0])
dicts, ok := c.GetPostFormMap("names")
ast.True(ok)
ast.Equal("thinkerou", dicts["a"])
ast.Equal("tianou", dicts["b"])
dicts, ok = c.GetPostFormMap("nokey")
ast.False(ok)
ast.Equal(0, len(dicts))
dicts = c.PostFormMap("names")
ast.Equal("thinkerou", dicts["a"])
ast.Equal("tianou", dicts["b"])
dicts = c.PostFormMap("nokey")
ast.Equal(0, len(dicts))
}
func TestContextHeaders(t *testing.T) {
ast := assert.NewAssert(t)
c, _ := CreateTestContext(httptest.NewRecorder())
c.Header("Content-Type", "text/plain")
c.Header("X-Custom", "value")
ast.Equal("text/plain", c.Writer.Header().Get("Content-Type"))
ast.Equal("value", c.Writer.Header().Get("X-Custom"))
c.Header("Content-Type", "text/html")
c.Header("X-Custom", "")
ast.Equal("text/html", c.Writer.Header().Get("Content-Type"))
_, exist := c.Writer.Header()["X-Custom"]
ast.False(exist)
}
func TestContextIsAborted(t *testing.T) {
ast := assert.NewAssert(t)
c, _ := CreateTestContext(httptest.NewRecorder())
ast.False(c.IsAborted())
c.Abort()
ast.True(c.IsAborted())
c.Next()
ast.True(c.IsAborted())
c.index++
ast.True(c.IsAborted())
}
func TestContextAbortWithStatus(t *testing.T) {
ast := assert.NewAssert(t)
w := httptest.NewRecorder()
c, _ := CreateTestContext(w)
c.index = 4
c.AbortWithStatus(http.StatusUnauthorized)
ast.Equal(abortIndex, c.index)
ast.Equal(http.StatusUnauthorized, c.Writer.Status())
ast.Equal(http.StatusUnauthorized, w.Code)
ast.True(c.IsAborted())
}
func TestContextContentType(t *testing.T) {
ast := assert.NewAssert(t)
c, _ := CreateTestContext(httptest.NewRecorder())
c.Request, _ = http.NewRequest("POST", "/", nil)
c.Request.Header.Set("Content-Type", "application/json; charset=utf-8")
ast.Equal("application/json", c.ContentType())
}
func TestContextAutoBindJSON(t *testing.T) {
ast := assert.NewAssert(t)
c, _ := CreateTestContext(httptest.NewRecorder())
c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
c.Request.Header.Add("Content-Type", binding.MIMEJSON)
var obj struct {
Foo string `json:"foo"`
Bar string `json:"bar"`
}
ast.Nil(c.Bind(&obj))
ast.Equal("foo", obj.Bar)
ast.Equal("bar", obj.Foo)
ast.Equal(len(c.Errors), 0)
}
func TestContextBindWithJSON(t *testing.T) {
ast := assert.NewAssert(t)
w := httptest.NewRecorder()
c, _ := CreateTestContext(w)
c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
c.Request.Header.Add("Content-Type", binding.MIMEXML) // set fake content-type
var obj struct {
Foo string `json:"foo"`
Bar string `json:"bar"`
}
ast.Nil(c.BindJSON(&obj))
ast.Equal("foo", obj.Bar)
ast.Equal("bar", obj.Foo)
ast.Equal(0, w.Body.Len())
}
func TestContextBindWithQuery(t *testing.T) {
ast := assert.NewAssert(t)
w := httptest.NewRecorder()
c, _ := CreateTestContext(w)
c.Request, _ = http.NewRequest("POST", "/?foo=bar&bar=foo", bytes.NewBufferString("foo=unused"))
var obj struct {
Foo string `form:"foo"`
Bar string `form:"bar"`
}
ast.Nil(c.BindQuery(&obj))
ast.Equal("foo", obj.Bar)
ast.Equal("bar", obj.Foo)
ast.Equal(0, w.Body.Len())
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。