Skip to content

HttpRequestTrait: expose the requests it received so tests can assert on them #66

Description

@remyperona

Is your feature request related to a problem? Please describe.

HttpRequestTrait sees every outbound request, but tests cannot read what it saw. When a test needs to assert on the request itself (method, headers, body, how many calls were made), it adds its own pre_http_request filter at a lower priority that records the request and passes $preempt through, plus the matching add_filter / remove_filter pair and a property to store the result.

WP Rocket has 9 of these spies:

  • Varnish cleanHome, cleanFile, cleanDomain: URL, method, blocking, redirection, headers.
  • Kinsta cleanKinstaCacheHome, cleanKinstaCacheUrl: URL, blocking, timeout.
  • Cloudflare purgeUrl: JSON body of the purge_cache request.
  • RocketCDN WebsiteSearch::find, APIClient::getSubscriptionData: number of calls to one endpoint.
  • RocketCDN DataManagerSubscriber::maybeRetryActivation: whether any request was made.

Describe the solution you'd like

Have the trait log the requests it receives and expose them:

/**
 * Requests received during the test, in order.
 *
 * @var array<int, array{url: string, args: array}>
 */
private $http_request_log = [];

public function http_callback( $response, $args, $url ) {
	$this->http_request_log[] = [ 'url' => $url, 'args' => $args ];
	// ... existing lookup unchanged
}

/**
 * Returns the requests received so far, optionally only those to one URL.
 *
 * @param string|null $url Exact URL to filter on.
 *
 * @return array<int, array{url: string, args: array}>
 */
protected function get_http_requests( $url = null ) { ... }
  • Log every request, mocked or blocked (blocked ones still fail the test as today).
  • reset_http() clears the log.
  • args holds the parsed request arguments: core fires pre_http_request after merging defaults, so method, blocking, timeout, headers and body are always present.
  • Do not reuse or come close to core's property names (see HttpRequestTrait fatals on WordPress 7.2: $blocked_http_requests clashes with WP_UnitTestCase_Base #62); $http_request_log avoids WP_UnitTestCase_Base::$blocked_http_requests.
  • Purely additive, so it can ship as a minor release (v3.4).

Consumer side, the spies become plain assertions:

$this->assertSame( 'PURGE', $this->get_http_requests()[0]['args']['method'] );
$this->assertCount( 1, $this->get_http_requests( self::SEARCH_ENDPOINT ) );
$this->assertSame( [], $this->get_http_requests() );

Describe alternatives you've considered

  • Keep per-test spy filters: works, but repeats the same filter, cleanup and storage boilerplate in every test, and AGENTS.md in WP Rocket already discourages bespoke pre_http_request filters in integration tests.
  • Expose $http_request_counts: only covers the counting cases, not method, headers or body.

Additional context

The log only sees requests that reach the trait's priority-10 filter. A test that short-circuits a request at a lower priority hides it from the log. None of the 9 WP Rocket spies does that: they all return $preempt unchanged.

Acceptance criteria

  • get_http_requests() returns every request received during the current test, in order, with url and args.
  • get_http_requests( $url ) returns only the requests to that exact URL.
  • Blocked (unmocked) requests are logged too.
  • The log is empty at the start of each test.
  • Covered in Tests/Integration/testHttpRequestTrait.php.
  • PHPCS and PHPStan pass.

Activity

  1. self-assigned this
    on Oct 28, 2026
  2. remyperona commented on Oct 28, 2026

    @remyperona
    ContributorAuthor

    Note

    Generated by the AI delivery pipeline (grooming-agent · Claude Opus 5.5).

    Grooming Plan — Issue #66

    Approach: Log every request in HttpRequestTrait::http_callback() (first statement, before the fixture lookup, so mocked, list-exhausted and blocked requests are all recorded), store it in a new private $http_request_log, expose it via protected get_http_requests( $url = null ), and clear it in reset_http().
    Effort: S · Risk: LOW · Complexity: LOW

    Key decisions

    • Fix lives in src/Integration/HttpRequestTrait.php only (already in the phpcs.xml.dist allow-list; PHPStan covers it). Purely additive, PHP 7.4 compatible, untyped property like its siblings.
    • $http_request_log / get_http_requests do not exist in the installed WP test suite and are not close to core's $blocked_http_requests, so no HttpRequestTrait fatals on WordPress 7.2: $blocked_http_requests clashes with WP_UnitTestCase_Base #62-style clash.
    • URL filter uses strict equality and must wrap array_filter in array_values, otherwise get_http_requests( $url )[0] breaks (keys preserved).
    • args are what core passes to pre_http_request (verified in WP_Http::request()): defaults merged and http_request_args applied, but headers are not yet normalised, so headers is whatever the caller passed (array or raw string). Document this; do not normalise.
    • The log is cleared by reset_http() (setup and teardown), so tests must read it before tear_down_http(). Blocked requests are still reported at teardown as today.
    • Document in the class docblock (README does not cover the trait): usage, args shape, the priority-10 limitation (lower-priority short-circuit filters hide requests), log unreadable after teardown.

    Tests (all in Tests/Integration/testHttpRequestTrait.php): empty log; order with url+args; parsed args (method PURGE, timeout, blocking, headers, body, plus core defaults); exact-URL filter incl. re-indexing, trailing-slash/query mismatch returning empty; list-mocked URL beyond its list still logged; blocked request logged and teardown still fails; log cleared on teardown and on setup. Do not add a new try/catch to that file (the PHPStan baseline has a catch.internalClass entry with count 1 there); reuse captureTearDownFailure(). Existing composition tests must stay green.

    Verify: npm run test:php:integration, composer phpcs, composer phpstan.

    Smoke test: in a consumer-style test using the trait, call wp_remote_request( $mocked_url, [ 'method' => 'PURGE' ] ) and assert get_http_requests()[0]['args']['method'] === 'PURGE' and count( get_http_requests( $mocked_url ) ) === 1; then request an unmocked URL and confirm it is logged and the test still fails at teardown.

    Out of scope: logging requests short-circuited at priority < 10, request counters/pattern filtering, normalising args, v3.4 release/tagging, CI or phpcs scope changes.

    PR splitting: not needed (effort S, one source file plus one test file).

    Full spec: .TemporaryItems/Issues/phpunit/issues/66-spec.md

  3. remyperona commented on Oct 28, 2026

    @remyperona
    ContributorAuthor

    Note

    Generated by the AI delivery pipeline (orchestrator · Claude Opus 5.5).

    PR: #67 | Status: READY FOR REVIEW

    Stage Result Notes
    Grooming ✅ effort: S, risk: LOW
    Challenger ⏭ Skipped S + LOW + LOW, high confidence
    Implementation ✅ branch: enhancement/66-httprequesttrait-expose-the-requests
    DOD L2 ✅ PASS —
    Lead Review ✅ PASS details on PR #67
    CI ✅ All Pass —
    QA ✅ PASS details on PR #67
    Follow-up tickets Tackled in PR (setup-reset test); 3 discarded —
  4. added a commit that references this issue on Oct 28, 2026
    4c09f25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions