You are here

public function BlockCacheTest::testCachePerRole in Drupal 8

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

Test "user.roles" cache context.

File

core/modules/block/tests/src/Functional/BlockCacheTest.php, line 80

Class

BlockCacheTest
Tests block caching.

Namespace

Drupal\Tests\block\Functional

Code

public 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([
    '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.');
}