httpmock

package module
v0.6.3 Latest Latest
Warning

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

Go to latest
Published: Apr 29, 2021 License: MIT Imports: 21 Imported by: 0

README

HTTP Mock for Golang

GitHub Releases Build Status codecov Go Report Card GoDevDoc Donate

httpmock is a mock library implementing httptest.Server to support HTTP behavioral tests.

Prerequisites

  • Go >= 1.14

Install

go get github.com/nhatthm/httpmock

Examples

func Test_Simple(t *testing.T) {
	mockServer := httpmock.New(func(s *httpmock.Server) {
		s.Expect(http.MethodGet, "/").
			Return("hello world!")
	})

	s := mockServer(t)

	code, _, body, _ := httpmock.DoRequest(t, http.MethodGet, s.URL+"/", nil, nil)

	expectedCode := http.StatusOK
	expectedBody := []byte(`hello world!`)

	assert.Equal(t, expectedCode, code)
	assert.Equal(t, expectedBody, body)
  
	// Success
}

func Test_CustomResponse(t *testing.T) {
	mockServer := httpmock.New(func(s *httpmock.Server) {
		s.Expect(http.MethodPost, "/create").
			WithHeader("Authorization", "Bearer token").
			WithBody(`{"name":"John Doe"}`).
			After(time.Second).
			ReturnCode(http.StatusCreated)
			ReturnJSON(map[string]interface{}{
				"id":   1,
				"name": "John Doe",
			})
	})

	s := mockServer(t)

	requestHeader := map[string]string{"Authorization": "Bearer token"}
	requestBody := []byte(`{"name":"John Doe"}`)
	code, _, body, _ := httpmock.DoRequestWithTimeout(t, http.MethodPost, s.URL()+"/create", requestHeader, requestBody, time.Second)

	expectedCode := http.StatusCreated
	expectedBody := []byte(`{"id":1,"name":"John Doe"}`)

	assert.Equal(t, expectedCode, code)
	assert.Equal(t, expectedBody, body)

	// Success
}

func Test_ExpectationsWereNotMet(t *testing.T) {
	mockServer := httpmock.New(func(s *httpmock.Server) {
		s.Expect(http.MethodGet, "/").
			Return("hello world!")

		s.Expect(http.MethodPost, "/create").
			WithHeader("Authorization", "Bearer token").
			WithBody(`{"name":"John Doe"}`).
			After(time.Second).
			ReturnJSON(map[string]interface{}{
				"id":   1,
				"name": "John Doe",
			})
	})

	s := mockServer(t)

	code, _, body, _ := httpmock.DoRequest(t, http.MethodGet, s.URL()+"/", nil, nil)

	expectedCode := http.StatusOK
	expectedBody := []byte(`hello world!`)

	assert.Equal(t, expectedCode, code)
	assert.Equal(t, expectedBody, body)
  
	// The test fails with
	// Error:      	Received unexpected error:
	//             	there are remaining expectations that were not met:
	//             	- POST /create
	//             	    with header:
	//             	        Authorization: Bearer token
	//             	    with body
	//             	        {"name":"John Doe"}
}

Donation

If this project help you reduce time to develop, you can give me a cup of coffee :)

Paypal donation

paypal

       or scan this

Documentation

Overview

Package httpmock provides functionalities for mocking http server.

Index

Constants

This section is empty.

Variables

View Source
var ErrUnsupportedDataType = errors.New("unsupported data type")

ErrUnsupportedDataType represents that the data type is not supported.

Functions

func AssertHeaderContains added in v0.4.5

func AssertHeaderContains(t assert.TestingT, headers, contains Header) bool

AssertHeaderContains asserts that the HTTP headers contains some specifics headers.

func DoRequest added in v0.3.0

func DoRequest(
	t *testing.T,
	method, requestURI string,
	headers Header,
	body []byte,
) (int, map[string]string, []byte, time.Duration)

DoRequest calls DoRequestWithTimeout with 1 second timeout. nolint:thelper // It is called in DoRequestWithTimeout.

func DoRequestWithTimeout added in v0.3.0

func DoRequestWithTimeout(
	t *testing.T,
	method, requestURI string,
	headers Header,
	body []byte,
	timeout time.Duration,
) (int, map[string]string, []byte, time.Duration)

DoRequestWithTimeout sends a simple HTTP request for testing and returns the status code, response headers and response body along with the total execution time.

code, headers, body, _ = DoRequestWithTimeout(t, http.MethodGet, "/", nil, nil, 0)

