function EntityViewBuilderTest::testEntityViewBuilderCacheToggling

Same name in other branches
  1. 8.9.x core/tests/Drupal/KernelTests/Core/Entity/EntityViewBuilderTest.php \Drupal\KernelTests\Core\Entity\EntityViewBuilderTest::testEntityViewBuilderCacheToggling()
  2. 10 core/tests/Drupal/KernelTests/Core/Entity/EntityViewBuilderTest.php \Drupal\KernelTests\Core\Entity\EntityViewBuilderTest::testEntityViewBuilderCacheToggling()
  3. 11.x core/tests/Drupal/KernelTests/Core/Entity/EntityViewBuilderTest.php \Drupal\KernelTests\Core\Entity\EntityViewBuilderTest::testEntityViewBuilderCacheToggling()

Tests entity render cache toggling.

File

core/tests/Drupal/KernelTests/Core/Entity/EntityViewBuilderTest.php, line 164

Class

EntityViewBuilderTest
Tests the entity view builder.

Namespace

Drupal\KernelTests\Core\Entity

Code

public function testEntityViewBuilderCacheToggling() {
    $entity_test = $this->createTestEntity('entity_test');
    $entity_test->save();
    // Test a view mode in default conditions: render caching is enabled for
    // the entity type and the view mode.
    $build = $this->container
        ->get('entity_type.manager')
        ->getViewBuilder('entity_test')
        ->view($entity_test, 'full');
    $this->assertNotEmpty($build['#cache']);
    $this->assertEquals([
        'tags',
        'contexts',
        'max-age',
        'keys',
        'bin',
    ], array_keys($build['#cache']), 'A view mode with render cache enabled has the correct output (cache tags, keys, contexts, max-age and bin).');
    // Test that a view mode can opt out of render caching.
    $build = $this->container
        ->get('entity_type.manager')
        ->getViewBuilder('entity_test')
        ->view($entity_test, 'test');
    $this->assertNotEmpty($build['#cache']);
    $this->assertEquals([
        'tags',
        'contexts',
        'max-age',
    ], array_keys($build['#cache']), 'A view mode with render cache disabled has the correct output (only cache tags, contexts and max-age).');
    // Test that an entity type can opt out of render caching completely.
    $this->installEntitySchema('entity_test_label');
    $entity_test_no_cache = $this->createTestEntity('entity_test_label');
    $entity_test_no_cache->save();
    $build = $this->container
        ->get('entity_type.manager')
        ->getViewBuilder('entity_test_label')
        ->view($entity_test_no_cache, 'full');
    $this->assertNotEmpty($build['#cache']);
    $this->assertEquals([
        'tags',
        'contexts',
        'max-age',
    ], array_keys($build['#cache']), 'An entity type can opt out of render caching regardless of view mode configuration, but always has cache tags, contexts and max-age set.');
}

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