mockhttpclient

package
v0.0.0-...-e00d976 Latest Latest
Warning

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

Go to latest
Published: Dec 18, 2024 License: BSD-3-Clause Imports: 17 Imported by: 4

Documentation

Index

Constants

View Source
const (
	TEST_FAILED_STATUS_CODE = 599
)

Variables

View Source
var DONT_CARE_REQUEST = []byte{0, 1, 2, 3, 4}

Functions

func HostMatcher

func HostMatcher(host string) func(http.Handler) http.Handler

HostMatcher is a middleware that returns 404 if the request does not match the given host.

func MuxSafeT

func MuxSafeT(orig expect.TestingT) require.TestingT

MuxSafeT wraps *testing.T to allow using the assert package (aka require package) within handler functions of the mux.Router passed to MuxClient. This is necessary because some users of http.Client behave badly when runtime.Goexit() (called by testing.T.FailNow) occurs during a request.

The documentation for testing.T.FailNow states "FailNow must be called from the goroutine running the test or benchmark function, not from other goroutines created during the test," so if the http.Client returned from MuxClient is used by a different goroutine, you should use MuxSafeT to ensure the test doesn't hang.

func New

func New(urlMap map[string]MockDialogue) *http.Client

New returns a new mocked HTTPClient.

func NewMuxClient

func NewMuxClient(r chi.Router) *http.Client

NewMuxClient returns an http.Client instance which sends requests to the given mux.Router.

NewMuxClient is more flexible than using httptest.NewServer because the returned client can accept requests for any scheme or host. It is more flexible than URLMock because it allows handling arbitrary URLs with arbitrary handlers. However, it is more difficult to use than URLMock when the same request URL should be handled differently on subsequent requests.

TODO(benjaminwagner): NewMuxClient does not currently support streaming responses, but does support streaming requests.

Examples:

// Mock out a URL to always respond with the same body.
r := chi.NewRouter()
r.With(SchemeMatcher("https"), HostMatcher("www.google.com")).
	Get("/", MockGetDialogue([]byte("Here's a response.")).ServeHTTP)
client := NewMuxClient(r)
res, _ := client.Get("https://www.google.com")
respBody, _ := io.ReadAll(res.Body)  // respBody == []byte("Here's a response.")

// Check that the client uses the correct ID in the request.
r.With(HostMatcher("example.com"), QueryMatcher("name", "foo", "size", "42")).
	Post("/add/{id:[a-zA-Z0-9]+}", func(w http.ResponseWriter, r *http.Request) {
	t := MuxSafeT(t)
	assert.Equal(t, chi.URLParam(r, "id"), values.Get("name"))
})

func QueryMatcher

func QueryMatcher(pairs ...string) func(http.Handler) http.Handler

QueryMatcher is a middleware that returns 404 if the request does not have the given key/value pairs in the query string. For example, QueryMatcher("name", "foo", "size", "42") would match "example.com/hello?name=foo&size=42" but it wouldn't match "example.com/hello?name=bar&length=123".

func SchemeMatcher

func SchemeMatcher(scheme string) func(http.Handler) http.Handler

SchemeMatcher is a middleware that returns 404 if the request does not match the given scheme.

Types

type MockDialogue

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

func MockDeleteDialogueWithResponseCode

func MockDeleteDialogueWithResponseCode(requestType string, requestBody, responseBody []byte, responseCode int) MockDialogue

func MockGetDialogue

func MockGetDialogue(responseBody []byte) MockDialogue

func MockGetDialogueWithResponseHeaders

func MockGetDialogueWithResponseHeaders(responseBody []byte, responseHeaders map[string][]string) MockDialogue

func MockGetError

func MockGetError(responseStatus string, responseCode int) MockDialogue

func MockGetWithRequestDialogue

func MockGetWithRequestDialogue(requestType string, requestBody, responseBody []byte) MockDialogue

func MockPatchDialogue

func MockPatchDialogue(requestType string, requestBody, responseBody []byte) MockDialogue

func MockPostDialogue

