Documentation ¶
Index ¶
- type Cleanable
- type Config
- type Configurer
- func (cb *Configurer) Addr(addr string) *Configurer
- func (cb *Configurer) Build() Config
- func (cb *Configurer) CORS(options ...cors.Config) *Configurer
- func (cb *Configurer) Context(context context.Context) *Configurer
- func (cb *Configurer) LogVerbosity(l LogVerbosity) *Configurer
- func (cb *Configurer) Middlewares(fn ...func(handler http.Handler) http.Handler) *Configurer
- func (cb *Configurer) RequestBodyParsers(bp ...RequestBodyParser) *Configurer
- func (cb *Configurer) Server(srv Server) *Configurer
- type ConsoleNotifier
- type Expectation
- type LogVerbosity
- type Mocha
- func (m *Mocha) AddMocks(builders ...*MockBuilder) *Scoped
- func (m *Mocha) AssertCalled(t T) bool
- func (m *Mocha) AssertHits(t T, expected int) bool
- func (m *Mocha) AssertNotCalled(t T) bool
- func (m *Mocha) Close() error
- func (m *Mocha) CloseOnCleanup(t Cleanable) *Mocha
- func (m *Mocha) Disable()
- func (m *Mocha) Enable()
- func (m *Mocha) Hits() int
- func (m *Mocha) Parameters() params.P
- func (m *Mocha) Start() ServerInfo
- func (m *Mocha) StartTLS() ServerInfo
- func (m *Mocha) Subscribe(evt hooks.Events)
- func (m *Mocha) URL() string
- type Mock
- type MockBuilder
- func Delete(m expect.Matcher) *MockBuilder
- func Get(m expect.Matcher) *MockBuilder
- func Head(m expect.Matcher) *MockBuilder
- func Options(m expect.Matcher) *MockBuilder
- func Patch(u expect.Matcher) *MockBuilder
- func Post(m expect.Matcher) *MockBuilder
- func Put(m expect.Matcher) *MockBuilder
- func Request() *MockBuilder
- func (b *MockBuilder) Body(matcherList ...expect.Matcher) *MockBuilder
- func (b *MockBuilder) Build() *Mock
- func (b *MockBuilder) FormField(field string, m expect.Matcher) *MockBuilder
- func (b *MockBuilder) Header(key string, m expect.Matcher) *MockBuilder
- func (b *MockBuilder) Method(method string) *MockBuilder
- func (b *MockBuilder) Name(name string) *MockBuilder
- func (b *MockBuilder) PostAction(action PostAction) *MockBuilder
- func (b *MockBuilder) Priority(p int) *MockBuilder
- func (b *MockBuilder) Query(key string, m expect.Matcher) *MockBuilder
- func (b *MockBuilder) Repeat(times int) *MockBuilder
- func (b *MockBuilder) Reply(rep reply.Reply) *MockBuilder
- func (b *MockBuilder) ReplyFunction(fn func(*http.Request, reply.M, params.P) (*reply.Response, error)) *MockBuilder
- func (b *MockBuilder) ReplyJust(status int, r ...*reply.StdReply) *MockBuilder
- func (b *MockBuilder) RequestMatches(m expect.Matcher) *MockBuilder
- func (b *MockBuilder) ScenarioIs(scenario string) *MockBuilder
- func (b *MockBuilder) ScenarioStateIs(requiredState string) *MockBuilder
- func (b *MockBuilder) ScenarioStateWillBe(newState string) *MockBuilder
- func (b *MockBuilder) StartScenario(name string) *MockBuilder
- func (b *MockBuilder) URL(m expect.Matcher) *MockBuilder
- type PostAction
- type PostActionArgs
- type RequestBodyParser
- type Scoped
- func (s *Scoped) AssertCalled(t T) bool
- func (s *Scoped) AssertNotCalled(t T) bool
- func (s *Scoped) Called() bool
- func (s *Scoped) Clean()
- func (s *Scoped) Disable()
- func (s *Scoped) Enable()
- func (s *Scoped) Get(id int) *Mock
- func (s *Scoped) Hits() int
- func (s *Scoped) IsPending() bool
- func (s *Scoped) ListAll() []*Mock
- func (s *Scoped) ListCalled() []*Mock
- func (s *Scoped) ListPending() []*Mock
- type Server
- type ServerInfo
- type T
- type ValueSelector
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Cleanable ¶
type Cleanable interface {
Cleanup(func())
}
Cleanable allows marking mocha instance to be closed on test cleanup.
type Config ¶
type Config struct { // Context to be used internally by Mocha. Context context.Context // Addr defines a custom server address. Addr string // BodyParsers defines request body parsers to be executed before core parsers. BodyParsers []RequestBodyParser // Middlewares defines a list of custom middlewares that will be // set after panic recover and before mock handler. Middlewares []func(http.Handler) http.Handler // CORS defines CORS configurations. CORS cors.Config // Server defines a custom mock HTTP server. Server Server // LogVerbosity defines the level of logs LogVerbosity LogVerbosity // contains filtered or unexported fields }
Config holds Mocha mock server configurations.
type Configurer ¶
type Configurer struct {
// contains filtered or unexported fields
}
Configurer is Config builder, Use this to build Mocha options, instead of creating a new Config struct manually.
func Configure ¶
func Configure() *Configurer
Configure inits a new Configurer. Entrypoint to start a new custom configuration for Mocha mock servers.
func (*Configurer) Addr ¶
func (cb *Configurer) Addr(addr string) *Configurer
Addr sets a custom address for the mock HTTP server.
func (*Configurer) Build ¶
func (cb *Configurer) Build() Config
Build builds a new Config with previously configured values.
func (*Configurer) CORS ¶
func (cb *Configurer) CORS(options ...cors.Config) *Configurer
CORS configures CORS for the mock server.
func (*Configurer) Context ¶
func (cb *Configurer) Context(context context.Context) *Configurer
Context sets a custom context.
func (*Configurer) LogVerbosity ¶
func (cb *Configurer) LogVerbosity(l LogVerbosity) *Configurer
LogVerbosity configure the verbosity of informative logs. Defaults to LogVerbose.
func (*Configurer) Middlewares ¶
func (cb *Configurer) Middlewares(fn ...func(handler http.Handler) http.Handler) *Configurer
Middlewares adds custom middlewares to the mock server. Use this to add custom request interceptors.
func (*Configurer) RequestBodyParsers ¶
func (cb *Configurer) RequestBodyParsers(bp ...RequestBodyParser) *Configurer
RequestBodyParsers adds a custom list of RequestBodyParsers.
func (*Configurer) Server ¶
func (cb *Configurer) Server(srv Server) *Configurer
Server configures a custom HTTP mock Server.
type ConsoleNotifier ¶
type ConsoleNotifier struct { }
ConsoleNotifier implements core.T outputting logs to the stdout.
func (*ConsoleNotifier) Errorf ¶
func (n *ConsoleNotifier) Errorf(format string, args ...any)
func (*ConsoleNotifier) Logf ¶
func (n *ConsoleNotifier) Logf(format string, args ...any)
type Expectation ¶
type Expectation struct { // Target is an optional metadata that describes the target of the matcher. // Example: the target could have the "header", meaning that the matcher will be applied to one request header. Target string // Matcher associated with this Expectation. Matcher expect.Matcher // ValueSelector will extract the http.Request or a portion of it and feed it to the associated Matcher. ValueSelector ValueSelector // Weight of this Expectation. Weight weight }
Expectation holds metadata related to one http.Request Matcher.
type LogVerbosity ¶
type LogVerbosity int
const ( LogSilently LogVerbosity = iota LogVerbose )
Log verbosity enum
type Mocha ¶
type Mocha struct {
// contains filtered or unexported fields
}
Mocha is the base for the mock server.
func New ¶
New creates a new Mocha mock server with the given configurations. Parameter config accepts a Config or a Configurer implementation.
func NewBasic ¶
func NewBasic() *Mocha
NewBasic creates a new Mocha mock server with default configurations.
func (*Mocha) AddMocks ¶
func (m *Mocha) AddMocks(builders ...*MockBuilder) *Scoped
AddMocks adds one or multiple request mocks. It returns a Scoped instance that allows control of the added mocks and also checking if they were called or not. The returned Scoped is useful for tests.
Usage:
scoped := m.AddMocks( Get(expect.URLPath("/test")). Header("test", expect.ToEqual("hello")). Query("filter", expect.ToEqual("all")). Reply(reply.Created().BodyString("hello world"))) assert.True(t, scoped.Called())
func (*Mocha) AssertCalled ¶
AssertCalled asserts that all mocks associated with this instance were called at least once.
func (*Mocha) AssertHits ¶
AssertHits asserts that the sum of request hits for mocks is equal to the given expected value.
func (*Mocha) AssertNotCalled ¶
AssertNotCalled asserts that all mocks associated with this instance were called at least once.
func (*Mocha) CloseOnCleanup ¶
CloseOnCleanup adds mocha server Close to the Cleanup.
func (*Mocha) Parameters ¶
Parameters allows managing custom parameters that will be available inside matchers.
type Mock ¶
type Mock struct { // ID is unique identifier for a Mock ID int // Name is an optional metadata. It helps to find and debug mocks. Name string // Priority sets the priority for a Mock. Priority int // Expectations are a list of Expectation. These will run on every request to find the correct Mock. Expectations []Expectation // Reply is the responder that will be used to serve the HTTP response stub, once matched against an // HTTP request. Reply reply.Reply // Enabled indicates if the Mock is enabled or disabled. Only enabled mocks are matched. Enabled bool // PostActions holds PostAction list to be executed after the Mock was matched and served. PostActions []PostAction // Repeat indicates how many times a mocked response should be served. // If value is equal or lower than zero, it will not be considered. Repeat int ScenarioName string ScenarioState string ScenarioRequiredState string ScenarioNewState string // contains filtered or unexported fields }
Mock holds metadata and expectations to be matched against HTTP requests in order to serve mocked responses. This is core entity of this project, mostly features works based on it.
func (*Mock) Disable ¶
func (m *Mock) Disable()
Disable disables the Mock. The Mock will not be eligible to be matched.
type MockBuilder ¶
type MockBuilder struct {
// contains filtered or unexported fields
}
MockBuilder is a builder for mock.Mock.
func (*MockBuilder) Body ¶
func (b *MockBuilder) Body(matcherList ...expect.Matcher) *MockBuilder
Body adds matchers to the request body. If request contains a JSON body, you can provide multiple matchers to several fields. Example:
m.Body(JSONPath("name", EqualTo("test")), JSONPath("address.street", ToContains("nowhere")))
func (*MockBuilder) Build ¶
func (b *MockBuilder) Build() *Mock
Build builds a mock.Mock with previously configured parameters. Used internally by Mocha.
func (*MockBuilder) FormField ¶
func (b *MockBuilder) FormField(field string, m expect.Matcher) *MockBuilder
FormField defines a matcher for a specific form field by its key.
func (*MockBuilder) Header ¶
func (b *MockBuilder) Header(key string, m expect.Matcher) *MockBuilder
Header adds a matcher to a specific http.Header key.
func (*MockBuilder) Method ¶
func (b *MockBuilder) Method(method string) *MockBuilder
Method sets the HTTP request method to be matched.
func (*MockBuilder) Name ¶
func (b *MockBuilder) Name(name string) *MockBuilder
Name defines a name for the mock. Useful to debug.
func (*MockBuilder) PostAction ¶
func (b *MockBuilder) PostAction(action PostAction) *MockBuilder
PostAction adds a post action to be executed after the mocked response is served.
func (*MockBuilder) Priority ¶
func (b *MockBuilder) Priority(p int) *MockBuilder
Priority sets the priority of the mock. A higher priority will take precedence during request matching.
func (*MockBuilder) Query ¶
func (b *MockBuilder) Query(key string, m expect.Matcher) *MockBuilder
Query defines a matcher to a specific query.
func (*MockBuilder) Repeat ¶
func (b *MockBuilder) Repeat(times int) *MockBuilder
Repeat defines to total times that a mock should be served, if request matches.
func (*MockBuilder) Reply ¶
func (b *MockBuilder) Reply(rep reply.Reply) *MockBuilder
Reply defines a response mock to be served if this mock matches to a request.
func (*MockBuilder) ReplyFunction ¶
func (b *MockBuilder) ReplyFunction(fn func(*http.Request, reply.M, params.P) (*reply.Response, error)) *MockBuilder
ReplyFunction defines a function to will build the response mock.
func (*MockBuilder) ReplyJust ¶
func (b *MockBuilder) ReplyJust(status int, r ...*reply.StdReply) *MockBuilder
ReplyJust sets the mock to return a simple response with the given status code. Optionally, you can provide a reply as well. The status provided in the first parameter will prevail. Only the first reply will be used.
func (*MockBuilder) RequestMatches ¶
func (b *MockBuilder) RequestMatches(m expect.Matcher) *MockBuilder
RequestMatches defines expect.Matcher to be applied to a http.Request.
func (*MockBuilder) ScenarioIs ¶
func (b *MockBuilder) ScenarioIs(scenario string) *MockBuilder
ScenarioIs mark this mock to be used only within the given scenario.
func (*MockBuilder) ScenarioStateIs ¶
func (b *MockBuilder) ScenarioStateIs(requiredState string) *MockBuilder
ScenarioStateIs mark this mock to be served only if the scenario state is equal to the given required state.
func (*MockBuilder) ScenarioStateWillBe ¶
func (b *MockBuilder) ScenarioStateWillBe(newState string) *MockBuilder
ScenarioStateWillBe defines the state of the scenario after this mock is matched, making the scenario flow continue.
func (*MockBuilder) StartScenario ¶
func (b *MockBuilder) StartScenario(name string) *MockBuilder
StartScenario sets that this mock will start a new scenario with the given name.
func (*MockBuilder) URL ¶
func (b *MockBuilder) URL(m expect.Matcher) *MockBuilder
URL defines a matcher to be applied to the http.Request url.URL.
type PostAction ¶
type PostAction interface { // Run runs the PostAction implementation. Run(args PostActionArgs) error }
PostAction defines the contract for an action that will be executed after serving a mocked HTTP response.
type PostActionArgs ¶
type PostActionArgs struct { Request *http.Request Response *reply.Response Mock *Mock Params params.P }
PostActionArgs represents the arguments that will be passed to every PostAction implementation
type RequestBodyParser ¶
type RequestBodyParser interface { // CanParse checks if current request body should be parsed by this component. // First parameter is the incoming content-type. CanParse(contentType string, r *http.Request) bool // Parse parses the request body. Parse(body []byte, r *http.Request) (any, error) }
RequestBodyParser parses request body if CanParse returns true. Multiple implementations of RequestBodyParser can be provided to Mocha using options.
type Scoped ¶
type Scoped struct {
// contains filtered or unexported fields
}
Scoped holds references to one or more added mocks allowing users perform operations on them, like enabling/disabling.
func (*Scoped) AssertCalled ¶
AssertCalled reports an error if there are still pending mocks.
func (*Scoped) AssertNotCalled ¶
AssertNotCalled reports an error if any mock was called.
func (*Scoped) Disable ¶
func (s *Scoped) Disable()
Disable scoped mocks. Disabled mocks will be ignored.
func (*Scoped) IsPending ¶
IsPending returns true when there are one or more mocks that were not called at least once.
func (*Scoped) ListCalled ¶
ListCalled returns all mocks that were called.
func (*Scoped) ListPending ¶
ListPending returns all mocks that were not called at least once.
type Server ¶
type Server interface { // Configure configures the HTTP mock. // It is the first method called by Mocha during initialization. Configure(Config, http.Handler) error // Start starts a server. Start() (ServerInfo, error) // StartTLS starts a TLS server. StartTLS() (ServerInfo, error) // Close the server. Close() error // Info returns server information. Info() ServerInfo }
Server defines HTTP mock server operations.
type ServerInfo ¶
type ServerInfo struct {
URL string
}
ServerInfo holds HTTP server information, like its URL.
type T ¶
T is based on testing.T and allow mocha components to log information and errors.
func NewConsoleNotifier ¶
func NewConsoleNotifier() T
NewConsoleNotifier returns a core.T implementation that logs to the stdout. FailNow() and Helper() will do nothing.
type ValueSelector ¶
type ValueSelector func(r *expect.RequestInfo) any
ValueSelector defines a function that will be used to extract RequestInfo value and provide it to Matcher instances.
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
_examples
|
|
Package cors implements functions to enable cross-origin resource sharing support for the mock server.
|
Package cors implements functions to enable cross-origin resource sharing support for the mock server. |
Package expect implements several Matcher functions to facilitate matching HTTP request parameters.
|
Package expect implements several Matcher functions to facilitate matching HTTP request parameters. |
Package hooks implements event listeners for mocha internal actions.
|
Package hooks implements event listeners for mocha internal actions. |
internal
|
|
colorize
Package colorize contains functions to stylize texts for terminal.
|
Package colorize contains functions to stylize texts for terminal. |
headers
Package headers contains common headers used internally.
|
Package headers contains common headers used internally. |
jsonx
Package jsonx implements functions to get JSON property values by their path.
|
Package jsonx implements functions to get JSON property values by their path. |
middleware
Package middleware contains utilities to handle middlewares and also common middlewares used internally by Mocha.
|
Package middleware contains utilities to handle middlewares and also common middlewares used internally by Mocha. |
mimetypes
Package mimetypes contains common mime types used internally by Mocha.
|
Package mimetypes contains common mime types used internally by Mocha. |
testutil
Package testutil contains internal test utilities.
|
Package testutil contains internal test utilities. |
Package params implements a simple in-memory key/value store, used internally by Mocha.
|
Package params implements a simple in-memory key/value store, used internally by Mocha. |
Package reply implements different response definition builders.
|
Package reply implements different response definition builders. |