testsrv

Test HTTP servers for Go tests

APACHE-2.0 License

Stars
7

testsrv

testsrv is a library for running real HTTP servers in the same process as Go tests, and inspecting the requests that the servers received.

Sample Usage

myHandler := func(w http.ResponseWriter, r *http.Request) {
  w.Write([]byte("Hello Gophers!"))
}
srv := testsrv.StartServer(http.HandlerFunc(myHandler))
defer srv.Close()
resp, err := http.Get(srv.URLStr())
//do something with resp and err

// get the last request that the server received
recv := srv.AcceptN(1, 1 * time.Second)

Possible Uses

Since StartServer takes in any http.Handler it's fairly flexible. Possible applications:

  • Testing your own handlers. For example, in situations where httptest.ResponseRecorder doesn't meet your needs
  • Testing your code that makes its own HTTP requests (for example, an external API call)

Development

To run tests, you can run the following if you have the Go toolchain installed.

go test ./...

But if you have Docker and Docker Compose, you don't need to do that. You can run:

docker-compose -p testsrv up --exit-code-from test --abort-on-container-exit test

If you do the docker-compose command, make sure to clean up afterwards:

docker-compose -p testsrv down
Package Rankings
Top 8.13% on Proxy.golang.org
Badges
Extracted from project README
GoDoc Build Status
Related Projects