httpfake

package module
v1.2.4 Latest Latest
Warning

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

Go to latest
Published: Oct 19, 2021 License: MIT Imports: 10 Imported by: 17

README

httpfake

LICENSE Godocs Build Status Coverage Status Go Report Card

httpfake provides is a simple wrapper for httptest with a handful chainable API for setting up handlers to a fake server. This package is aimed to be used in tests where the original external server must not be reached. Instead is used in its place a fake server which can be configured to handle any request as desired.

Installation

go get -u github.com/maxcnunes/httpfake

or

govendor fetch github.com/maxcnunes/httpfake

If possible give preference for using vendor. This way the version is locked up as a dependency in your project.

Changelog

See Releases for detailed history changes.

API

See godoc reference for detailed API documentation.

Assertions

There are built-in methods you can use to make assertions about requests to your HTTP handlers. The currently supported assertions are:

  • Presence of query parameters
  • Query parameter and its expected value
  • Presence of HTTP headers
  • HTTP header and its expected value
  • The expected body of your request

WithTesting must be provided as a server option when creating the test server if you intend to set request assertions. Failing to set the option when using request assertions will result in a panic.

Custom Assertions

You can also provide your own assertions by creating a type that implements the Assertor interface or utilizing the CustomAssertor function type. The Assertor.Log method will be called for each assertion before it's processed. The Assertor.Error method will only be called if the Assertor.Assert method returns an error.

Examples

For a full list of examples please check out the functional_tests folder.

// initialize the faker server
// will bring up a httptest.Server
fakeService := httpfake.New()

// bring down the server once we
// finish running our tests
defer fakeService.Close()

// register a handler for our fake service
fakeService.NewHandler().
  Get("/users").
  Reply(200).
  BodyString(`[{"username": "dreamer"}]`)

// run a real http request to that server
res, err := http.Get(fakeService.ResolveURL("/users"))

Contributing

See the Contributing guide for steps on how to contribute to this project.

Reference

This package was heavily inspired on gock. Check that you if you prefer mocking your requests.

Documentation

Overview

Package httpfake provides a simple wrapper for httptest with a handful chainable API for setting up handlers to a fake server. This package is aimed to be used in tests where the original external server must not be reached. Instead is used in its place a fake server which can be configured to handle any request as desired.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Respond

func Respond(w http.ResponseWriter, r *http.Request, rh *Request)

Respond writes the response based in the request handler settings

Types

type Assertor added in v1.2.0

type Assertor interface {
	Assert(r *http.Request) error
	Log(t testing.TB)
	Error(t testing.TB, err error)
}

Assertor provides an interface for setting assertions for http requests

type CustomAssertor added in v1.2.2

type CustomAssertor func(r *http.Request) error

CustomAssertor provides a function signature that implements the Assertor interface. This allows for adhoc creation of a custom assertion for use with the AssertCustom assertor.

func (CustomAssertor) Assert added in v1.2.2

func (c CustomAssertor) Assert(r *http.Request) error

Assert runs the CustomAssertor assertion against the provided request

func (CustomAssertor) Error added in v1.2.2

func (c CustomAssertor) Error(t testing.TB, err error)

Error prints a testing error for the CustomAssertor

func (CustomAssertor) Log added in v1.2.2

func (c CustomAssertor) Log(t testing.TB)

Log prints a testing info log for the CustomAssertor

type HTTPFake

type HTTPFake struct {
	Server          *httptest.Server
	RequestHandlers []*Request
	// contains filtered or unexported fields
}

HTTPFake is the root struct for the fake server

func New

func New(opts ...ServerOption) *HTTPFake

New starts a httptest.Server as the fake server and sets up the initial configuration to this server's request handlers

func (*HTTPFake) Close added in v1.2.0

func (f *HTTPFake) Close()

Close shuts down the HTTP Test server, this will block until all outstanding requests on the server have completed. If the WithTesting option was specified when setting up the server Close will assert that each http handler specified for this server was called

func (*HTTPFake) NewHandler

func (f *HTTPFake) NewHandler() *Request

NewHandler initializes the configuration for a new request handler

func (*HTTPFake) Reset

func (f *HTTPFake) Reset() *HTTPFake

Reset wipes the request handlers definitions

func (*HTTPFake) ResolveURL

func (f *HTTPFake) ResolveURL(path string, args ...interface{}) string

