function ViewsBlockTest::testCacheableMetadata

Tests that cacheable metadata is retrieved from the view and merged with block cacheable metadata.

@dataProvider providerTestCacheableMetadata

See also

\Drupal\views\Plugin\block\ViewsBlock::build()

File

core/modules/views/tests/src/Unit/Plugin/Block/ViewsBlockTest.php, line 187

Class

ViewsBlockTest
@coversDefaultClass \Drupal\views\Plugin\block\ViewsBlock[[api-linebreak]] @group views

Namespace

Drupal\Tests\views\Unit\Plugin\Block

Code

public function testCacheableMetadata(int $blockCacheMaxAge, int $viewCacheMaxAge, int $expectedCacheMaxAge) : void {
  $blockCacheTags = [
    'block-cachetag-1',
    'block-cachetag-2',
  ];
  $blockCacheContexts = [
    'block-cache-context-1',
    'block-cache-context-2',
  ];
  $viewCacheTags = [
    'view-cachetag-1',
    'view-cachetag-2',
  ];
  $viewCacheContexts = [
    'view-cache-context-1',
    'view-cache-context-2',
  ];
  // Mock view cache metadata.
  $viewCacheMetadata = $this->createMock(CacheableMetadata::class);
  $viewCacheMetadata->method('getCacheTags')
    ->willReturn($viewCacheTags);
  $viewCacheMetadata->method('getCacheContexts')
    ->willReturn($viewCacheContexts);
  $viewCacheMetadata->method('getCacheMaxAge')
    ->willReturn($viewCacheMaxAge);
  $this->executable->display_handler
    ->method('getCacheMetadata')
    ->willReturn($viewCacheMetadata);
  // Mock block context.
  $blockContext = $this->createMock(ContextInterface::class);
  $blockContext->method('getCacheTags')
    ->willReturn($blockCacheTags);
  $blockContext->method('getCacheContexts')
    ->willReturn($blockCacheContexts);
  $blockContext->method('getCacheMaxAge')
    ->willReturn($blockCacheMaxAge);
  // Create the views block.
  $block_id = 'views_block:test_view-block_1';
  $config = [];
  $definition = [
    'provider' => 'views',
  ];
  $plugin = new ViewsBlock($config, $block_id, $definition, $this->executableFactory, $this->storage, $this->account);
  $plugin->setContext('context_name', $blockContext);
  // Assertions.
  $this->assertEmpty(array_diff(Cache::mergeTags($viewCacheTags, $blockCacheTags), $plugin->getCacheTags()));
  $this->assertEmpty(array_diff(Cache::mergeContexts($viewCacheContexts, $blockCacheContexts), $plugin->getCacheContexts()));
  $this->assertEquals($expectedCacheMaxAge, $plugin->getCacheMaxAge());
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.