wiremock

package module
v1.9.0 Latest Latest
Warning

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

Go to latest
Published: Mar 26, 2024 License: MIT Imports: 8 Imported by: 1

README

go-wiremock

GoDoc Actions Status Slack Go Report Card

Go WireMock Logo

The Golang client library to stub API resources in WireMock using its REST API. The project connects to the instance and allows setting up stubs and response templating, or using administrative API to extract observability data.

Learn more: Golang & WireMock Solutions page

Documentation

GoDoc

Compatibility

The library was tested with the following distributions of WireMock:

  • WireMock 2.x - standalone deployments, including but not limited to official Docker images, Helm charts and the Java executable
  • WireMock 3.x Beta - partial support, some features are yet to be implemented. Contributions are welcome!
  • WireMock Cloud - proprietary SaaS edition by WireMock Inc.

Note that the CI pipelines run only against the official community distributions of WireMock. It may work for custom builds and other distributions. Should there be any issues, contact their vendors/maintainers.

Usage

Launch a standalone Docker instance:

docker run -it --rm -p 8080:8080 wiremock/wiremock

Connect to it using the client library:

package main

import (
    "net/http"
    "testing"

    "github.com/wiremock/go-wiremock"
)

func TestSome(t *testing.T) {
    wiremockClient := wiremock.NewClient("http://0.0.0.0:8080")
    defer wiremockClient.Reset()

    // stubbing POST http://0.0.0.0:8080/example
    wiremockClient.StubFor(wiremock.Post(wiremock.URLPathEqualTo("/example")).
        WithQueryParam("firstName", wiremock.EqualTo("John")).
        WithQueryParam("lastName", wiremock.NotMatching("Black")).
        WithBodyPattern(wiremock.EqualToJson(`{"meta": "information"}`)).
        WithHeader("x-session", wiremock.Matching("^\\S+fingerprint\\S+$")).
        WithBearerToken(wiremock.StartsWith("token")).
        WillReturnResponse(
            wiremock.NewResponse().
                WithJSONBody(map[string]interface{}{
                    "code":   400,
                    "detail": "detail",
                }).
                WithHeader("Content-Type", "application/json").
                WithStatus(http.StatusBadRequest),
        ).
        AtPriority(1))

    // scenario
    defer wiremockClient.ResetAllScenarios()
    wiremockClient.StubFor(wiremock.Get(wiremock.URLPathEqualTo("/status")).
        WillReturnResponse(
            wiremock.NewResponse().
                WithJSONBody(map[string]interface{}{
                    "status": nil,
                }).
                WithHeader("Content-Type", "application/json").
                WithStatus(http.StatusOK),
        ).
        InScenario("Set status").
        WhenScenarioStateIs(wiremock.ScenarioStateStarted))

    wiremockClient.StubFor(wiremock.Post(wiremock.URLPathEqualTo("/state")).
        WithBodyPattern(wiremock.EqualToJson(`{"status": "started"}`)).
        InScenario("Set status").
        WillSetStateTo("Status started"))

    statusStub := wiremock.Get(wiremock.URLPathEqualTo("/status")).
        WillReturnResponse(
            wiremock.NewResponse().
                WithJSONBody(map[string]interface{}{
                    "status": "started",
                }).
                WithHeader("Content-Type", "application/json").
                WithStatus(http.StatusOK),
        ).
        InScenario("Set status").
        WhenScenarioStateIs("Status started")
    wiremockClient.StubFor(statusStub)

    //testing code...

    verifyResult, _ := wiremockClient.Verify(statusStub.Request(), 1)
    if !verifyResult {
        //...
    }

    wiremockClient.DeleteStub(statusStub)
}

Support for Authentication Schemes

The library provides support for common authentication schemes, i.e.: Basic Authentication, API Token Authentication, Bearer Authentication, Digest Access Authentication. All of them are equivalent to manually specifying the "Authorization" header value with the appropriate prefix. E.g. WithBearerToken(wiremock.EqualTo("token123")). works the same as WithHeader("Authorization", wiremock.EqualTo("Bearer token123"))..

Example of usage

basicAuthStub := wiremock.Get(wiremock.URLPathEqualTo("/basic")).
    WithBasicAuth("username", "password"). // same as: WithHeader("Authorization", wiremock.EqualTo("Basic dXNlcm5hbWU6cGFzc3dvcmQ=")).
    WillReturnResponse(wiremock.NewResponse().WithStatus(http.StatusOK))

bearerTokenStub := wiremock.Get(wiremock.URLPathEqualTo("/bearer")).
    WithBearerToken(wiremock.Matching("^\\S+abc\\S+$")). // same as: WithHeader("Authorization", wiremock.Matching("^Bearer \\S+abc\\S+$")).
    WillReturnResponse(wiremock.NewResponse().WithStatus(http.StatusOK))

apiTokenStub := wiremock.Get(wiremock.URLPathEqualTo("/token")).
    WithAuthToken(wiremock.StartsWith("myToken123")). // same as: WithHeader("Authorization", wiremock.StartsWith("Token myToken123")).
    WillReturnResponse(wiremock.NewResponse().WithStatus(http.StatusOK))

digestAuthStub := wiremock.Get(wiremock.URLPathEqualTo("/digest")).
    WithDigestAuth(wiremock.Contains("realm")). // same as: WithHeader("Authorization", wiremock.StartsWith("Digest ").And(Contains("realm"))).
    WillReturnResponse(wiremock.NewResponse().WithStatus(http.StatusOK))

License

MIT License

See also

Documentation

Overview

Package wiremock is client for WireMock API. WireMock is a simulator for HTTP-based APIs. Some might consider it a service virtualization tool or a mock server.

HTTP request:

POST /example?firstName=John&lastName=Any string other than "Gray" HTTP/1.1
Host: 0.0.0.0:8080
x-session: somefingerprintsome
Content-Type: application/json
Content-Length: 23

{"meta": "information"}

With response:

Status: 400 Bad Request
"Content-Type": "application/json"
{"code": 400, "detail": "detail"}

Stub:

client := wiremock.NewClient("http://0.0.0.0:8080")
client.StubFor(wiremock.Post(wiremock.URLPathEqualTo("/example")).
	WithQueryParam("firstName", wiremock.EqualTo("John")).
	WithQueryParam("lastName", wiremock.NotMatching("Gray")).
	WithBodyPattern(wiremock.EqualToJson(`{"meta": "information"}`)).
	WithHeader("x-session", wiremock.Matching("^\\S+fingerprint\\S+$")).
	WillReturnResponse(
		wiremock.NewResponse().
			WithStatus(http.StatusBadRequest).
			WithHeader("Content-Type", "application/json").
			WithBody(`{"code": 400, "detail": "detail"}`),
	).
	AtPriority(1))

The client should reset all made stubs after tests:

client := wiremock.NewClient("http://0.0.0.0:8080")
defer wiremock.Reset()
client.StubFor(wiremock.Get(wiremock.URLPathEqualTo("/example")))
client.StubFor(wiremock.Get(wiremock.URLPathEqualTo("/example/1")))
// ...

To avoid conflicts, you can delete individual rules:

client := wiremock.NewClient("http://0.0.0.0:8080")
exampleStubRule := wiremock.Get(wiremock.URLPathEqualTo("/example"))
client.StubFor(exampleStubRule)
client.StubFor(wiremock.Get(wiremock.URLPathEqualTo("/example/1")))
// ...
client.DeleteStub(exampleStubRule)

You can verify if a request has been made that matches the mapping.

client := wiremock.NewClient("http://0.0.0.0:8080")
exampleStubRule := wiremock.Get(wiremock.URLPathEqualTo("/example"))
client.StubFor(exampleStubRule)
// ...
client.Verify(exampleStubRule.Request(), 1)

Index

Constants

View Source
const (
	MultipartMatchingTypeAny = "ANY"
	MultipartMatchingTypeAll = "ALL"
)
View Source
const ScenarioStateStarted = "Started"

Variables

This section is empty.

Functions

This section is empty.

Types

type BasicParamMatcher

type BasicParamMatcher interface {
	json.Marshaler
	ParseMatcher() map[string]interface{}
	Or(stringMatcher BasicParamMatcher) BasicParamMatcher
	And(stringMatcher BasicParamMatcher) BasicParamMatcher
}

func Absent

func Absent() BasicParamMatcher

Absent returns a matcher that matches when the parameter is absent.

func Contains

func Contains(param string) BasicParamMatcher

Contains returns a matcher that matches when the parameter contains the specified value.

func EqualTo

func EqualTo(value string) BasicParamMatcher

EqualTo returns a matcher that matches when the parameter equals the specified value.

func EqualToIgnoreCase

func EqualToIgnoreCase(value string) BasicParamMatcher

EqualToIgnoreCase returns a matcher that matches when the parameter equals the specified value, ignoring case.

func EqualToJson

func EqualToJson(param string, equalJsonFlags ...EqualFlag) BasicParamMatcher

EqualToJson returns a matcher that matches when the parameter is equal to the specified JSON.

func EqualToXml

func EqualToXml(param string) BasicParamMatcher

EqualToXml returns a matcher that matches when the parameter is equal to the specified XML.

func Matching

func Matching(param string) BasicParamMatcher

Matching returns a matcher that matches when the parameter matches the specified regular expression.

func MatchingJsonPath

func MatchingJsonPath(param string) BasicParamMatcher

MatchingJsonPath returns a matcher that matches when the parameter matches the specified JSON path.

func MatchingXPath

func MatchingXPath(param string) BasicParamMatcher

MatchingXPath returns a matcher that matches when the parameter matches the specified XPath.

func NotContains

func NotContains(param string) BasicParamMatcher

NotContains returns a matcher that matches when the parameter does not contain the specified value.

func NotMatching

func NotMatching(param string) BasicParamMatcher

NotMatching returns a matcher that matches when the parameter does not match the specified regular expression.

func StartsWith added in v1.8.0

func StartsWith(prefix string) BasicParamMatcher

StartsWith returns a matcher that matches when the parameter starts with the specified prefix. Matches also when prefix alone is the whole expression

type Client

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

A Client implements requests to the wiremock server.

func NewClient

func NewClient(url string) *Client

NewClient returns *Client.

func (*Client) Clear

func (c *Client) Clear() error

Clear deletes all stub mappings.

func (*Client) DeleteStub

func (c *Client) DeleteStub(s *StubRule) error

DeleteStub deletes stub mapping.

func (*Client) DeleteStubByID

func (c *Client) DeleteStubByID(id string) error

DeleteStubByID deletes stub by id.

func (*Client) GetCountRequests

func (c *Client) GetCountRequests(r *Request) (int64, error)

GetCountRequests gives count requests by criteria.

func (*Client) Reset

func (c *Client) Reset() error

Reset restores stub mappings to the defaults defined back in the backing store.

func (*Client) ResetAllScenarios

func (c *Client) ResetAllScenarios() error

ResetAllScenarios resets back to start of the state of all configured scenarios.

func (*Client) StubFor

func (c *Client) StubFor(stubRule *StubRule) error

StubFor creates a new stub mapping.

func (*Client) Verify

func (c *Client) Verify(r *Request, expectedCount int64) (bool, error)

Verify checks count of request sent.

type DelayInterface

type DelayInterface interface {
	ParseDelay() map[string]interface{}
}

func NewFixedDelay

func NewFixedDelay(delay time.Duration) DelayInterface

func NewLogNormalRandomDelay

func NewLogNormalRandomDelay(median time.Duration, sigma float64) DelayInterface

func NewUniformRandomDelay

func NewUniformRandomDelay(lower, upper time.Duration) DelayInterface

type EqualFlag

type EqualFlag string

EqualFlag is enum of less strict matching flag.

const (
	IgnoreArrayOrder    EqualFlag = "ignoreArrayOrder"
	IgnoreExtraElements EqualFlag = "ignoreExtraElements"
)

Type of less strict matching flags.

type Fault

type Fault string
const (
	FaultEmptyResponse          Fault = "EMPTY_RESPONSE"
	FaultMalformedResponseChunk Fault = "MALFORMED_RESPONSE_CHUNK"
	FaultRandomDataThenClose    Fault = "RANDOM_DATA_THEN_CLOSE"
	FaultConnectionResetByPeer  Fault = "CONNECTION_RESET_BY_PEER"
)

type LogicalMatcher

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

func And

func And(matchers ...BasicParamMatcher) LogicalMatcher

And returns a logical AND of the list of matchers.

func Or

func Or(matchers ...BasicParamMatcher) LogicalMatcher

Or returns a logical OR of the list of matchers.

func (LogicalMatcher) And

And returns a logical AND of the current matcher and the given matcher.

func (LogicalMatcher) MarshalJSON

func (m LogicalMatcher) MarshalJSON() ([]byte, error)

MarshalJSON returns the JSON encoding of the matcher.

func (LogicalMatcher) Or

Or returns a logical OR of the current matcher and the given matcher.

func (LogicalMatcher) ParseMatcher

func (m LogicalMatcher) ParseMatcher() map[string]interface{}

ParseMatcher returns the map representation of the structure.

type MatcherInterface

type MatcherInterface interface {
	json.Marshaler
	ParseMatcher() map[string]interface{}
}

type MultiValueMatcher

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

func HasExactly

func HasExactly(matchers ...BasicParamMatcher) MultiValueMatcher

HasExactly returns a matcher that matches when the parameter has exactly the specified values.

func Includes

func Includes(matchers ...BasicParamMatcher) MultiValueMatcher

Includes returns a matcher that matches when the parameter includes the specified values.

func (MultiValueMatcher) MarshalJSON

func (m MultiValueMatcher) MarshalJSON() ([]byte, error)

MarshalJSON returns the JSON encoding of the matcher.

func (MultiValueMatcher) ParseMatcher

func (m MultiValueMatcher) ParseMatcher() map[string]interface{}

ParseMatcher returns the map representation of the structure.

type MultiValueMatchingStrategy

type MultiValueMatchingStrategy string

MultiValueMatchingStrategy is enum multi value matching type.

const (
	ParamHasExactly MultiValueMatchingStrategy = "hasExactly"
	ParamIncludes   MultiValueMatchingStrategy = "includes"
)

type MultipartMatchingType

type MultipartMatchingType string

type MultipartPattern

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

func NewMultipartPattern

func NewMultipartPattern() *MultipartPattern

func (*MultipartPattern) MarshalJSON

func (m *MultipartPattern) MarshalJSON() ([]byte, error)

MarshalJSON gives valid JSON or error.

func (*MultipartPattern) ParseMultipartPattern

func (m *MultipartPattern) ParseMultipartPattern() map[string]interface{}

func (*MultipartPattern) WithAllMatchingType

func (m *MultipartPattern) WithAllMatchingType() *MultipartPattern

func (*MultipartPattern) WithAnyMatchingType

func (m *MultipartPattern) WithAnyMatchingType() *MultipartPattern

func (*MultipartPattern) WithBodyPattern

func (m *MultipartPattern) WithBodyPattern(matcher BasicParamMatcher) *MultipartPattern

func (*MultipartPattern) WithHeader

func (m *MultipartPattern) WithHeader(header string, matcher MatcherInterface) *MultipartPattern

func (*MultipartPattern) WithMatchingType

func (m *MultipartPattern) WithMatchingType(matchingType MultipartMatchingType) *MultipartPattern

func (*MultipartPattern) WithName

func (m *MultipartPattern) WithName(name string) *MultipartPattern

type MultipartPatternInterface

type MultipartPatternInterface interface {
	json.Marshaler
	ParseMultipartPattern() map[string]interface{}
}

type ParamMatchingStrategy

type ParamMatchingStrategy string

ParamMatchingStrategy is enum params matching type.

const (
	ParamEqualTo         ParamMatchingStrategy = "equalTo"
	ParamMatches         ParamMatchingStrategy = "matches"
	ParamContains        ParamMatchingStrategy = "contains"
	ParamEqualToXml      ParamMatchingStrategy = "equalToXml"
	ParamEqualToJson     ParamMatchingStrategy = "equalToJson"
	ParamMatchesXPath    ParamMatchingStrategy = "matchesXPath"
	ParamMatchesJsonPath ParamMatchingStrategy = "matchesJsonPath"
	ParamAbsent          ParamMatchingStrategy = "absent"
	ParamDoesNotMatch    ParamMatchingStrategy = "doesNotMatch"
	ParamDoesNotContains ParamMatchingStrategy = "doesNotContain"
)

Types of params matching.

type Request

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

A Request is the part of StubRule describing the matching of the http request

func NewRequest

func NewRequest(method string, urlMatcher URLMatcherInterface) *Request

NewRequest constructs minimum possible Request

func (*Request) MarshalJSON

func (r *Request) MarshalJSON() ([]byte, error)

MarshalJSON gives valid JSON or error.

func (*Request) WithBasicAuth

func (r *Request) WithBasicAuth(username, password string) *Request

WithBasicAuth adds basic auth credentials to Request

func (*Request) WithBodyPattern

func (r *Request) WithBodyPattern(matcher BasicParamMatcher) *Request

WithBodyPattern adds body pattern to list

func (*Request) WithCookie

func (r *Request) WithCookie(cookie string, matcher BasicParamMatcher) *Request

WithCookie is fluent-setter for cookie

func (*Request) WithFormParameter added in v1.9.0

func (r *Request) WithFormParameter(name string, matcher BasicParamMatcher) *Request

WithFormParameter adds form parameter to list

func (*Request) WithHeader

func (r *Request) WithHeader(header string, matcher MatcherInterface) *Request

WithHeader add header to header list

func (*Request) WithHost

func (r *Request) WithHost(host BasicParamMatcher) *Request

WithHost is fluent-setter for host

func (*Request) WithMethod

func (r *Request) WithMethod(method string) *Request

WithMethod is fluent-setter for http verb

func (*Request) WithMultipartPattern

func (r *Request) WithMultipartPattern(pattern *MultipartPattern) *Request

WithMultipartPattern adds multipart pattern to list

func (*Request) WithPort

func (r *Request) WithPort(port int64) *Request

WithPort is fluent-setter for port

func (*Request) WithQueryParam

func (r *Request) WithQueryParam(param string, matcher MatcherInterface) *Request

WithQueryParam add param to query param list

func (*Request) WithScheme

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

WithScheme is fluent-setter for scheme

func (*Request) WithURLMatched

func (r *Request) WithURLMatched(urlMatcher URLMatcherInterface) *Request

WithURLMatched is fluent-setter url matcher

type Response

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

func NewResponse

func NewResponse() Response

func (Response) ParseResponse

func (r Response) ParseResponse() map[string]interface{}

func (Response) WithBinaryBody

func (r Response) WithBinaryBody(body []byte) Response

WithBinaryBody sets binary body for response

func (Response) WithBody

func (r Response) WithBody(body string) Response

WithBody sets body for response

func (Response) WithBodyFile

func (r Response) WithBodyFile(fileName string) Response

WithBodyFile sets body file name for response

func (Response) WithChunkedDribbleDelay

func (r Response) WithChunkedDribbleDelay(numberOfChunks int64, totalDuration time.Duration) Response

WithChunkedDribbleDelay sets chunked dribble delay for response