func GetBody

func GetBody(r *http.Request) ([]byte, error)

GetBody returns request body and lets it re-readable.

Types

type CallbackMatch added in v0.6.0

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

CallbackMatch matches by calling a function.

func (*CallbackMatch) Expected added in v0.6.0

func (m *CallbackMatch) Expected() string

Expected returns the expectation.

func (*CallbackMatch) Match added in v0.6.0

func (m *CallbackMatch) Match(actual string) bool

Match determines if the actual is expected.

type ExactMatch added in v0.6.0

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

ExactMatch matches by exact value.

func Exact added in v0.6.0

func Exact(expected string) *ExactMatch

Exact matches two objects by their exact values.

func Exactf added in v0.6.2

func Exactf(format string, args ...interface{}) *ExactMatch

Exactf matches two objects by the formatted expectation.

func (*ExactMatch) Expected added in v0.6.0

func (m *ExactMatch) Expected() string

Expected returns the expectation.

func (*ExactMatch) Match added in v0.6.0

func (m *ExactMatch) Match(actual string) bool

Match determines if the actual is expected.

type Header map[string]string

Header is a list of HTTP headers.

type HeaderMatcher

type HeaderMatcher map[string]Matcher

HeaderMatcher is a list of HTTP headers.

type JSONMatch added in v0.6.0

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

JSONMatch matches by json with <ignore-diff> support.

func JSON added in v0.6.0

func JSON(expected string) *JSONMatch

JSON matches two json objects with <ignore-diff> support.

func (*JSONMatch) Expected added in v0.6.0

func (m *JSONMatch) Expected() string

Expected returns the expectation.

func (*JSONMatch) Match added in v0.6.0

func (m *JSONMatch) Match(actual string) bool

Match determines if the actual is expected.

type Matcher added in v0.6.0

type Matcher interface {
	Match(actual string) bool
	Expected() string
}

Matcher determines if the actual matches the expectation.

func Match added in v0.6.0

func Match(callback func() Matcher) Matcher

Match creates a callback matcher.

func ValueMatcher added in v0.6.0

func ValueMatcher(v interface{}) Matcher

ValueMatcher returns a matcher according to its type.

type Mocker

type Mocker func(t TestingT) *Server

Mocker is a function that applies expectations to the mocked server.

func New

func New(mocks ...func(s *Server)) Mocker

New creates a mocker server with expectations and assures that ExpectationsWereMet() is called.

s := httpmock.New(func(s *Server) {
	s.ExpectPost("/create").
		WithHeader("Authorization", "Bearer token").
		WithBody(`{"foo":"bar"}`).
		ReturnCode(http.StatusCreated).
		Return(`{"id":1,"foo":"bar"}`)
})(t)

code, _, body, _ := httpmock.DoRequest(t,
	http.MethodPost,
	s.URL()+"/create",
	map[string]string{"Authorization": "Bearer token"},
	[]byte(`{"foo":"bar"}`),
)

expectedCode := http.StatusCreated
expectedBody := []byte(`{"id":1,"foo":"bar"}`)

assert.Equal(t, expectedCode, code)
assert.Equal(t, expectedBody, body)

type RegexMatch added in v0.6.0

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

RegexMatch matches by regex.

func Regex added in v0.6.0

func Regex(regexp *regexp.Regexp) *RegexMatch

Regex matches two objects by using regex.

func RegexPattern added in v0.6.0

func RegexPattern(pattern string) *RegexMatch

RegexPattern matches two objects by using regex.

func (*RegexMatch) Expected added in v0.6.0

func (m *RegexMatch) Expected() string

Expected returns the expectation.

func (*RegexMatch) Match added in v0.6.0

func (m *RegexMatch) Match(actual string) bool

Match determines if the actual is expected.

type Request

type Request struct {

	// Method is the expected HTTP Method of the given request.
	Method string
	// RequestURI is the expected HTTP Request URI of the given request.
	// The uri does not need to be exactly same but satisfies the URIMatcher.
	RequestURI Matcher
	// RequestHeader is a list of expected headers of the given request.
	RequestHeader HeaderMatcher
	// RequestBody is the expected body of the given request.
	RequestBody Matcher

	// StatusCode is the response code when the request is handled.
	StatusCode int
	// ResponseHeader is a list of response headers to be sent to client when the request is handled.
	ResponseHeader Header

	// The number of times to return the return arguments when setting
	// expectations. 0 means to always return the value.
	Repeatability int
	// contains filtered or unexported fields
}

