diff --git a/src/Http/Middleware/CacheMiddleware.php b/src/Http/Middleware/CacheMiddleware.php index 228695f..32ee523 100644 --- a/src/Http/Middleware/CacheMiddleware.php +++ b/src/Http/Middleware/CacheMiddleware.php @@ -34,6 +34,10 @@ public function __construct( */ public function __invoke(PendingRequest $pendingRequest): ?FakeResponse { + if ($pendingRequest->getMockClient()?->shouldBypassResponseCache() === true) { + return null; + } + $driver = $this->driver; $cacheKey = hash('sha256', $this->cacheKey ?? CacheKeyHelper::create($pendingRequest)); diff --git a/tests/Feature/ResponseCacheMockFixtureTest.php b/tests/Feature/ResponseCacheMockFixtureTest.php new file mode 100644 index 0000000..6c40b8e --- /dev/null +++ b/tests/Feature/ResponseCacheMockFixtureTest.php @@ -0,0 +1,74 @@ +deleteDirectory('/'); +}); + +function cachedUserRequestFixtureAbsolutePath(): string +{ + $dir = getcwd().'/tests/Fixtures/Saloon'; + + if (! is_dir($dir)) { + mkdir($dir, 0755, true); + } + + return $dir.'/cached-user-request.json'; +} + +function writeCachedUserRequestFixture(int $version): void +{ + $payload = [ + 'statusCode' => 200, + 'headers' => ['Content-Type' => ['application/json']], + 'data' => json_encode(['version' => $version]), + 'context' => [], + ]; + + file_put_contents( + cachedUserRequestFixtureAbsolutePath(), + json_encode($payload, JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT) + ); +} + +test('response cache can return a stale body when mocks use fixtures and withoutCache is not used', function (): void { + writeCachedUserRequestFixture(1); + + $mockClient = new MockClient([ + CachedUserRequest::class => MockResponse::fixture('cached-user-request'), + ]); + + $connector = TestConnector::make(); + + expect($connector->send(new CachedUserRequest, $mockClient)->json('version'))->toBe(1); + + writeCachedUserRequestFixture(2); + + expect($connector->send(new CachedUserRequest, $mockClient)->json('version'))->toBe(1); +}); + +test('withoutCache on the mock client skips response cache so updated fixture files are used', function (): void { + writeCachedUserRequestFixture(1); + + $mockClient = (new MockClient([ + CachedUserRequest::class => MockResponse::fixture('cached-user-request'), + ]))->withoutCache(); + + $connector = TestConnector::make(); + + expect($connector->send(new CachedUserRequest, $mockClient)->json('version'))->toBe(1); + + writeCachedUserRequestFixture(2); + + expect($connector->send(new CachedUserRequest, $mockClient)->json('version'))->toBe(2); +}); diff --git a/tests/Fixtures/Saloon/cached-user-request.json b/tests/Fixtures/Saloon/cached-user-request.json new file mode 100644 index 0000000..0cc2f18 --- /dev/null +++ b/tests/Fixtures/Saloon/cached-user-request.json @@ -0,0 +1,10 @@ +{ + "statusCode": 200, + "headers": { + "Content-Type": [ + "application\/json" + ] + }, + "data": "{\"version\":2}", + "context": [] +} \ No newline at end of file