httpmock

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Mar 16, 2019 License: MIT Imports: 13 Imported by: 172

README

httpmock Build Status

Easy mocking of http responses from external resources.

Install

Uses gopkg to read from v1 branch:

go get gopkg.in/jarcoal/httpmock.v1

You can also use vendoring for the v1 branch if you feel so inclined.

Currently supports Go 1.7 - 1.12.

Simple Example:
func TestFetchArticles(t *testing.T) {
	httpmock.Activate()
	defer httpmock.DeactivateAndReset()

	httpmock.RegisterResponder("GET", "https://api.mybiz.com/articles.json",
		httpmock.NewStringResponder(200, `[{"id": 1, "name": "My Great Article"}]`))

  // get count info
  httpmock.GetTotalCallCount()

  // get the amount of calls for the registered responder
  info := httpmock.GetCallCountInfo()
  info["GET https://api.mybiz.com/articles.json"] // number of GET calls made to https://api.mybiz.com/articles.json

	// do stuff that makes a request to articles.json
}
Advanced Example:
func TestFetchArticles(t *testing.T) {
	httpmock.Activate()
	defer httpmock.DeactivateAndReset()

	// our database of articles
	articles := make([]map[string]interface{}, 0)

	// mock to list out the articles
	httpmock.RegisterResponder("GET", "https://api.mybiz.com/articles.json",
		func(req *http.Request) (*http.Response, error) {
			resp, err := httpmock.NewJsonResponse(200, articles)
			if err != nil {
				return httpmock.NewStringResponse(500, ""), nil
			}
			return resp, nil
		},
	)

	// mock to add a new article
	httpmock.RegisterResponder("POST", "https://api.mybiz.com/articles.json",
		func(req *http.Request) (*http.Response, error) {
			article := make(map[string]interface{})
			if err := json.NewDecoder(req.Body).Decode(&article); err != nil {
				return httpmock.NewStringResponse(400, ""), nil
			}

			articles = append(articles, article)

			resp, err := httpmock.NewJsonResponse(200, article)
			if err != nil {
				return httpmock.NewStringResponse(500, ""), nil
			}
			return resp, nil
		},
	)

	// do stuff that adds and checks articles
}
Ginkgo Example:
// article_suite_test.go

import (
	// ...
	"github.com/jarcoal/httpmock"
)
// ...
var _ = BeforeSuite(func() {
	// block all HTTP requests
	httpmock.Activate()
})

var _ = BeforeEach(func() {
	// remove any mocks
	httpmock.Reset()
})

var _ = AfterSuite(func() {
	httpmock.DeactivateAndReset()
})


// article_test.go

import (
	// ...
	"github.com/jarcoal/httpmock"
)

var _ = Describe("Articles", func() {
	It("returns a list of articles", func() {
		httpmock.RegisterResponder("GET", "https://api.mybiz.com/articles.json",
			httpmock.NewStringResponder(200, `[{"id": 1, "name": "My Great Article"}]`))

		// do stuff that makes a request to articles.json
	})
})
Ginkgo + Resty Example:
// article_suite_test.go

import (
	// ...
	"github.com/jarcoal/httpmock"
	"github.com/go-resty/resty"
)
// ...
var _ = BeforeSuite(func() {
	// block all HTTP requests
	httpmock.ActivateNonDefault(resty.DefaultClient.GetClient())
})

var _ = BeforeEach(func() {
	// remove any mocks
	httpmock.Reset()
})

var _ = AfterSuite(func() {
	httpmock.DeactivateAndReset()
})


// article_test.go

import (
	// ...
	"github.com/jarcoal/httpmock"
	"github.com/go-resty/resty"
)

var _ = Describe("Articles", func() {
	It("returns a list of articles", func() {
		fixture := `{"status":{"message": "Your message", "code": 200}}`
		responder, err := httpmock.NewJsonResponder(200, fixture)
		fakeUrl := "https://api.mybiz.com/articles.json"
		httpmock.RegisterResponder("GET", fakeUrl, responder)

		// fetch the article into struct
		articleObject := &models.Article{}
		_, err := resty.R().SetResult(articleObject).Get(fakeUrl)
		
		// do stuff with the article object ...
	})
})

Documentation

Overview

Package httpmock provides tools for mocking HTTP responses.

Simple Example:

func TestFetchArticles(t *testing.T) {
	httpmock.Activate()
	defer httpmock.DeactivateAndReset()

	httpmock.RegisterResponder("GET", "https://api.mybiz.com/articles.json",
		httpmock.NewStringResponder(200, `[{"id": 1, "name": "My Great Article"}]`))

	// do stuff that makes a request to articles.json
}

Advanced Example:

func TestFetchArticles(t *testing.T) {
	httpmock.Activate()
	defer httpmock.DeactivateAndReset()

	// our database of articles
	articles := make([]map[string]interface{}, 0)

	// mock to list out the articles
	httpmock.RegisterResponder("GET", "https://api.mybiz.com/articles.json",
		func(req *http.Request) (*http.Response, error) {
			resp, err := httpmock.NewJsonResponse(200, articles)
			if err != nil {
				return httpmock.NewStringResponse(500, ""), nil
			}
			return resp
		},
	)

	// mock to add a new article
	httpmock.RegisterResponder("POST", "https://api.mybiz.com/articles.json",
		func(req *http.Request) (*http.Response, error) {
			article := make(map[string]interface{})
			if err := json.NewDecoder(req.Body).Decode(&article); err != nil {
				return httpmock.NewStringResponse(400, ""), nil
			}

			articles = append(articles, article)

			resp, err := httpmock.NewJsonResponse(200, article)
			if err != nil {
				return httpmock.NewStringResponse(500, ""), nil
			}
			return resp, nil
		},
	)

	// do stuff that adds and checks articles
}

Index

Constants

This section is empty.

Variables

View Source
var DefaultTransport = NewMockTransport()

DefaultTransport is the default mock transport used by Activate, Deactivate, Reset, DeactivateAndReset, RegisterResponder, and RegisterNoResponder.

View Source
var InitialTransport = http.DefaultTransport

InitialTransport is a cache of the original transport used so we can put it back when Deactivate is called.

View Source
var NoResponderFound = errors.New("no responder found") // nolint: golint

NoResponderFound is returned when no responders are found for a given HTTP method and URL.

Functions

func Activate

func Activate()

Activate starts the mock environment. This should be called before your tests run. Under the hood this replaces the Transport on the http.DefaultClient with DefaultTransport.

To enable mocks for a test, simply activate at the beginning of a test:

func TestFetchArticles(t *testing.T) {
	httpmock.Activate()
	// all http requests will now be intercepted
}

If you want all of your tests in a package to be mocked, just call Activate from init():

func init() {
	httpmock.Activate()
}

func ActivateNonDefault

func ActivateNonDefault(client *http.Client)

ActivateNonDefault starts the mock environment with a non-default http.Client. This emulates the Activate function, but allows for custom clients that do not use http.DefaultTransport

To enable mocks for a test using a custom client, activate at the beginning of a test:

client := &http.Client{Transport: &http.Transport{TLSHandshakeTimeout: 60 * time.Second}}
httpmock.ActivateNonDefault(client)

func ConnectionFailure

func ConnectionFailure(*http.Request) (*http.Response, error)

ConnectionFailure is a responder that returns a connection failure. This is the default responder, and is called when no other matching responder is found.

func Deactivate

func Deactivate()

Deactivate shuts down the mock environment. Any HTTP calls made after this will use a live transport.

Usually you'll call it in a defer right after activating the mock environment:

func TestFetchArticles(t *testing.T) {
	httpmock.Activate()
	defer httpmock.Deactivate()

	// when this test ends, the mock environment will close
}

func DeactivateAndReset

func DeactivateAndReset()

DeactivateAndReset is just a convenience method for calling Deactivate() and then Reset() Happy deferring!

func Disabled

func Disabled() bool

Disabled allows to test whether httpmock is enabled or not. It depends on GONOMOCKS environment variable.

func GetCallCountInfo

func GetCallCountInfo() map[string]int

GetCallCountInfo gets the info on all the calls httpmock has taken since it was activated or reset. The info is returned as a map of the calling keys with the number of calls made to them as their value. The key is the method, a space, and the url all concatenated together.

func GetTotalCallCount

func GetTotalCallCount() int

GetTotalCallCount gets the total number of calls httpmock has taken since it was activated or reset.

func NewBytesResponse

func NewBytesResponse(status int, body []byte) *http.Response

NewBytesResponse creates an *http.Response with a body based on the given bytes. Also accepts an http status code.

func NewJsonResponse

