Help us shape the future of Go! Take the 2026 Go Developer Survey

apitest

package module
v1.8.0 Latest Latest
Warning

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

Go to latest
Published: Oct 27, 2026 License: MIT Imports: 34 Imported by: 21

README

Go Reference Build Status Coverage Status Mentioned in Awesome Go

apitest

A simple and extensible behavioural testing library for Go HTTP services. Tests are written the way a client uses the API: build a request, send it to the handler, and assert on the response. External HTTP calls can be mocked, and every test can render a sequence diagram of what happened.

In behavioural tests the internal structure of the app is not known by the tests. Data is input to the system and the outputs are expected to meet certain conditions.

  • Fluent builders for requests and expectations
  • Works with anything that implements http.Handler, or against a running server
  • Declarative mocks for outbound HTTP calls, with matchers for every part of the request
  • Sequence diagrams of each test, including mocked calls and database queries
  • No third party dependencies; integrates with testing, Ginkgo and custom assertion libraries

The API is stable. The library is maintained and issues are addressed; feature requests are considered.

Join the conversation at #apitest on https://gophers.slack.com.

Logo by @egonelbre

Documentation

This README covers the whole library. The same material with more narrative is at https://apitest.dev, and the API reference is on pkg.go.dev.

AI coding agents

This repository includes an Agent Skill that teaches coding agents how to write apitest tests, including the mistakes that are easy to make with mocks and JSONPath. In Claude Code, add the repository as a plugin marketplace and install the plugin:

claude plugin marketplace add steinfletcher/apitest
claude plugin install apitest@apitest

Inside a session, /plugin marketplace add steinfletcher/apitest followed by /plugin install apitest@apitest does the same. To use the skill without the plugin, or with another agent that supports Agent Skills, copy skills/apitest into the agent's skills directory, such as .claude/skills/apitest in your project.

The documentation is also available as Markdown for agents, at apitest.dev/llms-full.txt.

Installation

go get github.com/steinfletcher/apitest

Quick start

func TestGetUser(t *testing.T) {
	apitest.New().
		Handler(handler).
		Get("/user/1234").
		Expect(t).
		Status(http.StatusOK).
		Body(`{"id": "1234", "name": "Tate"}`).
		End()
}

Handler takes any http.Handler, so a http.ServeMux, a gin engine, an echo instance and so on all work. Everything before Expect(t) describes the request; everything after it describes the expected response. End() runs the test. When the expected body is valid JSON it is compared structurally, so key order and whitespace do not matter.

Demo

animated gif

Building the request

Method and URL

Get, Post, Put, Patch and Delete set the method and URL. Each has an f variant that formats the URL, and Method covers anything else.

apitest.Handler(handler).Getf("/user/%s", id)

apitest.Handler(handler).Method(http.MethodOptions).URL("/user")

A ready-made *http.Request can be used instead of the builder.

req := httptest.NewRequest(http.MethodGet, "/user/1234", nil)

apitest.Handler(handler).
	HttpRequest(req).
	Expect(t).
	Status(http.StatusOK).
	End()
Headers
apitest.Handler(handler).
	Get("/hello").
	Header("Authorization", "Bearer token").
	Headers(map[string]string{"X-Request-Id": "12345"}).
	ContentType("application/json").
	Expect(t).
	Status(http.StatusOK).
	End()
Query parameters

Query, QueryParams and QueryCollection can be combined. QueryCollection sets repeated parameters, so map[string][]string{"a": {"b", "c", "d"}} is encoded as a=b&a=c&a=d. A query string written in the URL, as in Get("/hello?page=2"), is kept, and parameters from the builder methods are appended to it.

apitest.Handler(handler).
	Get("/hello").
	QueryParams(map[string]string{"a": "1", "b": "2"}).
	Query("c", "d").
	QueryCollection(map[string][]string{"e": {"f", "g"}}).
	Expect(t).
	Status(http.StatusOK).
	End()
Cookies
apitest.Handler(handler).
	Get("/hello").
	Cookie("session", "12345").
	Cookies(apitest.NewCookie("theme").Value("dark").Path("/")).
	Expect(t).
	Status(http.StatusOK).
	End()
Body

Body sets a raw body. JSON sets the body and the Content-Type header; it accepts a string, a []byte, or any value that can be marshalled. BodyFromFile and JSONFromFile read the body from disk.

apitest.Handler(handler).
	Post("/user").
	JSON(map[string]any{"name": "jan", "age": 32}).
	Expect(t).
	Status(http.StatusCreated).
	End()

GraphQL requests are built with GraphQLQuery, or GraphQLRequest when an operation name is needed.

apitest.Handler(handler).
	Post("/graphql").
	GraphQLQuery(`query User($id: ID!) { user(id: $id) { name } }`, map[string]any{"id": "1234"}).
	Expect(t).
	Status(http.StatusOK).
	End()
Form data

FormData sends an application/x-www-form-urlencoded body.

apitest.Handler(handler).
	Post("/hello").
	FormData("a", "1").
	FormData("b", "2", "3").
	Expect(t).
	Status(http.StatusOK).
	End()

MultipartFormData and MultipartFile send multipart/form-data. The two form styles cannot be combined in one request.

apitest.Handler(handler).
	Post("/upload").
	MultipartFormData("description", "holiday photos").
	MultipartFile("file", "testdata/beach.jpg", "testdata/sunset.jpg").
	Expect(t).
	Status(http.StatusOK).
	End()

