本文整理汇总了Golang中github.com/ant0ine/go-json-rest/rest/test.RunRequest函数的典型用法代码示例。如果您正苦于以下问题:Golang RunRequest函数的具体用法?Golang RunRequest怎么用?Golang RunRequest使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了RunRequest函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestJSONP
func TestJSONP(t *testing.T) {
handler := ResourceHandler{
DisableJsonIndent: true,
PreRoutingMiddlewares: []Middleware{
&JsonpMiddleware{},
},
}
handler.SetRoutes(
&Route{"GET", "/ok",
func(w ResponseWriter, r *Request) {
w.WriteJson(map[string]string{"Id": "123"})
},
},
&Route{"GET", "/error",
func(w ResponseWriter, r *Request) {
Error(w, "gzipped error", 500)
},
},
)
recorded := test.RunRequest(t, &handler, test.MakeSimpleRequest("GET", "http://1.2.3.4/ok?callback=parseResponse", nil))
recorded.CodeIs(200)
recorded.HeaderIs("Content-Type", "text/javascript")
recorded.BodyIs("parseResponse({\"Id\":\"123\"})")
recorded = test.RunRequest(t, &handler, test.MakeSimpleRequest("GET", "http://1.2.3.4/error?callback=parseResponse", nil))
recorded.CodeIs(500)
recorded.HeaderIs("Content-Type", "text/javascript")
recorded.BodyIs("parseResponse({\"Error\":\"gzipped error\"})")
}
示例2: TestContentTypeCheckerMiddleware
func TestContentTypeCheckerMiddleware(t *testing.T) {
api := NewApi()
// the middleware to test
api.Use(&ContentTypeCheckerMiddleware{})
// a simple app
api.SetApp(AppSimple(func(w ResponseWriter, r *Request) {
w.WriteJson(map[string]string{"Id": "123"})
}))
// wrap all
handler := api.MakeHandler()
// no payload, no content length, no check
recorded := test.RunRequest(t, handler, test.MakeSimpleRequest("GET", "http://localhost/", nil))
recorded.CodeIs(200)
// JSON payload with correct content type
recorded = test.RunRequest(t, handler, test.MakeSimpleRequest("POST", "http://localhost/", map[string]string{"Id": "123"}))
recorded.CodeIs(200)
// JSON payload with correct content type specifying the utf-8 charset
req := test.MakeSimpleRequest("POST", "http://localhost/", map[string]string{"Id": "123"})
req.Header.Set("Content-Type", "application/json; charset=utf-8")
recorded = test.RunRequest(t, handler, req)
recorded.CodeIs(200)
// JSON payload with incorrect content type
req = test.MakeSimpleRequest("POST", "http://localhost/", map[string]string{"Id": "123"})
req.Header.Set("Content-Type", "text/x-json")
recorded = test.RunRequest(t, handler, req)
recorded.CodeIs(415)
}
示例3: TestHandler
func TestHandler(t *testing.T) {
handler := rest.ResourceHandler{
DisableJsonIndent: true,
ErrorLogger: log.New(ioutil.Discard, "", 0),
}
handler.SetRoutes(
&rest.Route{"POST", "/api/coach/checkin",
func(w rest.ResponseWriter, r *rest.Request) {
w.WriteHeader(http.StatusCreated)
data := map[string]string{"id": "53f87e7ad18a68e0a884d31e"}
w.WriteJson(data)
},
},
&rest.Route{"POST", "/api/coach/checkout",
func(w rest.ResponseWriter, r *rest.Request) {
w.WriteHeader(http.StatusAccepted)
},
},
)
recorded := test.RunRequest(t, &handler, test.MakeSimpleRequest(
"POST", "http://www.sprint3r.com/api/coach/checkin", &map[string]string{"name": "iporsut", "league": "dtac"}))
recorded.CodeIs(201)
recorded.ContentTypeIsJson()
recorded.BodyIs(`{"id":"53f87e7ad18a68e0a884d31e"}`)
recorded = test.RunRequest(t, &handler, test.MakeSimpleRequest(
"POST", "http://www.sprint3r.com/api/coach/checkout", &map[string]string{"name": "iporsut", "league": "dtac"}))
recorded.CodeIs(202)
recorded.ContentTypeIsJson()
}
示例4: TestJsonpMiddleware
func TestJsonpMiddleware(t *testing.T) {
api := NewApi()
// the middleware to test
api.Use(&JsonpMiddleware{})
// router app with success and error paths
router, err := MakeRouter(
Get("/ok", func(w ResponseWriter, r *Request) {
w.WriteJson(map[string]string{"Id": "123"})
}),
Get("/error", func(w ResponseWriter, r *Request) {
Error(w, "jsonp error", 500)
}),
)
if err != nil {
t.Fatal(err)
}
api.SetApp(router)
// wrap all
handler := api.MakeHandler()
recorded := test.RunRequest(t, handler, test.MakeSimpleRequest("GET", "http://localhost/ok?callback=parseResponse", nil))
recorded.CodeIs(200)
recorded.HeaderIs("Content-Type", "text/javascript")
recorded.BodyIs("parseResponse({\"Id\":\"123\"})")
recorded = test.RunRequest(t, handler, test.MakeSimpleRequest("GET", "http://localhost/error?callback=parseResponse", nil))
recorded.CodeIs(500)
recorded.HeaderIs("Content-Type", "text/javascript")
recorded.BodyIs("parseResponse({\"Error\":\"jsonp error\"})")
}
示例5: TestGzipEnabled
func TestGzipEnabled(t *testing.T) {
handler := ResourceHandler{
DisableJsonIndent: true,
EnableGzip: true,
}
handler.SetRoutes(
&Route{"GET", "/ok",
func(w ResponseWriter, r *Request) {
w.WriteJson(map[string]string{"Id": "123"})
},
},
&Route{"GET", "/error",
func(w ResponseWriter, r *Request) {
Error(w, "gzipped error", 500)
},
},
)
recorded := test.RunRequest(t, &handler, test.MakeSimpleRequest("GET", "http://1.2.3.4/ok", nil))
recorded.CodeIs(200)
recorded.ContentTypeIsJson()
recorded.ContentEncodingIsGzip()
recorded.HeaderIs("Vary", "Accept-Encoding")
recorded = test.RunRequest(t, &handler, test.MakeSimpleRequest("GET", "http://1.2.3.4/error", nil))
recorded.CodeIs(500)
recorded.ContentTypeIsJson()
recorded.ContentEncodingIsGzip()
recorded.HeaderIs("Vary", "Accept-Encoding")
}
示例6: TestAccessLogApacheMiddlewareMissingData
func TestAccessLogApacheMiddlewareMissingData(t *testing.T) {
api := NewApi()
// the uncomplete middlewares stack
buffer := bytes.NewBufferString("")
api.Use(&AccessLogApacheMiddleware{
Logger: log.New(buffer, "", 0),
Format: CommonLogFormat,
textTemplate: nil,
})
// a simple app
api.SetApp(AppSimple(func(w ResponseWriter, r *Request) {
w.WriteJson(map[string]string{"Id": "123"})
}))
// wrap all
handler := api.MakeHandler()
req := test.MakeSimpleRequest("GET", "http://localhost/", nil)
recorded := test.RunRequest(t, handler, req)
recorded.CodeIs(200)
recorded.ContentTypeIsJson()
// not much to log when the Env data is missing, but this should still work
apacheCommon := regexp.MustCompile(` - - "GET / HTTP/1.1" 0 -`)
if !apacheCommon.Match(buffer.Bytes()) {
t.Errorf("Got: %s", buffer.String())
}
}
示例7: TestAccessLogApacheMiddleware
func TestAccessLogApacheMiddleware(t *testing.T) {
api := NewApi()
// the middlewares stack
buffer := bytes.NewBufferString("")
api.Use(&AccessLogApacheMiddleware{
Logger: log.New(buffer, "", 0),
Format: CommonLogFormat,
textTemplate: nil,
})
api.Use(&TimerMiddleware{})
api.Use(&RecorderMiddleware{})
// a simple app
api.SetApp(AppSimple(func(w ResponseWriter, r *Request) {
w.WriteJson(map[string]string{"Id": "123"})
}))
// wrap all
handler := api.MakeHandler()
req := test.MakeSimpleRequest("GET", "http://localhost/", nil)
req.RemoteAddr = "127.0.0.1:1234"
recorded := test.RunRequest(t, handler, req)
recorded.CodeIs(200)
recorded.ContentTypeIsJson()
// log tests, eg: '127.0.0.1 - - 29/Nov/2014:22:28:34 +0000 "GET / HTTP/1.1" 200 12'
apacheCommon := regexp.MustCompile(`127.0.0.1 - - \d{2}/\w{3}/\d{4}:\d{2}:\d{2}:\d{2} [+\-]\d{4}\ "GET / HTTP/1.1" 200 12`)
if !apacheCommon.Match(buffer.Bytes()) {
t.Errorf("Got: %s", buffer.String())
}
}
示例8: APIRequest
func APIRequest(url string, method string, model interface{}, token string) {
jwtMiddleware := &jwt.JWTMiddleware{
Key: SecretKey,
Realm: Realm,
Timeout: time.Hour,
MaxRefresh: time.Hour * 24,
Authenticator: func(userId string, password string) bool {
return Authenticator(userId, password)
},
}
api := rest.NewApi()
api.Use(&rest.IfMiddleware{
Condition: func(request *rest.Request) bool {
return CheckCondition(request)
},
IfTrue: jwtMiddleware,
})
api.SetApp(NewRouter(jwtMiddleware, testConn))
Request = test.MakeSimpleRequest(method, url, model)
if token != "" {
Request.Header.Set("Authorization", "Bearer "+token)
}
recorded := test.RunRequest(tst, api.MakeHandler(), Request)
Response = recorded.Recorder
}
示例9: TestGetChannels
func TestGetChannels(t *testing.T) {
handler, err := MakeHandler()
assert.NoError(t, err)
recorded := test.RunRequest(t, handler, test.MakeSimpleRequest("GET", "http://1.2.3.4/channels", nil))
recorded.CodeIs(200)
recorded.ContentTypeIsJson()
}
示例10: TestGetEmailVerify
func TestGetEmailVerify(t *testing.T) {
handler := newHandler()
type testpair struct {
email string
valid bool
}
var tests = []testpair{
{"[email protected]", true},
{"[email protected]", true},
{"[email protected]", false},
{"not%20an%20email", false},
}
for _, pair := range tests {
recorded := test.RunRequest(t, &handler,
test.MakeSimpleRequest("GET",
"http://1.2.3.4/verify/?email="+pair.email, nil))
recorded.CodeIs(200)
recorded.ContentTypeIsJson()
// check actual response content
msg := Message{}
recorded.DecodeJsonPayload(&msg)
if msg.IsValid != pair.valid {
t.Errorf("For %v. Expected %v: Actual %v", pair.email, pair.valid, msg.IsValid)
}
}
}
示例11: TestAccountHandlerGetAllRefresh
func TestAccountHandlerGetAllRefresh(t *testing.T) {
ctx, handler := NewTestHandler(t)
defer ctx.Close()
c := core.NewTestConfig(t)
var ff gateway.FeedFactory = &gateway.AccountFeedFactory{AccountRefresh: c.AccountRefresh}
WaitForFeed(t, ctx, &ff, 15*time.Second)
nc := make(chan *core.Notification)
ctx.N.Subscribe(nc)
defer ctx.N.Unsubscribe(nc)
go func() {
req := test.MakeSimpleRequest("GET", "http://1.2.3.4/v1/accounts", nil)
req.Header.Add("Cache-Control", "private; max-age=0")
test.RunRequest(t, handler, req)
// NB: This request will not return data, as there's no feed running.
// Long timeouts avoided as the ctx.Close() closes the Notifier,
// which in turn closes the RefreshIfNeeded listener.
}()
outer:
for {
select {
case msg := <-nc:
if msg.Type == core.NtAccountRefresh {
// controller requested an account refresh, like it should have
break outer
}
case <-time.After(15 * time.Second):
t.Fatal("controller didn't request update before timeout")
}
}
}
示例12: TestCall
func TestCall(t *testing.T) {
err := os.Chdir("../../")
if err != nil {
log.Fatal(err)
}
handler := MakeHandler()
// Use BackendToken to avoid login
err = variables.LoadTokenKeys()
if err != nil {
t.Fatal(err)
}
// Test that call works
path := variables.APIPathCallServer
path = strings.Replace(path, ":number", "test number", 1)
testReq := test.MakeSimpleRequest(
"GET",
"http://localhost"+path,
nil,
)
testReq.Header.Set("Authorization", "Bearer "+variables.BackendToken)
// Do not gzip the response
testReq.Header.Set("Accept-Encoding", "identity")
testRes := test.RunRequest(t, *handler, testReq)
testRes.CodeIs(http.StatusOK)
testRes.ContentTypeIsJson()
}
示例13: TestRecoverMiddleware
func TestRecoverMiddleware(t *testing.T) {
api := NewApi()
// the middleware to test
api.Use(&RecoverMiddleware{
Logger: log.New(ioutil.Discard, "", 0),
EnableLogAsJson: false,
EnableResponseStackTrace: true,
})
// a simple app that fails
api.SetApp(AppSimple(func(w ResponseWriter, r *Request) {
panic("test")
}))
// wrap all
handler := api.MakeHandler()
req := test.MakeSimpleRequest("GET", "http://localhost/", nil)
recorded := test.RunRequest(t, handler, req)
recorded.CodeIs(500)
recorded.ContentTypeIsJson()
// payload
payload := map[string]string{}
err := recorded.DecodeJsonPayload(&payload)
if err != nil {
t.Fatal(err)
}
if payload["error"] == "" {
t.Errorf("Expected an error message, got: %v", payload)
}
}
示例14: TestGJRMiddleware
// TestRate tests ratelimit.Rate methods.
func TestGJRMiddleware(t *testing.T) {
api := rest.NewApi()
api.Use(NewGJRMiddleware(newRedisLimiter("10-M", "limitertests:gjr")))
var reset int64
api.SetApp(rest.AppSimple(func(w rest.ResponseWriter, r *rest.Request) {
reset = r.Env["ratelimit:reset"].(int64)
w.WriteJson(map[string]string{"message": "ok"})
}))
handler := api.MakeHandler()
req := test.MakeSimpleRequest("GET", "http://localhost/", nil)
req.RemoteAddr = fmt.Sprintf("178.1.2.%d:120", Random(1, 90))
i := 1
for i < 20 {
recorded := test.RunRequest(t, handler, req)
assert.True(t, math.Ceil(time.Since(time.Unix(reset, 0)).Seconds()) <= 60)
if i <= 10 {
recorded.BodyIs(`{"message":"ok"}`)
recorded.HeaderIs("X-Ratelimit-Limit", "10")
recorded.HeaderIs("X-Ratelimit-Remaining", fmt.Sprintf("%d", 10-i))
recorded.CodeIs(200)
} else {
recorded.BodyIs(`{"Error":"Limit exceeded"}`)
recorded.HeaderIs("X-Ratelimit-Limit", "10")
recorded.HeaderIs("X-Ratelimit-Remaining", "0")
recorded.CodeIs(429)
}
i++
}
}
示例15: TestGJRMiddlewareWithRaceCondition
// TestGJRMiddlewareWithRaceCondition test GRJ middleware under race condition.
func TestGJRMiddlewareWithRaceCondition(t *testing.T) {
runtime.GOMAXPROCS(4)
api := rest.NewApi()
api.Use(NewGJRMiddleware(newRedisLimiter("5-M", "limitertests:gjrrace")))
api.SetApp(rest.AppSimple(func(w rest.ResponseWriter, r *rest.Request) {
w.WriteJson(map[string]string{"message": "ok"})
}))
handler := api.MakeHandler()
req := test.MakeSimpleRequest("GET", "http://localhost/", nil)
req.RemoteAddr = fmt.Sprintf("178.1.2.%d:180", Random(1, 90))
nbRequests := 100
successCount := 0
var wg sync.WaitGroup
wg.Add(nbRequests)
for i := 1; i <= nbRequests; i++ {
go func() {
recorded := test.RunRequest(t, handler, req)
if recorded.Recorder.Code == 200 {
successCount++
}
wg.Done()
}()
}
wg.Wait()
assert.Equal(t, 5, successCount)
}