mock_server_client

package module
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Feb 20, 2022 License: MIT Imports: 10 Imported by: 0

README

Test client for MockServer

This is the go client with testing package integration to mock server:

How to use

Run examples

make docker-up
make examples 

Write tests

  1. Make sure mock server is up and running on some host (for example localhost:1080)
  2. Initiate MockServer to start using the mock:
import (
	...
    msc "github.com/YReshetko/mock-server-client"
	...
)

func TestSomething(t *testing.T) {
    mock := msc.NewMockServer(
		msc.Config{
            Host:    "localhost",
            Port:    1080,
            Verbose: true,
        },
    )
	...
}
  1. At some point, before you expect your system calls third party service that you are going to mock, setup expectations. For example:
func TestSomething(t *testing.T) {
	...
    expectRequest := SomeRequest{}
    expectation := mock.On(http.SomeMethod, "/some/{some_param}/endpoint").
        Request(
            msc.WithPathParameter("some_param", "[0-9]{1}"),
        ).
        SequentialResponse(
            msc.WithStatusCode(http.StatusCreated),
        ).
        SequentialResponse(
            msc.WithStatusCode(http.StatusOK),
        ).
        DefaultResponse(
            msc.WithStatusCode(http.StatusNotFound),
        ).
        NumCalls(3).
        AssertionAtCall(0, msc.NewAssertion().
            WithJsonBody(&expectRequest).
            AddHeader("User-Agent", "Go-http-client/1.1").
            WithPath("/some/1/endpoint"),
        )
    mock.Setup(context.Background(), expectation)
	...
}
  1. When your system did some work, and you are going to verify sent requests to the mocked third party you need to call Veryfy or VerifyExpectation method. At this point all expected bodies that were setup in assertions will be fulfilled by the MockServer:
func TestSomething(t *testing.T) {
	...
	mock.Verify(context.Background(), t)
	assert.Equal(t, "some-field-value", expectRequest.SomeField)
	...
}
  1. The most important thing is to reset MockServer each time when you start new test scenario, otherwise all previously created expectation can affect verification result. Remember if you create a new MockServer it doesn't mean that you have cleaned the expectation on mock server app.
func TestSomething(t *testing.T) {
	...
	mock.Reset(context.Background())
	...
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewAssertion

func NewAssertion() *assertion

NewAssertion creates new assertion to be checked on MockServer.Verify...

func NewMockServer

func NewMockServer(cfg Config) *mockServer

NewMockServer creates a new MockServer client

Types

type Config

type Config struct {
	Host    string
	Port    int
	Verbose bool
}

Config to communicate with mock server app.

type Expectation

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

Expectation contains references to expected HTTP request and responses, required assertions and so on. Each point can not be checked directly, but using AssertionAtCall and setup proper assertions. The verification can be done at any point by MockServer.Verify or MockServer.VerifyExpectation during testing.

func (*Expectation) AssertionAtCall

func (e *Expectation) AssertionAtCall(callNumber int, a *assertion) *Expectation

AssertionAtCall register the number of assertions which has to be done on the Expectation for particular callNumber. NewAssertion() creates an assertion that is designed with builder pattern, so it can be prepared accordingly: assertion.WithNoBody().AddHeader("key", "value")...

func (*Expectation) DefaultResponse

func (e *Expectation) DefaultResponse(opts ...ResponseOption) *Expectation

DefaultResponse prepares default response which is returned by mock server up when there is no SequentialResponse, or calls to all SequentialResponse are completed. Can not be called after the Expectation was MockServer.Setup to mock server app, it leads the panic().

func (*Expectation) Name

func (e *Expectation) Name(name string) *Expectation

Name set Expectation name for better debug, if the name is not set the new UUID will be generated instead. For example:

		Test failure on named Expectation:
			FAIL assertion:
       		Expectation name [Some user freandly name]
       		Assertion at call [0]
       		Reason: unexpected query parameter found [dev_modifier_14 admin_change_67] for key 'option'

		Test failure on random Expectation:
			FAIL assertion:
       		Expectation name [1cf2db7f-51c4-4961-be1a-de361a7c0db8]
       		Assertion at call [0]
       		Reason: unexpected query parameter found [dev_modifier_14 admin_change_67] for key 'option'

func (*Expectation) NumCalls

func (e *Expectation) NumCalls(value int) *Expectation

NumCalls specific assertion to check if corresponding request was sent exactly N times.

func (*Expectation) Request

func (e *Expectation) Request(opts ...RequestOption) *Expectation

Request prepares expected request. Can not be called after the Expectation was MockServer.Setup to mock server app, it leads the panic().

func (*Expectation) SequentialResponse

func (e *Expectation) SequentialResponse(opts ...ResponseOption) *Expectation

SequentialResponse prepares ordered responses which can be returned only once in the same order as SequentialResponse was called on Expectation. Can not be called after the Expectation was MockServer.Setup to mock server app, it leads the panic().

func (*Expectation) String

func (e *Expectation) String() string

String returns Expectation name or id if the name was not added.

type MockServer

type MockServer interface {
	On(method, path string) *Expectation

	Setup(context.Context, ...*Expectation) error

	Verify(context.Context, *testing.T) error
	VerifyExpectation(context.Context, *testing.T, *Expectation) error

	Clear(context.Context, *Expectation) error
	Reset(context.Context) error
}

MockServer to communicate with mock server application https://www.mock-server.com/#what-is-mockserver. It contains methods to create Expectation, Setup that on server and Verify any assertion during testing. When the particular test completed Reset method should be called to avoid other tests invalid verification results. During test execution somme expectation can be removed by Clear method.

type RequestOption

type RequestOption func(*request)

func WithPathParameter

func WithPathParameter(key, value string) RequestOption

WithPathParameter sets required request path parameter that has to be checked on mock server app to return corresponding response.

func WithQueryParameter

func WithQueryParameter(key, value string) RequestOption

WithQueryParameter sets required query parameter that has to be checked on mock server app to return corresponding response.

func WithRequestBody

func WithRequestBody(body interface{}) RequestOption

WithRequestBody sets required body that has to be checked on mock server app to return corresponding response.

func WithRequestHeader

func WithRequestHeader(key, value string) RequestOption

WithRequestHeader sets required header parameter that has to be checked on mock server app to return corresponding response.

type ResponseOption

type ResponseOption func(*response)

func WithDelay

func WithDelay(s time.Duration) ResponseOption

WithDelay sets HTTP response delay for mock server app.

func WithDropConnection

func WithDropConnection() ResponseOption

WithDropConnection sets true to brake HTTP connection from mock server app side for particular response.

func WithErrorBytes

func WithErrorBytes(b []byte) ResponseOption

WithErrorBytes sets error bytes within dropped connection on mock server side.

func WithReason

func WithReason(s string) ResponseOption

WithReason sets HTTP failure reason for mock server app.

func WithResponseBody

func WithResponseBody(body interface{}) ResponseOption

WithResponseBody sets response body to be returned within corresponding HTTP response from mock server app.

func WithResponseHeader

func WithResponseHeader(key, value string) ResponseOption

WithResponseHeader sets response header to be returned within corresponding HTTP response from mock server app.

func WithStatusCode

func WithStatusCode(s int) ResponseOption

WithStatusCode sets HTTP status code to be returned within corresponding HTTP response from mock server app.

Directories

Path Synopsis
examples
pet
internal

Jump to

Keyboard shortcuts

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