WorkspaceCacheContextTest.php in Drupal 10
File
core/modules/workspaces/tests/src/Functional/WorkspaceCacheContextTest.php
View source
<?php
namespace Drupal\Tests\workspaces\Functional;
use Drupal\Tests\BrowserTestBase;
use Drupal\Tests\system\Functional\Cache\AssertPageCacheContextsAndTagsTrait;
use Drupal\workspaces\Entity\Workspace;
use Drupal\workspaces\WorkspaceCacheContext;
class WorkspaceCacheContextTest extends BrowserTestBase {
use AssertPageCacheContextsAndTagsTrait;
protected static $modules = [
'block',
'node',
'workspaces',
];
protected $defaultTheme = 'stark';
public function testWorkspaceCacheContext() {
$renderer = \Drupal::service('renderer');
$cache_contexts_manager = \Drupal::service("cache_contexts_manager");
$this
->drupalGet('<front>');
$this
->assertCacheContext('workspace');
$cache_context = new WorkspaceCacheContext(\Drupal::service('workspaces.manager'));
$this
->assertSame('live', $cache_context
->getContext());
$this
->drupalCreateContentType([
'type' => 'page',
]);
$node = $this
->createNode();
$build = \Drupal::entityTypeManager()
->getViewBuilder('node')
->view($node, 'full');
$renderer
->renderRoot($build);
$this
->assertContains('workspace', $build['#cache']['contexts']);
$cid_parts = array_merge($build['#cache']['keys'], $cache_contexts_manager
->convertTokensToKeys($build['#cache']['contexts'])
->getKeys());
$this
->assertContains('[workspace]=live', $cid_parts);
$cid = implode(':', $cid_parts);
$bin = $build['#cache']['bin'];
$this
->assertInstanceOf(\stdClass::class, $this->container
->get('cache.' . $bin)
->get($cid));
$test_user = $this
->drupalCreateUser([
'view any workspace',
]);
$this
->drupalLogin($test_user);
$stage = Workspace::load('stage');
$workspace_manager = \Drupal::service('workspaces.manager');
$workspace_manager
->setActiveWorkspace($stage);
$cache_context = new WorkspaceCacheContext($workspace_manager);
$this
->assertSame('stage', $cache_context
->getContext());
$build = \Drupal::entityTypeManager()
->getViewBuilder('node')
->view($node, 'full');
$renderer
->renderRoot($build);
$this
->assertContains('workspace', $build['#cache']['contexts']);
$cid_parts = array_merge($build['#cache']['keys'], $cache_contexts_manager
->convertTokensToKeys($build['#cache']['contexts'])
->getKeys());
$this
->assertContains('[workspace]=stage', $cid_parts);
$cid = implode(':', $cid_parts);
$bin = $build['#cache']['bin'];
$this
->assertInstanceOf(\stdClass::class, $this->container
->get('cache.' . $bin)
->get($cid));
}
}