gock: github.com/h2non/gock Index | Files

package gock

import "github.com/h2non/gock"

Index

Package Files

gock.go matcher.go matchers.go mock.go request.go responder.go response.go store.go transport.go version.go

Constants

const EOL = 0xa

EOL represents the end of line character.

const Version = "1.0.12"

Version defines the current package semantic version.

Variables

var (
    // DefaultTransport stores the default mock transport used by gock.
    DefaultTransport = NewTransport()

    // NativeTransport stores the native net/http default transport
    // in order to restore it when needed.
    NativeTransport = http.DefaultTransport
)
var BodyTypeAliases = map[string]string{
    "html": "text/html",
    "text": "text/plain",
    "json": "application/json",
    "xml":  "application/xml",
    "form": "multipart/form-data",
    "url":  "application/x-www-form-urlencoded",
}

BodyTypeAliases stores a generic MIME type by alias.

var BodyTypes = []string{
    "text/html",
    "text/plain",
    "application/json",
    "application/xml",
    "multipart/form-data",
    "application/x-www-form-urlencoded",
}

BodyTypes stores the supported MIME body types for matching. Currently only text-based types.

var CompressionSchemes = []string{
    "gzip",
}

CompressionSchemes stores the supported Content-Encoding types for decompression.

var DefaultMatcher = NewMatcher()

DefaultMatcher stores the default Matcher instance used to match mocks.

var (
    // ErrCannotMatch store the error returned in case of no matches.
    ErrCannotMatch = errors.New("gock: cannot match any request")
)
var Matchers = append(MatchersHeader, MatchersBody...)

Matchers stores all the built-in mock matchers.

var MatchersBody = []MatchFunc{
    MatchBody,
}

MatchersBody exposes an slice of HTTP body specific built-in mock matchers.

var MatchersHeader = []MatchFunc{
    MatchMethod,
    MatchScheme,
    MatchHost,
    MatchPath,
    MatchHeaders,
    MatchQueryParams,
}

MatchersHeader exposes an slice of HTTP header specific mock matchers.

func Clean Uses

func Clean()

Clean cleans the mocks store removing disabled or obsolete mocks.

func CleanUnmatchedRequest Uses

func CleanUnmatchedRequest()

CleanUnmatchedRequest cleans the unmatched requests internal registry.

func Disable Uses

func Disable()

Disable disables HTTP traffic interception by gock.

func DisableNetworking Uses

func DisableNetworking()

DisableNetworking disables real HTTP networking

func DisableNetworkingFilters Uses

func DisableNetworkingFilters()

DisableNetworkingFilters disables registered networking filters.

func EnableNetworking Uses

func EnableNetworking()

EnableNetworking enables real HTTP networking

func Exists Uses

func Exists(m Mock) bool

Exists checks if the given Mock is already registered.

func Flush Uses

func Flush()

Flush flushes the current stack of registered mocks.

func GetUnmatchedRequests Uses

func GetUnmatchedRequests() []*http.Request

GetUnmatchedRequests returns all requests that have been received but haven't matched any mock

func HasUnmatchedRequest Uses

func HasUnmatchedRequest() bool

HasUnmatchedRequest returns true if gock has received any requests that didn't match a mock

func Intercept Uses

func Intercept()

Intercept enables HTTP traffic interception via http.DefaultTransport. If you are using a custom HTTP transport, you have to use `gock.Transport()`

func InterceptClient Uses

func InterceptClient(cli *http.Client)

InterceptClient allows the developer to intercept HTTP traffic using a custom http.Client who uses a non default http.Transport/http.RoundTripper implementation.

func Intercepting Uses

func Intercepting() bool

Intercepting returns true if gock is currently able to intercept.

func IsDone Uses

func IsDone() bool

IsDone returns true if all the registered mocks has been triggered successfully.

func IsPending Uses

func IsPending() bool

IsPending returns true if there are pending mocks.

func MatchBody Uses

func MatchBody(req *http.Request, ereq *Request) (bool, error)

MatchBody tries to match the request body. TODO: not too smart now, needs several improvements.

func MatchHeaders Uses

