ghttp

package
v0.20.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 26, 2015 License: MIT, Apache-2.0 Imports: 11 Imported by: 0

Documentation

Overview

Package ghttp supports testing HTTP clients by providing a test server (simply a thin wrapper around httptest's server) that supports registering multiple handlers. Incoming requests are not routed between the different handlers - rather it is merely the order of the handlers that matters. The first request is handled by the first registered handler, the second request by the second handler, etc.

The intent here is to have each handler *verify* that the incoming request is valid. To accomplish, ghttp also provides a collection of bite-size handlers that each perform one aspect of request verification. These can be composed together and registered with a ghttp server. The result is an expressive language for describing the requests generated by the client under test.

Here's a simple example, note that the server handler is only defined in one BeforeEach and then modified, as required, by the nested BeforeEaches. A more comprehensive example is available at https://onsi.github.io/gomega/#_testing_http_clients

var _ = Describe("A Sprockets Client", func() {
	var server *ghttp.Server
	var client *SprocketClient
	BeforeEach(func() {
		server = ghttp.NewServer()
		client = NewSprocketClient(server.URL(), "skywalker", "tk427")
	})

	AfterEach(func() {
		server.Close()
	})

	Describe("fetching sprockets", func() {
		var statusCode int
		var sprockets []Sprocket
		BeforeEach(func() {
			statusCode = http.StatusOK
			sprockets = []Sprocket{}
			server.AppendHandlers(ghttp.CombineHandlers(
				ghttp.VerifyRequest("GET", "/sprockets"),
				ghttp.VerifyBasicAuth("skywalker", "tk427"),
				ghttp.RespondWithJSONEncodedPtr(&statusCode, &sprockets),
			))
		})

		Context("when requesting all sprockets", func() {
			Context("when the response is succesful", func() {
				BeforeEach(func() {
					sprockets = []Sprocket{
						NewSprocket("Alfalfa"),
						NewSprocket("Banana"),
					}
				})

				It("should return the returned sprockets", func() {
					Ω(client.Sprockets()).Should(Equal(sprockets))
				})
			})

			Context("when the response is missing", func() {
				BeforeEach(func() {
					statusCode = http.StatusNotFound
				})

				It("should return an empty list of sprockets", func() {
					Ω(client.Sprockets()).Should(BeEmpty())
				})
			})

			Context("when the response fails to authenticate", func() {
				BeforeEach(func() {
					statusCode = http.StatusUnauthorized
				})

				It("should return an AuthenticationError error", func() {
					sprockets, err := client.Sprockets()
					Ω(sprockets).Should(BeEmpty())
					Ω(err).Should(MatchError(AuthenticationError))
				})
			})

			Context("when the response is a server failure", func() {
				BeforeEach(func() {
					statusCode = http.StatusInternalServerError
				})

				It("should return an InternalError error", func() {
					sprockets, err := client.Sprockets()
					Ω(sprockets).Should(BeEmpty())
					Ω(err).Should(MatchError(InternalError))
				})
			})
		})

		Context("when requesting some sprockets", func() {
			BeforeEach(func() {
				sprockets = []Sprocket{
					NewSprocket("Alfalfa"),
					NewSprocket("Banana"),
				}

				server.WrapHandler(0, ghttp.VerifyRequest("GET", "/sprockets", "filter=FOOD"))
			})

			It("should make the request with a filter", func() {
				Ω(client.Sprockets("food")).Should(Equal(sprockets))
			})
		})
	})
})

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CombineHandlers

func CombineHandlers(handlers ...http.HandlerFunc) http.HandlerFunc

CombineHandler takes variadic list of handlers and produces one handler that calls each handler in order.

func RespondWith

func RespondWith(statusCode int, body interface{}, optionalHeader ...http.Header) http.HandlerFunc

RespondWith returns a handler that responds to a request with the specified status code and body

Body may be a string or []byte

Also, RespondWith can be given an optional http.Header. The headers defined therein will be added to the response headers.

func RespondWithJSONEncoded

func RespondWithJSONEncoded(statusCode int, object interface{}, optionalHeader ...http.Header) http.HandlerFunc

RespondWithJSONEncoded returns a handler that responds to a request with the specified status code and a body containing the JSON-encoding of the passed in object

Also, RespondWithJSONEncoded can be given an optional http.Header. The headers defined therein will be added to the response headers.

func RespondWithJSONEncodedPtr

func RespondWithJSONEncodedPtr(statusCode *int, object *interface{}, optionalHeader ...http.Header) http.HandlerFunc

RespondWithJSONEncodedPtr behaves like RespondWithJSONEncoded but takes a pointer to a status code and object.

This allows different tests to share the same setup but specify different status codes and JSON-encoded objects.

Also, RespondWithJSONEncodedPtr can be given an optional http.Header. The headers defined therein will be added to the response headers. Since the http.Header can be mutated after the fact you don't need to pass in a pointer.

func RespondWithPtr

func RespondWithPtr(statusCode *int, body interface{}, optionalHeader ...http.Header) http.HandlerFunc

RespondWithPtr returns a handler that responds to a request with the specified status code and body

Unlike RespondWith, you pass RepondWithPtr a pointer to the status code and body allowing different tests to share the same setup but specify different status codes and bodies.

Also, RespondWithPtr can be given an optional http.Header. The headers defined therein will be added to the response headers. Since the http.Header can be mutated after the fact you don't need to pass in a pointer.

func VerifyBasicAuth

func VerifyBasicAuth(username string, password string) http.HandlerFunc

VerifyBasicAuth returns a handler that verifies the request contains a BasicAuth Authorization header matching the passed in username and password

func VerifyContentType

func VerifyContentType(contentType string) http.HandlerFunc

VerifyContentType returns a handler that verifies that a request has a Content-Type header set to the specified value

func VerifyHeader

func VerifyHeader(header http.Header) http.HandlerFunc

VerifyHeader returns a handler that verifies the request contains the passed in headers. The passed in header keys are first canonicalized via http.CanonicalHeaderKey.

The request must contain *all* the passed in headers, but it is allowed to have additional headers beyond the passed in set.

func VerifyHeaderKV

func VerifyHeaderKV(key string, values ...string) http.HandlerFunc

VerifyHeaderKV returns a handler that verifies the request contains a header matching the passed in key and values (recall that a `http.Header` is a mapping from string (key) to []string (values)) It is a convenience wrapper around `VerifyHeader` that allows you to avoid having to create an `http.Header` object.

func VerifyJSON

func VerifyJSON(expectedJSON string) http.HandlerFunc

VerifyJSON returns a handler that verifies that the body of the request is a valid JSON representation matching the passed in JSON string. It does this using Gomega's MatchJSON method

VerifyJSON also verifies that the request's content type is application/json

func VerifyJSONRepresenting

func VerifyJSONRepresenting(object interface{}) http.HandlerFunc

VerifyJSONRepresenting is similar to VerifyJSON. Instead of taking a JSON string, however, it takes an arbitrary JSON-encodable object and verifies that the requests's body is a JSON representation that matches the object

func VerifyRequest

func VerifyRequest(method string, path interface{}, rawQuery ...string) http.HandlerFunc

VerifyRequest returns a handler that verifies that a request uses the specified method to connect to the specified path You may also pass in an optional rawQuery string which is tested against the request's `req.URL.RawQuery`

For path, you may pass in a string, in which case strict equality will be applied Alternatively you can pass in a matcher (ContainSubstring("/foo") and MatchRegexp("/foo/[a-f0-9]+") for example)

Types

type Server

type Server struct {
	//The underlying httptest server
	HTTPTestServer *httptest.Server

	//Defaults to false.  If set to true, the Server will allow more requests than there are registered handlers.
	AllowUnhandledRequests bool

	//The status code returned when receiving an unhandled request.
	//Defaults to http.StatusInternalServerError.
	//Only applies if AllowUnhandledRequests is true
	UnhandledRequestStatusCode int
	// contains filtered or unexported fields
}

func NewServer

func NewServer() *Server

NewServer returns a new `*ghttp.Server` that wraps an `httptest` server. The server is started automatically.

func NewTLSServer

func NewTLSServer() *Server

NewTLSServer returns a new `*ghttp.Server` that wraps an `httptest` TLS server. The server is started automatically.

func NewUnstartedServer

func NewUnstartedServer() *Server

NewUnstartedServer return a new, unstarted, `*ghttp.Server`. Useful for specifying a custom listener on `server.HTTPTestServer`.

func (*Server) Addr

func (s *Server) Addr() string

Addr() returns the address on which the server is listening.

func (*Server) AppendHandlers

func (s *Server) AppendHandlers(handlers ...http.HandlerFunc)

AppendHandlers will appends http.HandlerFuncs to the server's list of registered handlers. The first incoming request is handled by the first handler, the second by the second, etc...

func (*Server) Close

func (s *Server) Close()

Close() should be called at the end of each test. It spins down and cleans up the test server.

func (*Server) CloseClientConnections

func (s *Server) CloseClientConnections()

func (*Server) GetHandler

func (s *Server) GetHandler(index int) http.HandlerFunc

GetHandler returns the handler registered at the passed in index.

func (*Server) ReceivedRequests

func (s *Server) ReceivedRequests() []*http.Request

ReceivedRequests is an array containing all requests received by the server (both handled and unhandled requests)

func (*Server) RouteToHandler

func (s *Server) RouteToHandler(method string, path interface{}, handler http.HandlerFunc)

RouteToHandler can be used to register handlers that will always handle requests that match the passed in method and path.

The path may be either a string object or a *regexp.Regexp.

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP() makes Server an http.Handler When the server receives a request it handles the request in the following order:

  1. If the request matches a handler registered with RouteToHandler, that handler is called.
  2. Otherwise, if there are handlers registered via AppendHandlers, those handlers are called in order.
  3. If all registered handlers have been called then: a) If AllowUnhandledRequests is true, the request will be handled with response code of UnhandledRequestStatusCode b) If AllowUnhandledRequests is false, the request will not be handled and the current test will be marked as failed.

func (*Server) SetHandler

func (s *Server) SetHandler(index int, handler http.HandlerFunc)

SetHandler overrides the registered handler at the passed in index with the passed in handler This is useful, for example, when a server has been set up in a shared context, but must be tweaked for a particular test.

func (*Server) Start

func (s *Server) Start()

Start() starts an unstarted ghttp server. It is a catastrophic error to call Start more than once (thanks, httptest).

func (*Server) URL

func (s *Server) URL() string

URL() returns a url that will hit the server

func (*Server) WrapHandler

func (s *Server) WrapHandler(index int, handler http.HandlerFunc)

WrapHandler combines the passed in handler with the handler registered at the passed in index. This is useful, for example, when a server has been set up in a shared context but must be tweaked for a particular test.

If the currently registered handler is A, and the new passed in handler is B then WrapHandler will generate a new handler that first calls A, then calls B, and assign it to index

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL