Categorygithub.com/wiremock/go-wiremock
modulepackage
1.11.0
Repository: https://github.com/wiremock/go-wiremock.git
Documentation: pkg.go.dev

# 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

# Functions

Absent returns a matcher that matches when the parameter is absent.
And returns a logical AND of the list of matchers.
Contains returns a matcher that matches when the parameter contains the specified value.
Delete returns *StubRule for DELETE method.
EqualTo returns a matcher that matches when the parameter equals the specified value.
EqualToIgnoreCase returns a matcher that matches when the parameter equals the specified value, ignoring case.
EqualToJson returns a matcher that matches when the parameter is equal to the specified JSON.
EqualToXml returns a matcher that matches when the parameter is equal to the specified XML.
Get returns *StubRule for GET method.
HasExactly returns a matcher that matches when the parameter has exactly the specified values.
Includes returns a matcher that matches when the parameter includes the specified values.
MatchesJsonSchema returns a matcher that matches when the parameter matches the specified JSON schema.
Matching returns a matcher that matches when the parameter matches the specified regular expression.
MatchingJsonPath returns a matcher that matches when the parameter matches the specified JSON path.
MatchingXPath returns a matcher that matches when the parameter matches the specified XPath.
MustEqualToJson returns a matcher that matches when the parameter is equal to the specified JSON.
NewClient returns *Client.
No description provided by the author
No description provided by the author
No description provided by the author
NewRequest constructs minimum possible Request.
No description provided by the author
NewStringValueMatcher creates a new StringValueMatcher.
NewStubRule returns a new *StubRule.
No description provided by the author
No description provided by the author
Not returns a logical NOT of the given matcher.
NotContains returns a matcher that matches when the parameter does not contain the specified value.
NotMatching returns a matcher that matches when the parameter does not match the specified regular expression.
No description provided by the author
Or returns a logical OR of the list of matchers.
Patch returns *StubRule for PATCH method.
Post
Post returns *StubRule for POST method.
Put returns *StubRule for PUT method.
StartsWith returns a matcher that matches when the parameter starts with the specified prefix.
URLEqualTo returns URLMatcher with URLEqualToRule matching strategy.
URLMatching returns URLMatcher with URLMatchingRule matching strategy.
URLPathEqualTo returns URLMatcher with URLPathEqualToRule matching strategy.
URLPathMatching returns URLMatcher with URLPathMatchingRule matching strategy.
URLPathTemplate URL paths can be matched using URI templates, conforming to the same subset of the URI template standard as used in OpenAPI.

# Constants

No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
Type of less strict matching flags.
Type of less strict matching flags.
No description provided by the author
No description provided by the author
Types of params matching.
Types of params matching.
Types of params matching.
Types of params matching.
Types of params matching.
Types of params matching.
Types of params matching.
No description provided by the author
No description provided by the author
Types of params matching.
Types of params matching.
Types of params matching.
Types of params matching.
No description provided by the author
Types of url matching.
Types of url matching.
Types of url matching.
Types of url matching.
Types of url matching.

# Structs

A Client implements requests to the wiremock server.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
A Request is the part of StubRule describing the matching of the http request.
No description provided by the author
No description provided by the author
StubRule is struct of http Request body to WireMock.
URLMatcher is structure for defining the type of url matching.
No description provided by the author

# Interfaces

No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
URLMatcherInterface is pair URLMatchingStrategy and string matched value.
No description provided by the author

# Type aliases

EqualFlag is enum of less strict matching flag.
No description provided by the author
No description provided by the author
MultiValueMatchingStrategy is enum multi value matching type.
ParamMatchingStrategy is enum params matching type.
URLMatchingStrategy is enum url matching type.