httpmockserver

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Feb 19, 2023 License: MIT Imports: 16 Imported by: 0

README

Go Report Card GitHub license

HTTP Mock Server for golang

HTTP Mock Server provides an easy way to mock external http resources instead mocking your own code in system tests.

TODO

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type IncomingRequest

type IncomingRequest struct {
	R    *http.Request
	Body []byte
}

type MockResponse

type MockResponse struct {
	Code    int
	Headers map[string]string
	Body    []byte
}

type MockServer

type MockServer interface {
	// BaseURL returns the base url of the mock server (default: http://127.0.0.1:<random_port>)
	BaseURL() string
	// ServeHTTP provides direct access to the http handler, normally this is not required
	ServeHTTP(w http.ResponseWriter, r *http.Request)
	// EVERY returns a RequestExpectation that will match on any call
	// (e.g. all requests should have a specific header, or all requests use GET)
	EVERY() RequestExpectation
	// EXPECT returns a RequestExpectation that can be used to create expectations
	// the default number of calls is expected to be exactly one
	// this can be changed by calling a method like: Times, MinTimes, MaxTimes, etc.
	EXPECT() RequestExpectation
	// DEFAULT returns a RequestExpectation that will be executed if no other expectation matches
	DEFAULT() RequestExpectation
	// AssertExpectations should be called to check if all expectations have been met
	AssertExpectations()
	// Shutdown should be called to stop the mock server (should be deferred at the beginning of the test function)
	Shutdown()
}

func New

func New(t T) MockServer

New creates a new mock server running on http://127.0.0.1:<random_port>

func NewWithOpts added in v0.2.0

func NewWithOpts(t T, opts Opts) MockServer

NewWithOpts can be used to create a mock server with custom options

type Opts added in v0.2.0

type Opts struct {
	// Port is the port the mock server will listen on (default: random port)
	Port string
	// UseSSL is used to enable SSL (default: false)
	UseSSL bool
	// Cert is the certificate used for SSL
	Cert io.Reader
	// Key is the key used for SSL
	Key io.Reader
}

Opts is used to configure the mock server it has reasonable defaults

type RequestExpectation

