httpclienttest

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2026 License: MIT Imports: 17 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package httpclienttest replaces an application's outgoing HTTP transport with a Fake that returns scripted responses and records every request, so tests never hit the network.

Install a fake on a test client with New, stub responses with Fake.Respond, and assert on the recorded requests:

func TestShowsAGitHubProfile(t *testing.T) {
	client := laraveltest.New(t, bootstrap.Options())
	github := httpclienttest.New(client).
		Respond("api.github.com/users/*", httpclienttest.JSON(map[string]any{"login": "taylorotwell"}))

	client.Get("/profile").AssertOK().AssertSee("taylorotwell")

	github.AssertSent(func(req *httpclienttest.Request) bool {
		return req.URL == "https://api.github.com/users/taylorotwell"
	})
}

Each application under test gets its own fake, so parallel tests never share stubs or recorded requests.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Answer

type Answer interface {
	// contains filtered or unexported methods
}

Answer produces a fake response or error for an outgoing Request. Build one with Status, Text, JSON, NewSequence, FailedConnection, or AnswerFunc.

func FailedConnection

func FailedConnection() Answer

FailedConnection returns an Answer that simulates a network connection failure, as if the remote host were unreachable. The outgoing request fails with *httpclient.ConnectionError.

type AnswerFunc

type AnswerFunc func(req *Request) Answer

AnswerFunc adapts a function to an Answer when the fake response depends on the incoming Request:

httpclienttest.AnswerFunc(func(req *httpclienttest.Request) httpclienttest.Answer {
	if req.HasHeader("Authorization", "Bearer secret") {
		return httpclienttest.Status(200)
	}
	return httpclienttest.Status(401)
})

type Fake

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

Fake intercepts an application's outgoing HTTP requests, answers them with scripted responses, and records each request. Unmatched requests receive an empty 200 OK response unless Fake.PreventStrayRequests or Fake.AllowStrayRequests is configured. Assertions report failures on the test associated with the client passed to New. Fake is safe for concurrent use.

func New

func New(client interface{ Context() context.Context }) *Fake

New installs a Fake on the application that client tests and returns it. Assertions on the returned fake report failures to the client's test. New fails the test if an HTTP client fake is already installed, and panics if client.Context does not carry a test client.

func (*Fake) AllowStrayRequests

func (f *Fake) AllowStrayRequests(urlPatterns ...string) *Fake

AllowStrayRequests allows unmatched requests whose URL matches any of urlPatterns to reach the real network, such as a local test server, and returns f for chaining.

func (*Fake) AssertNotSent

func (f *Fake) AssertNotSent(match func(req *Request) bool)

AssertNotSent fails the test if any recorded request satisfies match.

func (*Fake) AssertNothingSent

func (f *Fake) AssertNothingSent()

AssertNothingSent fails the test if any outgoing request was recorded.

func (*Fake) AssertSent

func (f *Fake) AssertSent(match func(req *Request) bool)

AssertSent fails the test unless at least one recorded request satisfies match:

fake.AssertSent(func(req *httpclienttest.Request) bool {
	return req.Method == http.MethodPost &&
		req.URL == "https://example.com/users" &&
		req.HasHeader("X-Tenant", "acme") &&
		req.Data()["name"] == "Taylor"
})

func (*Fake) AssertSentCount

func (f *Fake) AssertSentCount(count int)

AssertSentCount fails the test unless the total number of recorded requests, including retries, equals count.

func (*Fake) PreventStrayRequests

func (f *Fake) PreventStrayRequests() *Fake

PreventStrayRequests configures f to fail any request that matches no registered pattern with httpclient.ErrNotFaked instead of returning an empty 200 OK response, and returns f for chaining.

func (*Fake) Recorded

func (f *Fake) Recorded() []Record

Recorded returns a copy of every recorded request-response pair, in order. A request that failed or reached the network has a nil Response.

func (*Fake) Respond

func (f *Fake) Respond(urlPattern string, answer Answer) *Fake

Respond registers answer for outgoing requests whose URL matches urlPattern and returns f for chaining. Patterns match anywhere in the URL, with * matching any sequence of characters, so "github.com/*" matches "https://api.github.com/user". Matching checks both the raw URL and its path-unescaped form, so "customers/vip@example.com" matches "customers/vip%40example.com". When multiple patterns match, the first one registered wins:

