CacheWebTest.php in Drupal 9
File
core/modules/views/tests/src/Functional/Plugin/CacheWebTest.php
View source
<?php
namespace Drupal\Tests\views\Functional\Plugin;
use Drupal\Tests\system\Functional\Cache\AssertPageCacheContextsAndTagsTrait;
use Drupal\Tests\views\Functional\ViewTestBase;
use Drupal\views\Plugin\views\display\DisplayPluginBase;
use Drupal\views\Views;
class CacheWebTest extends ViewTestBase {
use AssertPageCacheContextsAndTagsTrait;
public static $testViews = [
'test_display',
];
protected static $modules = [
'taxonomy',
];
protected $defaultTheme = 'stark';
protected function setUp($import_test_views = TRUE) : void {
parent::setUp($import_test_views);
$this
->enableViewsTestModule();
}
public function testCacheOutputOnPage() {
$view = Views::getView('test_display');
$view->storage
->setStatus(TRUE);
$view
->setDisplay('page_1');
$view->display_handler
->overrideOption('cache', [
'type' => 'time',
'options' => [
'results_lifespan' => '3600',
'output_lifespan' => '3600',
],
]);
$view
->save();
$this->container
->get('router.builder')
->rebuildIfNeeded();
$render_cache = \Drupal::service('render_cache');
$cache_element = DisplayPluginBase::buildBasicRenderable('test_display', 'page_1');
$cache_element['#cache'] += [
'contexts' => $this->container
->getParameter('renderer.config')['required_cache_contexts'],
];
$this
->assertFalse($render_cache
->get($cache_element));
$this
->drupalGet('test-display');
$this
->assertSession()
->statusCodeEquals(200);
$this
->assertNotEmpty($render_cache
->get($cache_element));
$cache_tags = [
'config:user.role.anonymous',
'config:views.view.test_display',
'node_list',
'rendered',
];
$this
->assertCacheTags($cache_tags);
$this
->drupalGet('test-display');
$this
->assertSession()
->statusCodeEquals(200);
$this
->assertNotEmpty($render_cache
->get($cache_element));
$this
->assertCacheTags($cache_tags);
}
public function testDisplayWithoutCacheStillBubblesMetadata() {
$view = Views::getView('test_display');
$uncached_block = $view
->buildRenderable('block_1', [], FALSE);
$cached_block = $view
->buildRenderable('block_1', [], TRUE);
$this
->assertEquals($uncached_block['#cache']['contexts'], $cached_block['#cache']['contexts'], 'Cache contexts are the same when you render the view cached and uncached.');
}
}