You are here

public function CacheInvalidationOnGroupChangeTest::testCacheInvalidationOnGroupChange in Organic groups 8

Tests if the cache is correctly invalidated on group change.

File

tests/src/Kernel/Entity/CacheInvalidationOnGroupChangeTest.php, line 74

Class

CacheInvalidationOnGroupChangeTest
Tests if group content listings are invalidated when group audience changes.

Namespace

Drupal\Tests\og\Kernel\Entity

Code

public function testCacheInvalidationOnGroupChange() {

  // Create two groups.
  $groups = [];
  for ($i = 0; $i < 2; $i++) {
    $groups[$i] = EntityTest::create([
      'type' => 'group',
      'name' => $this
        ->randomString(),
    ]);
    $groups[$i]
      ->save();
  }

  // Create a group content entity that belong to the first group.
  $group_content = EntityTest::create([
    'type' => 'group_content',
    'name' => $this
      ->randomString(),
    OgGroupAudienceHelperInterface::DEFAULT_FIELD => $groups[0]
      ->id(),
  ]);
  $group_content
    ->save();

  // Cache some arbitrary data tagged with the OG group content tags for both
  // groups.
  $this
    ->populateCache($groups[0]);
  $this
    ->populateCache($groups[1]);

  // Sanity check, the cached content listings of both groups should be
  // populated.
  $this
    ->assertCachePopulated($groups[0]);
  $this
    ->assertCachePopulated($groups[1]);

  // Change the label of group 1. This should not affect any of the cached
  // listings.
  $groups[0]
    ->setName($this
    ->randomString())
    ->save();
  $this
    ->assertCachePopulated($groups[0]);
  $this
    ->assertCachePopulated($groups[1]);

  // Move the group content from group 1 to group 2. This should invalidate
  // the group content list cache tags of both groups.
  $group_content
    ->set(OgGroupAudienceHelperInterface::DEFAULT_FIELD, $groups[1]
    ->id())
    ->save();

  // Cache entries tagged with 'og-group-content:entity_type:{$group->id()}'
  // should have been invalidated at this point because the content members of
  // both groups have changed.
  $this
    ->assertCacheNotPopulated($groups[0]);
  $this
    ->assertCacheNotPopulated($groups[1]);

  // Now populate both caches while including the cache tags of the group
  // itself. This can happen for example if a listing of group content is
  // shown that includes the group name in its content.
  $this
    ->populateCache($groups[0], TRUE);
  $this
    ->populateCache($groups[1], TRUE);

  // Change the label of group 1. This should invalidate the cache of the
  // group content listing for group 1, but not for group 2.
  $groups[0]
    ->setName($this
    ->randomString())
    ->save();
  $this
    ->assertCacheNotPopulated($groups[0]);
  $this
    ->assertCachePopulated($groups[1]);
}