func MockPostDialogue(requestType string, requestBody, responseBody []byte) MockDialogue

func MockPostDialogueWithResponseCode

func MockPostDialogueWithResponseCode(requestType string, requestBody, responseBody []byte, responseCode int) MockDialogue

func MockPostError

func MockPostError(requestType string, requestBody []byte, responseStatus string, responseCode int) MockDialogue

func MockPutDialogue

func MockPutDialogue(requestType string, requestBody, responseBody []byte) MockDialogue

func (*MockDialogue) GetResponse

func (md *MockDialogue) GetResponse(r *http.Request) (*http.Response, error)

func (*MockDialogue) RequestHeader

func (md *MockDialogue) RequestHeader(key, value string)

RequestHeader adds the given header to the request.

func (*MockDialogue) ResponseHeader

func (md *MockDialogue) ResponseHeader(key, value string)

ResponseHeader adds the given header to the response.

func (MockDialogue) ServeHTTP

func (md MockDialogue) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler.

type URLMock

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

URLMock implements http.RoundTripper but returns mocked responses. It provides two methods for mocking responses to requests for particular URLs:

  • Mock: Adds a fake response for the given URL to be used every time a request is made for that URL.

  • MockOnce: Adds a fake response for the given URL to be used one time. MockOnce may be called multiple times for the same URL in order to simulate the response changing over time. Takes precedence over mocks specified using Mock.

Examples:

// Mock out a URL to always respond with the same body.
m := NewURLMock()
m.Mock("https://www.google.com", MockGetDialogue([]byte("Here's a response.")))
res, _ := m.Client().Get("https://www.google.com")
respBody, _ := io.ReadAll(res.Body)  // respBody == []byte("Here's a response.")

// Mock out a URL to give different responses.
m.MockOnce("https://www.google.com", MockGetDialogue([]byte("hi")))
m.MockOnce("https://www.google.com", MockGetDialogue([]byte("Second response.")))
res1, _ := m.Client().Get("https://www.google.com")
body1, _ := io.ReadAll(res1.Body)  // body1 == []byte("hi")
res2, _ := m.Client().Get("https://www.google.com")
body2, _ := io.ReadAll(res2.Body)  // body2 == []byte("Second response.")
// Fall back on the value previously set using Mock():
res3, _ := m.Client().Get("https://www.google.com")
body3, _ := io.ReadAll(res3.Body)  // body3 == []byte("Here's a response.")

func NewURLMock

func NewURLMock() *URLMock

NewURLMock returns an empty URLMock instance.

func (*URLMock) Client

func (m *URLMock) Client() *http.Client

Client returns an http.Client instance which uses the URLMock.

func (*URLMock) Empty

func (m *URLMock) Empty() bool

Empty returns true iff all of the URLs registered via MockOnce() have been used.

func (*URLMock) List

func (m *URLMock) List() []string

List returns the list of all URLs registered via MockOnce.

func (*URLMock) Mock

func (m *URLMock) Mock(url string, md MockDialogue)

Mock adds a mocked response for the given URL; whenever this URLMock is used as a transport for an http.Client, requests to the given URL will always receive the given body in their responses. Mocks specified using Mock() are independent of those specified using MockOnce(), except that those specified using MockOnce() take precedence when present.

func (*URLMock) MockOnce

func (m *URLMock) MockOnce(url string, md MockDialogue)

MockOnce adds a mocked response for the given URL, to be used exactly once. Mocks are stored in a FIFO queue and removed from the queue as they are requested. Therefore, multiple requests to the same URL must each correspond to a call to MockOnce, in the same order that the requests will be made. Mocks specified this way are independent of those specified using Mock(), except that those specified using MockOnce() take precedence when present.

func (*URLMock) RoundTrip

func (m *URLMock) RoundTrip(r *http.Request) (*http.Response, error)

RoundTrip is an implementation of http.RoundTripper.RoundTrip. It fakes responses for requests to URLs based on past calls to Mock() and MockOnce().

Jump to

Keyboard shortcuts

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