3 namespace Drupal\Tests\workspaces\Functional;
5 use Drupal\Tests\BrowserTestBase;
6 use Drupal\Tests\system\Functional\Cache\AssertPageCacheContextsAndTagsTrait;
7 use Drupal\workspaces\Entity\Workspace;
8 use Drupal\workspaces\WorkspaceCacheContext;
11 * Tests the workspace cache context.
16 class WorkspaceCacheContextTest extends BrowserTestBase {
18 use AssertPageCacheContextsAndTagsTrait;
23 public static $modules = ['block', 'node', 'workspaces'];
26 * Tests the 'workspace' cache context.
28 public function testWorkspaceCacheContext() {
29 $this->dumpHeaders = TRUE;
31 $renderer = \Drupal::service('renderer');
32 $cache_contexts_manager = \Drupal::service("cache_contexts_manager");
34 // Check that the 'workspace' cache context is present when the module is
36 $this->drupalGet('<front>');
37 $this->assertCacheContext('workspace');
39 $cache_context = new WorkspaceCacheContext(\Drupal::service('workspaces.manager'));
40 $this->assertSame('live', $cache_context->getContext());
42 // Create a node and check that its render array contains the proper cache
44 $this->drupalCreateContentType(['type' => 'page']);
45 $node = $this->createNode();
47 // Get a fully built entity view render array.
48 $build = \Drupal::entityTypeManager()->getViewBuilder('node')->view($node, 'full');
50 // Render it so the default cache contexts are applied.
51 $renderer->renderRoot($build);
52 $this->assertTrue(in_array('workspace', $build['#cache']['contexts'], TRUE));
54 $cid_parts = array_merge($build['#cache']['keys'], $cache_contexts_manager->convertTokensToKeys($build['#cache']['contexts'])->getKeys());
55 $this->assertTrue(in_array('[workspace]=live', $cid_parts, TRUE));
57 // Test that a cache entry is created.
58 $cid = implode(':', $cid_parts);
59 $bin = $build['#cache']['bin'];
60 $this->assertTrue($this->container->get('cache.' . $bin)->get($cid), 'The entity render element has been cached.');
62 // Switch to the 'stage' workspace and check that the correct workspace
63 // cache context is used.
64 $test_user = $this->drupalCreateUser(['view any workspace']);
65 $this->drupalLogin($test_user);
67 $stage = Workspace::load('stage');
68 $workspace_manager = \Drupal::service('workspaces.manager');
69 $workspace_manager->setActiveWorkspace($stage);
71 $cache_context = new WorkspaceCacheContext($workspace_manager);
72 $this->assertSame('stage', $cache_context->getContext());
74 $build = \Drupal::entityTypeManager()->getViewBuilder('node')->view($node, 'full');
76 // Render it so the default cache contexts are applied.
77 $renderer->renderRoot($build);
78 $this->assertTrue(in_array('workspace', $build['#cache']['contexts'], TRUE));
80 $cid_parts = array_merge($build['#cache']['keys'], $cache_contexts_manager->convertTokensToKeys($build['#cache']['contexts'])->getKeys());
81 $this->assertTrue(in_array('[workspace]=stage', $cid_parts, TRUE));