resttest

package
v0.1.13 Latest Latest
Warning

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

Go to latest
Published: Jan 11, 2021 License: MIT Imports: 13 Imported by: 1

Documentation

Overview

Package resttest provides utilities to test REST API.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

type Client struct {
	ConcurrencyLevel int
	JSONComparer     assertjson.Comparer

	Headers map[string]string
	// contains filtered or unexported fields
}

Client keeps state of expectations.

func NewClient

func NewClient(baseURL string) *Client

NewClient creates client instance.

Example
package main

import (
	"fmt"
	"net/http"

	"github.com/swaggest/rest/resttest"
)

func main() {
	// Prepare server mock.
	sm, url := resttest.NewServerMock()
	defer sm.Close()

	// This example shows Client and ServerMock working together for sake of portability.
	// In real-world scenarios Client would complement real server or ServerMock would complement real HTTP client.

	// Set successful expectation for first request out of concurrent batch.
	exp := resttest.Expectation{
		Method:     http.MethodPost,
		RequestURI: "/foo?q=1",
		RequestHeader: map[string]string{
			"X-Custom":     "def",
			"X-Header":     "abc",
			"Content-Type": "application/json",
		},
		RequestBody:  []byte(`{"foo":"bar"}`),
		Status:       http.StatusAccepted,
		ResponseBody: []byte(`{"bar":"foo"}`),
	}
	sm.Expect(exp)

	// Set failing expectation for other requests of concurrent batch.
	exp.Status = http.StatusConflict
	exp.ResponseBody = []byte(`{"error":"conflict"}`)
	exp.Unlimited = true
	sm.Expect(exp)

	// Prepare client request.
	c := resttest.NewClient(url)
	c.ConcurrencyLevel = 50
	c.Headers = map[string]string{
		"X-Header": "abc",
	}

	c.Reset().
		WithMethod(http.MethodPost).
		WithHeader("X-Custom", "def").
		WithContentType("application/json").
		WithBody([]byte(`{"foo":"bar"}`)).
		WithURI("/foo?q=1").
		Concurrently()

	// Check expectations errors.
	fmt.Println(
		c.ExpectResponseStatus(http.StatusAccepted),
		c.ExpectResponseBody([]byte(`{"bar":"foo"}`)),
		c.ExpectOtherResponsesStatus(http.StatusConflict),
		c.ExpectOtherResponsesBody([]byte(`{"error":"conflict"}`)),
	)

}
Output:

<nil> <nil> <nil> <nil>

func (*Client) Concurrently

func (c *Client) Concurrently() *Client

Concurrently enables concurrent calls to idempotent endpoint.

func (*Client) ExpectOtherResponsesBody

func (c *Client) ExpectOtherResponsesBody(body []byte) error

ExpectOtherResponsesBody sets expectation for response body to be received one or more times during concurrent calling.

For example, it may describe "Not Found" response on multiple DELETE or "Conflict" response on multiple POST. Does not affect single (non-concurrent) calls.

func (*Client) ExpectOtherResponsesStatus

func (c *Client) ExpectOtherResponsesStatus(statusCode int) error

ExpectOtherResponsesStatus sets expectation for response status to be received one or more times during concurrent calling.

For example, it may describe "Not Found" response on multiple DELETE or "Conflict" response on multiple POST. Does not affect single (non-concurrent) calls.

func (*Client) ExpectResponseBody

func (c *Client) ExpectResponseBody(body []byte) error

ExpectResponseBody sets expectation for response body to be received.

In concurrent mode such response mush be met only once or for all calls.

func (*Client) ExpectResponseStatus

func (c *Client) ExpectResponseStatus(statusCode int) error

ExpectResponseStatus sets expected response status code.

func (*Client) Reset

func (c *Client) Reset() *Client

Reset deletes client state.

func (*Client) WithBody

func (c *Client) WithBody(body []byte) *Client

WithBody sets request body.

func (*Client) WithContentType

func (c *Client) WithContentType(contentType string) *Client

WithContentType sets request content type.

func (*Client) WithHeader

func (c *Client) WithHeader(key, value string) *Client

WithHeader sets request header.

func (*Client) WithMethod

func (c *Client) WithMethod(method string) *Client

WithMethod sets request HTTP method.

func (*Client) WithPath deprecated

func (c *Client) WithPath(path string) *Client

WithPath sets request URI path.

Deprecated: use WithURI.

func (*Client) WithURI added in v0.1.5

func (c *Client) WithURI(uri string) *Client

WithURI sets request URI.

type Expectation added in v0.1.5

type Expectation struct {
	Method        string
	RequestURI    string
	RequestHeader map[string]string
	RequestBody   []byte

	Status         int
	ResponseHeader map[string]string
	ResponseBody   []byte

	// Unlimited enables reusing of this expectation unlimited number of times.
	Unlimited bool
	// Repeated defines how many times this expectation should be used.
	Repeated int
}

Expectation describes expected request and defines response.

type ServerMock added in v0.1.5

type ServerMock struct {
	// OnError is called on expectations mismatch or internal errors.
	OnError func(err error)

	// ErrorResponder allows custom failure responses.
	ErrorResponder func(rw http.ResponseWriter, err error)

	// DefaultResponseHeaders are added to every response to an expected request.
	DefaultResponseHeaders map[string]string

	// JSONComparer controls JSON equality check.
	JSONComparer assertjson.Comparer
	// contains filtered or unexported fields
}

ServerMock serves predefined response for predefined request.

func NewServerMock added in v0.1.5

func NewServerMock() (*ServerMock, string)

NewServerMock creates mocked server.

func (*ServerMock) Close added in v0.1.5

func (sm *ServerMock) Close()

Close closes mocked server.

func (*ServerMock) Expect added in v0.1.5

func (sm *ServerMock) Expect(e Expectation)

Expect adds expected operation.

func (*ServerMock) ExpectationsWereMet added in v0.1.5

func (sm *ServerMock) ExpectationsWereMet() error

ExpectationsWereMet checks whether all queued expectations were met in order. If any of them was not met - an error is returned.

func (*ServerMock) ResetExpectations added in v0.1.5

func (sm *ServerMock) ResetExpectations()

ResetExpectations discards all expectation to reset the state of mock.

func (*ServerMock) ServeHTTP added in v0.1.5

func (sm *ServerMock) ServeHTTP(rw http.ResponseWriter, req *http.Request)

ServeHTTP asserts request expectations and serves mocked response.

Jump to

Keyboard shortcuts

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