Created
November 21, 2022 02:11
-
-
Save mstrelan/5b996393f5a9931bdbc67412abe6a632 to your computer and use it in GitHub Desktop.
Fail tests if pages are not cacheable when they should be
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types=1); | |
namespace Drupal\Tests\my_profile\Traits; | |
use Behat\Mink\Exception\UnsupportedDriverActionException; | |
use Drupal\Core\Url; | |
/** | |
* Fails tests if pages are not cacheable when they should be. | |
*/ | |
trait ExpectsCacheableResponseTrait { | |
/** | |
* List of dynamic paths that are not cacheable.. | |
* | |
* @var string[] | |
*/ | |
private array $dynamicPaths = [ | |
'/user/login', | |
'/big_pipe/no-js', | |
'/batch', | |
]; | |
/** | |
* Option to pass to drupalGet to allow uncacheable responses. | |
* | |
* @todo use a constant in PHP 8.2 | |
* @see https://php.watch/versions/8.2/constants-in-traits | |
*/ | |
private string $uncacheableResponseOption = '_expect_uncacheable_response'; | |
/** | |
* Retrieves a Drupal path without checking cacheability. | |
*/ | |
protected function drupalGetUncacheablePage(string|Url $path, array $options = [], array $headers = []): string { | |
return $this->drupalGet($path, [$this->uncacheableResponseOption => TRUE] + $options, $headers); | |
} | |
/** | |
* Detects un-cacheable responses and fails if that is not allowed. | |
*/ | |
private function detectUncacheableResponse(string|Url $path, array $options = []): void { | |
if (($options[$this->uncacheableResponseOption] ?? FALSE)) { | |
return; | |
} | |
if ($this->isDynamicPath($path)) { | |
return; | |
} | |
try { | |
if ($this->getSession()->getResponseHeader('X-Drupal-Dynamic-Cache') === 'UNCACHEABLE') { | |
$this->fail(sprintf('Found an un-cacheable response at path: %s. If your test visits dynamic pages (cache-lifetime of zero) use ::drupalGetUncacheablePage method instead.', $this->buildUrl($path, $options))); | |
} | |
} | |
catch (UnsupportedDriverActionException $e) { | |
// Javascript tests don't support reading response headers. | |
} | |
} | |
/** | |
* Determines if the current path is uncacheable. | |
*/ | |
private function isDynamicPath(string|Url $path): bool { | |
$currentPath = $path instanceof Url ? $path->toString() : $path; | |
$currentUrl = $this->getSession()->getCurrentUrl(); | |
foreach ($this->dynamicPaths as $dynamicPath) { | |
if (str_contains($currentUrl, $dynamicPath)) { | |
return TRUE; | |
} | |
if (str_contains($currentPath, $dynamicPath)) { | |
return TRUE; | |
} | |
} | |
return FALSE; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: