apitest: github.com/steinfletcher/apitest Index | Files | Directories

package apitest

import "github.com/steinfletcher/apitest"

Index

Package Files

apitest.go assert.go cookies.go diagram.go mocks.go report.go template.go

Constants

const ConsumerName = "cli"

ConsumerName default consumer name

const SystemUnderTestDefaultName = "sut"

SystemUnderTestDefaultName default name for system under test

type APITest Uses

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

APITest is the top level struct holding the test spec

func New Uses

func New(name ...string) *APITest

New creates a new api test. The name is optional and will appear in test reports

func (*APITest) Debug Uses

func (a *APITest) Debug() *APITest

Debug logs to the console the http wire representation of all http interactions that are intercepted by apitest. This includes the inbound request to the application under test, the response returned by the application and any interactions that are intercepted by the mock server.

func (*APITest) Delete Uses

func (a *APITest) Delete(url string) *Request

Delete is a convenience method for setting the request as http.MethodDelete

func (*APITest) EnableNetworking Uses

func (a *APITest) EnableNetworking(cli ...*http.Client) *APITest

EnableNetworking will enable networking for provided clients

func (*APITest) Get Uses

func (a *APITest) Get(url string) *Request

Get is a convenience method for setting the request as http.MethodGet

func (*APITest) Handler Uses

func (a *APITest) Handler(handler http.Handler) *APITest

Handler defines the http handler that is invoked when the test is run

func (*APITest) HttpClient Uses

func (a *APITest) HttpClient(cli *http.Client) *APITest

HttpClient allows the developer to provide a custom http client when using mocks

func (*APITest) Intercept Uses

func (a *APITest) Intercept(interceptor Intercept) *APITest

Intercept is a builder method for setting the request interceptor

func (*APITest) Meta Uses

func (a *APITest) Meta(meta map[string]interface{}) *APITest

Meta provides a hook to add custom meta data to the test which can be picked up when defining a custom reporter

func (*APITest) Method Uses

func (a *APITest) Method(method string) *Request

Method is a builder method for setting the http method of the request

func (*APITest) Mocks Uses

func (a *APITest) Mocks(mocks ...*Mock) *APITest

Mocks is a builder method for setting the mocks

func (*APITest) Observe Uses

func (a *APITest) Observe(observers ...Observe) *APITest

Observe is a builder method for setting the observers

func (*APITest) ObserveMocks Uses

func (a *APITest) ObserveMocks(observer Observe) *APITest

ObserveMocks is a builder method for setting the mocks observers

func (*APITest) Patch Uses

func (a *APITest) Patch(url string) *Request

Patch is a convenience method for setting the request as http.MethodPatch

func (*APITest) Post Uses

func (a *APITest) Post(url string) *Request

Post is a convenience method for setting the request as http.MethodPost

func (*APITest) Put Uses

func (a *APITest) Put(url string) *Request

Put is a convenience method for setting the request as http.MethodPut

func (*APITest) Recorder Uses

func (a *APITest) Recorder(recorder *Recorder) *APITest

Recorder provides a hook to add a recorder to the test

func (*APITest) RecorderHook Uses

func (a *APITest) RecorderHook(hook RecorderHook) *APITest

RecorderHook allows the consumer to provider a function that will receive the recorder instance before the test runs. This can be used to inject custom events which can then be rendered in diagrams Deprecated: use Recorder() instead

func (*APITest) Report Uses

func (a *APITest) Report(reporter ReportFormatter) *APITest

Report provides a hook to add custom formatting to the output of the test

func (*APITest) Request Uses

func (a *APITest) Request() *Request

Request returns the request spec

func (*APITest) Response Uses

func (a *APITest) Response() *Response

Response returns the expected response

func (*APITest) Verifier Uses

func (a *APITest) Verifier(v Verifier) *APITest

Verifier allows consumers to override the verification implementation. By default testify is used to perform assertions

type Assert Uses

