You are here

public function CacheContextOptimizationTest::testUserRolesCacheContextOptimization in Zircon Profile 8

Same name and namespace in other branches
  1. 8.0 core/modules/system/src/Tests/Cache/CacheContextOptimizationTest.php \Drupal\system\Tests\Cache\CacheContextOptimizationTest::testUserRolesCacheContextOptimization()

Ensures that 'user.roles' still works when it is optimized away.

File

core/modules/system/src/Tests/Cache/CacheContextOptimizationTest.php, line 86
Contains \Drupal\system\Tests\Cache\CacheContextOptimizationTest.

Class

CacheContextOptimizationTest
Tests the cache context optimization.

Namespace

Drupal\system\Tests\Cache

Code

public function testUserRolesCacheContextOptimization() {
  $root_user = $this
    ->createUser();
  $this
    ->assertEqual($root_user
    ->id(), 1);
  $authenticated_user = $this
    ->createUser([
    'administer permissions',
  ]);
  $role = $authenticated_user
    ->getRoles()[1];
  $test_element = [
    '#cache' => [
      'keys' => [
        'test',
      ],
      'contexts' => [
        'user',
        'user.roles',
      ],
    ],
  ];
  \Drupal::service('account_switcher')
    ->switchTo($authenticated_user);
  $element = $test_element;
  $element['#markup'] = 'content for authenticated users';
  $output = \Drupal::service('renderer')
    ->renderRoot($element);
  $this
    ->assertEqual($output, 'content for authenticated users');

  // Verify that the render caching is working so that other tests can be
  // trusted.
  $element = $test_element;
  $element['#markup'] = 'this should not be visible';
  $output = \Drupal::service('renderer')
    ->renderRoot($element);
  $this
    ->assertEqual($output, 'content for authenticated users');

  // Even though the cache contexts have been optimized to only include 'user'
  // cache context, the element should have been changed because 'user.roles'
  // cache context defined a cache tag for user entity changes, which should
  // have bubbled up for the element when it was optimized away.
  $authenticated_user
    ->removeRole($role);
  $authenticated_user
    ->save();
  $element = $test_element;
  $element['#markup'] = 'this should be visible';
  $output = \Drupal::service('renderer')
    ->renderRoot($element);
  $this
    ->assertEqual($output, 'this should be visible');
}