modulepackage
0.0.0-20170621160705-e34d50431e7f
Repository: https://github.com/celrenheit/htest.git
Documentation: pkg.go.dev
# README
HTest

A lightweight high-level abstractions for testing HTTP inspired by supertest built around http.ResponseRecorder
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
# Functions
New returns a new HTTPTester instance.
NewResponseAsserter create a new response asserter.
NewStackFrame creates a new StackFrame instance It extracts the File, Line, Package and Function name for the passed Program Counter.
Trace parses the stacktrace and returns a slice of StackFrame.
# Structs
StackFrame describes a single stackframe with its Program Counter, Function name, Package, File and Line number.
# Interfaces
HTTPTester is an interface that represents the main entry point of HTest.
Requester is responsible for building an http request.
ResponseAsserter is responsible for making assertions based on the expected and the actual value returned from httptest.ResponseRecorder.
# Type aliases
StackFrames is a list of StackFrame.