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 ¶
- type Answer
- type AnswerFunc
- type Fake
- func (f *Fake) AllowStrayRequests(urlPatterns ...string) *Fake
- func (f *Fake) AssertNotSent(match func(req *Request) bool)
- func (f *Fake) AssertNothingSent()
- func (f *Fake) AssertSent(match func(req *Request) bool)
- func (f *Fake) AssertSentCount(count int)
- func (f *Fake) PreventStrayRequests() *Fake
- func (f *Fake) Recorded() []Record
- func (f *Fake) Respond(urlPattern string, answer Answer) *Fake
- func (f *Fake) Sent() []*Request
- func (f *Fake) Transport(next http.RoundTripper) http.RoundTripper
- type File
- type Record
- type Request
- type Response
- type Sequence
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
AssertSentCount fails the test unless the total number of recorded requests, including retries, equals count.
func (*Fake) PreventStrayRequests ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
HasFile reports whether the request attached a file named name under the form field named field.
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 ¶
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 (Response) WithHeader ¶
WithHeader returns a copy of r with header name set to value, replacing any existing value for that header.
func (Response) WithStatus ¶
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 ¶
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.