You are here

public function MessageDigestTest::testOrphanedEntityReferences in Message Digest 8

Tests that the message_digest table is cleaned up when deleting entities.

File

tests/src/Kernel/MessageDigestTest.php, line 327

Class

MessageDigestTest
Kernel tests for Message Digest.

Namespace

Drupal\Tests\message_digest\Kernel

Code

public function testOrphanedEntityReferences() {
  $template = $this
    ->createMessageTemplate('foo', 'Foo', 'Foo, foo', []);

  // Create 3 test users and send 3 messages, one to each user.
  $users = $messages = [];
  for ($i = 0; $i < 3; $i++) {
    $user = $this
      ->createUser();
    $message = Message::create([
      'template' => $template
        ->id(),
    ]);
    $message
      ->setOwner($user);
    $message
      ->save();
    $digest_notifier = $this->notifierManager
      ->createInstance('message_digest:weekly', [], $message);
    $this->notifierSender
      ->send($message, [], $digest_notifier
      ->getPluginId());
    $users[$i] = $user;
    $messages[$i] = $message;
  }

  // There should be 3 message digests.
  $this
    ->assertRowCount(3);

  // Delete one of the messages and verify that the corresponding message
  // digest is cleaned up.
  $orphaned_message_id = $messages[0]
    ->id();
  $messages[0]
    ->delete();
  $this
    ->assertRowCount(2);
  foreach ($this
    ->getAllMessageDigests() as $digest) {
    if ($digest->mid == $orphaned_message_id) {
      $this
        ->fail('When a message is deleted its corresponding message digest is cleaned up.');
    }
  }

  // Delete one of the users and verify that the corresponding message digest
  // is cleaned up.
  $orphaned_user_id = $users[1]
    ->id();
  $users[1]
    ->delete();
  $this
    ->assertRowCount(1);
  foreach ($this
    ->getAllMessageDigests() as $digest) {
    if ($digest->receiver == $orphaned_user_id) {
      $this
        ->fail('When a user is deleted its corresponding message digest is cleaned up.');
    }
  }
}