VOOZH about

URL: https://deepwiki.com/hypervel/http-client/9.1-faking-requests

⇱ Faking Requests | hypervel/http-client | DeepWiki


Loading...
Menu

Faking Requests

Purpose and Scope

This document explains how to fake HTTP requests in tests by intercepting them before they reach the network and returning predefined stubbed responses. This allows you to test code that makes HTTP requests without relying on external services or network connectivity.

For information about creating ordered response sequences, see Response Sequences. For assertion methods to verify request behavior, see Assertions.

Overview

The Hypervel HTTP Client provides a comprehensive faking system built into the Factory class. When you activate faking, the factory:

  1. Registers stub callbacks that intercept outgoing requests
  2. Automatically enables request/response recording for later assertions
  3. Matches incoming requests against URL patterns
  4. Returns predefined responses without making actual network calls

The fake system operates through a stub handler in the middleware stack (see Middleware and Request Modification) that executes before requests reach the Guzzle HTTP client.

Sources: src/Factory.php183-224

Basic Faking

Default Fake Response

The simplest form of faking returns a default 200 OK response with an empty body for all requests:


Sources: src/Factory.php183-224

Fake with Callback

Provide a callback that receives the Request and options array, returning a response for all requests:


The callback is invoked for every request and can inspect the request to return different responses based on request properties.

Sources: src/Factory.php183-224

Fake with URL Array

Register multiple URL-specific stubs by passing an associative array where keys are URL patterns and values are responses or callbacks:


Sources: src/Factory.php195-200

Creating Fake Responses

Factory::response()

The Factory::response() static method creates a promise-wrapped PSR-7 response suitable for stubbing:


The method signature accepts:

ParameterTypeDescription
$bodyarray|string|nullResponse body; arrays are JSON-encoded
$statusintHTTP status code (default: 200)
$headersarrayResponse headers

Returns: PromiseInterface wrapping a Psr7Response

Sources: src/Factory.php141-155

Response Creation Flow


Sources: src/Factory.php141-155

URL-Specific Stubbing

stubUrl() Method

The stubUrl() method registers a stub for requests matching a specific URL pattern:


Sources: src/Factory.php239-260

URL Pattern Matching

URL patterns support wildcard matching using *. The pattern is automatically prefixed with * if not already present, then matched against the full request URL using Str::is():

PatternMatchesDoes Not Match
https://api.example.com/usersExact URL onlyAny other URL
*/usersAny URL ending with /users/users/123
*github.com*Any URL containing github.comgitlab.com
*/api/*/users/api/v1/users, /api/v2/users/api/users

Sources: src/Factory.php242-243

URL Stub Value Types

The second parameter to stubUrl() accepts multiple value types:

TypeBehaviorExample
Integer (100-599)Return response with that status codestubUrl('*/users', 404)
String/IntegerReturn as response body with 200 statusstubUrl('*/users', 'Success')
ClosureExecute callback, receive Request and optionsstubUrl('*/users', fn($req) => ...)
ResponseSequenceInvoke sequence for ordered responsesstubUrl('*/users', $sequence)
PromiseInterfaceReturn promise directlystubUrl('*/users', $promise)

Sources: src/Factory.php246-258

Preventing Stray Requests

Overview

When writing tests, it's often desirable to ensure that all HTTP requests are explicitly faked. The preventStrayRequests() method throws a RuntimeException if any request is made that doesn't match a registered stub:


Sources: src/Factory.php265-270

Controlling Stray Request Behavior

MethodPurpose
preventStrayRequests(true)Enable exception throwing for unfaked requests
preventStrayRequests(false)Disable exception throwing
allowStrayRequests()Alias for preventStrayRequests(false)
preventingStrayRequests()Check if prevention is enabled

Sources: src/Factory.php265-286

How Prevention Works

When preventStrayRequests() is enabled, the stub handler in the middleware stack checks if any stub callback returned a response. If no stub matched and prevention is enabled, a RuntimeException is thrown before the request reaches the actual HTTP client.


Sources: src/Factory.php265-278

Simulating Connection Failures

Factory::failedConnection()

The failedConnection() static method creates a closure that simulates a connection failure when used as a stub:


The closure returns a rejected promise containing a GuzzleHttp\Exception\ConnectException.

Sources: src/Factory.php160-170

Custom Error Messages

Provide a custom error message as the first parameter:


If no message is provided, a default cURL error message is generated:

cURL error 6: Could not resolve host: {hostname} (see https://curl.haxx.se/libcurl/c/libcurl-errors.html) for {uri}

Sources: src/Factory.php162-167

Fake System Architecture

Component Relationships


Sources: src/Factory.php48-71 src/Factory.php183-224 src/Factory.php404-409

Request Processing with Fakes


Sources: src/Factory.php183-224 src/Factory.php291-306 src/Factory.php404-409

Stub Callback Processing

When a request is processed, the stub handler iterates through all registered stub callbacks in order. Each callback is invoked with the Request and options. The first callback that returns a non-null value provides the response:


Sources: src/Factory.php202-221

Stub Callback Collection

The stubCallbacks property is a Collection instance that stores all registered stub callbacks. Multiple calls to fake() merge new callbacks into the collection:


Each stub callback is wrapped in a closure that:

  1. Receives the request and options
  2. Executes the user-provided callback
  3. Unwraps nested closures (supports closures that return closures)
  4. Handles promise responses by calling the on_stats callback
  5. Returns the final response

Sources: src/Factory.php51 src/Factory.php202-221

Recording Behavior

When fake() is called, recording is automatically enabled via the protected record() method. This sets $recording = true and clears the $recorded array. All subsequent requests and their responses are captured by recordRequestResponsePair() and stored as [Request, Response] pairs.

The recording system operates independently of the stub system - requests are recorded whether they match a stub or make a real HTTP call (if stray requests are allowed).

Sources: src/Factory.php54-61 src/Factory.php185-188 src/Factory.php291-306

Integration with PendingRequest

When createPendingRequest() is called, the factory injects the stub callbacks and prevent flag into the PendingRequest:


The PendingRequest then builds its middleware stack with a stub handler that references these callbacks. This architecture allows each request to see the current stub configuration while maintaining a clean separation between the factory (configuration) and pending request (execution) layers.

Sources: src/Factory.php404-409

Code Entity Reference

EntityTypeLocationPurpose
Factory::$stubCallbacksPropertysrc/Factory.php51Collection storing registered stub callbacks
Factory::$recordingPropertysrc/Factory.php56Flag indicating if recording is enabled
Factory::$recordedPropertysrc/Factory.php61Array of [Request, Response] pairs
Factory::$preventStrayRequestsPropertysrc/Factory.php71Flag to throw exceptions for unfaked requests
Factory::response()Static Methodsrc/Factory.php141-155Create fake PSR-7 responses
Factory::failedConnection()Static Methodsrc/Factory.php160-170Create connection failure stubs
Factory::fake()Methodsrc/Factory.php183-224Register stub callbacks
Factory::stubUrl()Methodsrc/Factory.php239-260Register URL-specific stubs
Factory::preventStrayRequests()Methodsrc/Factory.php265-270Enable/disable stray request prevention
Factory::record()Methodsrc/Factory.php291-296Enable request recording
Factory::recordRequestResponsePair()Methodsrc/Factory.php301-306Store request/response pair

Sources: src/Factory.php1-526