d215df5ccd42a3c2c6a71d7a84a6de6727441ec3
[yaffs-website] / web / core / modules / system / src / Tests / Entity / EntityCacheTagsTestBase.php
1 <?php
2
3 namespace Drupal\system\Tests\Entity;
4
5 use Drupal\Core\Cache\Cache;
6 use Drupal\Core\Entity\EntityInterface;
7 use Drupal\Core\EventSubscriber\MainContentViewSubscriber;
8 use Drupal\Core\Field\FieldStorageDefinitionInterface;
9 use Drupal\Core\Language\LanguageInterface;
10 use Drupal\Core\Url;
11 use Drupal\field\Entity\FieldStorageConfig;
12 use Drupal\field\Entity\FieldConfig;
13 use Drupal\system\Tests\Cache\PageCacheTagsTestBase;
14 use Drupal\user\Entity\Role;
15 use Drupal\user\RoleInterface;
16
17 /**
18  * Provides helper methods for Entity cache tags tests.
19  *
20  * @deprecated Scheduled for removal in Drupal 9.0.0.
21  *   Use \Drupal\Tests\system\Functional\Entity\EntityCacheTagsTestBase instead.
22  */
23 abstract class EntityCacheTagsTestBase extends PageCacheTagsTestBase {
24
25   /**
26    * Modules to enable.
27    *
28    * @var array
29    */
30   public static $modules = ['entity_test', 'field_test'];
31
32   /**
33    * The main entity used for testing.
34    *
35    * @var \Drupal\Core\Entity\EntityInterface
36    */
37   protected $entity;
38
39   /**
40    * The entity instance referencing the main entity.
41    *
42    * @var \Drupal\Core\Entity\EntityInterface
43    */
44   protected $referencingEntity;
45
46   /**
47    * The entity instance not referencing the main entity.
48    *
49    * @var \Drupal\Core\Entity\EntityInterface
50    */
51   protected $nonReferencingEntity;
52
53   /**
54    * {@inheritdoc}
55    */
56   protected function setUp() {
57     parent::setUp();
58
59     // Give anonymous users permission to view test entities, so that we can
60     // verify the cache tags of cached versions of test entity pages.
61     $user_role = Role::load(RoleInterface::ANONYMOUS_ID);
62     $user_role->grantPermission('view test entity');
63     $user_role->save();
64
65     // Create an entity.
66     $this->entity = $this->createEntity();
67
68     // If this is an entity with field UI enabled, then add a configurable
69     // field. We will use this configurable field in later tests to ensure that
70     // field configuration invalidate render cache entries.
71     if ($this->entity->getEntityType()->get('field_ui_base_route')) {
72       // Add field, so we can modify the field storage and field entities to
73       // verify that changes to those indeed clear cache tags.
74       FieldStorageConfig::create([
75         'field_name' => 'configurable_field',
76         'entity_type' => $this->entity->getEntityTypeId(),
77         'type' => 'test_field',
78         'settings' => [],
79       ])->save();
80       FieldConfig::create([
81         'entity_type' => $this->entity->getEntityTypeId(),
82         'bundle' => $this->entity->bundle(),
83         'field_name' => 'configurable_field',
84         'label' => 'Configurable field',
85         'settings' => [],
86       ])->save();
87
88       // Reload the entity now that a new field has been added to it.
89       $storage = $this->container
90         ->get('entity.manager')
91         ->getStorage($this->entity->getEntityTypeId());
92       $storage->resetCache();
93       $this->entity = $storage->load($this->entity->id());
94     }
95
96     // Create a referencing and a non-referencing entity.
97     list(
98       $this->referencingEntity,
99       $this->nonReferencingEntity,
100     ) = $this->createReferenceTestEntities($this->entity);
101   }
102
103   /**
104    * Generates standardized entity cache tags test info.
105    *
106    * @param string $entity_type_label
107    *   The label of the entity type whose cache tags to test.
108    * @param string $group
109    *   The test group.
110    *
111    * @return array
112    *
113    * @see \Drupal\simpletest\TestBase::getInfo()
114    */
115   protected static function generateStandardizedInfo($entity_type_label, $group) {
116     return [
117       'name' => "$entity_type_label entity cache tags",
118       'description' => "Test the $entity_type_label entity's cache tags.",
119       'group' => $group,
120     ];
121   }
122
123   /**
124    * Creates the entity to be tested.
125    *
126    * @return \Drupal\Core\Entity\EntityInterface
127    *   The entity to be tested.
128    */
129   abstract protected function createEntity();
130
131   /**
132    * Returns the access cache contexts for the tested entity.
133    *
134    * Only list cache contexts that aren't part of the required cache contexts.
135    *
136    * @param \Drupal\Core\Entity\EntityInterface $entity
137    *   The entity to be tested, as created by createEntity().
138    *
139    * @return string[]
140    *   An array of the additional cache contexts.
141    *
142    * @see \Drupal\Core\Entity\EntityAccessControlHandlerInterface
143    */
144   protected function getAccessCacheContextsForEntity(EntityInterface $entity) {
145     return [];
146   }
147
148   /**
149    * Returns the additional (non-standard) cache contexts for the tested entity.
150    *
151    * Only list cache contexts that aren't part of the required cache contexts.
152    *
153    * @param \Drupal\Core\Entity\EntityInterface $entity
154    *   The entity to be tested, as created by createEntity().
155    *
156    * @return string[]
157    *   An array of the additional cache contexts.
158    *
159    * @see \Drupal\system\Tests\Entity\EntityCacheTagsTestBase::createEntity()
160    */
161   protected function getAdditionalCacheContextsForEntity(EntityInterface $entity) {
162     return [];
163   }
164
165   /**
166    * Returns the additional (non-standard) cache tags for the tested entity.
167    *
168    * @param \Drupal\Core\Entity\EntityInterface $entity
169    *   The entity to be tested, as created by createEntity().
170    * @return array
171    *   An array of the additional cache tags.
172    *
173    * @see \Drupal\system\Tests\Entity\EntityCacheTagsTestBase::createEntity()
174    */
175   protected function getAdditionalCacheTagsForEntity(EntityInterface $entity) {
176     return [];
177   }
178
179   /**
180    * Returns the additional cache tags for the tested entity's listing by type.
181    *
182    * @return string[]
183    *   An array of the additional cache contexts.
184    */
185   protected function getAdditionalCacheContextsForEntityListing() {
186     return [];
187   }
188
189   /**
190    * Returns the additional cache tags for the tested entity's listing by type.
191    *
192    * Necessary when there are unavoidable default entities of this type, e.g.
193    * the anonymous and administrator User entities always exist.
194    *
195    * @return array
196    *   An array of the additional cache tags.
197    */
198   protected function getAdditionalCacheTagsForEntityListing() {
199     return [];
200   }
201
202   /**
203    * Selects the preferred view mode for the given entity type.
204    *
205    * Prefers 'full', picks the first one otherwise, and if none are available,
206    * chooses 'default'.
207    */
208   protected function selectViewMode($entity_type) {
209     $view_modes = \Drupal::entityManager()
210       ->getStorage('entity_view_mode')
211       ->loadByProperties(['targetEntityType' => $entity_type]);
212
213     if (empty($view_modes)) {
214       return 'default';
215     }
216     else {
217       // Prefer the "full" display mode.
218       if (isset($view_modes[$entity_type . '.full'])) {
219         return 'full';
220       }
221       else {
222         $view_modes = array_keys($view_modes);
223         return substr($view_modes[0], strlen($entity_type) + 1);
224       }
225     }
226   }
227
228   /**
229    * Creates a referencing and a non-referencing entity for testing purposes.
230    *
231    * @param \Drupal\Core\Entity\EntityInterface $referenced_entity
232    *   The entity that the referencing entity should reference.
233    *
234    * @return \Drupal\Core\Entity\EntityInterface[]
235    *   An array containing a referencing entity and a non-referencing entity.
236    */
237   protected function createReferenceTestEntities($referenced_entity) {
238     // All referencing entities should be of the type 'entity_test'.
239     $entity_type = 'entity_test';
240
241     // Create a "foo" bundle for the given entity type.
242     $bundle = 'foo';
243     entity_test_create_bundle($bundle, NULL, $entity_type);
244
245     // Add a field of the given type to the given entity type's "foo" bundle.
246     $field_name = $referenced_entity->getEntityTypeId() . '_reference';
247     FieldStorageConfig::create([
248       'field_name' => $field_name,
249       'entity_type' => $entity_type,
250       'type' => 'entity_reference',
251       'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED,
252       'settings' => [
253         'target_type' => $referenced_entity->getEntityTypeId(),
254       ],
255     ])->save();
256     FieldConfig::create([
257       'field_name' => $field_name,
258       'entity_type' => $entity_type,
259       'bundle' => $bundle,
260       'settings' => [
261         'handler' => 'default',
262         'handler_settings' => [
263           'target_bundles' => [
264             $referenced_entity->bundle() => $referenced_entity->bundle(),
265           ],
266           'sort' => ['field' => '_none'],
267           'auto_create' => FALSE,
268         ],
269       ],
270     ])->save();
271     if (!$this->entity->getEntityType()->hasHandlerClass('view_builder')) {
272       entity_get_display($entity_type, $bundle, 'full')
273         ->setComponent($field_name, [
274           'type' => 'entity_reference_label',
275         ])
276         ->save();
277     }
278     else {
279       $referenced_entity_view_mode = $this->selectViewMode($this->entity->getEntityTypeId());
280       entity_get_display($entity_type, $bundle, 'full')
281         ->setComponent($field_name, [
282           'type' => 'entity_reference_entity_view',
283           'settings' => [
284             'view_mode' => $referenced_entity_view_mode,
285           ],
286         ])
287         ->save();
288     }
289
290     // Create an entity that does reference the entity being tested.
291     $label_key = \Drupal::entityManager()->getDefinition($entity_type)->getKey('label');
292     $referencing_entity = $this->container->get('entity_type.manager')
293       ->getStorage($entity_type)
294       ->create([
295         $label_key => 'Referencing ' . $entity_type,
296         'status' => 1,
297         'type' => $bundle,
298         $field_name => ['target_id' => $referenced_entity->id()],
299       ]);
300     $referencing_entity->save();
301
302     // Create an entity that does not reference the entity being tested.
303     $non_referencing_entity = $this->container->get('entity_type.manager')
304       ->getStorage($entity_type)
305       ->create([
306         $label_key => 'Non-referencing ' . $entity_type,
307         'status' => 1,
308         'type' => $bundle,
309       ]);
310     $non_referencing_entity->save();
311
312     return [
313       $referencing_entity,
314       $non_referencing_entity,
315     ];
316   }
317
318   /**
319    * Tests cache tags presence and invalidation of the entity when referenced.
320    *
321    * Tests the following cache tags:
322    * - entity type view cache tag: "<entity type>_view"
323    * - entity cache tag: "<entity type>:<entity ID>"
324    * - entity type list cache tag: "<entity type>_list"
325    * - referencing entity type view cache tag: "<referencing entity type>_view"
326    * - referencing entity type cache tag: "<referencing entity type>:<referencing entity ID>"
327    */
328   public function testReferencedEntity() {
329     $entity_type = $this->entity->getEntityTypeId();
330     $referencing_entity_url = $this->referencingEntity->urlInfo('canonical');
331     $non_referencing_entity_url = $this->nonReferencingEntity->urlInfo('canonical');
332     $listing_url = Url::fromRoute('entity.entity_test.collection_referencing_entities', [
333       'entity_reference_field_name' => $entity_type . '_reference',
334       'referenced_entity_type' => $entity_type,
335       'referenced_entity_id' => $this->entity->id(),
336     ]);
337     $empty_entity_listing_url = Url::fromRoute('entity.entity_test.collection_empty', ['entity_type_id' => $entity_type]);
338     $nonempty_entity_listing_url = Url::fromRoute('entity.entity_test.collection_labels_alphabetically', ['entity_type_id' => $entity_type]);
339
340     // The default cache contexts for rendered entities.
341     $default_cache_contexts = ['languages:' . LanguageInterface::TYPE_INTERFACE, 'theme', 'user.permissions'];
342     $entity_cache_contexts = $default_cache_contexts;
343     $page_cache_contexts = Cache::mergeContexts($default_cache_contexts, ['url.query_args:' . MainContentViewSubscriber::WRAPPER_FORMAT]);
344
345     // Cache tags present on every rendered page.
346     // 'user.permissions' is a required cache context, and responses that vary
347     // by this cache context when requested by anonymous users automatically
348     // also get this cache tag, to ensure correct invalidation.
349     $page_cache_tags = Cache::mergeTags(['http_response', 'rendered'], ['config:user.role.anonymous']);
350     // If the block module is used, the Block page display variant is used,
351     // which adds the block config entity type's list cache tags.
352     $page_cache_tags = Cache::mergeTags($page_cache_tags, \Drupal::moduleHandler()->moduleExists('block') ? ['config:block_list'] : []);
353
354     $page_cache_tags_referencing_entity = in_array('user.permissions', $this->getAccessCacheContextsForEntity($this->referencingEntity)) ? ['config:user.role.anonymous'] : [];
355
356     $view_cache_tag = [];
357     if ($this->entity->getEntityType()->hasHandlerClass('view_builder')) {
358       $view_cache_tag = \Drupal::entityManager()->getViewBuilder($entity_type)
359         ->getCacheTags();
360     }
361
362     $context_metadata = \Drupal::service('cache_contexts_manager')->convertTokensToKeys($entity_cache_contexts);
363     $cache_context_tags = $context_metadata->getCacheTags();
364
365     // Generate the cache tags for the (non) referencing entities.
366     $referencing_entity_cache_tags = Cache::mergeTags($this->referencingEntity->getCacheTags(), \Drupal::entityManager()->getViewBuilder('entity_test')->getCacheTags());
367     // Includes the main entity's cache tags, since this entity references it.
368     $referencing_entity_cache_tags = Cache::mergeTags($referencing_entity_cache_tags, $this->entity->getCacheTags());
369     $referencing_entity_cache_tags = Cache::mergeTags($referencing_entity_cache_tags, $this->getAdditionalCacheTagsForEntity($this->entity));
370     $referencing_entity_cache_tags = Cache::mergeTags($referencing_entity_cache_tags, $view_cache_tag);
371     $referencing_entity_cache_tags = Cache::mergeTags($referencing_entity_cache_tags, $cache_context_tags);
372     $referencing_entity_cache_tags = Cache::mergeTags($referencing_entity_cache_tags, ['rendered']);
373
374     $non_referencing_entity_cache_tags = Cache::mergeTags($this->nonReferencingEntity->getCacheTags(), \Drupal::entityManager()->getViewBuilder('entity_test')->getCacheTags());
375     $non_referencing_entity_cache_tags = Cache::mergeTags($non_referencing_entity_cache_tags, ['rendered']);
376
377     // Generate the cache tags for all two possible entity listing paths.
378     // 1. list cache tag only (listing query has no match)
379     // 2. list cache tag plus entity cache tag (listing query has a match)
380     $empty_entity_listing_cache_tags = Cache::mergeTags($this->entity->getEntityType()->getListCacheTags(), $page_cache_tags);
381
382     $nonempty_entity_listing_cache_tags = Cache::mergeTags($this->entity->getEntityType()->getListCacheTags(), $this->entity->getCacheTags());
383     $nonempty_entity_listing_cache_tags = Cache::mergeTags($nonempty_entity_listing_cache_tags, $this->getAdditionalCacheTagsForEntityListing($this->entity));
384     $nonempty_entity_listing_cache_tags = Cache::mergeTags($nonempty_entity_listing_cache_tags, $page_cache_tags);
385
386     $this->pass("Test referencing entity.", 'Debug');
387     $this->verifyPageCache($referencing_entity_url, 'MISS');
388
389     // Verify a cache hit, but also the presence of the correct cache tags.
390     $expected_tags = Cache::mergeTags($referencing_entity_cache_tags, $page_cache_tags);
391     $expected_tags = Cache::mergeTags($expected_tags, $page_cache_tags_referencing_entity);
392     $this->verifyPageCache($referencing_entity_url, 'HIT', $expected_tags);
393
394     // Also verify the existence of an entity render cache entry.
395     $cache_keys = ['entity_view', 'entity_test', $this->referencingEntity->id(), 'full'];
396     $cid = $this->createCacheId($cache_keys, $entity_cache_contexts);
397     $access_cache_contexts = $this->getAccessCacheContextsForEntity($this->entity);
398     $additional_cache_contexts = $this->getAdditionalCacheContextsForEntity($this->referencingEntity);
399     $redirected_cid = NULL;
400     if (count($access_cache_contexts) || count($additional_cache_contexts)) {
401       $cache_contexts = Cache::mergeContexts($entity_cache_contexts, $additional_cache_contexts);
402       $cache_contexts = Cache::mergeContexts($cache_contexts, $access_cache_contexts);
403       $redirected_cid = $this->createCacheId($cache_keys, $cache_contexts);
404       $context_metadata = \Drupal::service('cache_contexts_manager')->convertTokensToKeys($cache_contexts);
405       $referencing_entity_cache_tags = Cache::mergeTags($referencing_entity_cache_tags, $context_metadata->getCacheTags());
406     }
407     $this->verifyRenderCache($cid, $referencing_entity_cache_tags, $redirected_cid);
408
409     $this->pass("Test non-referencing entity.", 'Debug');
410     $this->verifyPageCache($non_referencing_entity_url, 'MISS');
411     // Verify a cache hit, but also the presence of the correct cache tags.
412     $this->verifyPageCache($non_referencing_entity_url, 'HIT', Cache::mergeTags($non_referencing_entity_cache_tags, $page_cache_tags));
413     // Also verify the existence of an entity render cache entry.
414     $cache_keys = ['entity_view', 'entity_test', $this->nonReferencingEntity->id(), 'full'];
415     $cid = $this->createCacheId($cache_keys, $entity_cache_contexts);
416     $this->verifyRenderCache($cid, $non_referencing_entity_cache_tags);
417
418     $this->pass("Test listing of referencing entities.", 'Debug');
419     // Prime the page cache for the listing of referencing entities.
420     $this->verifyPageCache($listing_url, 'MISS');
421
422     // Verify a cache hit, but also the presence of the correct cache tags.
423     $expected_tags = Cache::mergeTags($referencing_entity_cache_tags, $page_cache_tags);
424     $expected_tags = Cache::mergeTags($expected_tags, $page_cache_tags_referencing_entity);
425     $this->verifyPageCache($listing_url, 'HIT', $expected_tags);
426
427     $this->pass("Test empty listing.", 'Debug');
428     // Prime the page cache for the empty listing.
429     $this->verifyPageCache($empty_entity_listing_url, 'MISS');
430     // Verify a cache hit, but also the presence of the correct cache tags.
431     $this->verifyPageCache($empty_entity_listing_url, 'HIT', $empty_entity_listing_cache_tags);
432     // Verify the entity type's list cache contexts are present.
433     $contexts_in_header = $this->drupalGetHeader('X-Drupal-Cache-Contexts');
434     $this->assertEqual(Cache::mergeContexts($page_cache_contexts, $this->getAdditionalCacheContextsForEntityListing()), empty($contexts_in_header) ? [] : explode(' ', $contexts_in_header));
435
436     $this->pass("Test listing containing referenced entity.", 'Debug');
437     // Prime the page cache for the listing containing the referenced entity.
438     $this->verifyPageCache($nonempty_entity_listing_url, 'MISS', $nonempty_entity_listing_cache_tags);
439     // Verify a cache hit, but also the presence of the correct cache tags.
440     $this->verifyPageCache($nonempty_entity_listing_url, 'HIT', $nonempty_entity_listing_cache_tags);
441     // Verify the entity type's list cache contexts are present.
442     $contexts_in_header = $this->drupalGetHeader('X-Drupal-Cache-Contexts');
443     $this->assertEqual(Cache::mergeContexts($page_cache_contexts, $this->getAdditionalCacheContextsForEntityListing()), empty($contexts_in_header) ? [] : explode(' ', $contexts_in_header));
444
445     // Verify that after modifying the referenced entity, there is a cache miss
446     // for every route except the one for the non-referencing entity.
447     $this->pass("Test modification of referenced entity.", 'Debug');
448     $this->entity->save();
449     $this->verifyPageCache($referencing_entity_url, 'MISS');
450     $this->verifyPageCache($listing_url, 'MISS');
451     $this->verifyPageCache($empty_entity_listing_url, 'MISS');
452     $this->verifyPageCache($nonempty_entity_listing_url, 'MISS');
453     $this->verifyPageCache($non_referencing_entity_url, 'HIT');
454
455     // Verify cache hits.
456     $this->verifyPageCache($referencing_entity_url, 'HIT');
457     $this->verifyPageCache($listing_url, 'HIT');
458     $this->verifyPageCache($empty_entity_listing_url, 'HIT');
459     $this->verifyPageCache($nonempty_entity_listing_url, 'HIT');
460
461     // Verify that after modifying the referencing entity, there is a cache miss
462     // for every route except the ones for the non-referencing entity and the
463     // empty entity listing.
464     $this->pass("Test modification of referencing entity.", 'Debug');
465     $this->referencingEntity->save();
466     $this->verifyPageCache($referencing_entity_url, 'MISS');
467     $this->verifyPageCache($listing_url, 'MISS');
468     $this->verifyPageCache($nonempty_entity_listing_url, 'HIT');
469     $this->verifyPageCache($non_referencing_entity_url, 'HIT');
470     $this->verifyPageCache($empty_entity_listing_url, 'HIT');
471
472     // Verify cache hits.
473     $this->verifyPageCache($referencing_entity_url, 'HIT');
474     $this->verifyPageCache($listing_url, 'HIT');
475     $this->verifyPageCache($nonempty_entity_listing_url, 'HIT');
476
477     // Verify that after modifying the non-referencing entity, there is a cache
478     // miss only for the non-referencing entity route.
479     $this->pass("Test modification of non-referencing entity.", 'Debug');
480     $this->nonReferencingEntity->save();
481     $this->verifyPageCache($referencing_entity_url, 'HIT');
482     $this->verifyPageCache($listing_url, 'HIT');
483     $this->verifyPageCache($empty_entity_listing_url, 'HIT');
484     $this->verifyPageCache($nonempty_entity_listing_url, 'HIT');
485     $this->verifyPageCache($non_referencing_entity_url, 'MISS');
486
487     // Verify cache hits.
488     $this->verifyPageCache($non_referencing_entity_url, 'HIT');
489
490     if ($this->entity->getEntityType()->hasHandlerClass('view_builder')) {
491       // Verify that after modifying the entity's display, there is a cache miss
492       // for both the referencing entity, and the listing of referencing
493       // entities, but not for any other routes.
494       $referenced_entity_view_mode = $this->selectViewMode($this->entity->getEntityTypeId());
495       $this->pass("Test modification of referenced entity's '$referenced_entity_view_mode' display.", 'Debug');
496       $entity_display = entity_get_display($entity_type, $this->entity->bundle(), $referenced_entity_view_mode);
497       $entity_display->save();
498       $this->verifyPageCache($referencing_entity_url, 'MISS');
499       $this->verifyPageCache($listing_url, 'MISS');
500       $this->verifyPageCache($non_referencing_entity_url, 'HIT');
501       $this->verifyPageCache($empty_entity_listing_url, 'HIT');
502       $this->verifyPageCache($nonempty_entity_listing_url, 'HIT');
503
504       // Verify cache hits.
505       $this->verifyPageCache($referencing_entity_url, 'HIT');
506       $this->verifyPageCache($listing_url, 'HIT');
507     }
508
509     if ($bundle_entity_type_id = $this->entity->getEntityType()->getBundleEntityType()) {
510       // Verify that after modifying the corresponding bundle entity, there is a
511       // cache miss for both the referencing entity, and the listing of
512       // referencing entities, but not for any other routes.
513       $this->pass("Test modification of referenced entity's bundle entity.", 'Debug');
514       $bundle_entity = $this->container->get('entity_type.manager')
515         ->getStorage($bundle_entity_type_id)
516         ->load($this->entity->bundle());
517       $bundle_entity->save();
518       $this->verifyPageCache($referencing_entity_url, 'MISS');
519       $this->verifyPageCache($listing_url, 'MISS');
520       $this->verifyPageCache($non_referencing_entity_url, 'HIT');
521       // Special case: entity types may choose to use their bundle entity type
522       // cache tags, to avoid having excessively granular invalidation.
523       $is_special_case = $bundle_entity->getCacheTags() == $this->entity->getCacheTags() && $bundle_entity->getEntityType()->getListCacheTags() == $this->entity->getEntityType()->getListCacheTags();
524       if ($is_special_case) {
525         $this->verifyPageCache($empty_entity_listing_url, 'MISS');
526         $this->verifyPageCache($nonempty_entity_listing_url, 'MISS');
527       }
528       else {
529         $this->verifyPageCache($empty_entity_listing_url, 'HIT');
530         $this->verifyPageCache($nonempty_entity_listing_url, 'HIT');
531       }
532
533       // Verify cache hits.
534       $this->verifyPageCache($referencing_entity_url, 'HIT');
535       $this->verifyPageCache($listing_url, 'HIT');
536       if ($is_special_case) {
537         $this->verifyPageCache($empty_entity_listing_url, 'HIT');
538         $this->verifyPageCache($nonempty_entity_listing_url, 'HIT');
539       }
540     }
541
542     if ($this->entity->getEntityType()->get('field_ui_base_route')) {
543       // Verify that after modifying a configurable field on the entity, there
544       // is a cache miss.
545       $this->pass("Test modification of referenced entity's configurable field.", 'Debug');
546       $field_storage_name = $this->entity->getEntityTypeId() . '.configurable_field';
547       $field_storage = FieldStorageConfig::load($field_storage_name);
548       $field_storage->save();
549       $this->verifyPageCache($referencing_entity_url, 'MISS');
550       $this->verifyPageCache($listing_url, 'MISS');
551       $this->verifyPageCache($empty_entity_listing_url, 'HIT');
552       $this->verifyPageCache($nonempty_entity_listing_url, 'HIT');
553       $this->verifyPageCache($non_referencing_entity_url, 'HIT');
554
555       // Verify cache hits.
556       $this->verifyPageCache($referencing_entity_url, 'HIT');
557       $this->verifyPageCache($listing_url, 'HIT');
558
559       // Verify that after modifying a configurable field on the entity, there
560       // is a cache miss.
561       $this->pass("Test modification of referenced entity's configurable field.", 'Debug');
562       $field_name = $this->entity->getEntityTypeId() . '.' . $this->entity->bundle() . '.configurable_field';
563       $field = FieldConfig::load($field_name);
564       $field->save();
565       $this->verifyPageCache($referencing_entity_url, 'MISS');
566       $this->verifyPageCache($listing_url, 'MISS');
567       $this->verifyPageCache($empty_entity_listing_url, 'HIT');
568       $this->verifyPageCache($nonempty_entity_listing_url, 'HIT');
569       $this->verifyPageCache($non_referencing_entity_url, 'HIT');
570
571       // Verify cache hits.
572       $this->verifyPageCache($referencing_entity_url, 'HIT');
573       $this->verifyPageCache($listing_url, 'HIT');
574     }
575
576     // Verify that after invalidating the entity's cache tag directly, there is
577     // a cache miss for every route except the ones for the non-referencing
578     // entity and the empty entity listing.
579     $this->pass("Test invalidation of referenced entity's cache tag.", 'Debug');
580     Cache::invalidateTags($this->entity->getCacheTagsToInvalidate());
581     $this->verifyPageCache($referencing_entity_url, 'MISS');
582     $this->verifyPageCache($listing_url, 'MISS');
583     $this->verifyPageCache($nonempty_entity_listing_url, 'MISS');
584     $this->verifyPageCache($non_referencing_entity_url, 'HIT');
585     $this->verifyPageCache($empty_entity_listing_url, 'HIT');
586
587     // Verify cache hits.
588     $this->verifyPageCache($referencing_entity_url, 'HIT');
589     $this->verifyPageCache($listing_url, 'HIT');
590     $this->verifyPageCache($nonempty_entity_listing_url, 'HIT');
591
592     // Verify that after invalidating the entity's list cache tag directly,
593     // there is a cache miss for both the empty entity listing and the non-empty
594     // entity listing routes, but not for other routes.
595     $this->pass("Test invalidation of referenced entity's list cache tag.", 'Debug');
596     Cache::invalidateTags($this->entity->getEntityType()->getListCacheTags());
597     $this->verifyPageCache($empty_entity_listing_url, 'MISS');
598     $this->verifyPageCache($nonempty_entity_listing_url, 'MISS');
599     $this->verifyPageCache($referencing_entity_url, 'HIT');
600     $this->verifyPageCache($non_referencing_entity_url, 'HIT');
601     $this->verifyPageCache($listing_url, 'HIT');
602
603     // Verify cache hits.
604     $this->verifyPageCache($empty_entity_listing_url, 'HIT');
605     $this->verifyPageCache($nonempty_entity_listing_url, 'HIT');
606
607     if (!empty($view_cache_tag)) {
608       // Verify that after invalidating the generic entity type's view cache tag
609       // directly, there is a cache miss for both the referencing entity, and the
610       // listing of referencing entities, but not for other routes.
611       $this->pass("Test invalidation of referenced entity's 'view' cache tag.", 'Debug');
612       Cache::invalidateTags($view_cache_tag);
613       $this->verifyPageCache($referencing_entity_url, 'MISS');
614       $this->verifyPageCache($listing_url, 'MISS');
615       $this->verifyPageCache($non_referencing_entity_url, 'HIT');
616       $this->verifyPageCache($empty_entity_listing_url, 'HIT');
617       $this->verifyPageCache($nonempty_entity_listing_url, 'HIT');
618
619       // Verify cache hits.
620       $this->verifyPageCache($referencing_entity_url, 'HIT');
621       $this->verifyPageCache($listing_url, 'HIT');
622     }
623
624     // Verify that after deleting the entity, there is a cache miss for every
625     // route except for the non-referencing entity one.
626     $this->pass('Test deletion of referenced entity.', 'Debug');
627     $this->entity->delete();
628     $this->verifyPageCache($referencing_entity_url, 'MISS');
629     $this->verifyPageCache($listing_url, 'MISS');
630     $this->verifyPageCache($empty_entity_listing_url, 'MISS');
631     $this->verifyPageCache($nonempty_entity_listing_url, 'MISS');
632     $this->verifyPageCache($non_referencing_entity_url, 'HIT');
633
634     // Verify cache hits.
635     $referencing_entity_cache_tags = Cache::mergeTags($this->referencingEntity->getCacheTags(), \Drupal::entityManager()->getViewBuilder('entity_test')->getCacheTags());
636     $referencing_entity_cache_tags = Cache::mergeTags($referencing_entity_cache_tags, ['http_response', 'rendered']);
637
638     $nonempty_entity_listing_cache_tags = Cache::mergeTags($this->entity->getEntityType()->getListCacheTags(), $this->getAdditionalCacheTagsForEntityListing());
639     $nonempty_entity_listing_cache_tags = Cache::mergeTags($nonempty_entity_listing_cache_tags, $page_cache_tags);
640
641     $this->verifyPageCache($referencing_entity_url, 'HIT', Cache::mergeTags($referencing_entity_cache_tags, $page_cache_tags));
642     $this->verifyPageCache($listing_url, 'HIT', $page_cache_tags);
643     $this->verifyPageCache($empty_entity_listing_url, 'HIT', $empty_entity_listing_cache_tags);
644     $this->verifyPageCache($nonempty_entity_listing_url, 'HIT', $nonempty_entity_listing_cache_tags);
645   }
646
647   /**
648    * Creates a cache ID from a list of cache keys and a set of cache contexts.
649    *
650    * @param string[] $keys
651    *   A list of cache keys.
652    * @param string[] $contexts
653    *   A set of cache contexts.
654    *
655    * @return string
656    *   The cache ID string.
657    */
658   protected function createCacheId(array $keys, array $contexts) {
659     $cid_parts = $keys;
660
661     $contexts = \Drupal::service('cache_contexts_manager')->convertTokensToKeys($contexts);
662     $cid_parts = array_merge($cid_parts, $contexts->getKeys());
663
664     return implode(':', $cid_parts);
665   }
666
667   /**
668    * Verify that a given render cache entry exists, with the correct cache tags.
669    *
670    * @param string $cid
671    *   The render cache item ID.
672    * @param array $tags
673    *   An array of expected cache tags.
674    * @param string|null $redirected_cid
675    *   (optional) The redirected render cache item ID.
676    */
677   protected function verifyRenderCache($cid, array $tags, $redirected_cid = NULL) {
678     // Also verify the existence of an entity render cache entry.
679     $cache_entry = \Drupal::cache('render')->get($cid);
680     $this->assertTrue($cache_entry, 'A render cache entry exists.');
681     sort($cache_entry->tags);
682     sort($tags);
683     $this->assertIdentical($cache_entry->tags, $tags);
684     $is_redirecting_cache_item = isset($cache_entry->data['#cache_redirect']);
685     if ($redirected_cid === NULL) {
686       $this->assertFalse($is_redirecting_cache_item, 'Render cache entry is not a redirect.');
687       // If this is a redirecting cache item unlike we expected, log it.
688       if ($is_redirecting_cache_item) {
689         debug($cache_entry->data);
690       }
691     }
692     else {
693       // Verify that $cid contains a cache redirect.
694       $this->assertTrue($is_redirecting_cache_item, 'Render cache entry is a redirect.');
695       // If this is not a redirecting cache item unlike we expected, log it.
696       if (!$is_redirecting_cache_item) {
697         debug($cache_entry->data);
698       }
699       // Verify that the cache redirect points to the expected CID.
700       $redirect_cache_metadata = $cache_entry->data['#cache'];
701       $actual_redirection_cid = $this->createCacheId(
702         $redirect_cache_metadata['keys'],
703         $redirect_cache_metadata['contexts']
704       );
705       $this->assertIdentical($redirected_cid, $actual_redirection_cid);
706       // Finally, verify that the redirected CID exists and has the same cache
707       // tags.
708       $this->verifyRenderCache($redirected_cid, $tags);
709     }
710   }
711
712 }