You are here

function SimplenewsSendTest::testProgrammaticNewsletter in Simplenews 8

Creates and sends a node using the API.

File

src/Tests/SimplenewsSendTest.php, line 44
Simplenews send test functions.

Class

SimplenewsSendTest
Test cases for creating and sending newsletters.

Namespace

Drupal\simplenews\Tests

Code

function testProgrammaticNewsletter() {

  // Create a very basic node.
  $node = Node::create(array(
    'type' => 'simplenews_issue',
    'title' => $this
      ->randomString(10),
    'uid' => 0,
    'status' => 1,
  ));
  $node->simplenews_issue->target_id = $this
    ->getRandomNewsletter();
  $node->simplenews_issue->handler = 'simplenews_all';
  $node
    ->save();

  // Send the node.
  \Drupal::service('simplenews.spool_storage')
    ->addFromEntity($node);
  $node
    ->save();

  // Send mails.
  \Drupal::service('simplenews.mailer')
    ->sendSpool();
  \Drupal::service('simplenews.spool_storage')
    ->clear();

  // Update sent status for newsletter admin panel.
  \Drupal::service('simplenews.mailer')
    ->updateSendStatus();

  // Verify mails.
  $mails = $this
    ->drupalGetMails();
  $this
    ->assertEqual(5, count($mails), t('All mails were sent.'));
  foreach ($mails as $mail) {
    $this
      ->assertEqual($mail['subject'], '[Default newsletter] ' . $node
      ->getTitle(), t('Mail has correct subject'));
    $this
      ->assertTrue(isset($this->subscribers[$mail['to']]), t('Found valid recipient'));
    unset($this->subscribers[$mail['to']]);
  }
  $this
    ->assertEqual(0, count($this->subscribers), t('all subscribers have been received a mail'));

  // Create another node.
  $node = Node::create(array(
    'type' => 'simplenews_issue',
    'title' => $this
      ->randomString(10),
    'uid' => 0,
    'status' => 1,
  ));
  $node->simplenews_issue->target_id = $this
    ->getRandomNewsletter();
  $node->simplenews_issue->handler = 'simplenews_all';
  $node
    ->save();

  // Send the node.
  \Drupal::service('simplenews.spool_storage')
    ->addFromEntity($node);
  $node
    ->save();

  // Make sure that they have been added.
  $this
    ->assertEqual(\Drupal::service('simplenews.spool_storage')
    ->countMails(), 5);

  // Mark them as pending, fake a currently running send process.
  $this
    ->assertEqual(count(\Drupal::service('simplenews.spool_storage')
    ->getMails(2)), 2);

  // Those two should be excluded from the count now.
  $this
    ->assertEqual(\Drupal::service('simplenews.spool_storage')
    ->countMails(), 3);

  // Get two additional spool entries.
  $this
    ->assertEqual(count(\Drupal::service('simplenews.spool_storage')
    ->getMails(2)), 2);

  // Now only one should be returned by the count.
  $this
    ->assertEqual(\Drupal::service('simplenews.spool_storage')
    ->countMails(), 1);
}