You are here

function BlockCacheTest::testCachePerRole in Zircon Profile 8

Same name and namespace in other branches
  1. 8.0 core/modules/block/src/Tests/BlockCacheTest.php \Drupal\block\Tests\BlockCacheTest::testCachePerRole()

Test "user.roles" cache context.

File

core/modules/block/src/Tests/BlockCacheTest.php, line 77
Contains \Drupal\block\Tests\BlockCacheTest.

Class

BlockCacheTest
Tests block caching.

Namespace

Drupal\block\Tests

Code

function testCachePerRole() {
  \Drupal::state()
    ->set('block_test.cache_contexts', [
    'user.roles',
  ]);

  // Enable our test block. Set some content for it to display.
  $current_content = $this
    ->randomMachineName();
  \Drupal::state()
    ->set('block_test.content', $current_content);
  $this
    ->drupalLogin($this->normalUser);
  $this
    ->drupalGet('');
  $this
    ->assertText($current_content, 'Block content displays.');

  // Change the content, but the cached copy should still be served.
  $old_content = $current_content;
  $current_content = $this
    ->randomMachineName();
  \Drupal::state()
    ->set('block_test.content', $current_content);
  $this
    ->drupalGet('');
  $this
    ->assertText($old_content, 'Block is served from the cache.');

  // Clear the cache and verify that the stale data is no longer there.
  Cache::invalidateTags(array(
    'block_view',
  ));
  $this
    ->drupalGet('');
  $this
    ->assertNoText($old_content, 'Block cache clear removes stale cache data.');
  $this
    ->assertText($current_content, 'Fresh block content is displayed after clearing the cache.');

  // Test whether the cached data is served for the correct users.
  $old_content = $current_content;
  $current_content = $this
    ->randomMachineName();
  \Drupal::state()
    ->set('block_test.content', $current_content);
  $this
    ->drupalLogout();
  $this
    ->drupalGet('');
  $this
    ->assertNoText($old_content, 'Anonymous user does not see content cached per-role for normal user.');
  $this
    ->drupalLogin($this->normalUserAlt);
  $this
    ->drupalGet('');
  $this
    ->assertText($old_content, 'User with the same roles sees per-role cached content.');
  $this
    ->drupalLogin($this->adminUser);
  $this
    ->drupalGet('');
  $this
    ->assertNoText($old_content, 'Admin user does not see content cached per-role for normal user.');
  $this
    ->drupalLogin($this->normalUser);
  $this
    ->drupalGet('');
  $this
    ->assertText($old_content, 'Block is served from the per-role cache.');
}