function BlockCacheTest::testCachePerRole
Same name in other branches
- 9 core/modules/block/tests/src/Functional/BlockCacheTest.php \Drupal\Tests\block\Functional\BlockCacheTest::testCachePerRole()
- 8.9.x core/modules/block/tests/src/Functional/BlockCacheTest.php \Drupal\Tests\block\Functional\BlockCacheTest::testCachePerRole()
- 11.x core/modules/block/tests/src/Functional/BlockCacheTest.php \Drupal\Tests\block\Functional\BlockCacheTest::testCachePerRole()
Tests "user.roles" cache context.
File
-
core/
modules/ block/ tests/ src/ Functional/ BlockCacheTest.php, line 83
Class
- BlockCacheTest
- Tests block caching.
Namespace
Drupal\Tests\block\FunctionalCode
public function testCachePerRole() : void {
\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->assertSession()
->pageTextContains($current_content);
// 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->assertSession()
->pageTextContains($old_content);
// Clear the cache and verify that the stale data is no longer there.
Cache::invalidateTags([
'block_view',
]);
$this->drupalGet('');
$this->assertSession()
->pageTextNotContains($old_content);
// Fresh block content is displayed after clearing the cache.
$this->assertSession()
->pageTextContains($current_content);
// 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('');
// Anonymous user does not see content cached per-role for normal user.
$this->assertSession()
->pageTextNotContains($old_content);
// User with the same roles sees per-role cached content.
$this->drupalLogin($this->normalUserAlt);
$this->drupalGet('');
$this->assertSession()
->pageTextContains($old_content);
// Admin user does not see content cached per-role for normal user.
$this->drupalLogin($this->adminUser);
$this->drupalGet('');
$this->assertSession()
->pageTextNotContains($old_content);
// Block is served from the per-role cache.
$this->drupalLogin($this->normalUser);
$this->drupalGet('');
$this->assertSession()
->pageTextContains($old_content);
}
Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.