func (Response) WithDelay

func (r Response) WithDelay(delay DelayInterface) Response

WithDelay sets delay for response

func (Response) WithFault

func (r Response) WithFault(fault Fault) Response

func (Response) WithFixedDelay

func (r Response) WithFixedDelay(delay time.Duration) Response

WithFixedDelay sets fixed delay milliseconds for response

func (Response) WithHeader

func (r Response) WithHeader(key, value string) Response

WithHeader sets header for response

func (Response) WithHeaders

func (r Response) WithHeaders(headers map[string]string) Response

WithHeaders sets headers for response

func (Response) WithJSONBody

func (r Response) WithJSONBody(body interface{}) Response

WithJSONBody sets json body for response

func (Response) WithLogNormalRandomDelay

func (r Response) WithLogNormalRandomDelay(median time.Duration, sigma float64) Response

WithLogNormalRandomDelay sets log normal random delay for response

func (Response) WithStatus

func (r Response) WithStatus(status int64) Response

WithStatus sets status for response

func (Response) WithUniformRandomDelay

func (r Response) WithUniformRandomDelay(lower, upper time.Duration) Response

WithUniformRandomDelay sets uniform random delay for response

type ResponseInterface

type ResponseInterface interface {
	ParseResponse() map[string]interface{}
}

type StringValueMatcher

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

func NewStringValueMatcher

func NewStringValueMatcher(strategy ParamMatchingStrategy, value string, flags ...string) StringValueMatcher

NewStringValueMatcher creates a new StringValueMatcher.

func (StringValueMatcher) And

And returns a logical AND of the two matchers.

func (StringValueMatcher) MarshalJSON

func (m StringValueMatcher) MarshalJSON() ([]byte, error)

MarshalJSON returns the JSON encoding of the matcher.

func (StringValueMatcher) Or

Or returns a logical OR of the two matchers.

func (StringValueMatcher) ParseMatcher

func (m StringValueMatcher) ParseMatcher() map[string]interface{}

ParseMatcher returns the map representation of the structure.

type StubRule

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

StubRule is struct of http Request body to WireMock

func Delete

func Delete(urlMatchingPair URLMatcher) *StubRule

Delete returns *StubRule for DELETE method.

func Get

func Get(urlMatchingPair URLMatcher) *StubRule

Get returns *StubRule for GET method.

func NewStubRule

func NewStubRule(method string, urlMatcher URLMatcher) *StubRule

NewStubRule returns a new *StubRule.

func Patch

func Patch(urlMatchingPair URLMatcher) *StubRule

Patch returns *StubRule for PATCH method.

func Post

func Post(urlMatchingPair URLMatcher) *StubRule

Post returns *StubRule for POST method.

func Put

func Put(urlMatchingPair URLMatcher) *StubRule

Put returns *StubRule for PUT method.

func (*StubRule) AtPriority

func (s *StubRule) AtPriority(priority int64) *StubRule

AtPriority sets priority and returns *StubRule

func (*StubRule) InScenario

func (s *StubRule) InScenario(scenarioName string) *StubRule

InScenario sets scenarioName and returns *StubRule

func (*StubRule) MarshalJSON

func (s *StubRule) MarshalJSON() ([]byte, error)

MarshalJSON makes json body for http Request

func (*StubRule) Request

func (s *StubRule) Request() *Request

Request is getter for Request

func (*StubRule) UUID

func (s *StubRule) UUID() string

UUID is getter for uuid

func (*StubRule) WhenScenarioStateIs

func (s *StubRule) WhenScenarioStateIs(scenarioState string) *StubRule

WhenScenarioStateIs sets requiredScenarioState and returns *StubRule

func (*StubRule) WillReturn deprecated

func (s *StubRule) WillReturn(body string, headers map[string]string, status int64) *StubRule

Deprecated: Use WillReturnResponse(NewResponse().WithBody(body).WithHeaders(headers).WithStatus(status)) instead WillReturn sets response and returns *StubRule

