Documentation ¶
Index ¶
- Constants
- Variables
- func Clean()
- func CleanUnmatchedRequest()
- func Disable()
- func DisableNetworking()
- func DisableNetworkingFilters()
- func EnableNetworking()
- func Exists(m Mock) bool
- func Flush()
- func GetUnmatchedRequests() []*http.Request
- func HasUnmatchedRequest() bool
- func Intercept()
- func InterceptClient(cli *http.Client)
- func Intercepting() bool
- func IsDone() bool
- func IsPending() bool
- func MatchBody(req *http.Request, ereq *Request) (bool, error)
- func MatchHeaders(req *http.Request, ereq *Request) (bool, error)
- func MatchHost(req *http.Request, ereq *Request) (bool, error)
- func MatchMethod(req *http.Request, ereq *Request) (bool, error)
- func MatchPath(req *http.Request, ereq *Request) (bool, error)
- func MatchPathParams(req *http.Request, ereq *Request) (bool, error)
- func MatchQueryParams(req *http.Request, ereq *Request) (bool, error)
- func MatchScheme(req *http.Request, ereq *Request) (bool, error)
- func NetworkingFilter(fn FilterRequestFunc)
- func Observe(fn ObserverFunc)
- func Off()
- func OffAll()
- func Register(mock Mock)
- func Remove(m Mock)
- func Responder(req *http.Request, mock *Response, res *http.Response) (*http.Response, error)
- func RestoreClient(cli *http.Client)
- type FilterRequestFunc
- type FilterResponseFunc
- type MapRequestFunc
- type MapResponseFunc
- type MatchFunc
- type Matcher
- type Mock
- type MockMatcher
- type Mocker
- type ObserverFunc
- type Options
- type Request
- func (r *Request) AddMatcher(fn MatchFunc) *Request
- func (r *Request) BasicAuth(username, password string) *Request
- func (r *Request) Body(body io.Reader) *Request
- func (r *Request) BodyString(body string) *Request
- func (r *Request) Compression(scheme string) *Request
- func (r *Request) Delete(path string) *Request
- func (r *Request) EnableNetworking() *Request
- func (r *Request) File(path string) *Request
- func (r *Request) Filter(fn FilterRequestFunc) *Request
- func (r *Request) Get(path string) *Request
- func (r *Request) Head(path string) *Request
- func (r *Request) HeaderPresent(key string) *Request
- func (r *Request) JSON(data interface{}) *Request
- func (r *Request) Map(fn MapRequestFunc) *Request
- func (r *Request) MatchHeader(key, value string) *Request
- func (r *Request) MatchHeaders(headers map[string]string) *Request
- func (r *Request) MatchParam(key, value string) *Request
- func (r *Request) MatchParams(params map[string]string) *Request
- func (r *Request) MatchType(kind string) *Request
- func (r *Request) ParamPresent(key string) *Request
- func (r *Request) Patch(path string) *Request
- func (r *Request) Path(path string) *Request
- func (r *Request) PathParam(key, val string) *Request
- func (r *Request) Persist() *Request
- func (r *Request) Post(path string) *Request
- func (r *Request) Put(path string) *Request
- func (r *Request) Reply(status int) *Response
- func (r *Request) ReplyError(err error) *Response
- func (r *Request) ReplyFunc(replier func(*Response)) *Response
- func (r *Request) SetMatcher(matcher Matcher) *Request
- func (r *Request) SetURL(u *url.URL) *Request
- func (r *Request) Times(num int) *Request
- func (r *Request) URL(uri string) *Request
- func (r *Request) WithOptions(options Options) *Request
- func (r *Request) XML(data interface{}) *Request
- type Response
- func (r *Response) AddHeader(key, value string) *Response
- func (r *Response) Body(body io.Reader) *Response
- func (r *Response) BodyString(body string) *Response
- func (r *Response) Delay(delay time.Duration) *Response
- func (r *Response) Done() bool
- func (r *Response) EnableNetworking() *Response
- func (r *Response) File(path string) *Response
- func (r *Response) Filter(fn FilterResponseFunc) *Response
- func (r *Response) JSON(data interface{}) *Response
- func (r *Response) Map(fn MapResponseFunc) *Response
- func (r *Response) SetError(err error) *Response
- func (r *Response) SetHeader(key, value string) *Response
- func (r *Response) SetHeaders(headers map[string]string) *Response
- func (r *Response) Status(code int) *Response
- func (r *Response) Type(kind string) *Response
- func (r *Response) XML(data interface{}) *Response
- type Transport
Constants ¶
const EOL = 0xa
EOL represents the end of line character.
const Version = "1.2.0"
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, MatchPathParams, }
MatchersHeader exposes an slice of HTTP header specific mock matchers.
Functions ¶
func CleanUnmatchedRequest ¶ added in v1.0.5
func CleanUnmatchedRequest()
CleanUnmatchedRequest cleans the unmatched requests internal registry.
func DisableNetworkingFilters ¶
func DisableNetworkingFilters()
DisableNetworkingFilters disables registered networking filters.
func GetUnmatchedRequests ¶ added in v1.0.3
GetUnmatchedRequests returns all requests that have been received but haven't matched any mock
func HasUnmatchedRequest ¶ added in v1.0.3
func HasUnmatchedRequest() bool
HasUnmatchedRequest returns true if gock has received any requests that didn't match a mock
func Intercept ¶
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 ¶
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 ¶
func Intercepting() bool
Intercepting returns true if gock is currently able to intercept.
func IsDone ¶
func IsDone() bool
IsDone returns true if all the registered mocks has been triggered successfully.
func MatchBody ¶
MatchBody tries to match the request body. TODO: not too smart now, needs several improvements.
func MatchHeaders ¶
MatchHeaders matches the headers fields of the given request.
func MatchMethod ¶
MatchMethod matches the HTTP method of the given request.
func MatchPathParams ¶ added in v1.0.13
MatchPathParams matches the URL path parameters of the given request.
func MatchQueryParams ¶
MatchQueryParams matches the URL query params fields of the given request.
func MatchScheme ¶
MatchScheme matches the request URL protocol scheme.
func NetworkingFilter ¶
func NetworkingFilter(fn FilterRequestFunc)
NetworkingFilter determines if an http.Request should be triggered or not.
func Observe ¶ added in v1.0.11
func Observe(fn ObserverFunc)
Observe provides a hook to support inspection of the request and matched mock
func Off ¶
func Off()
Off disables the default HTTP interceptors and removes all the registered mocks, even if they has not been intercepted yet.
func OffAll ¶ added in v1.0.5
func OffAll()
OffAll is like `Off()`, but it also removes the unmatched requests registry.
func RestoreClient ¶
RestoreClient allows the developer to disable and restore the original transport in the given http.Client.
Types ¶
type FilterRequestFunc ¶
FilterRequestFunc represents the required function interface for request filters.
type FilterResponseFunc ¶
FilterResponseFunc represents the required function interface impletemed by response filters.
type MapRequestFunc ¶
MapRequestFunc represents the required function interface for request mappers.
type MapResponseFunc ¶
MapResponseFunc represents the required function interface impletemed by response mappers.
type Matcher ¶
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 ¶
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.
type MockMatcher ¶
type MockMatcher struct {
Matchers []MatchFunc
}
MockMatcher implements a mock matcher
func NewBasicMatcher ¶
func NewBasicMatcher() *MockMatcher
NewBasicMatcher creates a new matcher with header only mock matchers.
func NewEmptyMatcher ¶
func NewEmptyMatcher() *MockMatcher
NewEmptyMatcher creates a new empty matcher without default matchers.
func NewMatcher ¶
func NewMatcher() *MockMatcher
NewMatcher creates a new mock matcher using the default matcher functions.
func (*MockMatcher) Clone ¶ added in v1.2.0
func (m *MockMatcher) Clone() *MockMatcher
Clone returns a separate MockMatcher instance that has a copy of the same MatcherFuncs
func (*MockMatcher) Get ¶
func (m *MockMatcher) Get() []MatchFunc
Get returns a slice of registered function matchers.
func (*MockMatcher) Match ¶
Match matches the given http.Request with a mock request returning true in case that the request matches, otherwise false.
func (*MockMatcher) Set ¶
func (m *MockMatcher) Set(stack []MatchFunc)
Set sets a new stack of matchers functions.
type Mocker ¶
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 ¶
NewMock creates a new HTTP mock based on the given request and response instances. It's mostly used internally.
func (*Mocker) AddMatcher ¶
AddMatcher adds a new matcher function for the current mock expectation.
func (*Mocker) Done ¶
Done returns true in case that the current mock instance is disabled and therefore must be removed.
func (*Mocker) Match ¶
Match matches the given http.Request with the current Request mock expectation, returning true if matches.
func (*Mocker) Response ¶
Response returns the Response instance configured for the current HTTP mock.
func (*Mocker) SetMatcher ¶
SetMatcher sets a new matcher implementation for the current mock expectation.
type ObserverFunc ¶ added in v1.0.11
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 Options ¶ added in v1.2.0
type Options struct { // DisableRegexpHost stores if the host is only a plain string rather than regular expression, // if DisableRegexpHost is true, host sets in gock.New(...) will be treated as plain string DisableRegexpHost bool }
Options represents customized option for gock
type Request ¶
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 // Options stores options for current Request. Options Options // 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 // PathParams stores the path parameters to match. PathParams map[string]string // 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 ¶
New creates and registers a new HTTP mock with default settings and returns the Request DSL for HTTP mock definition and set up.
func (*Request) AddMatcher ¶
AddMatcher adds a new matcher function to match the request.
func (*Request) BasicAuth ¶ added in v1.2.0
BasicAuth defines a username and password for HTTP Basic Authentication
func (*Request) BodyString ¶
BodyString defines the body to match based on a given string.
func (*Request) Compression ¶ added in v1.0.2
Compression defines the request compression scheme, and enables automatic body decompression. Supports only the "gzip" scheme so far.
func (*Request) EnableNetworking ¶
EnableNetworking enables the use real networking for the current mock.
func (*Request) Filter ¶
func (r *Request) Filter(fn FilterRequestFunc) *Request
Filter filters a new request filter function to filter http.Request before the matching process.
func (*Request) HeaderPresent ¶
HeaderPresent defines that a header field must be present in the request.
func (*Request) Map ¶
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 ¶
MatchHeader defines a new key and value header to match.
func (*Request) MatchHeaders ¶
MatchHeaders defines a map of key-value headers to match.
func (*Request) MatchParam ¶
MatchParam defines a new key and value URL query param to match.
func (*Request) MatchParams ¶
MatchParams defines a map of URL query param key-value to match.
func (*Request) MatchType ¶
MatchType defines the request Content-Type MIME header field. Supports custom MIME types and type aliases. E.g: json, xml, form, text...
func (*Request) ParamPresent ¶
ParamPresent matches if the given query param key is present in the URL.
func (*Request) PathParam ¶ added in v1.0.13
PathParam matches if a given path parameter key is present in the URL.
The value is representative of the restful resource the key defines, e.g.
// /users/123/name r.PathParam("users", "123")
would match.
func (*Request) Persist ¶
Persist defines the current HTTP mock as persistent and won't be removed after intercepting it.
func (*Request) ReplyError ¶
ReplyError defines the Response simulated error.
func (*Request) ReplyFunc ¶
ReplyFunc allows the developer to define the mock response via a custom function.
func (*Request) SetMatcher ¶
SetMatcher sets a new matcher function to match the request.
func (*Request) Times ¶
Times defines the number of times that the current HTTP mock should remain active.
func (*Request) WithOptions ¶ added in v1.2.0
WithOptions sets the options for the request.
type Response ¶
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 (*Response) AddHeader ¶
AddHeader adds a new header field in the mock response with out removing an existent one.
func (*Response) BodyString ¶
BodyString defines the response body as string.
func (*Response) Delay ¶
Delay defines the response simulated delay. This feature is still experimental and will be improved in the future.
func (*Response) EnableNetworking ¶
EnableNetworking enables the use real networking for the current mock.
func (*Response) File ¶
File defines the response body reading the data from disk based on the file path string.
func (*Response) Filter ¶
func (r *Response) Filter(fn FilterResponseFunc) *Response
Filter filters a new request filter function to filter http.Request before the matching process.
func (*Response) Map ¶
func (r *Response) Map(fn MapResponseFunc) *Response
Map adds a new response mapper function to map http.Response before the matching process.
func (*Response) SetHeaders ¶
SetHeaders sets a map of header fields in the mock response.
func (*Response) Status ¶
Status defines the desired HTTP status code to reply in the current response.
type Transport ¶
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 ¶
func NewTransport() *Transport
NewTransport creates a new *Transport with no responders.
func (*Transport) CancelRequest ¶
CancelRequest is a no-op function.
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
_examples
|
|
networking_partially_enabled
This example shows how to enable the networking for a request to a local server and mock a second request to a remote server.
|
This example shows how to enable the networking for a request to a local server and mock a second request to a remote server. |