You are here

protected function BlockViewBuilderTest::assertBlockRenderedWithExpectedCacheability in Zircon Profile 8.0

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

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

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.

1 call to BlockViewBuilderTest::assertBlockRenderedWithExpectedCacheability()
BlockViewBuilderTest::testBlockViewBuilderBuildAlter in core/modules/block/src/Tests/BlockViewBuilderTest.php
Tests block build altering.

File

core/modules/block/src/Tests/BlockViewBuilderTest.php, line 294
Contains \Drupal\block\Tests\BlockViewBuilderTest.

Class

BlockViewBuilderTest
Tests the block view builder.

Namespace

Drupal\block\Tests

Code

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

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

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

  // - the render cache item.
  $this
    ->pass('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
    ->assertTrue($cache_item, 'The block render element has been cached with the expected cache ID.');
  $this
    ->assertIdentical(Cache::mergeTags($expected_tags, [
    'rendered',
  ]), $cache_item->tags);
  $this
    ->assertIdentical($final_cache_contexts, $cache_item->data['#cache']['contexts']);
  $this
    ->assertIdentical($expected_tags, $cache_item->data['#cache']['tags']);
  $this
    ->assertIdentical($expected_max_age, $cache_item->data['#cache']['max-age']);
  $this->container
    ->get('cache.render')
    ->delete($cid);
}