type RequestExpectation interface {
	// AnyTimes expects a given request any number of times (same as MinTimes(0).MaxTimes(∞))
	AnyTimes() RequestExpectation
	// Once expects a given request exactly once (same as Times(1))
	Once() RequestExpectation
	// Twice expects a given request exactly twice (same as Times(2))
	Twice() RequestExpectation
	// AtMostOnce expects a given request at most once (same as MinTimes(0).MaxTimes(1))
	AtMostOnce() RequestExpectation
	// AtLeastOnce expects a given request at least once (same as MinTimes(1).MaxTimes(∞))
	AtLeastOnce() RequestExpectation
	// Times expects a given request exactly n times (same as MinTimes(n).MaxTimes(n))
	Times(n int) RequestExpectation
	// MinTimes expects a given request at least n times (increases MaxTimes to at least n)
	MinTimes(n int) RequestExpectation
	// MaxTimes expects a given request at most n times (decreases MinTimes to at least n)
	MaxTimes(n int) RequestExpectation

	// Request expects a given request with a specific method and path
	Request(method string, path string) RequestExpectation
	// RequestMatches expects a given request with a specific method and path matching a regex (e.g. `^/foo/bar/\d+$`)
	RequestMatches(method string, pathRegex string) RequestExpectation
	// Method expects a given request with a specific method (e.g. GET, POST, PUT, DELETE)
	Method(method string) RequestExpectation
	// Path expects a given request with a specific path (e.g. /foo/bar)
	Path(path string) RequestExpectation
	// PathMatches expects a given request with a path matching a regex (e.g. `^/foo/bar/\d+$`)
	PathMatches(pathRegex string) RequestExpectation

	// GET expects a given request with a GET method
	// use if no path should be matched (otherwise use Get(path))
	GET() RequestExpectation
	// POST expects a given request with a POST method
	// use if no path should be matched (otherwise use Post(path))
	POST() RequestExpectation
	// PUT expects a given request with a PUT method
	// use if no path should be matched (otherwise use Put(path))
	PUT() RequestExpectation
	// DELETE expects a given request with a DELETE method
	// use if no path should be matched (otherwise use Delete(path))
	DELETE() RequestExpectation
	// HEAD expects a given request with a HEAD method
	// use if no path should be matched (otherwise use Head(path))
	HEAD() RequestExpectation

	// Get expects a given request with a GET method and a specific path (e.g. /foo/bar)
	Get(path string) RequestExpectation
	// GetMatches expects a given request with a GET method and a path matching a regex (e.g. `^/foo/bar/\d+$`)
	GetMatches(pathRegex string) RequestExpectation
	// Post expects a given request with a POST method and a specific path (e.g. /foo/bar)
	Post(path string) RequestExpectation
	// PostMatches expects a given request with a POST method and a path matching a regex (e.g. `^/foo/bar/\d+$`)
	PostMatches(pathRegex string) RequestExpectation
	// Put expects a given request with a PUT method and a specific path (e.g. /foo/bar)
	Put(path string) RequestExpectation
	// PutMatches expects a given request with a PUT method and a path matching a regex (e.g. `^/foo/bar/\d+$`)
	PutMatches(pathRegex string) RequestExpectation
	// Delete expects a given request with a DELETE method and a specific path (e.g. /foo/bar)
	Delete(path string) RequestExpectation
	// DeleteMatches expects a given request with a DELETE method and a path matching a regex (e.g. `^/foo/bar/\d+$`)
	DeleteMatches(pathRegex string) RequestExpectation
	// Head expects a given request with a HEAD method and a specific path (e.g. /foo/bar)
	Head(path string) RequestExpectation
	// HeadMatches expects a given request with a HEAD method and a path matching a regex (e.g. `^/foo/bar/\d+$`)
	HeadMatches(pathRegex string) RequestExpectation

	// Header expects a given request with a specific header (e.g. "Content-Type", "application/json")
	Header(name, value string) RequestExpectation
	// HeaderMatches expects a given request with a header matching a regex (e.g. "Content-Type", `^application/(json|xml)$`)
	HeaderMatches(name, valueRegex string) RequestExpectation
	// HeaderExists expects a given request with a specific header (e.g. "Authorization")
	HeaderExists(name string) RequestExpectation
	// Headers expects a given request with specific list of headers
	Headers(map[string]string) RequestExpectation

	// FormParameter expects a given request with a specific form parameter (e.g. "foo", "bar")
	FormParameter(name, value string) RequestExpectation
	// FormParameterMatches expects a given request with a form parameter matching a regex (e.g. "foo", `^bar\d+$`)
	FormParameterMatches(name string, regex string) RequestExpectation
	// FormParameterExists expects a given request with a specific form parameter (e.g. "foo")
	FormParameterExists(name string) RequestExpectation
	// FormParameters expects a given request with specific list of form parameters
	FormParameters(map[string]string) RequestExpectation

	// QueryParameter expects a given request with a specific query parameter (e.g. "?foo=bar")
	QueryParameter(name, value string) RequestExpectation
	// QueryParameterMatches expects a given request with a query parameter matching a regex (e.g. "?foo=`^bar\d+$`)
	QueryParameterMatches(name string, regex string) RequestExpectation
	// QueryParameterExists expects a given request with a specific query parameter (e.g. "foo")
	QueryParameterExists(name string) RequestExpectation
	// QueryParameters expects a given request with specific list of query parameters
	QueryParameters(map[string]string) RequestExpectation

	// BasicAuth expects a given request with a specific basic auth username and password
	BasicAuth(user, password string) RequestExpectation
	// BasicAuthExists expects a given request with basic auth
	BasicAuthExists() RequestExpectation

	// JWTTokenExists expects a given request with a jwt auth token
	JWTTokenExists() RequestExpectation
	// JWTTokenClaimPath expects a given request with a jwt auth token containing a specific claim using jsonPath notation
	// (e.g. `$.foo.bar` for `{"foo":{"bar":"baz"}}`)
	// see: https://github.com/oliveagle/jsonpath
	JWTTokenClaimPath(jsonPath string, value interface{}) RequestExpectation

	// Body expects a given request with a specific body in bytes (e.g. []byte(`{"foo":"bar"}`))
	Body(body []byte) RequestExpectation
	// StringBody expects a given request with a specific body as string (e.g. `{"foo":"bar"}`)
	StringBody(body string) RequestExpectation
	// StringBodyContains expects a given request with a body containing a specific substring (e.g. `foo`)
	StringBodyContains(substring string) RequestExpectation
	// StringBodyMatches expects a given request with a body matching a regex (e.g. `^abcd\d+$`)
	StringBodyMatches(regex string) RequestExpectation
	// JSONBody expects a given request with a specific body.
	// The body can be either a go object that wil be parsed to a json string (e.g. `map[string]string{"foo":"bar"}`)
	// or a json string (e.g. `{"foo":"bar"}`).
	// The body will be normalized (e.g. whitespace will be removed, fields will be sorted) and compared by string equality.
	JSONBody(object interface{}) RequestExpectation
	// JSONPathContains expects a given request with a body containing a specific json value using jsonPath notation
	// see: https://github.com/oliveagle/jsonpath
	JSONPathContains(jsonPath string, value interface{}) RequestExpectation

	// BodyFunc expects a given request with a custom validation function
	// you can use the provided body to do arbitrary validation
	// return nil if the request matched the given requirements
	// if an error is returned, another expectation is tried (or the default expectation is used, if any)
	BodyFunc(func(body []byte) error) RequestExpectation

	// Custom expects a given request with a custom validation function
	// return nil if the request matched the given requirements
	// if an error is returned, another expectation is tried (or the default expectation is used, if any)
	Custom(validation RequestValidationFunc, description string) RequestExpectation

	// Response returns the given status code and switches to response expectation mode
	// where you can specify the response body and headers
	Response(code int) ResponseExpectation
}

RequestExpectation is used to set expectations on incoming requests EVERY(): used to set expectations that are checked on every request EXPECT(): used to set expectations that are checked on a specific request (specified number of times) DEFAULT(): used to set expectations that are checked on a request if no other expectation matches

type RequestValidationFunc

type RequestValidationFunc func(r *IncomingRequest) error

type ResponseExpectation

type ResponseExpectation interface {
	Header(key, value string) ResponseExpectation
	Headers(headers map[string]string) ResponseExpectation
	StringBody(body string) ResponseExpectation
	JsonBody(object interface{}) ResponseExpectation
	Body(data []byte) ResponseExpectation
}

ResponseExpectation is a builder for a MockResponse you may set Headers, Body, and Code on the response this response is returned to the caller when the corresponding request is matched

type T added in v1.0.0

type T interface {
	Fatal(args ...interface{})
	Fatalf(format string, args ...interface{})
	Errorf(format string, args ...interface{})
}

Jump to

Keyboard shortcuts

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