type Assert func(*http.Response, *http.Request) error

Assert is a user defined custom assertion function

var IsClientError Assert = func(response *http.Response, request *http.Request) error {
    if response.StatusCode >= 400 && response.StatusCode < 500 {
        return nil
    }
    return fmt.Errorf("not a client error. Status code=%d", response.StatusCode)
}

IsClientError is a convenience function to assert on a range of client error status codes

var IsServerError Assert = func(response *http.Response, request *http.Request) error {
    if response.StatusCode >= 500 {
        return nil
    }
    return fmt.Errorf("not a server error. Status code=%d", response.StatusCode)
}

IsServerError is a convenience function to assert on a range of server error status codes

var IsSuccess Assert = func(response *http.Response, request *http.Request) error {
    if response.StatusCode >= 200 && response.StatusCode < 400 {
        return nil
    }
    return fmt.Errorf("not success. Status code=%d", response.StatusCode)
}

IsSuccess is a convenience function to assert on a range of happy path status codes

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

Cookie used to represent an http cookie

func FromHTTPCookie Uses

func FromHTTPCookie(httpCookie *http.Cookie) *Cookie

FromHTTPCookie transforms an http cookie into a Cookie

func NewCookie Uses

func NewCookie(name string) *Cookie

NewCookie creates a new Cookie with the provided name

func (*Cookie) Domain Uses

func (cookie *Cookie) Domain(domain string) *Cookie

Domain sets the domain of the Cookie

func (*Cookie) Expires Uses

func (cookie *Cookie) Expires(expires time.Time) *Cookie

Expires sets the expires time of the Cookie

func (*Cookie) HttpOnly Uses

func (cookie *Cookie) HttpOnly(httpOnly bool) *Cookie

HttpOnly sets the httpOnly bool of the Cookie

func (*Cookie) MaxAge Uses

func (cookie *Cookie) MaxAge(maxAge int) *Cookie

MaxAge sets the maxage of the Cookie

func (*Cookie) Path Uses

func (cookie *Cookie) Path(path string) *Cookie

Path sets the path of the Cookie

func (*Cookie) Secure Uses

func (cookie *Cookie) Secure(secure bool) *Cookie

Secure sets the secure bool of the Cookie

func (*Cookie) ToHttpCookie Uses

func (cookie *Cookie) ToHttpCookie() *http.Cookie

ToHttpCookie transforms the Cookie to an http cookie

func (*Cookie) Value Uses

func (cookie *Cookie) Value(value string) *Cookie

Value sets the value of the Cookie

type Event Uses

type Event interface {
    GetTime() time.Time
}

Event represents a reporting event

type FinalResponse Uses

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

FinalResponse used to wrap the final response with a timestamp

type HttpRequest Uses

type HttpRequest struct {
    Source    string
    Target    string
    Value     *http.Request
    Timestamp time.Time
}

HttpRequest represents an http request

func (HttpRequest) GetTime Uses

func (r HttpRequest) GetTime() time.Time

GetTime gets the time of the HttpRequest interaction

type HttpResponse Uses

type HttpResponse struct {
    Source    string
    Target    string
    Value     *http.Response
    Timestamp time.Time
}

HttpResponse represents an http response

func (HttpResponse) GetTime Uses

func (r HttpResponse) GetTime() time.Time

GetTime gets the time of the HttpResponse interaction

type InboundRequest Uses

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

InboundRequest used to wrap the incoming request with a timestamp

type Intercept Uses

type Intercept func(*http.Request)

Intercept will be called before the request is made. Updates to the request will be reflected in the test

type Matcher Uses

type Matcher func(*http.Request, *MockRequest) error

Matcher type accepts the actual request and a mock request to match against. Will return an error that describes why there was a mismatch if the inputs do not match or nil if they do.

type MessageRequest Uses

type MessageRequest struct {
    Source    string
    Target    string
    Header    string
    Body      string
    Timestamp time.Time
}

MessageRequest represents a request interaction

func (MessageRequest) GetTime Uses

func (r MessageRequest) GetTime() time.Time

GetTime gets the time of the MessageRequest interaction

type MessageResponse Uses

type MessageResponse struct {
    Source    string
    Target    string
    Header    string
    Body      string
    Timestamp time.Time
}

MessageResponse represents a response interaction

func (MessageResponse) GetTime Uses

func (r MessageResponse) GetTime() time.Time

GetTime gets the time of the MessageResponse interaction

type Mock Uses

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

Mock represents the entire interaction for a mock to be used for testing

func NewMock Uses

func NewMock() *Mock

NewMock create a new mock, ready for configuration using the builder pattern

func (*Mock) Debug Uses

func (m *Mock) Debug() *Mock

Debug is used to set debug mode for mocks in standalone mode. This is overridden by the debug setting in the `APITest` struct

func (*Mock) Delete Uses

func (m *Mock) Delete(u string) *MockRequest

Delete configures the mock to match http method DELETE

func (*Mock) Get Uses

func (m *Mock) Get(u string) *MockRequest

Get configures the mock to match http method GET

func (*Mock) HttpClient Uses

func (m *Mock) HttpClient(cli *http.Client) *Mock

HttpClient allows the developer to provide a custom http client when using mocks

func (*Mock) Matches Uses

func (m *Mock) Matches(req *http.Request) []error

Matches checks whether the given request matches the mock

func (*Mock) Method Uses

func (m *Mock) Method(method string) *MockRequest

Method configures mock to match given http method

func (*Mock) Patch Uses

func (m *Mock) Patch(u string) *MockRequest

Patch configures the mock to match http method PATCH

func (*Mock) Post Uses

func (m *Mock) Post(u string) *MockRequest

Post configures the mock to match http method POST

func (*Mock) Put Uses

func (m *Mock) Put(u string) *MockRequest

Put configures the mock to match http method PUT

type MockRequest Uses

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

MockRequest represents the http request side of a mock interaction

func (*MockRequest) AddMatcher Uses

func (r *MockRequest) AddMatcher(matcher Matcher) *MockRequest

AddMatcher configures the mock request to match using a custom matcher

func (*MockRequest) Body Uses

func (r *MockRequest) Body(b string) *MockRequest

Body configures the mock request to match the given body

func (*MockRequest) Cookie Uses

func (r *MockRequest) Cookie(name, value string) *MockRequest

Cookie configures the mock request to match a cookie

func (*MockRequest) CookieNotPresent Uses

func (r *MockRequest) CookieNotPresent(name string) *MockRequest

CookieNotPresent configures the mock request to match when a cookie is not present

func (*MockRequest) CookiePresent Uses

func (r *MockRequest) CookiePresent(name string) *MockRequest

CookiePresent configures the mock request to match when a cookie is present, regardless of value

func (*MockRequest) FormData Uses

func (r *MockRequest) FormData(key string, values ...string) *MockRequest

FormData configures the mock request to math the given form data

func (*MockRequest) FormDataNotPresent Uses

func (r *MockRequest) FormDataNotPresent(key string) *MockRequest

FormDataNotPresent configures the mock request to match when the form data is not present

func (*MockRequest) FormDataPresent Uses

func (r *MockRequest) FormDataPresent(key string) *MockRequest

FormDataPresent configures the mock request to match when the form data is present, regardless of values

func (*MockRequest) Header Uses

func (r *MockRequest) Header(key, value string) *MockRequest

Header configures the mock request to match the given header

func (*MockRequest) HeaderNotPresent Uses

func (r *MockRequest) HeaderNotPresent(key string) *MockRequest

HeaderNotPresent configures the mock request to match when the header is not present

func (*MockRequest) HeaderPresent Uses

func (r *MockRequest) HeaderPresent(key string) *MockRequest

HeaderPresent configures the mock request to match when this header is present, regardless of value