func MatchHeaders(req *http.Request, ereq *Request) (bool, error)

MatchHeaders matches the headers fields of the given request.

func MatchHost Uses

func MatchHost(req *http.Request, ereq *Request) (bool, error)

MatchHost matches the HTTP host header field of the given request.

func MatchMethod Uses

func MatchMethod(req *http.Request, ereq *Request) (bool, error)

MatchMethod matches the HTTP method of the given request.

func MatchPath Uses

func MatchPath(req *http.Request, ereq *Request) (bool, error)

MatchPath matches the HTTP URL path of the given request.

func MatchQueryParams Uses

func MatchQueryParams(req *http.Request, ereq *Request) (bool, error)

MatchQueryParams matches the URL query params fields of the given request.

func MatchScheme Uses

func MatchScheme(req *http.Request, ereq *Request) (bool, error)

MatchScheme matches the request URL protocol scheme.

func NetworkingFilter Uses

func NetworkingFilter(fn FilterRequestFunc)

NetworkingFilter determines if an http.Request should be triggered or not.

func Observe Uses

func Observe(fn ObserverFunc)

Observe provides a hook to support inspection of the request and matched mock

func Off Uses

func Off()

Off disables the default HTTP interceptors and removes all the registered mocks, even if they has not been intercepted yet.

func OffAll Uses

func OffAll()

OffAll is like `Off()`, but it also removes the unmatched requests registry.

func Register Uses

func Register(mock Mock)

Register registers a new mock in the current mocks stack.

func Remove Uses

func Remove(m Mock)

Remove removes a registered mock by reference.

func Responder Uses

func Responder(req *http.Request, mock *Response, res *http.Response) (*http.Response, error)

Responder builds a mock http.Response based on the given Response mock.

func RestoreClient Uses

func RestoreClient(cli *http.Client)

RestoreClient allows the developer to disable and restore the original transport in the given http.Client.

type FilterRequestFunc Uses

type FilterRequestFunc func(*http.Request) bool

FilterRequestFunc represents the required function interface for request filters.

type FilterResponseFunc Uses

type FilterResponseFunc func(*http.Response) bool

FilterResponseFunc represents the required function interface impletemed by response filters.

type MapRequestFunc Uses

type MapRequestFunc func(*http.Request) *http.Request

MapRequestFunc represents the required function interface for request mappers.

type MapResponseFunc Uses

type MapResponseFunc func(*http.Response) *http.Response

MapResponseFunc represents the required function interface impletemed by response mappers.

type MatchFunc Uses

type MatchFunc func(*http.Request, *Request) (bool, error)

MatchFunc represents the required function interface implemented by matchers.

type Matcher Uses

type Matcher interface {
    // Get returns a slice of registered function matchers.
    Get() []MatchFunc

    // Add adds a new matcher function.
    Add(MatchFunc)

    // Set sets the matchers functions stack.
    Set([]MatchFunc)

    // Flush flushes the current matchers function stack.
    Flush()

    // Match matches the given http.Request with a mock Request.
    Match(*http.Request, *Request) (bool, error)
}

Matcher represents the required interface implemented by mock matchers.

type Mock Uses

type Mock interface {
    // Disable disables the current mock manually.
    Disable()

    // Done returns true if the current mock is disabled.
    Done() bool

    // Request returns the mock Request instance.
    Request() *Request

    // Response returns the mock Response instance.
    Response() *Response

    // Match matches the given http.Request with the current mock.
    Match(*http.Request) (bool, error)

    // AddMatcher adds a new matcher function.
    AddMatcher(MatchFunc)

    // SetMatcher uses a new matcher implementation.
    SetMatcher(Matcher)
}

Mock represents the required interface that must be implemented by HTTP mock instances.

func GetAll Uses

func GetAll() []Mock

GetAll returns the current stack of registed mocks.

func MatchMock Uses

func MatchMock(req *http.Request) (Mock, error)

MatchMock is a helper function that matches the given http.Request in the list of registered mocks, returning it if matches or error if it fails.

func Pending Uses

func Pending() []Mock

Pending returns an slice of pending mocks.

