Grokking
Grokking

Reputation: 715

Application test to verify caching on an endpoint with ETag

I'm trying to test caching, but second response is not 304, but still 200. Controller works great, tried with several HTTP clients and also while debugging the test. But in the test response is different, by some reason

Also tried using disableReboot or reboot on the client, but no effect

It feels like something is missing to be done in the test

Symfony 6.3 PHPUnit 10.4

public function testCache() {
    $client = static::createClient();

    $client->request('GET', '/test?param=123');

    $response = $client->getResponse();

    $this->assertResponseIsSuccessful();

    $etag = $response->getEtag();

    $client->request('GET', '/test?param=123', [
        'headers' => [
            'If-None-Match' => $etag
        ]
    ]);

    $this->assertResponseStatusCodeSame(Response::HTTP_NOT_MODIFIED); // 200 instead of 304
}

Example of the response I receive:

HTTP/1.1 200 OK
Age:              1
Cache-Control:    public
Content-Length:   76
Content-Type:     application/json
Date:             Mon, 19 Feb 2024 22:03:45 GMT
Etag:             "bc4a907bcc4d3e601993f1646938d2a2"
X-Content-Digest: en1c1a61e2a1702c01d3298b4b204a21dd
X-Robots-Tag:     noindex
X-Symfony-Cache:  GET /test?param=123&headers%5BIf-None-Match%5D=%22bc4a907bcc4d3e601993f1646938d2a2%22&param2=321: stale, valid, store

Upvotes: 1

Views: 125

Answers (1)

Grokking
Grokking

Reputation: 715

Reason of this issue, as always a little bit silly - the incorrect way of passing headers

GET /test?param=123&headers%5BIf-None-Match%5D=%22bc4a907bcc4d3e601993f1646938d2a2%22&param2=321: stale, valid, store

That's why there is a header in query params here

Correct way to pass the header is like this:

$client->request('GET', $endpointUrl, [], [], ['HTTP_If-None-Match' => $etag]);

Works like a charm

Upvotes: 2

Related Questions