Files are read from the OS by default. UseFS swaps in any fs.FS, such as an in-memory fstest.MapFS.

inMemFS := fstest.MapFS{
	"audio.wav": &fstest.MapFile{Data: []byte{19, 2, 123, 12, 35, 1}},
}

apitest.Handler(handler).
	UseFS(inMemFS).
	Post("/upload").
	MultipartFile("file", "audio.wav").
	Expect(t).
	Status(http.StatusOK).
	End()
Basic auth
apitest.Handler(handler).
	Get("/hello").
	BasicAuth("username", "password").
	Expect(t).
	Status(http.StatusOK).
	End()
Context

WithContext sets the request context, which is how deadlines, cancellation and context values reach the handler.

ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()

apitest.Handler(handler).
	Get("/hello").
	WithContext(ctx).
	Expect(t).
	Status(http.StatusOK).
	End()
Intercept

Intercept receives the built *http.Request just before it is sent, for changes the builder does not cover.

apitest.Handler(handler).
	Intercept(func(req *http.Request) {
		req.URL.RawQuery = "a[]=xxx&a[]=yyy"
	}).
	Get("/hello").
	Expect(t).
	Status(http.StatusOK).
	End()

Asserting on the response

Status and body
apitest.Handler(handler).
	Get("/user/1234").
	Expect(t).
	Status(http.StatusOK).
	Body(`{"id": "1234", "name": "Tate"}`).
	End()

A JSON body is compared structurally. Any other body is compared as an exact string. Bodyf formats the expected body and BodyFromFile reads it from disk.

Headers
apitest.Handler(handler).
	Get("/hello").
	Expect(t).
	Status(http.StatusOK).
	Header("Content-Type", "application/json").
	Headers(map[string]string{"X-Request-Id": "12345"}).
	HeaderPresent("Etag").
	HeaderNotPresent("X-Powered-By").
	End()
Cookies

Only the fields set on the expected cookie are compared, so NewCookie("session").Value("12345") ignores the path, expiry and other attributes of the actual cookie.

apitest.Handler(handler).
	Patch("/hello").
	Expect(t).
	Status(http.StatusOK).
	Cookie("session", "12345").
	Cookies(apitest.NewCookie("theme").Value("dark").HttpOnly(true)).
	CookiePresent("csrf").
	CookieNotPresent("legacy").
	End()
Custom assertions

Assert takes a function that receives copies of the response and request and returns an error on failure. It can be called several times.

apitest.Handler(handler).
	Get("/hello").
	Expect(t).
	Assert(func(res *http.Response, req *http.Request) error {
		if res.Header.Get("X-Rate-Limit") == "" {
			return errors.New("expected a rate limit header")
		}
		return nil
	}).
	End()

apitest.IsSuccess, apitest.IsClientError and apitest.IsServerError are ready-made assertions on the status code range.

JSONPath

For asserting on parts of the response body, the separate apitest-jsonpath module provides JSONPath assertions. It is packaged separately to keep this library dependency free.

Given the response {"a": 12345, "b": [{"key": "c", "value": "result"}]}:

apitest.Handler(handler).
	Get("/hello").
	Expect(t).
	Assert(jsonpath.Contains(`$.b[? @.key=="c"].value`, "result")).
	Assert(jsonpath.Equal(`$.a`, float64(12345))).
	End()
The result

End() returns a Result holding the response, so further checks can be made after the test has run.

result := apitest.Handler(handler).
	Get("/user/1234").
	Expect(t).
	Status(http.StatusOK).
	End()

var user struct {
	Name string `json:"name"`
}
result.JSON(&user)

Mocking external HTTP calls

If the handler under test calls other services, those calls can be answered by mocks. A mock describes the request to match and the response to return.

var getUser = apitest.NewMock().
	Get("http://users/api/user/12345").
	RespondWith().
	Body(`{"name": "jon", "id": "1234"}`).
	Status(http.StatusOK).
	End()

var getPreferences = apitest.NewMock().
	Get("http://preferences/api/preferences/12345").
	Header("Authorization", "Bearer .*").
	RespondWith().
	JSON(map[string]any{"is_contactable": true}).
	Status(http.StatusOK).
	End()

func TestGetUser(t *testing.T) {
	apitest.New().
		Mocks(getUser, getPreferences).
		Handler(handler).
		Get("/user/12345").
		Expect(t).
		Status(http.StatusOK).
		Body(`{"name": "jon", "is_contactable": true}`).
		End()
}

The request side supports Header, Headers, Query, QueryParams, QueryCollection, Body, Bodyf, BodyFromFile, BodyRegexp, JSON, FormData, Cookie and BasicAuth, plus Present and NotPresent variants for headers, query parameters, form data and cookies. The response side supports Status, Body, Bodyf, BodyFromFile, JSON, Header, Headers, Cookie and Cookies. When no Content-Type is set on the response, application/json is used for a JSON body and text/plain otherwise.

Mocks work by replacing the transport of http.DefaultClient for the duration of the test. If the code under test uses its own http.Client, pass it with HttpClient so its transport is replaced instead. Because the default transport is process-wide, tests that use mocks should not run in parallel unless each provides its own client.

apitest.New().
	HttpClient(client).
	Mocks(getUser).
	Handler(handler).
	Get("/user/12345").
	Expect(t).
	Status(http.StatusOK).
	End()
How mocks are matched

Mocks are tried in the order they are passed to Mocks, and the first mock whose matchers all pass is used. Each mock is used once unless Times or AnyTimes is set. The built-in matchers behave as follows:

  • Path must equal the mock path, or match it as a regular expression. The expression is not anchored, so Get("/user") also matches /user/1234; use Get("^/user$") for an exact match.
  • Host and scheme must equal the mock's when the mock URL specifies them, otherwise they are ignored.
  • Method must equal the mock's. A mock started with Method instead of a verb method such as Get matches any URL unless one is set, as in NewMock().Method(http.MethodOptions).URL("http://users/api/user").
  • Header, query and form data values are regular expressions matched against the received values. HeaderPresent, QueryPresent, FormDataPresent and CookiePresent (and their NotPresent counterparts) check for presence regardless of value.
  • Body must equal the mock body, or be equivalent JSON. BodyRegexp matches the body against a regular expression.
  • Cookies and basic auth must equal the mock's.

When no mock matches, the call fails with an error listing why each mock was rejected. Run the test with Debug() to see it.

Custom matchers

AddMatcher adds a matcher alongside the built-in ones. It receives the actual request and the mock's request specification, and returns an error when the request should not match.

var getPreferences = apitest.NewMock().
	Get("/preferences/12345").
	AddMatcher(func(r *http.Request, mr *apitest.MockRequest) error {
		if r.URL.Scheme != "https" {
			return errors.New("expected an https request")
		}
		return nil
	}).
	RespondWith().
	Status(http.StatusOK).
	End()
Times and unused mocks

By default a mock answers one request. Times(n) makes it answer n requests and fails the test if it is called fewer times. AnyTimes lets a mock answer any number of calls, including none, and takes precedence over Times.

var getUser = apitest.NewMock().
	Get("http://users/api/user/12345").
	RespondWith().
	Status(http.StatusOK).
	Times(2).
	End()

var healthCheck = apitest.NewMock().
	Get("http://users/health").
	RespondWith().
	Status(http.StatusOK).
	AnyTimes().
	End()

Mocks that were never called are reported on the result.

result := apitest.New().
	Mocks(getUser, getPreferences).
	Handler(handler).
	Get("/user/12345").
	Expect(t).
	Status(http.StatusOK).
	End()

for _, unmatched := range result.UnmatchedMocks() {
	t.Logf("mock not called: %s", unmatched.URL.String())
}
Slow and failing dependencies

Timeout makes the mocked call fail with a timeout error. FixedDelay waits the given number of milliseconds before responding, and only takes effect when the test enables delays with EnableMockResponseDelay.

var slowUsers = apitest.NewMock().
	Get("http://users/api/user/12345").
	RespondWith().
	FixedDelay(500).
	Status(http.StatusOK).
	End()

var brokenPreferences = apitest.NewMock().
	Get("http://preferences/api/preferences/12345").
	RespondWith().
	Timeout().
	End()

func TestGetUser_WhenDependenciesAreSlow(t *testing.T) {
	apitest.New().
		EnableMockResponseDelay().
		Mocks(slowUsers, brokenPreferences).
		Handler(handler).
		Get("/user/12345").
		Expect(t).
		Status(http.StatusGatewayTimeout).
		End()
}
Observing mock calls

ObserveMocks is called with the request and response of every mocked call.

apitest.New().
	ObserveMocks(func(res *http.Response, req *http.Request, apiTest *apitest.APITest) {
		t.Logf("%s %s -> %d", req.Method, req.URL, res.StatusCode)
	}).
	Mocks(getUser).
	Handler(handler).
	Get("/user/12345").
	Expect(t).
	Status(http.StatusOK).
	End()
Standalone mocks

Mocks can also be used outside an apitest test, for example in a unit test of an HTTP client. EndStandalone and NewStandaloneMocks(...).End() install the mocks and return a function that removes them. Times and AnyTimes set how many calls each mock answers, as in a test, but a mock called fewer times than expected is not reported.

func TestUserClient(t *testing.T) {
	reset := apitest.NewMock().
		Get("http://users/api/user/12345").
		RespondWith().
		Body(`{"name": "jon"}`).
		Status(http.StatusOK).
		EndStandalone()
	defer reset()

	user, err := userClient.Get("12345")
	if err != nil {
		t.Fatal(err)
	}
	if user.Name != "jon" {
		t.Fatalf("unexpected user %+v", user)
	}
}

Use HttpClient on the mock to target a specific client, and Debug on the mock to log the matching.

Sequence diagrams and reports

Report renders every test into a report once it completes. The built-in SequenceDiagram formatter writes an HTML page per test with a sequence diagram of the request, any mocked calls, and the response, followed by the wire representation of each message. See the demo.

An apitest report for GET /user/1234, with a sequence diagram of the calls to the users and preferences services and the list of messages

The page is self-contained: styles, scripts and the diagram are inline, so it loads nothing from the network and can be archived as a CI artifact. Click an arrow to jump to its message, filter the events, focus on one participant, and copy any request as a curl command. Requests that received no response, such as calls that matched no mock, are flagged. The diagram is drawn as SVG on the server side, so it renders even where JavaScript is disabled.

func TestGetUser(t *testing.T) {
	apitest.New("gets the user").
		Report(apitest.SequenceDiagram()).
		Mocks(getUser, getPreferences).
		Handler(handler).
		Get("/user/12345").
		Expect(t).
		Status(http.StatusOK).
		End()
}