type MockMatcher Uses

type MockMatcher struct {
    Matchers []MatchFunc
}

MockMatcher implements a mock matcher

func NewBasicMatcher Uses

func NewBasicMatcher() *MockMatcher

NewBasicMatcher creates a new matcher with header only mock matchers.

func NewEmptyMatcher Uses

func NewEmptyMatcher() *MockMatcher

NewEmptyMatcher creates a new empty matcher with out default amtchers.

func NewMatcher Uses

func NewMatcher() *MockMatcher

NewMatcher creates a new mock matcher using the default matcher functions.

func (*MockMatcher) Add Uses

func (m *MockMatcher) Add(fn MatchFunc)

Add adds a new function matcher.

func (*MockMatcher) Flush Uses

func (m *MockMatcher) Flush()

Flush flushes the current matcher

func (*MockMatcher) Get Uses

func (m *MockMatcher) Get() []MatchFunc

Get returns a slice of registered function matchers.

func (*MockMatcher) Match Uses

func (m *MockMatcher) Match(req *http.Request, ereq *Request) (bool, error)

Match matches the given http.Request with a mock request returning true in case that the request matches, otherwise false.

func (*MockMatcher) Set Uses

func (m *MockMatcher) Set(stack []MatchFunc)

Set sets a new stack of matchers functions.

type Mocker Uses

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

Mocker implements a Mock capable interface providing a default mock configuration used internally to store mocks.

func NewMock Uses

func NewMock(req *Request, res *Response) *Mocker

NewMock creates a new HTTP mock based on the given request and response instances. It's mostly used internally.

func (*Mocker) AddMatcher Uses

func (m *Mocker) AddMatcher(fn MatchFunc)

AddMatcher adds a new matcher function for the current mock expectation.

func (*Mocker) Disable Uses

func (m *Mocker) Disable()

Disable disables the current mock manually.

func (*Mocker) Done Uses

func (m *Mocker) Done() bool

Done returns true in case that the current mock instance is disabled and therefore must be removed.

func (*Mocker) Match Uses

func (m *Mocker) Match(req *http.Request) (bool, error)

Match matches the given http.Request with the current Request mock expectation, returning true if matches.

func (*Mocker) Request Uses

func (m *Mocker) Request() *Request

Request returns the Request instance configured for the current HTTP mock.

func (*Mocker) Response Uses

func (m *Mocker) Response() *Response

Response returns the Response instance configured for the current HTTP mock.

func (*Mocker) SetMatcher Uses

func (m *Mocker) SetMatcher(matcher Matcher)

SetMatcher sets a new matcher implementation for the current mock expectation.

type ObserverFunc Uses

type ObserverFunc func(*http.Request, Mock)

ObserverFunc is implemented by users to inspect the outgoing intercepted HTTP traffic

var DumpRequest ObserverFunc = func(request *http.Request, mock Mock) {
    bytes, _ := httputil.DumpRequestOut(request, true)
    fmt.Println(string(bytes))
    fmt.Printf("\nMatches: %v\n---\n", mock != nil)
}

DumpRequest is a default implementation of ObserverFunc that dumps the HTTP/1.x wire representation of the http request

type Request Uses

type Request struct {
    // Mock stores the parent mock reference for the current request mock used for method delegation.
    Mock Mock

    // Response stores the current Response instance for the current matches Request.
    Response *Response

    // Error stores the latest mock request configuration error.
    Error error

    // Counter stores the pending times that the current mock should be active.
    Counter int

    // Persisted stores if the current mock should be always active.
    Persisted bool

    // URLStruct stores the parsed URL as *url.URL struct.
    URLStruct *url.URL

    // Method stores the Request HTTP method to match.
    Method string

    // CompressionScheme stores the Request Compression scheme to match and use for decompression.
    CompressionScheme string

    // Header stores the HTTP header fields to match.
    Header http.Header

    // Cookies stores the Request HTTP cookies values to match.
    Cookies []*http.Cookie

    // BodyBuffer stores the body data to match.
    BodyBuffer []byte

    // Mappers stores the request functions mappers used for matching.
    Mappers []MapRequestFunc

    // Filters stores the request functions filters used for matching.
    Filters []FilterRequestFunc
}