ResolveURL resolves the full URL to the fake server for a given path

type Request

type Request struct {
	sync.Mutex
	Method       string
	URL          *url.URL
	Response     *Response
	CustomHandle Responder
	// contains filtered or unexported fields
}

Request stores the settings for a request handler Such as how to match this handler for the incoming requests And how this request will respond back

func NewRequest

func NewRequest() *Request

NewRequest creates a new Request

func (*Request) AssertBody added in v1.2.0

func (r *Request) AssertBody(body []byte) *Request

AssertBody will assert that that the provided body matches in the requests to this handler

func (*Request) AssertCustom added in v1.2.0

func (r *Request) AssertCustom(assertor Assertor) *Request

AssertCustom will run the provided assertor against requests to this handler

func (*Request) AssertHeaderValue added in v1.2.0

func (r *Request) AssertHeaderValue(key, value string) *Request

AssertHeaderValue will assert that the provided header key and value are present in the requests to this handler

func (*Request) AssertHeaders added in v1.2.0

func (r *Request) AssertHeaders(keys ...string) *Request

AssertHeaders will assert that the provided header keys are present in the requests to this handler

func (*Request) AssertQueries added in v1.2.0

func (r *Request) AssertQueries(key ...string) *Request

AssertQueries will assert that the provided query parameters are present in the requests to this handler

func (*Request) AssertQueryValue added in v1.2.0

func (r *Request) AssertQueryValue(key, value string) *Request

AssertQueryValue will assert that the provided query parameter and value are present in the requests to this handler

func (*Request) Delete

func (r *Request) Delete(path string) *Request

Delete ...

func (*Request) Get

func (r *Request) Get(path string) *Request

Get sets a GET request handler for a given path

func (*Request) Handle

func (r *Request) Handle(handle Responder)

Handle sets a custom handle By setting this responder it gives full control to the user over this request handler

func (*Request) Head

func (r *Request) Head(path string) *Request

Head sets a HEAD request handler for a given path

func (*Request) Patch

func (r *Request) Patch(path string) *Request

Patch sets a PATCH request handler for a given path

func (*Request) Post

func (r *Request) Post(path string) *Request

Post sets a POST request handler for a given path

func (*Request) Put

func (r *Request) Put(path string) *Request

Put sets a PUT request handler for a given path

func (*Request) Reply

func (r *Request) Reply(status int) *Response

Reply sets a response status for this request And returns the Response struct to allow chaining the response settings

type Responder

type Responder func(w http.ResponseWriter, r *http.Request, rh *Request)

Responder are callbacks to handle the request and write the response

type Response

type Response struct {
	StatusCode int
	BodyBuffer []byte
	Header     http.Header
}

Response stores the settings defined by the request handler of how it will respond the request back

func NewResponse

func NewResponse() *Response

NewResponse creates a new Response

func (*Response) AddHeader

func (r *Response) AddHeader(key, value string) *Response

AddHeader adds a HTTP header into the response

func (*Response) Body added in v1.1.0

func (r *Response) Body(body []byte) *Response

Body sets the response body from a byte array

func (*Response) BodyString

func (r *Response) BodyString(body string) *Response

BodyString sets the response body from a string Example:

BodyString(`[{"username": "dreamer"}]`)

func (*Response) BodyStruct added in v1.1.0

func (r *Response) BodyStruct(body interface{}) *Response

BodyStruct sets the response body from a struct. The provided struct will be marsheled to json internally. Example:

BodyStruct(&entity.User{UserName: "dreamer"})

func (*Response) SetHeader

func (r *Response) SetHeader(key, value string) *Response

SetHeader sets the a HTTP header to the response

func (*Response) Status

func (r *Response) Status(status int) *Response

Status sets the response status

type ServerOption added in v1.2.0

type ServerOption func(opts *ServerOptions)

ServerOption provides a functional signature for providing configuration options to the fake server

func WithTesting added in v1.2.0

func WithTesting(t testing.TB) ServerOption

WithTesting returns a configuration function that allows you to configure the testing object on the fake server. The testing object is utilized for assertions set on the request object and will throw a testing error if an endpoint is not called.

type ServerOptions added in v1.2.0

type ServerOptions struct {
	// contains filtered or unexported fields
}

ServerOptions a configuration object for the fake test server

Jump to

Keyboard shortcuts

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