func (*MockRequest) Headers Uses

func (r *MockRequest) Headers(headers map[string]string) *MockRequest

Headers configures the mock request to match the given headers

func (*MockRequest) Query Uses

func (r *MockRequest) Query(key, value string) *MockRequest

Query configures the mock request to match a query param

func (*MockRequest) QueryNotPresent Uses

func (r *MockRequest) QueryNotPresent(key string) *MockRequest

QueryNotPresent configures the mock request to match when the query param is not present

func (*MockRequest) QueryParams Uses

func (r *MockRequest) QueryParams(queryParams map[string]string) *MockRequest

QueryParams configures the mock request to match a number of query params

func (*MockRequest) QueryPresent Uses

func (r *MockRequest) QueryPresent(key string) *MockRequest

QueryPresent configures the mock request to match when a query param is present, regardless of value

func (*MockRequest) RespondWith Uses

func (r *MockRequest) RespondWith() *MockResponse

RespondWith finalises the mock request phase of set up and allowing the definition of response attributes to be defined

type MockResponse Uses

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

MockResponse represents the http response side of a mock interaction

func (*MockResponse) Body Uses

func (r *MockResponse) Body(body string) *MockResponse

Body respond with the given body

func (*MockResponse) Cookie Uses

func (r *MockResponse) Cookie(name, value string) *MockResponse

Cookie respond with the given cookie

func (*MockResponse) Cookies Uses

func (r *MockResponse) Cookies(cookie ...*Cookie) *MockResponse

Cookies respond with the given cookies

func (*MockResponse) End Uses

func (r *MockResponse) End() *Mock

End finalise the response definition phase in order for the mock to be used

func (*MockResponse) EndStandalone Uses

func (r *MockResponse) EndStandalone(other ...*Mock) func()

EndStandalone finalises the response definition of standalone mocks

func (*MockResponse) Header Uses

func (r *MockResponse) Header(key string, value string) *MockResponse

Header respond with the given header

func (*MockResponse) Headers Uses

func (r *MockResponse) Headers(headers map[string]string) *MockResponse

Headers respond with the given headers

func (*MockResponse) Status Uses

func (r *MockResponse) Status(statusCode int) *MockResponse

Status respond with the given status

func (*MockResponse) Times Uses

func (r *MockResponse) Times(times int) *MockResponse

Times respond the given number of times

type NoopVerifier Uses

type NoopVerifier struct{}

NoopVerifier is a verifier that does not perform verification

func (NoopVerifier) Equal Uses

func (n NoopVerifier) Equal(t *testing.T, expected, actual interface{}, msgAndArgs ...interface{}) bool

Equal does not perform any assertion and always returns true

func (NoopVerifier) Fail Uses

func (n NoopVerifier) Fail(t *testing.T, failureMessage string, msgAndArgs ...interface{}) bool

Fail does not perform any assertion and always returns true

func (NoopVerifier) JSONEq Uses

func (n NoopVerifier) JSONEq(t *testing.T, expected string, actual string, msgAndArgs ...interface{}) bool

JSONEq does not perform any assertion and always returns true

type Observe Uses

type Observe func(*http.Response, *http.Request, *APITest)

Observe will be called by with the request and response on completion

type Recorder Uses

type Recorder struct {
    Title    string
    SubTitle string
    Meta     map[string]interface{}
    Events   []Event
}

Recorder represents all of the report data

func NewTestRecorder Uses

func NewTestRecorder() *Recorder

NewTestRecorder creates a new TestRecorder

func (*Recorder) AddHttpRequest Uses

func (r *Recorder) AddHttpRequest(req HttpRequest) *Recorder

AddHttpRequest add an http request to recorder

func (*Recorder) AddHttpResponse Uses

func (r *Recorder) AddHttpResponse(req HttpResponse) *Recorder

AddHttpResponse add an HttpResponse to the recorder

func (*Recorder) AddMessageRequest Uses

