Exemplo n.º 1
0
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\"})")
}
Exemplo n.º 2
0
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)
}
Exemplo n.º 3
0
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()
}
Exemplo n.º 4
0
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\"})")
}
Exemplo n.º 5
0
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")
}
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())
	}
}
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())
	}
}
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
}
Exemplo n.º 9
0
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()
}
func TestGetEmailVerify(t *testing.T) {
	handler := newHandler()

	type testpair struct {
		email string
		valid bool
	}

	var tests = []testpair{
		{"*****@*****.**", true},
		{"*****@*****.**", true},
		{"*****@*****.**", 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)
		}
	}
}
Exemplo n.º 11
0
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")
		}
	}
}
Exemplo n.º 12
0
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()
}
Exemplo n.º 13
0
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)
	}
}
Exemplo n.º 14
0
// 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++
	}
}
Exemplo n.º 15
0
// 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)
}
Exemplo n.º 16
0
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))
	}
}
Exemplo n.º 17
0
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))
	}
}
Exemplo n.º 18
0
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()
}
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()
}
Exemplo n.º 20
0
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}")
}
Exemplo n.º 21
0
func TestErrorHandlerDataNotFound(t *testing.T) {
	ctx, handler := NewTestHandler(t)
	defer ctx.Close()

	accountCode := "neverfind"
	url := fmt.Sprintf("http://1.2.3.4/v1/accounts/%s", accountCode)
	recorded := test.RunRequest(t, handler, test.MakeSimpleRequest("GET", url, nil))
	recorded.CodeIs(http.StatusNotFound)
	recorded.ContentTypeIsJson()
}
Exemplo n.º 22
0
func TestHttpResponseLayer(t *testing.T) {

	api := NewApi()
	router, err := MakeRouter(
		Get("/r/:id", func(w ResponseWriter, r *Request) {
			id := r.PathParam("id")
			w.WriteJson(map[string]string{"Id": id})
		}),
		Post("/r/:id", func(w ResponseWriter, r *Request) {
			// JSON echo
			data := map[string]string{}
			err := r.DecodeJsonPayload(&data)
			if err != nil {
				t.Fatal(err)
			}
			w.WriteJson(data)
		}),
	)
	if err != nil {
		t.Fatal(err)
	}
	api.SetApp(router)

	handler := api.MakeHandler()

	// valid get resource
	recorded := test.RunRequest(t, handler, test.MakeSimpleRequest("GET", "http://1.2.3.4/r/123", nil))
	recorded.CodeIs(200)
	recorded.ContentTypeIsJson()
	recorded.BodyIs(`{"Id":"123"}`)

	// auto 405 on undefined route (wrong method)
	recorded = test.RunRequest(t, handler, test.MakeSimpleRequest("DELETE", "http://1.2.3.4/r/123", nil))
	recorded.CodeIs(405)
	recorded.ContentTypeIsJson()
	recorded.BodyIs(`{"Error":"Method not allowed"}`)

	// auto 404 on undefined route (wrong path)
	recorded = test.RunRequest(t, handler, test.MakeSimpleRequest("GET", "http://1.2.3.4/s/123", nil))
	recorded.CodeIs(404)
	recorded.ContentTypeIsJson()
	recorded.BodyIs(`{"Error":"Resource not found"}`)
}
Exemplo n.º 23
0
func TestNotFoundResponse(t *testing.T) {

	api := NewApi()
	api.SetApp(AppSimple(func(w ResponseWriter, r *Request) {
		NotFound(w, r)
	}))

	recorded := test.RunRequest(t, api.MakeHandler(), test.MakeSimpleRequest("GET", "http://localhost/", nil))
	recorded.CodeIs(404)
	recorded.ContentTypeIsJson()
	recorded.BodyIs("{\"Error\":\"Resource not found\"}")
}
Exemplo n.º 24
0
func TestErrorResponse(t *testing.T) {

	api := NewApi()
	api.SetApp(AppSimple(func(w ResponseWriter, r *Request) {
		Error(w, "test", 500)
	}))

	recorded := test.RunRequest(t, api.MakeHandler(), test.MakeSimpleRequest("GET", "http://localhost/", nil))
	recorded.CodeIs(500)
	recorded.ContentTypeIsJson()
	recorded.BodyIs("{\"Error\":\"test\"}")
}
Exemplo n.º 25
0
func TestWriteJsonResponse(t *testing.T) {

	api := NewApi()
	api.SetApp(AppSimple(func(w ResponseWriter, r *Request) {
		w.WriteJson(map[string]string{"Id": "123"})
	}))

	recorded := test.RunRequest(t, api.MakeHandler(), test.MakeSimpleRequest("GET", "http://localhost/", nil))
	recorded.CodeIs(200)
	recorded.ContentTypeIsJson()
	recorded.BodyIs("{\"Id\":\"123\"}")
}
Exemplo n.º 26
0
func TestAccountHandlerGetAll(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)

	recorded := test.RunRequest(t, handler, test.MakeSimpleRequest("GET", "http://1.2.3.4/v1/accounts", nil))
	recorded.CodeIs(http.StatusOK)
	recorded.ContentTypeIsJson()
	recorded.HeaderIs("Cache-Control", "private, max-age=60")
}
Exemplo n.º 27
0
func testXPoweredBy(t *testing.T, rh *ResourceHandler, expected string) {
	rh.SetRoutes(
		&Route{"GET", "/r/:id",
			func(w ResponseWriter, r *Request) {
				id := r.PathParam("id")
				w.WriteJson(map[string]string{"Id": id})
			},
		},
	)
	recorded := test.RunRequest(t, rh, test.MakeSimpleRequest("GET", "http://1.2.3.4/r/123", nil))
	recorded.CodeIs(200)
	recorded.ContentTypeIsJson()
	recorded.HeaderIs("X-Powered-By", expected)
}
Exemplo n.º 28
0
func TestTimerMiddleware(t *testing.T) {

	api := NewApi()

	// a middleware carrying the Env tests
	api.Use(MiddlewareSimple(func(handler HandlerFunc) HandlerFunc {
		return func(w ResponseWriter, r *Request) {

			handler(w, r)

			if r.Env["ELAPSED_TIME"] == nil {
				t.Error("ELAPSED_TIME is nil")
			}
			elapsedTime := r.Env["ELAPSED_TIME"].(*time.Duration)
			if elapsedTime.Nanoseconds() <= 0 {
				t.Errorf(
					"ELAPSED_TIME is expected to be at least 1 nanosecond %d",
					elapsedTime.Nanoseconds(),
				)
			}

			if r.Env["START_TIME"] == nil {
				t.Error("START_TIME is nil")
			}
			start := r.Env["START_TIME"].(*time.Time)
			if start.After(time.Now()) {
				t.Errorf(
					"START_TIME is expected to be in the past %s",
					start.String(),
				)
			}
		}
	}))

	// the middleware to test
	api.Use(&TimerMiddleware{})

	// 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()
}
Exemplo n.º 29
0
func TestGzipEnabled(t *testing.T) {

	api := NewApi()

	// the middleware to test
	api.Use(&GzipMiddleware{})

	// 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, "gzipped 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", nil))
	recorded.CodeIs(200)
	recorded.ContentTypeIsJson()
	recorded.ContentEncodingIsGzip()
	recorded.HeaderIs("Vary", "Accept-Encoding")

	recorded = test.RunRequest(t, handler, test.MakeSimpleRequest("GET", "http://localhost/error", nil))
	recorded.CodeIs(500)
	recorded.ContentTypeIsJson()
	recorded.ContentEncodingIsGzip()
	recorded.HeaderIs("Vary", "Accept-Encoding")
}
Exemplo n.º 30
0
func sendRequest(method, path string, body interface{}, t *testing.T) *test.Recorded {
	if !IsInitialized() {
		restApi := rest.NewApi()
		Initialize(restApi)
		apiHandler = restApi.MakeHandler()
	}

	req := test.MakeSimpleRequest(method, "http://localhost"+path, body)

	if token != "" {
		req.Header.Add("Authorization", "Bearer "+token)
	}

	return test.RunRequest(t, apiHandler, req)
}