fake.Respond("api.github.com/users/*", httpclienttest.JSON(user)).
	Respond("api.stripe.com/*", httpclienttest.JSON(declined).WithStatus(402)).
	Respond("example.com/health", httpclienttest.Status(503)).
	Respond("*", httpclienttest.Text("Hello World"))

func (*Fake) Sent

func (f *Fake) Sent() []*Request

Sent returns every outgoing request recorded by f, in order, including retries and requests that received no response.

func (*Fake) Transport

func (f *Fake) Transport(next http.RoundTripper) http.RoundTripper

Transport wraps next in an http.RoundTripper that intercepts requests with f and forwards only requests permitted by Fake.AllowStrayRequests to next.

type File

type File struct {
	// Field is the multipart form field name.
	Field string
	// Name is the filename sent in the multipart part header.
	Name string
	// ContentType is the MIME type sent in the multipart part header.
	ContentType string
	// Contents holds the raw bytes of the uploaded file.
	Contents []byte
}

File is a file uploaded in a multipart form request.

type Record

type Record struct {
	// Request is the snapshot of the outgoing HTTP request as sent.
	Request *Request
	// Response is the fake response returned to the application, or nil if the
	// request failed or reached the network through [Fake.AllowStrayRequests].
	Response *httpclient.Response
}

Record pairs an outgoing Request with the fake httpclient.Response it received.

type Request

type Request struct {
	// Method is the HTTP method, such as GET or POST.
	Method string
	// URL is the full request URL, including the base URL and query string.
	URL string
	// Header holds all request headers, including the client's User-Agent.
	Header http.Header
	// Body holds the raw request body. It is empty when the request has no body
	// or uses multipart/form-data, in which case fields are available through
	// [Request.Data] and uploads through Files.
	Body []byte
	// Files holds the files attached to a multipart form, in order.
	Files []File
	// contains filtered or unexported fields
}

Request is a snapshot of an outgoing HTTP request as sent by the application, including its final URL, headers, body, and attached files.

func (*Request) Data

func (r *Request) Data() map[string]any

Data returns the request payload as a map for quick assertions, such as req.Data()["name"] == "Taylor". It decodes JSON object bodies and URL-encoded or multipart form fields (keeping the first value of each form field as a string). It returns nil if the body is neither a form nor a JSON object.

func (*Request) HasFile

func (r *Request) HasFile(field, name string) bool

HasFile reports whether the request attached a file named name under the form field named field.

func (*Request) HasHeader

func (r *Request) HasHeader(name, value string) bool

HasHeader reports whether the request includes a header named name with the exact value given.

func (*Request) JSON

func (r *Request) JSON[T any]() (T, error)

JSON decodes the request body as T and returns any unmarshal error:

payload, err := req.JSON[CreateUser]()

type Response

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

Response is a scripted HTTP response returned by a Fake. Construct one with Status, Text, or JSON, then customize it with Response.WithStatus, Response.WithHeader, and Response.WithBody.

func JSON

func JSON(body any) Response

JSON returns a 200 OK Response with Content-Type set to application/json and body encoded as JSON. It panics if body cannot be marshaled to JSON.

func Status

func Status(status int) Response

Status returns an empty Response with the given HTTP status code.

func Text

func Text(body string) Response

Text returns a 200 OK Response with body as its response body.

func (Response) WithBody

func (r Response) WithBody(body []byte) Response

WithBody returns a copy of r with its response body replaced by body.

func (Response) WithHeader

func (r Response) WithHeader(name, value string) Response

WithHeader returns a copy of r with header name set to value, replacing any existing value for that header.

func (Response) WithStatus

func (r Response) WithStatus(status int) Response

WithStatus returns a copy of r with its HTTP status code set to status.

type Sequence

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

Sequence answers successive matching requests with each Answer in order. Create one with NewSequence. Sequence is safe for concurrent use.

func NewSequence

func NewSequence(answers ...Answer) *Sequence

NewSequence returns a Sequence that serves answers in order, such as failing twice before succeeding:

httpclienttest.NewSequence(
	httpclienttest.FailedConnection(),
	httpclienttest.Status(503),
	httpclienttest.JSON(user),
)

Once all answers are consumed, further requests fail with httpclient.ErrNotFaked unless a fallback is configured with Sequence.WhenEmpty.

func (*Sequence) WhenEmpty

func (s *Sequence) WhenEmpty(answer Answer) *Sequence

WhenEmpty configures answer as the fallback response once every answer in s has been consumed, instead of failing with httpclient.ErrNotFaked, and returns s for chaining.

Jump to

Keyboard shortcuts

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