func (r *Recorder) AddMessageRequest(m MessageRequest) *Recorder

AddMessageRequest add a MessageRequest to the recorder

func (*Recorder) AddMessageResponse Uses

func (r *Recorder) AddMessageResponse(m MessageResponse) *Recorder

AddMessageResponse add a MessageResponse to the recorder

func (*Recorder) AddMeta Uses

func (r *Recorder) AddMeta(meta map[string]interface{}) *Recorder

AddMeta add Meta to the recorder

func (*Recorder) AddSubTitle Uses

func (r *Recorder) AddSubTitle(subTitle string) *Recorder

AddSubTitle add a SubTitle to the recorder

func (*Recorder) AddTitle Uses

func (r *Recorder) AddTitle(title string) *Recorder

AddTitle add a Title to the recorder

func (*Recorder) Reset Uses

func (r *Recorder) Reset()

Reset resets the recorder to default starting state

func (*Recorder) ResponseStatus Uses

func (r *Recorder) ResponseStatus() (int, error)

ResponseStatus get response status of the recorder, returning an error when this wasn't possible

type RecorderHook Uses

type RecorderHook func(*Recorder)

RecorderHook used to implement a custom interaction recorder

type ReportFormatter Uses

type ReportFormatter interface {
    // Format formats the events received from the recorder
    Format(*Recorder)
}

ReportFormatter represents the report formatter

type Request Uses

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

Request is the user defined request that will be invoked on the handler under test

func (*Request) BasicAuth Uses

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

BasicAuth is a builder method to sets basic auth on the request.

func (*Request) Body Uses

func (r *Request) Body(b string) *Request

Body is a builder method to set the request body

func (*Request) ContentType Uses

func (r *Request) ContentType(contentType string) *Request

ContentType is a builder method to set the Content-Type header of the request

func (*Request) Cookie Uses

func (r *Request) Cookie(name, value string) *Request

Cookie is a convenience method for setting a single request cookies by name and value

func (*Request) Cookies Uses

func (r *Request) Cookies(c ...*Cookie) *Request

Cookies is a builder method to set the request cookies

func (*Request) Expect Uses

func (r *Request) Expect(t *testing.T) *Response

Expect marks the request spec as complete and following code will define the expected response

func (*Request) FormData Uses

func (r *Request) FormData(name string, values ...string) *Request

FormData is a builder method to set the body form data Also sets the content type of the request to application/x-www-form-urlencoded

func (*Request) Header Uses

func (r *Request) Header(key, value string) *Request

Header is a builder method to set the request headers

func (*Request) Headers Uses

func (r *Request) Headers(headers map[string]string) *Request

Headers is a builder method to set the request headers

func (*Request) JSON Uses

func (r *Request) JSON(b string) *Request

JSON is a convenience method for setting the request body and content type header as "application/json"

func (*Request) Query Uses

func (r *Request) Query(key, value string) *Request

Query is a convenience method to add a query parameter to the request.

func (*Request) QueryCollection Uses

func (r *Request) QueryCollection(q map[string][]string) *Request

QueryCollection is a builder method to set the request query parameters This can be used in combination with request.Query

func (*Request) QueryParams Uses

func (r *Request) QueryParams(params map[string]string) *Request

QueryParams is a builder method to set the request query parameters. This can be used in combination with request.QueryCollection

func (*Request) URL Uses

func (r *Request) URL(url string) *Request

URL is a builder method for setting the url of the request

type Response Uses

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

Response is the user defined expected response from the application under test

func (*Response) Assert Uses

func (r *Response) Assert(fn func(*http.Response, *http.Request) error) *Response

Assert allows the consumer to provide a user defined function containing their own custom assertions

func (*Response) Body Uses

func (r *Response) Body(b string) *Response

Body is the expected response body

func (*Response) Cookie Uses

func (r *Response) Cookie(name, value string) *Response

Cookie is used to match on an individual cookie name/value pair in the expected response cookies

