Overview

Package httptest provides utilities for HTTP testing.

Package files

httptest.go server.go

Constants

DefaultRemoteAddr is the default remote address to return in RemoteAddr if an
explicit DefaultRemoteAddr isn’t set on ResponseRecorder.

  1. func NewRequest(method, target , body io.) *http.

NewRequest returns a new incoming server Request, suitable for passing to an
http.Handler for testing.

The target is the RFC 7230 “request-target”: it may be either a path or an
absolute URL. If target is an absolute URL, the host name from the URL is used.
Otherwise, “example.com” is used.

The TLS field is set to a non-nil dummy value if target has scheme “https”.

The Request.Proto is always HTTP/1.1.

An empty method means “GET”.

The provided body may be nil. If the body is of type bytes.Reader, strings.Reader, or *bytes.Buffer, the Request.ContentLength is set.

NewRequest panics on error for ease of use in testing, where a panic is
acceptable.

To generate a client HTTP request instead of a server request, see the
NewRequest function in the net/http package.

type ResponseRecorder

  1. type ResponseRecorder struct {
  2. // Code is the HTTP response code set by WriteHeader.
  3. //
  4. // Note that if a Handler never calls WriteHeader or Write,
  5. // this might end up being 0, rather than the implicit
  6. // http.StatusOK. To get the implicit value, use the Result
  7. // method.
  8. Code int
  9.  
  10. // HeaderMap contains the headers explicitly set by the Handler.
  11. //
  12. // To get the implicit headers set by the server (such as
  13. // automatic Content-Type), use the Result method.
  14. HeaderMap .Header
  15.  
  16. // If nil, the Writes are silently discarded.
  17. Body *.Buffer
  18.  
  19. // Flushed is whether the Handler called Flush.
  20. Flushed
  21. // contains filtered or unexported fields
  22. }

ResponseRecorder is an implementation of http.ResponseWriter that records its
mutations for later inspection in tests.


Example:

  1. handler := func(w http.ResponseWriter, r *http.Request) {
  2. io.WriteString(w, "<html><body>Hello World!</body></html>")
  3. }
  4. req := httptest.NewRequest("GET", "http://example.com/foo", nil)
  5. w := httptest.NewRecorder()
  6. handler(w, req)
  7. resp := w.Result()
  8. body, _ := ioutil.ReadAll(resp.Body)
  9. fmt.Println(resp.StatusCode)
  10. fmt.Println(resp.Header.Get("Content-Type"))
  11. fmt.Println(string(body))
  12. // Output:
  13. // 200
  14. // <html><body>Hello World!</body></html>

func

  1. func NewRecorder() *

NewRecorder returns an initialized ResponseRecorder.

func (*ResponseRecorder) Flush

  1. func (rw *ResponseRecorder) Flush()

Flush sets rw.Flushed to true.

func (*ResponseRecorder)

  1. func (rw *) Header() http.

Header returns the response headers.

func (*ResponseRecorder) Result

Result returns the response generated by the handler.

The returned Response will have at least its StatusCode, Header, Body, and
optionally Trailer populated. More fields may be populated in the future, so
callers should not DeepEqual the result in tests.

The Response.Header is a snapshot of the headers at the time of the first write
call, or at the time of this call, if the handler never did a write.

The Response.Body is guaranteed to be non-nil and Body.Read call is guaranteed
to not return any error other than io.EOF.

Result must only be called after the handler has finished running.

  1. func (rw *ResponseRecorder) Write(buf []) (int, )

Write always succeeds and writes to rw.Body, if not nil.

func (*ResponseRecorder) WriteHeader

  1. func (rw *ResponseRecorder) WriteHeader(code )

WriteHeader sets rw.Code. After it is called, changing rw.Header will not affect
rw.HeaderMap.

func (*ResponseRecorder) WriteString

  1. func (rw *ResponseRecorder) WriteString(str ) (int, )

WriteString always succeeds and writes to rw.Body, if not nil.

  1. type Server struct {
  2. URL string // base URL of form http://ipaddr:port with no trailing slash
  3. Listener .Listener
  4.  
  5. // TLS is the optional TLS configuration, populated with a new config
  6. // after TLS is started. If set on an unstarted server before StartTLS
  7. // is called, existing fields are copied into the new config.
  8. TLS *.Config
  9.  
  10. // Config may be changed after calling NewUnstartedServer and
  11. // before Start or StartTLS.
  12. // contains filtered or unexported fields
  13. }

A Server is an HTTP server listening on a system-chosen port on the local
loopback interface, for use in end-to-end HTTP tests.


Example:

  1. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  2. fmt.Fprintln(w, "Hello, client")
  3. }))
  4. defer ts.Close()
  5. res, err := http.Get(ts.URL)
  6. if err != nil {
  7. log.Fatal(err)
  8. }
  9. greeting, err := ioutil.ReadAll(res.Body)
  10. res.Body.Close()
  11. if err != nil {
  12. log.Fatal(err)
  13. }
  14. fmt.Printf("%s", greeting)

func NewServer

  1. func NewServer(handler http.) *Server

NewServer starts and returns a new Server. The caller should call Close when
finished, to shut it down.

func

NewTLSServer starts and returns a new Server using TLS. The caller should call
Close when finished, to shut it down.


Example:

  1. ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  2. fmt.Fprintln(w, "Hello, client")
  3. }))
  4. defer ts.Close()
  5. client := ts.Client()
  6. res, err := client.Get(ts.URL)
  7. if err != nil {
  8. log.Fatal(err)
  9. }
  10. greeting, err := ioutil.ReadAll(res.Body)
  11. res.Body.Close()
  12. if err != nil {
  13. log.Fatal(err)
  14. }
  15. // Output: Hello, client

func NewUnstartedServer

  1. func NewUnstartedServer(handler http.) *Server

NewUnstartedServer returns a new Server but doesn’t start it.

After changing its configuration, the caller should call Start or StartTLS.

The caller should call Close when finished, to shut it down.

  1. func (s *) Certificate() *x509.

Certificate returns the certificate used by the server, or nil if the server
doesn’t use TLS.

func (*Server) Client

  1. func (s *Server) Client() *.Client

Client returns an HTTP client configured for making requests to the server. It
is configured to trust the server’s TLS test certificate and will close its idle
connections on Server.Close.

func (*Server)

  1. func (s *) Close()

Close shuts down the server and blocks until all outstanding requests on this
server have completed.

func (*Server) CloseClientConnections

    CloseClientConnections closes any open HTTP connections to the test Server.

    func (*Server) Start

    Start starts a server from NewUnstartedServer.

    func (*Server) StartTLS

    1. func (s *Server) StartTLS()

    StartTLS starts TLS on a server from NewUnstartedServer.