func (*StubRule) WillReturnBinary deprecated

func (s *StubRule) WillReturnBinary(body []byte, headers map[string]string, status int64) *StubRule

Deprecated: Use WillReturnResponse(NewResponse().WithBinaryBody(body).WithHeaders(headers).WithStatus(status)) instead WillReturnBinary sets response with binary body and returns *StubRule

func (*StubRule) WillReturnFileContent deprecated

func (s *StubRule) WillReturnFileContent(bodyFileName string, headers map[string]string, status int64) *StubRule

Deprecated: Use WillReturnResponse(NewResponse().WithBodyFile(file).WithHeaders(headers).WithStatus(status)) instead WillReturnFileContent sets response with some file content and returns *StubRule

func (*StubRule) WillReturnJSON deprecated

func (s *StubRule) WillReturnJSON(json interface{}, headers map[string]string, status int64) *StubRule

Deprecated: Use WillReturnResponse(NewResponse().WithJsonBody(json).WithHeaders(headers).WithStatus(status)) instead WillReturnJSON sets response with json body and returns *StubRule

func (*StubRule) WillReturnResponse

func (s *StubRule) WillReturnResponse(response ResponseInterface) *StubRule

WillReturnResponse sets response and returns *StubRule

func (*StubRule) WillSetStateTo

func (s *StubRule) WillSetStateTo(scenarioState string) *StubRule

WillSetStateTo sets newScenarioState and returns *StubRule

func (*StubRule) WithAuthToken added in v1.8.0

func (s *StubRule) WithAuthToken(tokenMatcher BasicParamMatcher) *StubRule

WithAuthToken adds Authorization header with Token auth method *StubRule

func (*StubRule) WithBasicAuth

func (s *StubRule) WithBasicAuth(username, password string) *StubRule

WithBasicAuth adds basic auth credentials

func (*StubRule) WithBearerToken added in v1.8.0

func (s *StubRule) WithBearerToken(tokenMatcher BasicParamMatcher) *StubRule

WithBearerToken adds Authorization header with Bearer auth method *StubRule

func (*StubRule) WithBodyPattern

func (s *StubRule) WithBodyPattern(matcher BasicParamMatcher) *StubRule

WithBodyPattern adds body pattern and returns *StubRule

func (*StubRule) WithCookie

func (s *StubRule) WithCookie(cookie string, matcher BasicParamMatcher) *StubRule

WithCookie adds cookie and returns *StubRule

func (*StubRule) WithDigestAuth added in v1.8.0

func (s *StubRule) WithDigestAuth(matcher BasicParamMatcher) *StubRule

WithDigestAuth adds Authorization header with Digest auth method *StubRule

func (*StubRule) WithFixedDelayMilliseconds deprecated

func (s *StubRule) WithFixedDelayMilliseconds(delay time.Duration) *StubRule

Deprecated: Use WillReturnResponse(NewResponse().WithFixedDelay(time.Second)) instead WithFixedDelayMilliseconds adds delay to response and returns *StubRule

func (*StubRule) WithFormParameter added in v1.9.0

func (s *StubRule) WithFormParameter(param string, matcher BasicParamMatcher) *StubRule

WithFormParameter adds form parameter and returns *StubRule

func (*StubRule) WithHeader

func (s *StubRule) WithHeader(header string, matcher MatcherInterface) *StubRule

WithHeader adds header to Headers and returns *StubRule

func (*StubRule) WithHost

func (s *StubRule) WithHost(host BasicParamMatcher) *StubRule

WithHost adds host and returns *StubRule

func (*StubRule) WithMultipartPattern

func (s *StubRule) WithMultipartPattern(pattern *MultipartPattern) *StubRule

WithMultipartPattern adds multipart body pattern and returns *StubRule

func (*StubRule) WithPort

func (s *StubRule) WithPort(port int64) *StubRule

WithPort adds port and returns *StubRule

func (*StubRule) WithPostServeAction