Request represents the high-level HTTP request used to store request fields used to match intercepted requests.

func New Uses

func New(uri string) *Request

New creates and registers a new HTTP mock with default settings and returns the Request DSL for HTTP mock definition and set up.

func NewRequest Uses

func NewRequest() *Request

NewRequest creates a new Request instance.

func (*Request) AddMatcher Uses

func (r *Request) AddMatcher(fn MatchFunc) *Request

AddMatcher adds a new matcher function to match the request.

func (*Request) Body Uses

func (r *Request) Body(body io.Reader) *Request

Body defines the body data to match based on a io.Reader interface.

func (*Request) BodyString Uses

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

BodyString defines the body to match based on a given string.

func (*Request) Compression Uses

func (r *Request) Compression(scheme string) *Request

Compression defines the request compression scheme, and enables automatic body decompression. Supports only the "gzip" scheme so far.

func (*Request) Delete Uses

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

Delete specifies the DELETE method and the given URL path to match.

func (*Request) EnableNetworking Uses

func (r *Request) EnableNetworking() *Request

EnableNetworking enables the use real networking for the current mock.

func (*Request) File Uses

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

File defines the body to match based on the given file path string.

func (*Request) Filter Uses

func (r *Request) Filter(fn FilterRequestFunc) *Request

Filter filters a new request filter function to filter http.Request before the matching process.

func (*Request) Get Uses

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

Get specifies the GET method and the given URL path to match.

func (*Request) Head Uses

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

Head specifies the HEAD method and the given URL path to match.

func (*Request) HeaderPresent Uses

func (r *Request) HeaderPresent(key string) *Request

HeaderPresent defines that a header field must be present in the request.

func (*Request) JSON Uses

func (r *Request) JSON(data interface{}) *Request

JSON defines the JSON body to match based on a given structure.

func (*Request) Map Uses

func (r *Request) Map(fn MapRequestFunc) *Request

Map adds a new request mapper function to map http.Request before the matching process.

func (*Request) MatchHeader Uses

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

MatchHeader defines a new key and value header to match.

func (*Request) MatchHeaders Uses

func (r *Request) MatchHeaders(headers map[string]string) *Request

MatchHeaders defines a map of key-value headers to match.

func (*Request) MatchParam Uses

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

MatchParam defines a new key and value URL query param to match.

func (*Request) MatchParams Uses

func (r *Request) MatchParams(params map[string]string) *Request

MatchParams defines a map of URL query param key-value to match.

func (*Request) MatchType Uses

func (r *Request) MatchType(kind string) *Request

MatchType defines the request Content-Type MIME header field. Supports type alias. E.g: json, xml, form, text...

func (*Request) ParamPresent Uses

func (r *Request) ParamPresent(key string) *Request

ParamPresent matches if the given query param key is present in the URL.

func (*Request) Patch Uses

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

Patch specifies the PATCH method and the given URL path to match.

func (*Request) Path Uses

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

Path defines the mock URL path value to match.

func (*Request) Persist Uses

func (r *Request) Persist() *Request

Persist defines the current HTTP mock as persistent and won't be removed after intercepting it.

func (*Request) Post Uses

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

Post specifies the POST method and the given URL path to match.

func (*Request) Put Uses

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

Put specifies the PUT method and the given URL path to match.

func (*Request) Reply Uses

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

Reply defines the Response status code and returns the mock Response DSL.

func (*Request) ReplyError Uses

func (r *Request) ReplyError(err error) *Response

ReplyError defines the Response simulated error.

func (*Request) ReplyFunc Uses

func (r *Request) ReplyFunc(replier func(*Response)) *Response

ReplyFunc allows the developer to define the mock response via a custom function.

func (*Request) SetMatcher Uses

func (r *Request) SetMatcher(matcher Matcher) *Request

SetMatcher sets a new matcher function to match the request.

func (*Request) SetURL Uses

func (r *Request) SetURL(u *url.URL) *Request

SetURL defines the url.URL struct to be used for matching.

