|
8 | 8 |
|
9 | 9 | class Test_BFCache_Compatibility_Headers extends WP_UnitTestCase {
|
10 | 10 |
|
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 |
| - |
31 | 11 | /**
|
32 | 12 | * Test that the bfcache compatibility test is added to the site health tests.
|
33 | 13 | *
|
@@ -64,7 +44,7 @@ public function test_perflab_bfcache_compatibility_headers_add_test_is_attached(
|
64 | 44 | * @param string $expected_message The expected message.
|
65 | 45 | */
|
66 | 46 | 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( '/' ) ); |
68 | 48 |
|
69 | 49 | $result = perflab_bfcache_compatibility_headers_check();
|
70 | 50 |
|
@@ -113,20 +93,23 @@ public function data_test_bfcache_compatibility(): array {
|
113 | 93 | }
|
114 | 94 |
|
115 | 95 | /**
|
116 |
| - * Mock HTTP requests for assets to simulate different responses. |
| 96 | + * Mock HTTP response for a given URL. |
117 | 97 | *
|
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. |
122 | 100 | */
|
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 | + ); |
130 | 113 | }
|
131 | 114 |
|
132 | 115 | /**
|
|
0 commit comments