The name passed to New appears in the report. Diagrams are written to .sequence by default; pass a path to SequenceDiagram to change that. The participants are labelled cli and sut unless Meta provides names.

apitest.New("gets the user").
	Report(apitest.SequenceDiagram(".sequence-diagrams")).
	Meta(map[string]any{
		"consumerName":        "web-app",
		"systemUnderTestName": "user-api",
	}).
	Handler(handler).
	Get("/user/12345").
	Expect(t).
	Status(http.StatusOK).
	End()
Database calls in diagrams

The x/db package wraps a database/sql driver so that queries made during the test appear in the diagram. Wrap the driver with a Recorder, register the wrapped driver, open the database through it, and pass the same recorder to the test.

var recorder = apitest.NewTestRecorder()

func init() {
	sql.Register("recorded-sqlite3", apitestdb.WrapWithRecorder("sqlite3", recorder))
}

func TestGetUser(t *testing.T) {
	db, err := sql.Open("recorded-sqlite3", "./users.db")
	if err != nil {
		t.Fatal(err)
	}
	defer db.Close()

	apitest.New("gets the user").
		Recorder(recorder).
		Report(apitest.SequenceDiagram()).
		Handler(newApp(db)).
		Get("/user/12345").
		Expect(t).
		Status(http.StatusOK).
		End()
}

WrapConnectorWithRecorder does the same for a driver.Connector. See the sqlite, mysql and postgres examples.

Custom reports

Anything implementing ReportFormatter can be passed to Report. It receives the Recorder, which holds the title, the meta data and the ordered list of events, so reports can be rendered in any format. The PlantUML companion library is one example. Custom events can be added to the recorder from your own code with AddMessageRequest and AddMessageResponse.

Testing a running server

EnableNetworking sends the request over the network instead of to a handler. Pass a client to control timeouts, cookies and redirects.

client := &http.Client{Timeout: 5 * time.Second}

apitest.New().
	EnableNetworking(client).
	Get("http://localhost:8080/health").
	Expect(t).
	Status(http.StatusOK).
	End()

Debugging

Debug prints the wire representation of the inbound request, the final response, and every mocked call, together with the reasons a request failed to match any mock.

apitest.New().
	Debug().
	Handler(handler).
	Get("/hello").
	Expect(t).
	Status(http.StatusOK).
	End()

Observe gives programmatic access to the same data.

apitest.New().
	Observe(func(res *http.Response, req *http.Request, apiTest *apitest.APITest) {
		// inspect the copies of res and req
	}).
	Handler(handler).
	Get("/hello").
	Expect(t).
	Status(http.StatusOK).
	End()

Testing handler timeouts

Wrap the handler in the standard library's http.TimeoutHandler when passing it to apitest. A handler that overruns the timeout produces the 503 status and body that TimeoutHandler generates, which can be asserted on as usual. To check that a handler honours a deadline instead, pass a context with a deadline using WithContext.

func TestSlowEndpoint(t *testing.T) {
	handler := http.TimeoutHandler(slowHandler, 50*time.Millisecond, "request timed out")

	apitest.Handler(handler).
		Get("/slow").
		Expect(t).
		Status(http.StatusServiceUnavailable).
		Body("request timed out").
		End()
}

Test framework integration

Expect accepts any value implementing TestingT, which is the subset of *testing.T that apitest needs: Errorf, Fatal and Fatalf. Ginkgo's GinkgoT() satisfies it, so apitest works inside Ginkgo specs; see the Ginkgo example.

Assertions are performed through the Verifier interface. Verifier swaps in a different implementation, for example NoopVerifier to run a test without failing it, or an adapter over your preferred assertion library.

apitest.New().
	Verifier(apitest.NoopVerifier{}).
	Handler(handler).
	Get("/hello").
	Expect(t).
	Status(http.StatusTeapot).
	End()

Examples

Framework and library integration examples
Example Comment
gin popular martini-like web framework
graphql using gqlgen.com to generate a graphql server
gorilla the gorilla web toolkit
iris iris web framework
echo High performance, extensible, minimalist Go web framework
fiber Express inspired web framework written in Go
httprouter High performance HTTP request router that scales well
Ginkgo Ginkgo BDD test framework
mocks mocking out external http calls, including a custom matcher
websockets a websocket handler under test
sequence diagrams generate sequence diagrams from tests. See the demo
sqlite, mysql, postgres database queries recorded in sequence diagrams
Companion libraries
Library Comment
JSONPath JSONPath assertion addons
CSS Selectors CSS selector assertion addons
PlantUML Export sequence diagrams as plantUML
DynamoDB Add DynamoDB interactions to sequence diagrams
Credits

This library was influenced by the following software packages:

  • YatSpec for creating sequence diagrams from tests
  • MockMVC and superagent for the concept and behavioural testing approach
  • Gock for the approach to mocking HTTP services in Go
  • Baloo for API design

Contributing

View the contributing guide.

Documentation

Index

Constants

View Source
const ConsumerDefaultName = "cli"

ConsumerDefaultName default consumer name

View Source
const SystemUnderTestDefaultName = "sut"

SystemUnderTestDefaultName default name for system under test

Variables

This section is empty.

Functions

This section is empty.

Types

type APITest

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

APITest is the top level struct holding the test spec

func Handler added in v1.5.4

func Handler(handler http.Handler) *APITest

Handler is a convenience method for creating a new apitest with a handler

func HandlerFunc added in v1.5.4

func HandlerFunc(handlerFunc http.HandlerFunc) *APITest

HandlerFunc is a convenience method for creating a new apitest with a handler func

func New

func New(name ...string) *APITest

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

func (*APITest) Debug

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 added in v1.0.3

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

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

func (*APITest) Deletef added in v1.4.14

func (a *APITest) Deletef(format string, args ...any) *Request

Deletef is a convenience method that adds formatting support to Delete

func (*APITest) EnableMockResponseDelay added in v1.5.0

func (a *APITest) EnableMockResponseDelay() *APITest

EnableMockResponseDelay turns on mock response delays (defaults to OFF)

func (*APITest) EnableNetworking added in v1.3.0

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

EnableNetworking will enable networking for provided clients

func (*APITest) Get added in v1.0.3

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

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

func (*APITest) Getf added in v1.4.14

func (a *APITest) Getf(format string, args ...any) *Request

Getf is a convenience method that adds formatting support to Get

func (*APITest) Handler

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

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

func (*APITest) HandlerFunc added in v1.4.5

func (a *APITest) HandlerFunc(handlerFunc http.HandlerFunc) *APITest

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

func (*APITest) Host added in v1.6.0

func (a *APITest) Host(host string) *APITest

Host is a builder method for explicitly setting the host

func (*APITest) HttpClient

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

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

func (*APITest) HttpRequest added in v1.5.11

func (a *APITest) HttpRequest(req *http.Request) *Request

HttpRequest defines the native `http.Request`

func (*APITest) Intercept added in v1.0.3

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

Intercept is a builder method for setting the request interceptor

func (*APITest) Meta added in v1.0.2

func (a *APITest) Meta(meta map[string]any) *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 added in v1.0.3

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

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

func (*APITest) Mocks

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

Mocks is a builder method for setting the mocks

func (*APITest) Observe

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

Observe is a builder method for setting the observers

func (*APITest) ObserveMocks

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

ObserveMocks is a builder method for setting the mocks observers

func (*APITest) Patch added in v1.0.3

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

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

func (*APITest) Patchf added in v1.4.14

func (a *APITest) Patchf(format string, args ...any) *Request

Patchf is a convenience method that adds formatting support to Patch

func (*APITest) Post added in v1.0.3

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

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

func (*APITest) Postf added in v1.4.14

func (a *APITest) Postf(format string, args ...any) *Request

Postf is a convenience method that adds formatting support to Post

func (*APITest) Put added in v1.0.3

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

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

func (*APITest) Putf added in v1.4.14

func (a *APITest) Putf(format string, args ...any) *Request

Putf is a convenience method that adds formatting support to Put

func (*APITest) Recorder added in v1.1.3

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

Recorder provides a hook to add a recorder to the test

func (*APITest) RecorderHook

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 added in v1.0.2

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

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

func (*APITest) Request

func (a *APITest) Request() *Request

Request returns the request spec

func (*APITest) Response

func (a *APITest) Response() *Response

Response returns the expected response

func (*APITest) UseFS added in v1.6.0

func (a *APITest) UseFS(fs fs.FS) *APITest

Use filesystem allows you to change to a custom fs.FS filesystem that you can define (Used by Request.MultipartFile). e.g: fstest.MapFS Your os filesystem is used by default

func (*APITest) Verifier added in v1.3.8

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

Verifier allows consumers to override the verification implementation.

type Assert

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 added in v1.3.10

func FromHTTPCookie(httpCookie *http.Cookie) *Cookie

FromHTTPCookie transforms an http cookie into a Cookie

func NewCookie

func NewCookie(name string) *Cookie

NewCookie creates a new Cookie with the provided name

func (*Cookie) Domain

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

Domain sets the domain of the Cookie

func (*Cookie) Expires

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

Expires sets the expires time of the Cookie

func (*Cookie) HttpOnly

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

HttpOnly sets the httpOnly bool of the Cookie

func (*Cookie) MaxAge

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

MaxAge sets the maxage of the Cookie

func (*Cookie) Path

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

Path sets the path of the Cookie

func (*Cookie) Secure

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

Secure sets the secure bool of the Cookie

func (*Cookie) ToHttpCookie

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

ToHttpCookie transforms the Cookie to an http cookie

func (*Cookie) Value

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

Value sets the value of the Cookie

type DefaultVerifier added in v1.5.7

type DefaultVerifier struct{}

DefaultVerifier is a verifier that uses some code from https://github.com/stretchr/testify to perform assertions

func (DefaultVerifier) Equal added in v1.5.7

func (a DefaultVerifier) Equal(t TestingT, expected, actual any, msgAndArgs ...any) bool

func (DefaultVerifier) Fail added in v1.5.7

func (a DefaultVerifier) Fail(t TestingT, failureMessage string, msgAndArgs ...any) bool

Fail reports a failure

func (DefaultVerifier) JSONEq added in v1.5.7

func (a DefaultVerifier) JSONEq(t TestingT, expected string, actual string, msgAndArgs ...any) bool

JSONEq asserts that two JSON strings are equivalent

func (DefaultVerifier) NoError added in v1.5.7

func (a DefaultVerifier) NoError(t TestingT, err error, msgAndArgs ...any) bool

NoError asserts that a function returned no error

func (DefaultVerifier) True added in v1.5.7

func (a DefaultVerifier) True(t TestingT, value bool, msgAndArgs ...any) bool

type Event

type Event interface {
	GetTime() time.Time
}

Event represents a reporting event

type FinalResponse deprecated

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

FinalResponse used to wrap the final response with a timestamp

Deprecated: FinalResponse is not used by apitest and is retained only for API compatibility.

type GraphQLRequestBody added in v1.4.10

type GraphQLRequestBody struct {
	Query         string         `json:"query"`
	Variables     map[string]any `json:"variables,omitempty"`
	OperationName string         `json:"operationName,omitempty"`
}

GraphQLRequestBody represents the POST request body as per the GraphQL spec

type HttpRequest

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

HttpRequest represents an http request

func (HttpRequest) GetTime

func (r HttpRequest) GetTime() time.Time

GetTime gets the time of the HttpRequest interaction

type HttpResponse

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

HttpResponse represents an http response

func (HttpResponse) GetTime

func (r HttpResponse) GetTime() time.Time

GetTime gets the time of the HttpResponse interaction

type InboundRequest deprecated

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

InboundRequest used to wrap the incoming request with a timestamp

Deprecated: InboundRequest is not used by apitest and is retained only for API compatibility.

type Intercept

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

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

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

MessageRequest represents a request interaction

func (MessageRequest) GetTime

func (r MessageRequest) GetTime() time.Time

GetTime gets the time of the MessageRequest interaction

type MessageResponse

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

MessageResponse represents a response interaction

func (MessageResponse) GetTime

func (r MessageResponse) GetTime() time.Time

GetTime gets the time of the MessageResponse interaction

type Mock

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

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

func NewMock

func NewMock() *Mock

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

func (*Mock) Debug added in v1.2.0

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

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

Delete configures the mock to match http method DELETE

func (*Mock) Deletef added in v1.4.15

func (m *Mock) Deletef(format string, args ...any) *MockRequest

Deletef configures the mock to match http method DELETE and supports formatting

func (*Mock) Get

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

Get configures the mock to match http method GET

func (*Mock) Getf added in v1.4.15

func (m *Mock) Getf(format string, args ...any) *MockRequest

Getf configures the mock to match http method GET and supports formatting

func (*Mock) Head added in v1.4.1

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

Head configures the mock to match http method HEAD

func (*Mock) HttpClient added in v1.2.0

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

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

func (*Mock) Matches added in v1.3.7

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

Matches checks whether the given request matches the mock

func (*Mock) Method

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

Method configures mock to match given http method. The mock matches any url unless one is set using MockRequest.URL

func (*Mock) Patch

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

Patch configures the mock to match http method PATCH

func (*Mock) Patchf added in v1.4.15

func (m *Mock) Patchf(format string, args ...any) *MockRequest

Patchf configures the mock to match http method PATCH and supports formatting

func (*Mock) Post

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

Post configures the mock to match http method POST

func (*Mock) Postf added in v1.4.15

func (m *Mock) Postf(format string, args ...any) *MockRequest

Postf configures the mock to match http method POST and supports formatting

func (*Mock) Put

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

Put configures the mock to match http method PUT

func (*Mock) Putf added in v1.4.15

func (m *Mock) Putf(format string, args ...any) *MockRequest

Putf configures the mock to match http method PUT and supports formatting

type MockRequest

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

MockRequest represents the http request side of a mock interaction

func (*MockRequest) AddMatcher added in v1.1.0

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

AddMatcher configures the mock request to match using a custom matcher

func (*MockRequest) BasicAuth added in v1.4.6

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

BasicAuth configures the mock request to match the given basic auth parameters

func (*MockRequest) Body

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

Body configures the mock request to match the given body

func (*MockRequest) BodyFromFile added in v1.4.0

func (r *MockRequest) BodyFromFile(f string) *MockRequest

BodyFromFile configures the mock request to match the given body from a file

func (*MockRequest) BodyRegexp added in v1.5.6

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

BodyRegexp configures the mock request to match the given body using the regexp matcher

func (*MockRequest) Bodyf added in v1.4.15

func (r *MockRequest) Bodyf(format string, args ...any) *MockRequest

Bodyf configures the mock request to match the given body. Supports formatting the body

func (*MockRequest) Cookie added in v1.1.5

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

Cookie configures the mock request to match a cookie

func (*MockRequest) CookieNotPresent added in v1.1.5

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

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

func (*MockRequest) CookiePresent added in v1.1.5

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 added in v1.3.3

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

FormData configures the mock request to math the given form data

func (*MockRequest) FormDataNotPresent added in v1.3.3

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

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

func (*MockRequest) FormDataPresent added in v1.3.3

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

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

Header configures the mock request to match the given header

func (*MockRequest) HeaderNotPresent added in v1.2.1

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

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

func (*MockRequest) HeaderPresent added in v1.2.1

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

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

Headers configures the mock request to match the given headers

func (*MockRequest) JSON added in v1.5.2

func (r *MockRequest) JSON(v any) *MockRequest

JSON is a convenience method for setting the mock request body

func (*MockRequest) Query

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

Query configures the mock request to match a query param

func (*MockRequest) QueryCollection added in v1.4.6

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 (*MockRequest) QueryNotPresent added in v1.2.1

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

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

func (*MockRequest) QueryParams

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

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

func (*MockRequest) QueryPresent

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

func (r *MockRequest) RespondWith() *MockResponse

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

func (*MockRequest) URL added in v1.7.0

func (r *MockRequest) URL(u string) *MockRequest

URL configures the mock request to match the given url

func (*MockRequest) URLf added in v1.7.0

func (r *MockRequest) URLf(format string, args ...any) *MockRequest

URLf configures the mock request to match the given url and supports formatting

type MockResponse

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

MockResponse represents the http response side of a mock interaction

func (*MockResponse) AnyTimes added in v1.5.17

func (r *MockResponse) AnyTimes() *MockResponse

AnyTimes respond any number of times

func (*MockResponse) Body

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

Body sets the mock response body

func (*MockResponse) BodyFromFile added in v1.4.0

func (r *MockResponse) BodyFromFile(f string) *MockResponse

BodyFromFile defines the mock response body from a file

func (*MockResponse) Bodyf added in v1.4.15

func (r *MockResponse) Bodyf(format string, args ...any) *MockResponse

Bodyf sets the mock response body. Supports formatting

func (*MockResponse) Cookie

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

Cookie respond with the given cookie

func (*MockResponse) Cookies

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

Cookies respond with the given cookies

func (*MockResponse) End

func (r *MockResponse) End() *Mock

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

func (*MockResponse) EndStandalone added in v1.2.0

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

EndStandalone finalises the response definition of standalone mocks

func (*MockResponse) FixedDelay added in v1.5.0

func (r *MockResponse) FixedDelay(delay int64) *MockResponse

FixedDelay will return the response after the given number of milliseconds. APITest::EnableMockResponseDelay must be set for this to take effect. If Timeout is set this has no effect.

func (*MockResponse) Header

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

Header respond with the given header

func (*MockResponse) Headers

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

Headers respond with the given headers

func (*MockResponse) JSON added in v1.5.2

func (r *MockResponse) JSON(v any) *MockResponse

JSON is a convenience method for setting the mock response body

func (*MockResponse) Status

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

Status respond with the given status

func (*MockResponse) Timeout added in v1.4.11

func (r *MockResponse) Timeout() *MockResponse

Timeout forces the mock to return a http timeout

func (*MockResponse) Times

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

Times respond the given number of times, if AnyTimes is set this has no effect

type NoopVerifier added in v1.3.8

type NoopVerifier struct{}

NoopVerifier is a verifier that does not perform verification

func (NoopVerifier) Equal added in v1.3.8

func (n NoopVerifier) Equal(t TestingT, expected, actual any, msgAndArgs ...any) bool

Equal does not perform any assertion and always returns true

func (NoopVerifier) Fail added in v1.3.8

func (n NoopVerifier) Fail(t TestingT, failureMessage string, msgAndArgs ...any) bool

Fail does not perform any assertion and always returns true

func (NoopVerifier) JSONEq added in v1.3.8

func (n NoopVerifier) JSONEq(t TestingT, expected string, actual string, msgAndArgs ...any) bool

JSONEq does not perform any assertion and always returns true

func (NoopVerifier) NoError added in v1.4.8

func (n NoopVerifier) NoError(t TestingT, err error, msgAndArgs ...any) bool

NoError asserts that a function returned no error

func (NoopVerifier) True added in v1.5.7

func (n NoopVerifier) True(t TestingT, v bool, msgAndArgs ...any) bool

type OSFS added in v1.6.0

type OSFS struct {
}

An implementation of fs.FS that wraps your OS's filesystem

func (OSFS) Open added in v1.6.0

func (OSFS) Open(name string) (file fs.File, err error)

Calls os.Open

type Observe

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

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

type Recorder

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

Recorder represents all of the report data

func NewTestRecorder

func NewTestRecorder() *Recorder

NewTestRecorder creates a new TestRecorder

func (*Recorder) AddHttpRequest

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

AddHttpRequest add an http request to recorder

func (*Recorder) AddHttpResponse

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

AddHttpResponse add an HttpResponse to the recorder

func (*Recorder) AddMessageRequest

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

AddMessageRequest add a MessageRequest to the recorder

func (*Recorder) AddMessageResponse

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

AddMessageResponse add a MessageResponse to the recorder

func (*Recorder) AddMeta

func (r *Recorder) AddMeta(meta map[string]any) *Recorder

AddMeta add Meta to the recorder

func (*Recorder) AddSubTitle

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

AddSubTitle add a SubTitle to the recorder

func (*Recorder) AddTitle

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

AddTitle add a Title to the recorder

func (*Recorder) Reset added in v1.2.2

func (r *Recorder) Reset()

Reset resets the recorder to default starting state

func (*Recorder) ResponseStatus

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

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

type RecorderHook

type RecorderHook func(*Recorder)

RecorderHook used to implement a custom interaction recorder

type ReportFormatter

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

ReportFormatter represents the report formatter

type Request

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

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

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

func (*Request) Body

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

Body is a builder method to set the request body

func (*Request) BodyFromFile added in v1.4.0

func (r *Request) BodyFromFile(f string) *Request

BodyFromFile is a builder method to set the request body

func (*Request) Bodyf added in v1.5.3

func (r *Request) Bodyf(format string, args ...any) *Request

Bodyf sets the request body and supports a formatter

func (*Request) ContentType added in v1.3.3

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

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

func (*Request) Cookie

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

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

Cookies is a builder method to set the request cookies

func (*Request) Expect

func (r *Request) Expect(t TestingT) *Response

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

func (*Request) FormData added in v1.3.3

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) GraphQLQuery added in v1.4.10

func (r *Request) GraphQLQuery(query string, variables ...map[string]any) *Request

GraphQLQuery is a convenience method for building a graphql POST request

func (*Request) GraphQLRequest added in v1.4.10

func (r *Request) GraphQLRequest(body GraphQLRequestBody) *Request

GraphQLRequest builds a graphql POST request

func (*Request) Header

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

Header is a builder method to set the request headers

func (*Request) Headers

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

Headers is a builder method to set the request headers

func (*Request) JSON

func (r *Request) JSON(v any) *Request

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

func (*Request) JSONFromFile added in v1.4.0

func (r *Request) JSONFromFile(f string) *Request

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

func (*Request) MultipartFile added in v1.5.12

func (r *Request) MultipartFile(name string, ff ...string) *Request

MultipartFile is a builder method to set the file in multipart form data Also sets the content type of the request to multipart/form-data

func (*Request) MultipartFormData added in v1.5.12

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

MultipartFormData is a builder method to set the field in multipart form data Also sets the content type of the request to multipart/form-data

func (*Request) Query

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

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

func (*Request) QueryCollection

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

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

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

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

func (*Request) URLf added in v1.4.14

func (r *Request) URLf(format string, args ...any) *Request

URLf is a builder method for setting the url of the request and supports a formatter

func (*Request) WithContext added in v1.5.14

func (r *Request) WithContext(ctx context.Context) *Request

WithContext is a builder method to set a context on the request

type Response

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

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

func (*Response) Assert

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

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

Body is the expected response body

func (*Response) BodyFromFile added in v1.4.0

func (r *Response) BodyFromFile(f string) *Response

BodyFromFile reads the given file and uses the content as the expected response body

func (*Response) Bodyf added in v1.4.14

func (r *Response) Bodyf(format string, args ...any) *Response

Bodyf is the expected response body that supports a formatter

func (*Response) Cookie added in v1.0.12

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

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

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

func (*Response) CookiePresent

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

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

Cookies is the expected response cookies

func (*Response) End

func (r *Response) End() Result

End runs the test returning the result to the caller

func (*Response) Header

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

Header is a builder method to set the request headers

func (*Response) HeaderNotPresent added in v1.1.5

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

HeaderNotPresent is a builder method to set the headers that should not be present in the response. The check fails whenever the header key exists, regardless of value, including an empty value.

func (*Response) HeaderPresent added in v1.1.5

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

HeaderPresent is a builder method to set the headers that should be present in the response. The check passes when the header key exists, regardless of value, including an empty value.

func (*Response) Headers

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

Headers is a builder method to set the request headers

func (*Response) Status

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

Status is the expected response http status code

type Result added in v1.1.5

type Result struct {
	Response *http.Response
	// contains filtered or unexported fields
}

Result provides the final result

func (Result) JSON added in v1.3.1

func (r Result) JSON(t any)

JSON unmarshal the result response body to a valid struct

func (Result) UnmatchedMocks added in v1.4.9

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

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

SequenceDiagramFormatter implementation of a ReportFormatter

func SequenceDiagram added in v1.0.2

func SequenceDiagram(path ...string) *SequenceDiagramFormatter

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

func (*SequenceDiagramFormatter) Format

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

Format formats the events received by the recorder

type StandaloneMocks added in v1.3.2

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

StandaloneMocks for using mocks outside of API tests context

func NewStandaloneMocks added in v1.3.2

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

NewStandaloneMocks create a series of StandaloneMocks

func (*StandaloneMocks) Debug added in v1.3.2

func (r *StandaloneMocks) Debug() *StandaloneMocks

Debug switch on debugging mode

func (*StandaloneMocks) End added in v1.3.2

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

End finalises the mock, ready for use

func (*StandaloneMocks) HttpClient added in v1.3.2

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

HttpClient use the given http client

type TestingT added in v1.5.2

type TestingT interface {
	Errorf(format string, args ...any)
	Fatal(args ...any)
	Fatalf(format string, args ...any)
}

TestingT is an interface to wrap the native *testing.T interface, this allows integration with GinkgoT() interface GinkgoT interface defined in https://github.com/onsi/ginkgo/blob/55c858784e51c26077949c81b6defb6b97b76944/ginkgo_dsl.go#L91

type Transport

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

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

func (r *Transport) Reset()

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

func (*Transport) RoundTrip

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 UnmatchedMock added in v1.4.9

type UnmatchedMock struct {
	URL url.URL
}

UnmatchedMock exposes some information about mocks that failed to match a request

type Verifier added in v1.3.8

type Verifier interface {
	Equal(t TestingT, expected, actual any, msgAndArgs ...any) bool
	True(t TestingT, value bool, msgAndArgs ...any) bool
	JSONEq(t TestingT, expected string, actual string, msgAndArgs ...any) bool
	Fail(t TestingT, failureMessage string, msgAndArgs ...any) bool
	NoError(t TestingT, err error, msgAndArgs ...any) 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

Path Synopsis
Package difflib is a partial port of Python difflib module.
Package difflib is a partial port of Python difflib module.
examples module
x
db

Jump to

Keyboard shortcuts

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