carsdotcom / php-request-class

Structure the logic around Guzzle API requests into object-oriented classes
MIT License
2 stars 1 forks source link

Port cache assertions #14

Open jwadhams opened 1 month ago

jwadhams commented 1 month ago

Our private assertion helpers stopped working after the 1.1.1 upgrade, because they didn't track the new shape of the cached body.

If they were part of the shared library and part of its test coverage, everyone could benefit from them, and they'd upgrade when the library does, win-win.

jwadhams commented 1 month ago

Working post-1.2.0 implementations

    /**
     * Create a fake cache entry for a given request.
     */
    protected static function mockRequestCachedResponse(
        AbstractRequest $request,
        string $body,
        int $status = 200,
        array $headers = [],
        array $logs = [],
    ) {
        $tags = getProperty($request, 'cacheTags');
        Cache::tags($tags)->put($request->cacheKey(), [
            'logs' => $logs,
            'response' => [$status, $headers, $body],
        ]);
    }

    /**
     * Fetch the cached response to a request and assert that it contains a substring
     */
    protected static function requestCacheBodyContains(
        string $substring,
        AbstractRequest $request,
        string $message = '',
    ): void {
        $cached = callMethod($request, 'responseFromCache');
        self::assertNotNull($cached, 'Cache should not be empty for request.');
        self::assertStringContainsString($substring, (string) $cached->getBody(), $message);
    }

Note these both rely on our mockery helper methods, but those are already present in tests/bootstrap.php so no biggie