func NewJsonResponse(status int, body interface{}) (*http.Response, error)

NewJsonResponse creates an *http.Response with a body that is a json encoded representation of the given interface{}. Also accepts an http status code.

func NewRespBodyFromBytes

func NewRespBodyFromBytes(body []byte) io.ReadCloser

NewRespBodyFromBytes creates an io.ReadCloser from a byte slice that is suitable for use as an http response body.

func NewRespBodyFromString

func NewRespBodyFromString(body string) io.ReadCloser

NewRespBodyFromString creates an io.ReadCloser from a string that is suitable for use as an http response body.

func NewStringResponse

func NewStringResponse(status int, body string) *http.Response

NewStringResponse creates an *http.Response with a body based on the given string. Also accepts an http status code.

func NewXmlResponse

func NewXmlResponse(status int, body interface{}) (*http.Response, error)

NewXmlResponse creates an *http.Response with a body that is an xml encoded representation of the given interface{}. Also accepts an http status code.

func RegisterNoResponder

func RegisterNoResponder(responder Responder)

RegisterNoResponder adds a mock that will be called whenever a request for an unregistered URL is received. The default behavior is to return a connection error.

In some cases you may not want all URLs to be mocked, in which case you can do this:

func TestFetchArticles(t *testing.T) {
	httpmock.Activate()
	httpmock.DeactivateAndReset()
	httpmock.RegisterNoResponder(httpmock.InitialTransport.RoundTrip)

	// any requests that don't have a registered URL will be fetched normally
}

func RegisterResponder

func RegisterResponder(method, url string, responder Responder)

RegisterResponder adds a mock that will catch requests to the given HTTP method and URL (or path), then route them to the Responder which will generate a response to be returned to the client.

Example:

func TestFetchArticles(t *testing.T) {
	httpmock.Activate()
	httpmock.DeactivateAndReset()

	httpmock.RegisterResponder("GET", "http://example.com/",
		httpmock.NewStringResponder(200, "hello world"))

	httpmock.RegisterResponder("GET", "/path/only",
		httpmock.NewStringResponder("any host hello world", 200))

	// requests to http://example.com/ will now return 'hello world' and
	// requests to any host with path /path/only will return 'any host hello world'
}

func RegisterResponderWithQuery

func RegisterResponderWithQuery(method, path string, query interface{}, responder Responder)

RegisterResponderWithQuery it is same as RegisterResponder, but doesn't depends on query items order.

query type can be:

url.Values
map[string]string
string, a query string like "a=12&a=13&b=z&c" (see net/url.ParseQuery function)

If the query type is not recognized or the string cannot be parsed using net/url.ParseQuery, a panic() occurs.

Example using a net/url.Values:

func TestFetchArticles(t *testing.T) {
	httpmock.Activate()
	httpmock.DeactivateAndReset()

	expectedQuery := net.Values{
		"a": []string{"3", "1", "8"},
		"b": []string{"4", "2"},
	}
	httpmock.RegisterResponderWithQueryValues("GET", "http://example.com/", expectedQuery,
		httpmock.NewStringResponder("hello world", 200))

	// requests to http://example.com?a=1&a=3&a=8&b=2&b=4
	//      and to http://example.com?b=4&a=2&b=2&a=8&a=1
	// will now return 'hello world'
}

or using a map[string]string:

func TestFetchArticles(t *testing.T) {
	httpmock.Activate()
	httpmock.DeactivateAndReset()

	expectedQuery := map[string]string{
		"a": "1",
		"b": "2"
	}
	httpmock.RegisterResponderWithQuery("GET", "http://example.com/", expectedQuery,
		httpmock.NewStringResponder("hello world", 200))

	// requests to http://example.com?a=1&b=2 and http://example.com?b=2&a=1 will now return 'hello world'
}

or using a query string:

func TestFetchArticles(t *testing.T) {
	httpmock.Activate()
	httpmock.DeactivateAndReset()

	expectedQuery := "a=3&b=4&b=2&a=1&a=8"
	httpmock.RegisterResponderWithQueryValues("GET", "http://example.com/", expectedQuery,
		httpmock.NewStringResponder("hello world", 200))

	// requests to http://example.com?a=1&a=3&a=8&b=2&b=4
	//      and to http://example.com?b=4&a=2&b=2&a=8&a=1
	// will now return 'hello world'
}

