You are here

public function SimplenewsSourceTest::testSendCaching in Simplenews 3.x

Same name and namespace in other branches
  1. 8.2 tests/src/Functional/SimplenewsSourceTest.php \Drupal\Tests\simplenews\Functional\SimplenewsSourceTest::testSendCaching()

Test sending a newsletter to 100 recipients with caching enabled.

File

tests/src/Functional/SimplenewsSourceTest.php, line 130

Class

SimplenewsSourceTest
Test cases for creating and sending newsletters.

Namespace

Drupal\Tests\simplenews\Functional

Code

public function testSendCaching() {
  $this
    ->setUpSubscribers(100);
  $edit = [
    'title[0][value]' => $this
      ->randomString(10),
    'body[0][value]' => "Mail token: <strong>[simplenews-subscriber:mail]</strong>",
    'simplenews_issue[target_id]' => 'default',
  ];
  $this
    ->drupalGet('node/add/simplenews_issue');
  $this
    ->submitForm($edit, 'Save');
  $this
    ->assertEqual(1, preg_match('|node/(\\d+)$|', $this
    ->getUrl(), $matches), 'Node created');
  $node = Node::load($matches[1]);

  // Add node to spool.
  \Drupal::service('simplenews.spool_storage')
    ->addIssue($node);

  // Unsubscribe one of the recipients to make sure that they don't receive
  // the mail.
  \Drupal::service('simplenews.subscription_manager')
    ->unsubscribe(array_shift($this->subscribers), $this
    ->getRandomNewsletter(), FALSE, 'test');
  $before = microtime(TRUE);
  \Drupal::service('simplenews.mailer')
    ->sendSpool();
  $after = microtime(TRUE);

  // Make sure that 99 mails have been sent.
  $this
    ->assertEqual(99, count($this
    ->getMails()));

  // Test that tokens are correctly replaced.
  foreach (array_slice($this
    ->getMails(), 0, 3) as $mail) {

    // Make sure that the same mail was used in the body token as it has been
    // sent to. Also verify that the mail is plaintext.
    $this
      ->assertStringContainsString('*' . $mail['to'] . '*', $mail['body']);
    $this
      ->assertStringNotContainsString('<strong>', $mail['body']);

    // Make sure the body is only attached once.
    $this
      ->assertEqual(1, preg_match_all('/Mail token/', $mail['body'], $matches));
    $this
      ->assertStringContainsString((string) t('Unsubscribe from this newsletter'), $mail['body']);

    // Make sure the mail has the correct unsubscribe hash.
    $hash = simplenews_generate_hash($mail['to'], 'remove');
    $this
      ->assertStringContainsString($hash, $mail['body'], 'Correct hash is used');
    $this
      ->assertStringContainsString($hash, $mail['headers']['List-Unsubscribe'], 'Correct hash is used in header');
  }

  // Report time. @todo: Find a way to actually do some assertions here.
  $this
    ->pass(t('Mails have been sent in @sec seconds with build caching enabled.', [
    '@sec' => round($after - $before, 3),
  ]));
}