func (*Request) Times Uses

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

Times defines the number of times that the current HTTP mock should remain active.

func (*Request) URL Uses

func (r *Request) URL(uri string) *Request

URL defines the mock URL to match.

func (*Request) XML Uses

func (r *Request) XML(data interface{}) *Request

XML defines the XML body to match based on a given structure.

type Response Uses

type Response struct {
    // Mock stores the parent mock reference for the current response mock used for method delegation.
    Mock Mock

    // Error stores the latest response configuration or injected error.
    Error error

    // UseNetwork enables the use of real network for the current mock.
    UseNetwork bool

    // StatusCode stores the response status code.
    StatusCode int

    // Headers stores the response headers.
    Header http.Header

    // Cookies stores the response cookie fields.
    Cookies []*http.Cookie

    // BodyBuffer stores the array of bytes to use as body.
    BodyBuffer []byte

    // ResponseDelay stores the simulated response delay.
    ResponseDelay time.Duration

    // Mappers stores the request functions mappers used for matching.
    Mappers []MapResponseFunc

    // Filters stores the request functions filters used for matching.
    Filters []FilterResponseFunc
}

Response represents high-level HTTP fields to configure and define HTTP responses intercepted by gock.

func NewResponse Uses

func NewResponse() *Response

NewResponse creates a new Response.

func (*Response) AddHeader Uses

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

AddHeader adds a new header field in the mock response with out removing an existent one.

func (*Response) Body Uses

func (r *Response) Body(body io.Reader) *Response

Body sets the HTTP response body to be used.

func (*Response) BodyString Uses

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

BodyString defines the response body as string.

func (*Response) Delay Uses

func (r *Response) Delay(delay time.Duration) *Response

Delay defines the response simulated delay. This feature is still experimental and will be improved in the future.

func (*Response) Done Uses

func (r *Response) Done() bool

Done returns true if the mock was done and disabled.

func (*Response) EnableNetworking Uses

func (r *Response) EnableNetworking() *Response

EnableNetworking enables the use real networking for the current mock.

func (*Response) File Uses

func (r *Response) File(path string) *Response

File defines the response body reading the data from disk based on the file path string.

func (*Response) Filter Uses

func (r *Response) Filter(fn FilterResponseFunc) *Response

Filter filters a new request filter function to filter http.Request before the matching process.

func (*Response) JSON Uses

func (r *Response) JSON(data interface{}) *Response

JSON defines the response body based on a JSON based input.

func (*Response) Map Uses

func (r *Response) Map(fn MapResponseFunc) *Response

Map adds a new response mapper function to map http.Response before the matching process.

func (*Response) SetError Uses

func (r *Response) SetError(err error) *Response

SetError defines the response simulated error.

func (*Response) SetHeader Uses

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

SetHeader sets a new header field in the mock response.

func (*Response) SetHeaders Uses

func (r *Response) SetHeaders(headers map[string]string) *Response

SetHeaders sets a map of header fields in the mock response.

func (*Response) Status Uses

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

Status defines the desired HTTP status code to reply in the current response.

func (*Response) Type Uses

func (r *Response) Type(kind string) *Response

Type defines the response Content-Type MIME header field. Supports type alias. E.g: json, xml, form, text...

func (*Response) XML Uses

func (r *Response) XML(data interface{}) *Response

XML defines the response body based on a XML based input.

type Transport Uses

type Transport struct {

    // Transport encapsulates the original http.RoundTripper transport interface for delegation.
    Transport http.RoundTripper
    // contains filtered or unexported fields
}

Transport implements http.RoundTripper, which fulfills single http requests issued by an http.Client.

gock's Transport encapsulates a given or default http.Transport for further delegation, if needed.

func NewTransport Uses

func NewTransport() *Transport

NewTransport creates a new *Transport with no responders.

func (*Transport) CancelRequest Uses

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

CancelRequest is a no-op function.

func (*Transport) RoundTrip Uses

func (m *Transport) 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.

Package gock imports 17 packages (graph) and is imported by 2 packages. Updated 2018-11-13. Refresh now. Tools for package owners.