作者:auroralaboratorie
项目:corona-ap
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\"})")
}
作者:charsh
项目:registr
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)
}
作者:roongr2k
项目:time_tracker_ap
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()
}
作者:freeform
项目:go-inkblo
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\"})")
}
作者:auroralaboratorie
项目:corona-ap
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")
}
作者:Catroqu
项目:go-json-res
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())
}
}
作者:Catroqu
项目:go-json-res
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())
}
}
作者:yetis-b
项目:travelPlannin
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
}
作者:joshheinrich
项目:geosourc
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()
}
作者:taterbas
项目:smtp-callback-verificatio
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)
}
}
}
作者:jacktan
项目:ibconnect.g
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")
}
}
}
作者:pdxjohnn
项目:hangouts-call-cente
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()
}
作者:mhemming
项目:go-json-res
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)
}
}
作者:wppurkin
项目:limite
// 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++
}
}
作者:wppurkin
项目:limite
// 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)
}
作者:auroralaboratorie
项目:corona-ap
func TestStatus(t *testing.T) {
handler := ResourceHandler{
EnableStatusService: true,
}
handler.SetRoutes(
&Route{"GET", "/r",
func(w ResponseWriter, r *Request) {
w.WriteJson(map[string]string{"Id": "123"})
},
},
&Route{"GET", "/.status",
func(w ResponseWriter, r *Request) {
w.WriteJson(handler.GetStatus())
},
},
)
// one request to the API
recorded := test.RunRequest(t, &handler, test.MakeSimpleRequest("GET", "http://1.2.3.4/r", nil))
recorded.CodeIs(200)
recorded.ContentTypeIsJson()
// check the status
recorded = test.RunRequest(t, &handler, test.MakeSimpleRequest("GET", "http://1.2.3.4/.status", nil))
recorded.CodeIs(200)
recorded.ContentTypeIsJson()
payload := map[string]interface{}{}
err := recorded.DecodeJsonPayload(&payload)
if err != nil {
t.Fatal(err)
}
if payload["Pid"] == nil {
t.Error("Expected a non nil Pid")
}
if payload["TotalCount"].(float64) != 1 {
t.Errorf("TotalCount 1 Expected, got: %f", payload["TotalCount"].(float64))
}
if payload["StatusCodeCount"].(map[string]interface{})["200"].(float64) != 1 {
t.Errorf("StatusCodeCount 200 1 Expected, got: %f", payload["StatusCodeCount"].(map[string]interface{})["200"].(float64))
}
}
作者:Catroqu
项目:go-json-res
func TestStatusMiddleware(t *testing.T) {
api := NewApi()
// the middlewares
status := &StatusMiddleware{}
api.Use(status)
api.Use(&TimerMiddleware{})
api.Use(&RecorderMiddleware{})
// an app that return the Status
api.SetApp(AppSimple(func(w ResponseWriter, r *Request) {
w.WriteJson(status.GetStatus())
}))
// wrap all
handler := api.MakeHandler()
// one request
recorded := test.RunRequest(t, handler, test.MakeSimpleRequest("GET", "http://localhost/1", nil))
recorded.CodeIs(200)
recorded.ContentTypeIsJson()
// another request
recorded = test.RunRequest(t, handler, test.MakeSimpleRequest("GET", "http://localhost/2", nil))
recorded.CodeIs(200)
recorded.ContentTypeIsJson()
// payload
payload := map[string]interface{}{}
err := recorded.DecodeJsonPayload(&payload)
if err != nil {
t.Fatal(err)
}
if payload["Pid"] == nil {
t.Error("Expected a non nil Pid")
}
if payload["TotalCount"].(float64) != 1 {
t.Errorf("TotalCount 1 Expected, got: %f", payload["TotalCount"].(float64))
}
if payload["StatusCodeCount"].(map[string]interface{})["200"].(float64) != 1 {
t.Errorf("StatusCodeCount 200 1 Expected, got: %f", payload["StatusCodeCount"].(map[string]interface{})["200"].(float64))
}
}
作者:pdxjohnn
项目:numap
func TestAllOtherPathsNeedAuth(t *testing.T) {
handler := MakeHandler()
req := test.MakeSimpleRequest("GET", "http://localhost/", nil)
res := test.RunRequest(t, *handler, req)
res.CodeIs(401)
res.ContentTypeIsJson()
}
作者:auroralaboratorie
项目:corona-ap
func TestAuthBasic(t *testing.T) {
handler := ResourceHandler{
PreRoutingMiddlewares: []Middleware{
&AuthBasicMiddleware{
Realm: "test zone",
Authenticator: func(userId string, password string) bool {
if userId == "admin" && password == "admin" {
return true
}
return false
},
},
},
}
handler.SetRoutes(
&Route{"GET", "/r",
func(w ResponseWriter, r *Request) {
w.WriteJson(map[string]string{"Id": "123"})
},
},
)
// simple request fails
recorded := test.RunRequest(t, &handler, test.MakeSimpleRequest("GET", "http://1.2.3.4/r", nil))
recorded.CodeIs(401)
recorded.ContentTypeIsJson()
// auth with wrong cred fails
wrongCredReq := test.MakeSimpleRequest("GET", "http://1.2.3.4/r", nil)
encoded := base64.StdEncoding.EncodeToString([]byte("admin:AdmIn"))
wrongCredReq.Header.Set("Authorization", "Basic "+encoded)
recorded = test.RunRequest(t, &handler, wrongCredReq)
recorded.CodeIs(401)
recorded.ContentTypeIsJson()
// auth with right cred succeeds
rightCredReq := test.MakeSimpleRequest("GET", "http://1.2.3.4/r", nil)
encoded = base64.StdEncoding.EncodeToString([]byte("admin:admin"))
rightCredReq.Header.Set("Authorization", "Basic "+encoded)
recorded = test.RunRequest(t, &handler, rightCredReq)
recorded.CodeIs(200)
recorded.ContentTypeIsJson()
}
作者:Catroqu
项目:go-json-res
func TestIfMiddleware(t *testing.T) {
api := NewApi()
// the middleware to test
api.Use(&IfMiddleware{
Condition: func(r *Request) bool {
if r.URL.Path == "/true" {
return true
}
return false
},
IfTrue: MiddlewareSimple(func(handler HandlerFunc) HandlerFunc {
return func(w ResponseWriter, r *Request) {
r.Env["TRUE_MIDDLEWARE"] = true
handler(w, r)
}
}),
IfFalse: MiddlewareSimple(func(handler HandlerFunc) HandlerFunc {
return func(w ResponseWriter, r *Request) {
r.Env["FALSE_MIDDLEWARE"] = true
handler(w, r)
}
}),
})
// a simple app
api.SetApp(AppSimple(func(w ResponseWriter, r *Request) {
w.WriteJson(r.Env)
}))
// wrap all
handler := api.MakeHandler()
recorded := test.RunRequest(t, handler, test.MakeSimpleRequest("GET", "http://localhost/", nil))
recorded.CodeIs(200)
recorded.ContentTypeIsJson()
recorded.BodyIs("{\"FALSE_MIDDLEWARE\":true}")
recorded = test.RunRequest(t, handler, test.MakeSimpleRequest("GET", "http://localhost/true", nil))
recorded.CodeIs(200)
recorded.ContentTypeIsJson()
recorded.BodyIs("{\"TRUE_MIDDLEWARE\":true}")
}