|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace ProcessMaker\Tests\Feature\Etag; |
| 4 | + |
| 5 | +use Illuminate\Foundation\Testing\WithFaker; |
| 6 | +use Illuminate\Support\Facades\Route; |
| 7 | +use ProcessMaker\Models\Process; |
| 8 | +use ProcessMaker\Models\User; |
| 9 | +use Tests\TestCase; |
| 10 | + |
| 11 | +class HandleEtagCacheInvalidationTest extends TestCase |
| 12 | +{ |
| 13 | + use WithFaker; |
| 14 | + |
| 15 | + protected $faker; |
| 16 | + |
| 17 | + private string $response = 'OK'; |
| 18 | + |
| 19 | + private const TEST_ROUTE = '/_test/etag-cache-invalidation'; |
| 20 | + |
| 21 | + public function setUp(): void |
| 22 | + { |
| 23 | + parent::setUp(); |
| 24 | + |
| 25 | + // Define a route with the etag middleware and etag_tables default. |
| 26 | + Route::middleware('etag') |
| 27 | + ->get(self::TEST_ROUTE, function () { |
| 28 | + return response($this->response, 200); |
| 29 | + }) |
| 30 | + ->defaults('etag_tables', 'processes'); |
| 31 | + } |
| 32 | + |
| 33 | + public function testEtagInvalidatesOnDatabaseUpdate() |
| 34 | + { |
| 35 | + $user = User::factory()->create(); |
| 36 | + $this->actingAs($user); |
| 37 | + |
| 38 | + // Create a process record to simulate database changes. |
| 39 | + $process = Process::factory()->create([ |
| 40 | + 'updated_at' => now()->yesterday(), |
| 41 | + ]); |
| 42 | + |
| 43 | + // First request: Get the initial ETag. |
| 44 | + $response = $this->get(self::TEST_ROUTE); |
| 45 | + $initialEtag = $response->headers->get('ETag'); |
| 46 | + $this->assertNotNull($initialEtag, 'Initial ETag was set'); |
| 47 | + |
| 48 | + // Simulate a database update by changing `updated_at`. |
| 49 | + $process->update(['name' => $this->faker->name]); |
| 50 | + |
| 51 | + // Second request: ETag should change due to the database update. |
| 52 | + $responseAfterUpdate = $this->get(self::TEST_ROUTE); |
| 53 | + $newEtag = $responseAfterUpdate->headers->get('ETag'); |
| 54 | + |
| 55 | + $this->assertNotNull($newEtag, 'New ETag was set after database update'); |
| 56 | + $this->assertNotEquals($initialEtag, $newEtag, 'ETag changed after database update'); |
| 57 | + |
| 58 | + // Third request: Simulate a client sending the old ETag. |
| 59 | + $responseWithOldEtag = $this->withHeaders(['If-None-Match' => $initialEtag]) |
| 60 | + ->get(self::TEST_ROUTE); |
| 61 | + |
| 62 | + $responseWithOldEtag->assertStatus(200); |
| 63 | + $responseWithOldEtag->assertHeader('ETag', $newEtag, 'Response did not return the updated ETag'); |
| 64 | + } |
| 65 | +} |
0 commit comments