func Reset

func Reset()

Reset will remove any registered mocks and return the mock environment to it's initial state.

Types

type MockTransport

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

MockTransport implements http.RoundTripper, which fulfills single http requests issued by an http.Client. This implementation doesn't actually make the call, instead deferring to the registered list of responders.

func NewMockTransport

func NewMockTransport() *MockTransport

NewMockTransport creates a new *MockTransport with no responders.

func (*MockTransport) CancelRequest

func (m *MockTransport) CancelRequest(req *http.Request)

CancelRequest does nothing with timeout.

func (*MockTransport) GetCallCountInfo

func (m *MockTransport) GetCallCountInfo() map[string]int

GetCallCountInfo returns callCountInfo

func (*MockTransport) GetTotalCallCount

func (m *MockTransport) GetTotalCallCount() int

GetTotalCallCount returns the totalCallCount

func (*MockTransport) RegisterNoResponder

func (m *MockTransport) RegisterNoResponder(responder Responder)

RegisterNoResponder is used to register a responder that will be called if no other responder is found. The default is ConnectionFailure.

func (*MockTransport) RegisterResponder

func (m *MockTransport) RegisterResponder(method, url string, responder Responder)

RegisterResponder adds a new responder, associated with a given HTTP method and URL (or path).

When a request comes in that matches, the responder will be called and the response returned to the client.

If url contains query parameters, their order matters.

func (*MockTransport) RegisterResponderWithQuery

func (m *MockTransport) RegisterResponderWithQuery(method, path string, query interface{}, responder Responder)

RegisterResponderWithQuery is same as RegisterResponder, but it doesn't depend on query items order.

query type can be:

url.Values
map[string]string
string, a query string like "a=12&a=13&b=z&c" (see net/url.ParseQuery function)

If the query type is not recognized or the string cannot be parsed using net/url.ParseQuery, a panic() occurs.

func (*MockTransport) Reset

func (m *MockTransport) Reset()

Reset removes all registered responders (including the no responder) from the MockTransport

func (*MockTransport) RoundTrip

func (m *MockTransport) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip receives HTTP requests and routes them to the appropriate responder. It is required to implement the http.RoundTripper interface. You will not interact with this directly, instead the *http.Client you are using will call it for you.

type Responder

type Responder func(*http.Request) (*http.Response, error)

Responder is a callback that receives and http request and returns a mocked response.

func NewBytesResponder

func NewBytesResponder(status int, body []byte) Responder

NewBytesResponder creates a Responder from a given body (as a byte slice) and status code.

func NewErrorResponder

func NewErrorResponder(err error) Responder

NewErrorResponder creates a Responder that returns an empty request and the given error. This can be used to e.g. imitate more deep http errors for the client.

func NewJsonResponder

func NewJsonResponder(status int, body interface{}) (Responder, error)

NewJsonResponder creates a Responder from a given body (as an interface{} that is encoded to json) and status code.

func NewJsonResponderOrPanic

func NewJsonResponderOrPanic(status int, body interface{}) Responder

NewJsonResponderOrPanic is like NewJsonResponder but panics in case of error.

It simplifies the call of RegisterResponder, avoiding the use of a temporary variable and an error check, and so can be used as NewStringResponder or NewBytesResponder in such context:

RegisterResponder(
  "GET",
  "/test/path",
  NewJSONResponderOrPanic(200, &MyBody),
)

func NewStringResponder

func NewStringResponder(status int, body string) Responder

NewStringResponder creates a Responder from a given body (as a string) and status code.

func NewXmlResponder

func NewXmlResponder(status int, body interface{}) (Responder, error)

NewXmlResponder creates a Responder from a given body (as an interface{} that is encoded to xml) and status code.

func NewXmlResponderOrPanic

func NewXmlResponderOrPanic(status int, body interface{}) Responder

NewXmlResponderOrPanic is like NewXmlResponder but panics in case of error.

It simplifies the call of RegisterResponder, avoiding the use of a temporary variable and an error check, and so can be used as NewStringResponder or NewBytesResponder in such context:

RegisterResponder(
  "GET",
  "/test/path",
  NewXmlResponderOrPanic(200, &MyBody),
)

func ResponderFromResponse

func ResponderFromResponse(resp *http.Response) Responder

ResponderFromResponse wraps an *http.Response in a Responder

Jump to

Keyboard shortcuts

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