API overview
Every exported type and method in apitest, grouped by where it is used.
This page lists the whole API of github.com/steinfletcher/apitest v1.8.0, the release these docs are tested against, with links to the guides. Signatures and doc comments are on pkg.go.dev.
Starting a test
| Function | Returns | Description |
|---|---|---|
New(name ...string) | *APITest | Starts a test. The optional name appears in reports. |
Handler(h http.Handler) | *APITest | Shorthand for New().Handler(h). |
HandlerFunc(f http.HandlerFunc) | *APITest | Shorthand for New().HandlerFunc(f). |
APITest
Configuration methods return *APITest. The request methods return *Request. See anatomy of a test.
| Method | Description |
|---|---|
Handler(http.Handler), HandlerFunc(http.HandlerFunc) | The handler under test. Requests |
Mocks(...*Mock) | The mocks for this test. Replaces earlier mocks. Mocks |
HttpClient(*http.Client) | Mock the transport of this client instead of http.DefaultTransport. HTTP clients |
EnableMockResponseDelay() | Honour FixedDelay on mocks. Failures and latency |
ObserveMocks(Observe) | Called for every mocked call. Observing mocks |
Observe(...Observe) | Called with the final response. Replaces earlier observers. Debugging |
Debug() | Print every request and response. Debugging |
Report(ReportFormatter) | Render the test as a report. Sequence diagrams |
Recorder(*Recorder) | Use this recorder, for custom events. Custom reports |
Meta(map[string]any) | Values passed to reports. Sequence diagrams |
Intercept(Intercept) | Change the request before it is sent. Intercept |
EnableNetworking(...*http.Client) | Send the request over the network. End-to-end tests |
Verifier(Verifier) | Replace the assertion implementation. Test frameworks |
UseFS(fs.FS) | The file system for MultipartFile. Forms |
Host(string) | The request Host. Defaults to sut. Requests |
Get, Post, Put, Patch, Delete (url string) | Start the request with a method and URL. |
Getf, Postf, Putf, Patchf, Deletef (format string, args ...any) | As above, with a formatted URL. |
Method(string) | Start the request with a method. Set the URL with URL. |
HttpRequest(*http.Request) | Use a ready-made request. Requests |
Request(), Response() | The request and expectation builders of the test. |
RecorderHook(RecorderHook) | Deprecated. Use Recorder. |
Request
Request methods return *Request. Expect(t) returns *Response.
| Method | Description |
|---|---|
URL(string), URLf(format, args...) | The URL. |
Header(key, value), Headers(map[string]string) | Add headers. Headers |
ContentType(string) | Set Content-Type. |
Query(key, value), QueryParams(map[string]string), QueryCollection(map[string][]string) | Add query parameters. Query parameters |
Cookie(name, value), Cookies(...*Cookie) | Add cookies. Cookies |
Body(string), Bodyf(format, args...), BodyFromFile(path) | Set the body. Body |
JSON(any), JSONFromFile(path) | Set a JSON body and content type. Body |
FormData(name, values...) | Add URL encoded form fields. Forms |
MultipartFormData(name, values...), MultipartFile(name, paths...) | Add multipart fields and files. Forms |
GraphQLQuery(query, variables...), GraphQLRequest(GraphQLRequestBody) | Build a GraphQL request. GraphQL |
BasicAuth(username, password) | Set basic auth credentials. Authentication |
WithContext(context.Context) | Set the request context. Context |
Expect(TestingT) | End the request and start the expectations. |
Response
Expectation methods return *Response. End() returns Result.
| Method | Description |
|---|---|
Status(int) | The status code. Assertions |
Body(string), Bodyf(format, args...), BodyFromFile(path) | The body, compared as JSON when valid JSON. Body |
Header(key, value), Headers(map[string]string) | Header values. Headers |
HeaderPresent(key), HeaderNotPresent(key) | Header presence. |
Cookie(name, value), Cookies(...*Cookie) | Cookies. Cookies |
CookiePresent(name), CookieNotPresent(name) | Cookie presence. |
Assert(func(*http.Response, *http.Request) error) | A custom assertion. Custom assertions |
End() | Run the test. |
Result
| Member | Description |
|---|---|
Response *http.Response | A copy of the final response. The result |
JSON(any) | Decode the response body. |
UnmatchedMocks() []UnmatchedMock | Mocks no request matched. Each has a URL url.URL. |
Mock
NewMock() returns *Mock. The verb methods return *MockRequest.
| Method | Description |
|---|---|
Get, Post, Put, Patch, Delete, Head (url string) | Match the method and URL. Defining mocks |
Getf, Postf, Putf, Patchf, Deletef (format, args...) | As above, with a formatted URL. |
Method(string) | Match any method. Matches any URL unless URL or URLf sets one. Request matchers |
HttpClient(*http.Client), Debug() | Options for standalone mocks. |
Matches(*http.Request) []error | Run the mock's matchers against a request. |
MockRequest
Matchers return *MockRequest. RespondWith() returns *MockResponse. See request matchers.
| Method | Matches |
|---|---|
URL(url), URLf(format, args...) | The URL, for a mock started with Method. Added in v1.7.0. |
Header(key, pattern), Headers(map[string]string) | Header values, as regular expressions. |
HeaderPresent(key), HeaderNotPresent(key) | Header presence. |
Query(key, pattern), QueryParams(map[string]string), QueryCollection(map[string][]string) | Query values, as regular expressions. |
QueryPresent(key), QueryNotPresent(key) | Query presence. |
Body(string), Bodyf(format, args...), BodyFromFile(path), JSON(any) | The body, exactly or as equivalent JSON. |
BodyRegexp(pattern) | The body, as a regular expression. |
FormData(key, patterns...) | Form values, as regular expressions. |
FormDataPresent(key), FormDataNotPresent(key) | Form field presence. |
Cookie(name, value), CookiePresent(name), CookieNotPresent(name) | Cookies. |
BasicAuth(username, password) | Basic auth credentials. |
AddMatcher(Matcher) | A custom matcher. |
RespondWith() | End the request and start the response. |
MockResponse
Methods return *MockResponse. End() returns *Mock. See responses.
| Method | Description |
|---|---|
Status(int) | The status code. Defaults to 0. |
Header(key, value), Headers(map[string]string) | Response headers. |
Cookie(name, value), Cookies(...*Cookie) | Response cookies. |
Body(string), Bodyf(format, args...), BodyFromFile(path), JSON(any) | The body. |
Times(int), AnyTimes() | How many calls the mock answers. Call counts |
Timeout(), FixedDelay(ms int64) | Fail with a timeout, or respond slowly. Failures and latency |
End() | Finish the mock. |
EndStandalone(...*Mock) func() | Install as a standalone mock and return the reset function. |
StandaloneMocks
NewStandaloneMocks returns a *StandaloneMocks. See standalone mocks.
| Function or method | Description |
|---|---|
NewStandaloneMocks(...*Mock) | Group mocks for standalone use. |
HttpClient(*http.Client), Debug() | Options. |
End() func() | Install the mocks and return the reset function. |
Cookie
| Function or method | Description |
|---|---|
NewCookie(name) | Start a cookie. |
Value, Path, Domain, Expires, MaxAge, Secure, HttpOnly | Set a field. Unset fields are ignored in comparisons. |
FromHTTPCookie(*http.Cookie), ToHttpCookie() | Convert to and from *http.Cookie. |
Reports
| Name | Description |
|---|---|
SequenceDiagram(path ...string) | Returns a *SequenceDiagramFormatter, the HTML sequence diagram formatter. Its Format method writes the report. |
ReportFormatter | The interface for custom formatters. |
NewTestRecorder(), Recorder | The recorded title, subtitle, meta data and events. |
Recorder.AddHttpRequest, AddHttpResponse, AddMessageRequest, AddMessageResponse | Add events. |
Recorder.AddTitle, AddSubTitle, AddMeta, Reset, ResponseStatus | Manage the recorder. |
HttpRequest, HttpResponse, MessageRequest, MessageResponse | The event types. Each implements Event, whose GetTime returns when it happened. |
ConsumerDefaultName, SystemUnderTestDefaultName | The participant names cli and sut. |
Types for extension
| Type | Signature |
|---|---|
Assert | func(*http.Response, *http.Request) error |
Matcher | func(*http.Request, *MockRequest) error |
Observe | func(*http.Response, *http.Request, *APITest) |
Intercept | func(*http.Request) |
TestingT | Errorf, Fatal and Fatalf. Test frameworks |
Verifier | Equal, True, JSONEq, Fail and NoError. Implemented by DefaultVerifier and NoopVerifier. |
GraphQLRequestBody | Query, Variables and OperationName. |
Ready-made assertions
IsSuccess, IsClientError and IsServerError assert that the status code is in the 200 to 399, 400 to 499, or 500 and above range.
Internal and deprecated
These are exported but rarely needed in tests.
| Name | Description |
|---|---|
Transport | The http.RoundTripper that answers mocked calls. Hijack installs it, Reset restores the original transport, and RoundTrip matches a request against the mocks. apitest manages it for you. |
OSFS | The default fs.FS behind UseFS. Open reads from the operating system. |
InboundRequest, FinalResponse | Deprecated. Not used by apitest, and kept for compatibility. |
RecorderHook | Deprecated. Use Recorder. |
Sub-packages
| Package | Contents |
|---|---|
github.com/steinfletcher/apitest/x/db | WrapWithRecorder and WrapConnectorWithRecorder. Database interactions |
github.com/steinfletcher/apitest/mocks | MockVerifier, a stubbable Verifier. |