import "github.com/steinfletcher/apitest"
apitest.go assert.go cookies.go diagram.go mocks.go report.go template.go
const ConsumerName = "cli"
ConsumerName default consumer name
const SystemUnderTestDefaultName = "sut"
SystemUnderTestDefaultName default name for system under test
type APITest struct {
// contains filtered or unexported fields
}
APITest is the top level struct holding the test spec
New creates a new api test. The name is optional and will appear in test reports
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.
Delete is a convenience method for setting the request as http.MethodDelete
Deletef is a convenience method that adds formatting support to Delete
EnableNetworking will enable networking for provided clients
Get is a convenience method for setting the request as http.MethodGet
Getf is a convenience method that adds formatting support to Get
Handler defines the http handler that is invoked when the test is run
func (a *APITest) HandlerFunc(handlerFunc http.HandlerFunc) *APITest
HandlerFunc defines the http handler that is invoked when the test is run
HttpClient allows the developer to provide a custom http client when using mocks
Intercept is a builder method for setting the request interceptor
Meta provides a hook to add custom meta data to the test which can be picked up when defining a custom reporter
Method is a builder method for setting the http method of the request
Mocks is a builder method for setting the mocks
Observe is a builder method for setting the observers
ObserveMocks is a builder method for setting the mocks observers
Patch is a convenience method for setting the request as http.MethodPatch
Patchf is a convenience method that adds formatting support to Patch
Post is a convenience method for setting the request as http.MethodPost
Postf is a convenience method that adds formatting support to Post
Put is a convenience method for setting the request as http.MethodPut
Putf is a convenience method that adds formatting support to Put
Recorder provides a hook to add a recorder to the test
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 (a *APITest) Report(reporter ReportFormatter) *APITest
Report provides a hook to add custom formatting to the output of the test
Request returns the request spec
Response returns the expected response
Verifier allows consumers to override the verification implementation. By default testify is used to perform assertions
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
FromHTTPCookie transforms an http cookie into a Cookie
NewCookie creates a new Cookie with the provided name
Domain sets the domain of the Cookie
Expires sets the expires time of the Cookie
HttpOnly sets the httpOnly bool of the Cookie
MaxAge sets the maxage of the Cookie
Path sets the path of the Cookie
Secure sets the secure bool of the Cookie
ToHttpCookie transforms the Cookie to an http cookie
Value sets the value of the Cookie
Event represents a reporting event
type FinalResponse struct {
// contains filtered or unexported fields
}
FinalResponse used to wrap the final response with a timestamp
type GraphQLRequestBody struct { Query string `json:"query"` Variables map[string]interface{} `json:"variables,omitempty"` OperationName string `json:"operationName,omitempty"` }
GraphQLRequestBody represents the POST request body as per the GraphQL spec
HttpRequest represents an http request
func (r HttpRequest) GetTime() time.Time
GetTime gets the time of the HttpRequest interaction
HttpResponse represents an http response
func (r HttpResponse) GetTime() time.Time
GetTime gets the time of the HttpResponse interaction
type InboundRequest struct {
// contains filtered or unexported fields
}
InboundRequest used to wrap the incoming request with a timestamp
Intercept will be called before the request is made. Updates to the request will be reflected in the test
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 struct { Source string Target string Header string Body string Timestamp time.Time }
MessageRequest represents a request interaction
func (r MessageRequest) GetTime() time.Time
GetTime gets the time of the MessageRequest interaction
type MessageResponse struct { Source string Target string Header string Body string Timestamp time.Time }
MessageResponse represents a response interaction
func (r MessageResponse) GetTime() time.Time
GetTime gets the time of the MessageResponse interaction
type Mock struct {
// contains filtered or unexported fields
}
Mock represents the entire interaction for a mock to be used for testing
NewMock create a new mock, ready for configuration using the builder pattern
Debug is used to set debug mode for mocks in standalone mode. This is overridden by the debug setting in the `APITest` struct
func (m *Mock) Delete(u string) *MockRequest
Delete configures the mock to match http method DELETE
func (m *Mock) Deletef(format string, args ...interface{}) *MockRequest
Deletef configures the mock to match http method DELETE and supports formatting
func (m *Mock) Get(u string) *MockRequest
Get configures the mock to match http method GET
func (m *Mock) Getf(format string, args ...interface{}) *MockRequest
Getf configures the mock to match http method GET and supports formatting
func (m *Mock) Head(u string) *MockRequest
Head configures the mock to match http method HEAD
HttpClient allows the developer to provide a custom http client when using mocks
Matches checks whether the given request matches the mock
func (m *Mock) Method(method string) *MockRequest
Method configures mock to match given http method
func (m *Mock) Patch(u string) *MockRequest
Patch configures the mock to match http method PATCH
func (m *Mock) Patchf(format string, args ...interface{}) *MockRequest
Patchf configures the mock to match http method PATCH and supports formatting
func (m *Mock) Post(u string) *MockRequest
Post configures the mock to match http method POST
func (m *Mock) Postf(format string, args ...interface{}) *MockRequest
Postf configures the mock to match http method POST and supports formatting
func (m *Mock) Put(u string) *MockRequest
Put configures the mock to match http method PUT
func (m *Mock) Putf(format string, args ...interface{}) *MockRequest
Putf configures the mock to match http method PUT and supports formatting
type MockRequest struct {
// contains filtered or unexported fields
}
MockRequest represents the http request side of a mock interaction
func (r *MockRequest) AddMatcher(matcher Matcher) *MockRequest
AddMatcher configures the mock request to match using a custom matcher
func (r *MockRequest) BasicAuth(username, password string) *MockRequest
BasicAuth configures the mock request to match the given basic auth parameters
func (r *MockRequest) Body(b string) *MockRequest
Body configures the mock request to match the given body
func (r *MockRequest) BodyFromFile(f string) *MockRequest
BodyFromFile configures the mock request to match the given body from a file
func (r *MockRequest) Bodyf(format string, args ...interface{}) *MockRequest
Bodyf configures the mock request to match the given body. Supports formatting the body
func (r *MockRequest) Cookie(name, value string) *MockRequest
Cookie configures the mock request to match a cookie
func (r *MockRequest) CookieNotPresent(name string) *MockRequest
CookieNotPresent configures the mock request to match when a cookie is not present
func (r *MockRequest) CookiePresent(name string) *MockRequest
CookiePresent configures the mock request to match when a cookie is present, regardless of value
func (r *MockRequest) FormData(key string, values ...string) *MockRequest
FormData configures the mock request to math the given form data
func (r *MockRequest) FormDataNotPresent(key string) *MockRequest
FormDataNotPresent configures the mock request to match when the form data is not present
func (r *MockRequest) FormDataPresent(key string) *MockRequest
FormDataPresent configures the mock request to match when the form data is present, regardless of values
func (r *MockRequest) Header(key, value string) *MockRequest
Header configures the mock request to match the given header
func (r *MockRequest) HeaderNotPresent(key string) *MockRequest
HeaderNotPresent configures the mock request to match when the header is not present
func (r *MockRequest) HeaderPresent(key string) *MockRequest
HeaderPresent configures the mock request to match when this header is present, regardless of value
func (r *MockRequest) Headers(headers map[string]string) *MockRequest
Headers configures the mock request to match the given headers
func (r *MockRequest) Query(key, value string) *MockRequest
Query configures the mock request to match a query param
func (r *MockRequest) QueryCollection(queryParams map[string][]string) *MockRequest
QueryCollection configures the mock request to match a number of repeating query params, e.g. ?a=1&a=2&a=3
func (r *MockRequest) QueryNotPresent(key string) *MockRequest
QueryNotPresent configures the mock request to match when the query param is not present
func (r *MockRequest) QueryParams(queryParams map[string]string) *MockRequest
QueryParams configures the mock request to match a number of query params
func (r *MockRequest) QueryPresent(key string) *MockRequest
QueryPresent configures the mock request to match when a query param is present, regardless of value
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 struct {
// contains filtered or unexported fields
}
MockResponse represents the http response side of a mock interaction
func (r *MockResponse) Body(body string) *MockResponse
Body sets the mock response body
func (r *MockResponse) BodyFromFile(f string) *MockResponse
BodyFromFile defines the mock response body from a file
func (r *MockResponse) Bodyf(format string, args ...interface{}) *MockResponse
Bodyf sets the mock response body. Supports formatting
func (r *MockResponse) Cookie(name, value string) *MockResponse
Cookie respond with the given cookie
func (r *MockResponse) Cookies(cookie ...*Cookie) *MockResponse
Cookies respond with the given cookies
func (r *MockResponse) End() *Mock
End finalise the response definition phase in order for the mock to be used
func (r *MockResponse) EndStandalone(other ...*Mock) func()
EndStandalone finalises the response definition of standalone mocks
func (r *MockResponse) Header(key string, value string) *MockResponse
Header respond with the given header
func (r *MockResponse) Headers(headers map[string]string) *MockResponse
Headers respond with the given headers
func (r *MockResponse) Status(statusCode int) *MockResponse
Status respond with the given status
func (r *MockResponse) Timeout() *MockResponse
Timeout forces the mock to return a http timeout
func (r *MockResponse) Times(times int) *MockResponse
Times respond the given number of times
type NoopVerifier struct{}
NoopVerifier is a verifier that does not perform verification
func (n NoopVerifier) Equal(t *testing.T, expected, actual interface{}, msgAndArgs ...interface{}) bool
Equal does not perform any assertion and always returns true
Fail does not perform any assertion and always returns true
func (n NoopVerifier) JSONEq(t *testing.T, expected string, actual string, msgAndArgs ...interface{}) bool
JSONEq does not perform any assertion and always returns true
NoError asserts that a function returned no error
Observe will be called by with the request and response on completion
Recorder represents all of the report data
NewTestRecorder creates a new TestRecorder
func (r *Recorder) AddHttpRequest(req HttpRequest) *Recorder
AddHttpRequest add an http request to recorder
func (r *Recorder) AddHttpResponse(req HttpResponse) *Recorder
AddHttpResponse add an HttpResponse to the recorder
func (r *Recorder) AddMessageRequest(m MessageRequest) *Recorder
AddMessageRequest add a MessageRequest to the recorder
func (r *Recorder) AddMessageResponse(m MessageResponse) *Recorder
AddMessageResponse add a MessageResponse to the recorder
AddMeta add Meta to the recorder
AddSubTitle add a SubTitle to the recorder
AddTitle add a Title to the recorder
Reset resets the recorder to default starting state
ResponseStatus get response status of the recorder, returning an error when this wasn't possible
RecorderHook used to implement a custom interaction recorder
type ReportFormatter interface { // Format formats the events received from the recorder Format(*Recorder) }
ReportFormatter represents the report formatter
type Request struct {
// contains filtered or unexported fields
}
Request is the user defined request that will be invoked on the handler under test
BasicAuth is a builder method to sets basic auth on the request.
Body is a builder method to set the request body
BodyFromFile is a builder method to set the request body
ContentType is a builder method to set the Content-Type header of the request
Cookie is a convenience method for setting a single request cookies by name and value
Cookies is a builder method to set the request cookies
Expect marks the request spec as complete and following code will define the expected response
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
GraphQLQuery is a convenience method for building a graphql POST request
func (r *Request) GraphQLRequest(body GraphQLRequestBody) *Request
GraphQLRequest builds a graphql POST request
Header is a builder method to set the request headers
Headers is a builder method to set the request headers
JSON is a convenience method for setting the request body and content type header as "application/json". If v is not a string or []byte it will marshall the provided variable as json
JSONFromFile is a convenience method for setting the request body and content type header as "application/json"
Query is a convenience method to add a query parameter to the request.
QueryCollection is a builder method to set the request query parameters This can be used in combination with request.Query
QueryParams is a builder method to set the request query parameters. This can be used in combination with request.QueryCollection
URL is a builder method for setting the url of the request
URLf is a builder method for setting the url of the request and supports a formatter
type Response struct {
// contains filtered or unexported fields
}
Response is the user defined expected response from the application under test
Assert allows the consumer to provide a user defined function containing their own custom assertions
Body is the expected response body
BodyFromFile reads the given file and uses the content as the expected response body
Bodyf is the expected response body that supports a formatter
Cookie is used to match on an individual cookie name/value pair in the expected response cookies
CookieNotPresent is used to assert that a cookie is not present in the response
CookiePresent is used to assert that a cookie is present in the response, regardless of its value
Cookies is the expected response cookies
End runs the test returning the result to the caller
Header is a builder method to set the request headers
HeaderNotPresent is a builder method to set the request headers that should not be present in the response
HeaderPresent is a builder method to set the request headers that should be present in the response
Headers is a builder method to set the request headers
Status is the expected response http status code
Result provides the final result
JSON unmarshal the result response body to a valid struct
func (r Result) UnmatchedMocks() []UnmatchedMock
UnmatchedMocks returns any mocks that were not used, e.g. there was not a matching http Request for the mock
type SequenceDiagramFormatter struct {
// contains filtered or unexported fields
}
SequenceDiagramFormatter implementation of a ReportFormatter
func SequenceDiagram(path ...string) *SequenceDiagramFormatter
SequenceDiagram produce a sequence diagram at the given path or .sequence by default
func (r *SequenceDiagramFormatter) Format(recorder *Recorder)
Format formats the events received by the recorder
type StandaloneMocks struct {
// contains filtered or unexported fields
}
StandaloneMocks for using mocks outside of API tests context
func NewStandaloneMocks(mocks ...*Mock) *StandaloneMocks
NewStandaloneMocks create a series of StandaloneMocks
func (r *StandaloneMocks) Debug() *StandaloneMocks
Debug switch on debugging mode
func (r *StandaloneMocks) End() func()
End finalises the mock, ready for use
func (r *StandaloneMocks) HttpClient(cli *http.Client) *StandaloneMocks
HttpClient use the given http client
type Transport struct {
// contains filtered or unexported fields
}
Transport wraps components used to observe and manipulate the real request and response objects
Hijack replace the transport implementation of the interaction under test in order to observe, mock and inject expectations
Reset replace the hijacked transport implementation of the interaction under test to the original implementation
RoundTrip implementation intended to match a given expected mock request or throw an error with a list of reasons why no match was found.
UnmatchedMock exposes some information about mocks that failed to match a request
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 NoError(t *testing.T, err error, 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
Path | Synopsis |
---|---|
mocks |
Package apitest imports 25 packages (graph) and is imported by 5 packages. Updated 2021-01-20. Refresh now. Tools for package owners.