Request is an expectation.

func (*Request) After

func (r *Request) After(d time.Duration) *Request

After sets how long to block until the call returns

Server.Expect(http.MethodGet, "/path").
	After(time.Second).
	Return("hello world!")

func (*Request) Handle added in v0.6.3

func (r *Request) Handle(req *http.Request) ([]byte, error)

Handle handles the HTTP request.

func (*Request) Once

func (r *Request) Once() *Request

Once indicates that the mock should only return the value once.

Server.Expect(http.MethodGet, "/path").
	Return("hello world!").
	Once()

func (*Request) Return

func (r *Request) Return(v interface{}) *Request

Return sets the result to return to client.

Server.Expect(http.MethodGet, "/path").
	Return("hello world!")

func (*Request) ReturnCode

func (r *Request) ReturnCode(code int) *Request

ReturnCode sets the response code.

Server.Expect(http.MethodGet, "/path").
	ReturnCode(http.StatusBadRequest)

func (*Request) ReturnFile added in v0.1.1

func (r *Request) ReturnFile(filePath string) *Request

ReturnFile reads the file using ioutil.ReadFile and uses it as the result to return to client.

Server.Expect(http.MethodGet, "/path").
	ReturnFile("resources/fixtures/response.txt")

nolint:unparam

func (*Request) ReturnHeader

func (r *Request) ReturnHeader(header, value string) *Request

ReturnHeader sets a response header.

Server.Expect(http.MethodGet, "/path").
	ReturnHeader("foo", "bar")

func (*Request) ReturnHeaders

func (r *Request) ReturnHeaders(headers Header) *Request

ReturnHeaders sets a list of response headers.

Server.Expect(http.MethodGet, "/path").
	ReturnHeaders(httpmock.Header{"foo": "bar"})

func (*Request) ReturnJSON

func (r *Request) ReturnJSON(body interface{}) *Request

ReturnJSON marshals the object using json.Marshal and uses it as the result to return to client.

Server.Expect(http.MethodGet, "/path").
	ReturnJSON(map[string]string{"foo": "bar"})

func (*Request) Returnf added in v0.1.3

func (r *Request) Returnf(format string, args ...interface{}) *Request

Returnf formats according to a format specifier and use it as the result to return to client.

Server.Expect(http.MethodGet, "/path").
	Returnf("hello %s", "john")

func (*Request) Times

func (r *Request) Times(i int) *Request

Times indicates that the mock should only return the indicated number of times.

Server.Expect(http.MethodGet, "/path").
	Return("hello world!").
	Times(5)

func (*Request) Twice

func (r *Request) Twice() *Request

Twice indicates that the mock should only return the value twice.

Server.Expect(http.MethodGet, "/path").
	Return("hello world!").
	Twice()

func (*Request) UnlimitedTimes added in v0.5.2

func (r *Request) UnlimitedTimes() *Request

UnlimitedTimes indicates that the mock should return the value at least once and there is no max limit in the number of return.

Server.Expect(http.MethodGet, "/path").
	Return("hello world!").
	UnlimitedTimes()

func (*Request) WaitUntil

func (r *Request) WaitUntil(w <-chan time.Time) *Request

WaitUntil sets the channel that will block the mock's return until its closed or a message is received.

Server.Expect(http.MethodGet, "/path").
	WaitUntil(time.After(time.Second)).
	Return("hello world!")

func (*Request) WithBody

func (r *Request) WithBody(body interface{}) *Request

WithBody sets the expected body of the given request. It could be []byte, string, fmt.Stringer, or a Matcher.

Server.Expect(http.MethodGet, "/path").
	WithBody("hello world!")

func (*Request) WithBodyJSON added in v0.1.2

func (r *Request) WithBodyJSON(v interface{}) *Request

WithBodyJSON marshals the object and use it as the expected body of the given request.

Server.Expect(http.MethodGet, "/path").
	WithBodyJSON(map[string]string{"foo": "bar"})

nolint:unparam

func (*Request) WithBodyf added in v0.1.3

func (r *Request) WithBodyf(format string, args ...interface{}) *Request

WithBodyf formats according to a format specifier and use it as the expected body of the given request.