func (s *StubRule) WithPostServeAction(extensionName string, webhook WebhookInterface) *StubRule

func (*StubRule) WithQueryParam

func (s *StubRule) WithQueryParam(param string, matcher MatcherInterface) *StubRule

WithQueryParam adds query param and returns *StubRule

func (*StubRule) WithScheme

func (s *StubRule) WithScheme(scheme string) *StubRule

WithScheme adds scheme and returns *StubRule

type URLMatcher

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

URLMatcher is structure for defining the type of url matching.

func URLEqualTo

func URLEqualTo(url string) URLMatcher

URLEqualTo returns URLMatcher with URLEqualToRule matching strategy.

func URLMatching

func URLMatching(url string) URLMatcher

URLMatching returns URLMatcher with URLMatchingRule matching strategy.

func URLPathEqualTo

func URLPathEqualTo(url string) URLMatcher

URLPathEqualTo returns URLMatcher with URLPathEqualToRule matching strategy.

func URLPathMatching

func URLPathMatching(url string) URLMatcher

URLPathMatching returns URLMatcher with URLPathMatchingRule matching strategy.

func (URLMatcher) Strategy

func (m URLMatcher) Strategy() URLMatchingStrategy

Strategy returns URLMatchingStrategy of URLMatcher.

func (URLMatcher) Value

func (m URLMatcher) Value() string

Value returns value of URLMatcher.

type URLMatcherInterface

type URLMatcherInterface interface {
	Strategy() URLMatchingStrategy
	Value() string
}

URLMatcherInterface is pair URLMatchingStrategy and string matched value

type URLMatchingStrategy

type URLMatchingStrategy string

URLMatchingStrategy is enum url matching type.

const (
	URLEqualToRule      URLMatchingStrategy = "url"
	URLPathEqualToRule  URLMatchingStrategy = "urlPath"
	URLPathMatchingRule URLMatchingStrategy = "urlPathPattern"
	URLMatchingRule     URLMatchingStrategy = "urlPattern"
)

Types of url matching.

type Webhook

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

func NewWebhook

func NewWebhook() Webhook

func (Webhook) MarshalJSON

func (w Webhook) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface.

func (Webhook) ParseWebhook

func (w Webhook) ParseWebhook() map[string]interface{}

ParseWebhook returns a map representation of the webhook.

func (Webhook) WithBody

func (w Webhook) WithBody(body string) Webhook

WithBody sets the body of the webhook.

func (Webhook) WithDelay

func (w Webhook) WithDelay(delay DelayInterface) Webhook

WithDelay sets the delay of the webhook.

func (Webhook) WithFixedDelay

func (w Webhook) WithFixedDelay(delay time.Duration) Webhook

WithFixedDelay sets the fixed delay of the webhook.

func (Webhook) WithHeader

func (w Webhook) WithHeader(key string, value string) Webhook

WithHeader sets a header of the webhook.

func (Webhook) WithLogNormalRandomDelay

func (w Webhook) WithLogNormalRandomDelay(median time.Duration, sigma float64) Webhook

WithLogNormalRandomDelay sets the log normal delay of the webhook.

func (Webhook) WithMethod

func (w Webhook) WithMethod(method string) Webhook

WithMethod sets the HTTP method of the webhook.

func (Webhook) WithName

func (w Webhook) WithName(name string) WebhookInterface

WithName sets the name of the webhook and returns the webhook.

func (Webhook) WithURL

func (w Webhook) WithURL(url string) Webhook

WithURL sets the URL of the webhook.

func (Webhook) WithUniformRandomDelay

func (w Webhook) WithUniformRandomDelay(lower, upper time.Duration) Webhook

WithUniformRandomDelay sets the uniform random delay of the webhook.

type WebhookInterface

type WebhookInterface interface {
	json.Marshaler
	WithName(name string) WebhookInterface
	ParseWebhook() map[string]interface{}
}

Jump to

Keyboard shortcuts

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