Exemple #1
0
func TestGzip(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")
}
Exemple #2
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))
	}
}
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()
}
Exemple #4
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)
}
Exemple #5
0
func TestHandler(t *testing.T) {

	handler := ResourceHandler{
		DisableJsonIndent: true,
		// make the test output less verbose by discarding the error log
		ErrorLogger: log.New(ioutil.Discard, "", 0),
	}
	handler.SetRoutes(
		&Route{"GET", "/r/:id",
			func(w ResponseWriter, r *Request) {
				id := r.PathParam("id")
				w.WriteJson(map[string]string{"Id": id})
			},
		},
		&Route{"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)
			},
		},
		&Route{"GET", "/auto-fails",
			func(w ResponseWriter, r *Request) {
				a := []int{}
				_ = a[0]
			},
		},
		&Route{"GET", "/user-error",
			func(w ResponseWriter, r *Request) {
				Error(w, "My error", 500)
			},
		},
		&Route{"GET", "/user-notfound",
			func(w ResponseWriter, r *Request) {
				NotFound(w, r)
			},
		},
	)

	// 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"}`)

	// valid post resource
	recorded = test.RunRequest(t, &handler, test.MakeSimpleRequest(
		"POST", "http://1.2.3.4/r/123", &map[string]string{"Test": "Test"}))
	recorded.CodeIs(200)
	recorded.ContentTypeIsJson()
	recorded.BodyIs(`{"Test":"Test"}`)

	// broken Content-Type post resource
	request := test.MakeSimpleRequest("POST", "http://1.2.3.4/r/123", &map[string]string{"Test": "Test"})
	request.Header.Set("Content-Type", "text/html")
	recorded = test.RunRequest(t, &handler, request)
	recorded.CodeIs(415)
	recorded.ContentTypeIsJson()
	recorded.BodyIs(`{"Error":"Bad Content-Type or charset, expected 'application/json'"}`)

	// broken Content-Type post resource
	request = test.MakeSimpleRequest("POST", "http://1.2.3.4/r/123", &map[string]string{"Test": "Test"})
	request.Header.Set("Content-Type", "application/json; charset=ISO-8859-1")
	recorded = test.RunRequest(t, &handler, request)
	recorded.CodeIs(415)
	recorded.ContentTypeIsJson()
	recorded.BodyIs(`{"Error":"Bad Content-Type or charset, expected 'application/json'"}`)

	// Content-Type post resource with charset
	request = test.MakeSimpleRequest("POST", "http://1.2.3.4/r/123", &map[string]string{"Test": "Test"})
	request.Header.Set("Content-Type", "application/json;charset=UTF-8")
	recorded = test.RunRequest(t, &handler, request)
	recorded.CodeIs(200)
	recorded.ContentTypeIsJson()
	recorded.BodyIs(`{"Test":"Test"}`)

	// 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"}`)

	// auto 500 on unhandled userecorder error
	recorded = test.RunRequest(t, &handler, test.MakeSimpleRequest("GET", "http://1.2.3.4/auto-fails", nil))
	recorded.CodeIs(500)
	recorded.ContentTypeIsJson()
	recorded.BodyIs(`{"Error":"Internal Server Error"}`)

	// userecorder error
	recorded = test.RunRequest(t, &handler, test.MakeSimpleRequest("GET", "http://1.2.3.4/user-error", nil))
	recorded.CodeIs(500)
	recorded.ContentTypeIsJson()
	recorded.BodyIs(`{"Error":"My error"}`)

	// userecorder notfound
	recorded = test.RunRequest(t, &handler, test.MakeSimpleRequest("GET", "http://1.2.3.4/user-notfound", nil))
	recorded.CodeIs(404)
	recorded.ContentTypeIsJson()
	recorded.BodyIs(`{"Error":"Resource not found"}`)
}