Skip to content

Commit e576f73

Browse files
committed
Refactor response mocking
1 parent cad0b92 commit e576f73

File tree

1 file changed

+16
-33
lines changed

1 file changed

+16
-33
lines changed

plugins/performance-lab/tests/includes/site-health/bfcache-compatibility-headers/test-bfcache-compatibility-headers.php

Lines changed: 16 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -8,26 +8,6 @@
88

99
class Test_BFCache_Compatibility_Headers extends WP_UnitTestCase {
1010

11-
/**
12-
* Holds mocked response headers for different test scenarios.
13-
*
14-
* @var array<string, array<string, mixed>>
15-
*/
16-
protected $mocked_responses = array();
17-
18-
/**
19-
* Setup each test.
20-
*/
21-
public function setUp(): void {
22-
parent::setUp();
23-
24-
// Clear any filters or mocks.
25-
remove_all_filters( 'pre_http_request' );
26-
27-
// Add the filter to mock HTTP requests.
28-
add_filter( 'pre_http_request', array( $this, 'mock_http_requests' ), 10, 3 );
29-
}
30-
3111
/**
3212
* Test that the bfcache compatibility test is added to the site health tests.
3313
*
@@ -64,7 +44,7 @@ public function test_perflab_bfcache_compatibility_headers_add_test_is_attached(
6444
* @param string $expected_message The expected message.
6545
*/
6646
public function test_perflab_bfcache_compatibility_headers_check( $response, string $expected_status, string $expected_message ): void {
67-
$this->mocked_responses = array( home_url( '/' ) => $response );
47+
$this->mock_http_request( $response, home_url( '/' ) );
6848

6949
$result = perflab_bfcache_compatibility_headers_check();
7050

@@ -113,20 +93,23 @@ public function data_test_bfcache_compatibility(): array {
11393
}
11494

11595
/**
116-
* Mock HTTP requests for assets to simulate different responses.
96+
* Mock HTTP response for a given URL.
11797
*
118-
* @param bool $response A preemptive return value of an HTTP request. Default false.
119-
* @param array<string, mixed> $args Request arguments.
120-
* @param string $url The request URL.
121-
* @return array<string, mixed>|WP_Error Mocked response.
98+
* @param array<string, mixed>|WP_Error $mocked_response The mocked response.
99+
* @param non-empty-string $url The request URL.
122100
*/
123-
public function mock_http_requests( bool $response, array $args, string $url ) {
124-
if ( isset( $this->mocked_responses[ $url ] ) ) {
125-
return $this->mocked_responses[ $url ];
126-
}
127-
128-
// If no specific mock set, default to a generic success with no caching.
129-
return $this->build_response( 200 );
101+
public function mock_http_request( $mocked_response, string $url ): void {
102+
add_filter(
103+
'pre_http_request',
104+
static function ( $pre, $args, $request_url ) use ( $url, $mocked_response ) {
105+
if ( $url === $request_url ) {
106+
return $mocked_response;
107+
}
108+
return $pre;
109+
},
110+
10,
111+
3
112+
);
130113
}
131114

132115
/**

0 commit comments

Comments
 (0)