func (*Response) CookieNotPresent Uses

func (r *Response) CookieNotPresent(cookieName string) *Response

CookieNotPresent is used to assert that a cookie is not present in the response

func (*Response) CookiePresent Uses

func (r *Response) CookiePresent(cookieName string) *Response

CookiePresent is used to assert that a cookie is present in the response, regardless of its value

func (*Response) Cookies Uses

func (r *Response) Cookies(cookies ...*Cookie) *Response

Cookies is the expected response cookies

func (*Response) End Uses

func (r *Response) End() Result

End runs the test returning the result to the caller

func (*Response) Header Uses

func (r *Response) Header(key, value string) *Response

Header is a builder method to set the request headers

func (*Response) HeaderNotPresent Uses

func (r *Response) HeaderNotPresent(name string) *Response

HeaderNotPresent is a builder method to set the request headers that should not be present in the response

func (*Response) HeaderPresent Uses

func (r *Response) HeaderPresent(name string) *Response

HeaderPresent is a builder method to set the request headers that should be present in the response

func (*Response) Headers Uses

func (r *Response) Headers(headers map[string]string) *Response

Headers is a builder method to set the request headers

func (*Response) Status Uses

func (r *Response) Status(s int) *Response

Status is the expected response http status code

type Result Uses

type Result struct {
    Response *http.Response
}

Result provides the final result

func (Result) JSON Uses

func (r Result) JSON(t interface{})

JSON unmarshal the result response body to a valid struct

type SequenceDiagramFormatter Uses

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

SequenceDiagramFormatter implementation of a ReportFormatter

func SequenceDiagram Uses

func SequenceDiagram(path ...string) *SequenceDiagramFormatter

SequenceDiagram produce a sequence diagram at the given path or .sequence by default

func (*SequenceDiagramFormatter) Format Uses

func (r *SequenceDiagramFormatter) Format(recorder *Recorder)

Format formats the events received by the recorder

type StandaloneMocks Uses

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

StandaloneMocks for using mocks outside of API tests context

func NewStandaloneMocks Uses

func NewStandaloneMocks(mocks ...*Mock) *StandaloneMocks

NewStandaloneMocks create a series of StandaloneMocks

func (*StandaloneMocks) Debug Uses

func (r *StandaloneMocks) Debug() *StandaloneMocks

Debug switch on debugging mode

func (*StandaloneMocks) End Uses

func (r *StandaloneMocks) End() func()

End finalises the mock, ready for use

func (*StandaloneMocks) HttpClient Uses

func (r *StandaloneMocks) HttpClient(cli *http.Client) *StandaloneMocks

HttpClient use the given http client

type Transport Uses

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

Transport wraps components used to observe and manipulate the real request and response objects

func (*Transport) Hijack Uses

func (r *Transport) Hijack()

Hijack replace the transport implementation of the interaction under test in order to observe, mock and inject expectations

func (*Transport) Reset Uses

func (r *Transport) Reset()

Reset replace the hijacked transport implementation of the interaction under test to the original implementation

func (*Transport) RoundTrip Uses

func (r *Transport) RoundTrip(req *http.Request) (mockResponse *http.Response, matchErrors error)

RoundTrip implementation intended to match a given expected mock request or throw an error with a list of reasons why no match was found.

type Verifier Uses

type Verifier interface {
    Equal(t *testing.T, expected, actual interface{}, msgAndArgs ...interface{}) bool
    JSONEq(t *testing.T, expected string, actual string, msgAndArgs ...interface{}) bool
    Fail(t *testing.T, failureMessage string, msgAndArgs ...interface{}) bool
}

Verifier is the assertion interface allowing consumers to inject a custom assertion implementation. It also allows failure scenarios to be tested within apitest

Directories

PathSynopsis
mocks

Package apitest imports 24 packages (graph) and is imported by 3 packages. Updated 2019-10-23. Refresh now. Tools for package owners.