Server.Expect(http.MethodGet, "/path").
	WithBodyf("hello %s", "john)

func (*Request) WithHandler added in v0.5.4

func (r *Request) WithHandler(handler func(r *http.Request) ([]byte, error)) *Request

WithHandler sets the handler to handle a given request.

   Server.Expect(http.MethodGet, "/path").
		WithHandler(func(_ *http.Request) ([]byte, error) {
			return []byte("hello world!"), nil
		})

func (*Request) WithHeader

func (r *Request) WithHeader(header string, value interface{}) *Request

WithHeader sets an expected header of the given request.

Server.Expect(http.MethodGet, "/path").
	WithHeader("foo", "bar")

func (*Request) WithHeaders

func (r *Request) WithHeaders(headers map[string]interface{}) *Request

WithHeaders sets a list of expected headers of the given request.

Server.Expect(http.MethodGet, "/path").
	WithHeaders(map[string]interface{}{"foo": "bar"})

type RequestMatcher

type RequestMatcher func(r *http.Request, expectations []*Request) (*Request, []*Request, error)

RequestMatcher matches a request with one of the expectations.

func SequentialRequestMatcher

func SequentialRequestMatcher() RequestMatcher

SequentialRequestMatcher matches a request in sequence.

type RequestMatcherError

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

RequestMatcherError represents an error that occurs while matching a request.

func MatcherError

func MatcherError(expected *Request, request *http.Request, message string, args ...interface{}) *RequestMatcherError

MatcherError instantiates a new RequestMatcherError.

func (RequestMatcherError) Error

func (e RequestMatcherError) Error() string

Error satisfies the error interface.

type Server

type Server struct {
	// Represents the requests that are expected of a server.
	ExpectedRequests []*Request

	// Holds the requested that were made to this server.
	Requests []Request
	// contains filtered or unexported fields
}

Server is a Mock server.

func MockServer

func MockServer(t TestingT, mocks ...func(s *Server)) *Server

MockServer creates a mocked server.

func NewServer

func NewServer(t TestingT) *Server

NewServer creates mocked server.

func (*Server) Close

func (s *Server) Close()

Close closes mocked server.

func (*Server) Expect

func (s *Server) Expect(method string, requestURI interface{}) *Request

Expect adds a new expected request.

Server.Expect(http.MethodGet, "/path").

func (*Server) ExpectDelete added in v0.3.0

func (s *Server) ExpectDelete(requestURI string) *Request

ExpectDelete adds a new expected http.MethodDelete request.

Server.ExpectDelete("/path")

func (*Server) ExpectGet added in v0.3.0

func (s *Server) ExpectGet(requestURI string) *Request

ExpectGet adds a new expected http.MethodGet request.

Server.ExpectGet("/path")

func (*Server) ExpectHead added in v0.3.0

func (s *Server) ExpectHead(requestURI string) *Request

ExpectHead adds a new expected http.MethodHead request.

Server.ExpectHead("/path")

func (*Server) ExpectPatch added in v0.3.0

func (s *Server) ExpectPatch(requestURI string) *Request

ExpectPatch adds a new expected http.MethodPatch request.

Server.ExpectPatch("/path")

func (*Server) ExpectPost added in v0.3.0

func (s *Server) ExpectPost(requestURI string) *Request

ExpectPost adds a new expected http.MethodPost request.

Server.ExpectPost("/path")

func (*Server) ExpectPut added in v0.3.0

func (s *Server) ExpectPut(requestURI string) *Request

ExpectPut adds a new expected http.MethodPut request.

Server.ExpectPut("/path")

func (*Server) ExpectationsWereMet

func (s *Server) ExpectationsWereMet() error

ExpectationsWereMet checks whether all queued expectations were met in order. If any of them was not met - an error is returned.

func (*Server) ResetExpectations added in v0.4.4

func (s *Server) ResetExpectations()

ResetExpectations resets all the expectations.

func (*Server) ServeHTTP

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

ServeHTTP serves the request.

func (*Server) URL

func (s *Server) URL() string

URL returns the current URL of the httptest.Server.

func (*Server) WithDefaultResponseHeaders

func (s *Server) WithDefaultResponseHeaders(headers Header) *Server

WithDefaultResponseHeaders sets the default response headers of the server.

func (*Server) WithRequestMatcher

func (s *Server) WithRequestMatcher(matcher RequestMatcher) *Server

WithRequestMatcher sets the RequestMatcher of the server.

type TestingT

type TestingT interface {
	Errorf(format string, args ...interface{})
	FailNow()
	Cleanup(func())
}

TestingT is an interface wrapper around *testing.T.

Jump to

Keyboard shortcuts

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