Skip to content

A lightweight high-level abstraction for testing HTTP inspired by supertest built around httptest.ResponseRecorder

License

Notifications You must be signed in to change notification settings

celrenheit/htest

Repository files navigation

HTest Build Status GoDoc License

A lightweight high-level abstractions for testing HTTP inspired by supertest built around http.ResponseRecorder

Screenshot

Install/Update

$ go get -u github.com/celrenheit/htest

Usage

Let's say that when we hit /admin we get a status code of 401 Unauthorized, a response body of You are not authorized and a header of foo=bar

mux := http.NewServeMux()
mux.HandleFunc("/admin", func(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("foo", "bar")
	w.WriteHeader(http.StatusUnauthorized)
	fmt.Fprintf(w, "You are not authorized")
})

We can write a Test to test if our program behaves correctly

func TestUnauthorized(t *testing.T) {
  // We create a new instance for HTTPTester
  // It requires a testing.T and an http.Handler as argument
	h := htest.New(t, mux)

  // We make assertions to the repsonse received
	h.Get("/admin").Do().
		ExpectHeader("foo", "bar").
		ExpectStatus(http.StatusUnauthorized).
		ExpectBody("You are not authorized")
}

h.Get returns a Requester to be able to easily build your request. We call the Do() to execute the request and get a ResponseAsserter.

There are methods for each http methods in the HTTPTester interface

Building the request

We send some arbitrary data and set a header to the request. The response should have the same body and the same header value.

func TestBuildingRequest(t *testing.T) {
	mux := http.NewServeMux()
	mux.HandleFunc("/path", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("foo", r.Header.Get("foo"))
		io.Copy(w, r.Body)
	})

	test := htest.New(t, mux)

	test.Get("/path").
		// Set a header to the request
		AddHeader("foo", "barbar").
		// Send a string to the request's body
		SendString("my data").

		// Executes the request
		Do().

		// The body sent should stay the same
		ExpectBody("my data").
		// The header sent should stay the same
		ExpectHeader("foo", "barbar")
}

Credits

About

A lightweight high-level abstraction for testing HTTP inspired by supertest built around httptest.ResponseRecorder

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages