You are here

protected function BlockViewBuilderTest::assertBlockRenderedWithExpectedCacheability in Drupal 10

Same name and namespace in other branches
  1. 8 core/modules/block/tests/src/Kernel/BlockViewBuilderTest.php \Drupal\Tests\block\Kernel\BlockViewBuilderTest::assertBlockRenderedWithExpectedCacheability()
  2. 9 core/modules/block/tests/src/Kernel/BlockViewBuilderTest.php \Drupal\Tests\block\Kernel\BlockViewBuilderTest::assertBlockRenderedWithExpectedCacheability()

Asserts that a block is built/rendered/cached with expected cacheability.

@internal

Parameters

string[] $expected_keys: The expected cache keys.

string[] $expected_contexts: The expected cache contexts.

string[] $expected_tags: The expected cache tags.

int $expected_max_age: The expected max-age.

File

core/modules/block/tests/src/Kernel/BlockViewBuilderTest.php, line 294

Class

BlockViewBuilderTest
Tests the block view builder.

Namespace

Drupal\Tests\block\Kernel

Code

protected function assertBlockRenderedWithExpectedCacheability(array $expected_keys, array $expected_contexts, array $expected_tags, int $expected_max_age) : void {
  $required_cache_contexts = [
    'languages:' . LanguageInterface::TYPE_INTERFACE,
    'theme',
    'user.permissions',
  ];

  // Check that the expected cacheability metadata is present in:
  // - the built render array;
  $build = $this
    ->getBlockRenderArray();
  $this
    ->assertSame($expected_keys, $build['#cache']['keys']);
  $this
    ->assertEqualsCanonicalizing($expected_contexts, $build['#cache']['contexts']);
  $this
    ->assertEqualsCanonicalizing($expected_tags, $build['#cache']['tags']);
  $this
    ->assertSame($expected_max_age, $build['#cache']['max-age']);
  $this
    ->assertFalse(isset($build['#create_placeholder']));

  // - the rendered render array;
  $this->renderer
    ->renderRoot($build);

  // - the render cache item.
  $final_cache_contexts = Cache::mergeContexts($expected_contexts, $required_cache_contexts);
  $cid = implode(':', $expected_keys) . ':' . implode(':', \Drupal::service('cache_contexts_manager')
    ->convertTokensToKeys($final_cache_contexts)
    ->getKeys());
  $cache_item = $this->container
    ->get('cache.render')
    ->get($cid);
  $this
    ->assertNotEmpty($cache_item, 'The block render element has been cached with the expected cache ID.');
  $this
    ->assertEqualsCanonicalizing(Cache::mergeTags($expected_tags, [
    'rendered',
  ]), $cache_item->tags);
  $this
    ->assertEqualsCanonicalizing($final_cache_contexts, $cache_item->data['#cache']['contexts']);
  $this
    ->assertEqualsCanonicalizing($expected_tags, $cache_item->data['#cache']['tags']);
  $this
    ->assertSame($expected_max_age, $cache_item->data['#cache']['max-age']);
  $this->container
    ->get('cache.render')
    ->delete($cid);
}