You are here

simplenews.test in Simplenews 6.2

Same filename and directory in other branches
  1. 7.2 tests/simplenews.test
  2. 7 tests/simplenews.test

Simplenews test functions.

@todo Redo all database functions: http://drupal.org/node/224333#dbtng @todo Where possible build re-usable functions wrapped around database calls.

File

tests/simplenews.test
View source
<?php

/**
 * @file
 * Simplenews test functions.
 *
 * @ingroup simplenews
 * @todo Redo all database functions: http://drupal.org/node/224333#dbtng
 * @todo Where possible build re-usable functions wrapped around database calls.
 */
class SimplenewsTestCase extends DrupalWebTestCase {
  public function setUp() {
    parent::setUp('taxonomy', 'simplenews', 'token');

    //$this->simplenews_admin_user = $this->drupalCreateUser(array('administer newsletters', 'administer simplenews settings', 'administer simplenews subscriptions'));

    //$this->sender_user = $this->drupalCreateUser(array('create simplenews content', 'edit own simplenews content', 'send newsletter'));
    variable_set('site_mail', 'user@example.com');
  }

  /**
   * Set anonymous user permission to subscribe.
   *
   * @param boolean $enabled
   *   Allow anonymous commenting.
   */
  function setAnonymousUserSubscription($enabled) {
    if ($enabled) {
      db_query("\n        UPDATE {permission}\n        SET perm = '%s'\n        WHERE rid = %d", 'access content, subscribe to newsletters', DRUPAL_ANONYMOUS_RID);
    }
    else {
      db_query("\n        UPDATE {permission}\n        SET perm = '%s'\n        WHERE rid = %d", 'access content', DRUPAL_ANONYMOUS_RID);
    }
  }

  /**
   * Set anonymous user permission to subscribe.
   *
   * @param boolean $enabled
   *   Allow anonymous commenting.
   */
  function setAuthenticatedUserSubscription($enabled) {
    if ($enabled) {
      db_query("\n        UPDATE {permission}\n        SET perm = '%s'\n        WHERE rid = %d", 'access content, subscribe to newsletters', DRUPAL_AUTHENTICATED_RID);
    }
    else {
      db_query("\n        UPDATE {permission}\n        SET perm = '%s'\n        WHERE rid = %d", 'access content', DRUPAL_AUTHENTICATED_RID);
    }
  }

  /**
   * Generates a random email address.
   *
   * @todo: Make this function redundant by modification of Simplenews.
   * Email addresses are case sensitive, simplenews system should handle with
   * this correctly.
   */
  function randomEmail($number = 4, $prefix = 'simpletest_', $domain = 'example.com') {
    return strtolower($this
      ->randomName($number, $prefix) . '@' . $domain);
  }

  /**
   * Select randomly one of the available newsletters.
   *
   * @return newsletter tid.
   */
  function getRandomNewsletter() {
    if ($taxonomies = taxonomy_get_tree(variable_get('simplenews_vid', ''))) {
      $tids = array();
      foreach ($taxonomies as $newsletter) {
        $tids[] = $newsletter->tid;
      }
      $key = array_rand($tids);
      return $tids[$key];
    }
    return 0;
  }

  /**
   * Enable newsletter subscription block.
   *
   * @param integer $tid
   *   newsletter term id
   * @param array $settings
   *  ['message'] = Block message
   *  ['form'] = '1': Subscription form; '0': Link to form
   *  ['link to previous'] = {1, 0} Display link to previous issues
   *  ['previous issues'] = {1, 0} Display previous issues
   *  ['issue count'] = {1, 2, 3, ...}Number of issues to display
   *  ['rss feed'] = {1, 0} Display RSS-feed icon
   */
  function setupSubscriptionBlock($tid, $settings = array()) {
    $bid = db_result(db_query("\n      SELECT bid\n      FROM {blocks}\n      WHERE module = 'simplenews'\n        AND delta = '%s'", array(
      $tid,
    )));

    // Check to see if the box was created by checking that it's in the database..
    $this
      ->assertNotNull($bid, t('Block found in database'));

    // Enable the block in the left side bar.

    //@todo: replace this by BlockTestCase::moveBlockToRegion in D7
    $block['module'] = 'simplenews';
    $block['delta'] = $tid;
    $edit['' . $block['module'] . '_' . $block['delta'] . '[region]'] = 'left';
    $this
      ->drupalPost('admin/build/block', $edit, t('Save blocks'));

    // Set block parameters
    $edit = array();
    if (isset($settings['message'])) {
      $edit['simplenews_block_m_' . $tid] = $settings['message'];
    }
    if (isset($settings['form'])) {
      $edit['simplenews_block_f_' . $tid] = $settings['form'];
    }
    if (isset($settings['link to previous'])) {
      $edit['simplenews_block_l_' . $tid] = $settings['link to previous'];
    }
    if (isset($settings['previous issues'])) {
      $edit['simplenews_block_i_status_' . $tid] = $settings['previous issues'];
    }
    if (isset($settings['issue count'])) {
      $edit['simplenews_block_i_' . $tid] = $settings['issue count'];

      // @todo check the count
    }
    if (isset($settings['rss feed'])) {
      $edit['simplenews_block_r_' . $tid] = $settings['rss feed'];
    }

    // Simplify confirmation form submission by hiding the subscribe block on
    // that page. Same for the newsletter/subscriptions page.
    $edit['pages'] = "newsletter/confirm/add/*\nnewsletter/subscriptions";
    $this
      ->drupalPost('admin/build/block/configure/simplenews/' . $tid . '', $edit, t('Save block'));
    $this
      ->assertText('The block configuration has been saved.', 'The newsletter block configuration has been saved.');
  }

}
class SimplenewsSubscribeTestCase extends SimplenewsTestCase {

  /**
   * Implementation of getInfo().
   */
  function getInfo() {
    return array(
      'name' => t('Subscribe and unsubscribe users'),
      'description' => t('(un)subscription of anonymous and authenticated users. Subscription via block, subscription page and account page'),
      'group' => t('Simplenews'),
    );
  }

  /**
   * testSubscribeAnonymous
   *
   * Steps performed:
   *   0. Preparation
   *   1. Subscribe anonymous via block
   *   2. Subscribe anonymous via subscription page
   *   3. Subscribe anonymous via multi block
   */
  function testSubscribeAnonymous() {

    // Include simplenews.subscription.inc for simplenews_mask_mail().
    module_load_include('inc', 'simplenews', 'includes/simplenews.subscription');

    // 0. Preparation
    // Login admin
    // Set permission for anonymous to subscribe
    // Enable newsletter block
    // Logout admin
    $admin_user = $this
      ->drupalCreateUser(array(
      'administer blocks',
      'administer content types',
      'administer nodes',
      'access administration pages',
      'administer permissions',
    ));
    $this
      ->drupalLogin($admin_user);
    $this
      ->setAnonymousUserSubscription(TRUE);

    // Setup subscription block with subscription form.
    $block_settings = array(
      'message' => $this
        ->randomName(4),
      'form' => '1',
      'link to previous' => FALSE,
      'previous issues' => FALSE,
      'rss feed' => TRUE,
    );
    $tid = $this
      ->getRandomNewsletter();
    $this
      ->setupSubscriptionBlock($tid, $block_settings);
    $this
      ->drupalLogout();

    //file_put_contents('output.html', $this->drupalGetContent());

    // 1. Subscribe anonymous via block
    // Subscribe + submit
    // Assert confirmation message
    // Assert outgoing email
    //
    // Confirm using mail link
    // Confirm using mail link
    // Assert confirmation message
    $mail = $this
      ->randomEmail(8, 'testmail');
    $edit = array(
      'mail' => $mail,
    );
    $this
      ->drupalPost(NULL, $edit, t('Subscribe'));
    $this
      ->assertText(t('You will receive a confirmation email shortly containing further instructions on how to complete your subscription.'), t('Subscription confirmation e-mail sent.'));
    $mails = $this
      ->drupalGetMails();
    $body = $mails[0]['body'];
    $pattern = '@newsletter/confirm/add/[0-9,a-f]+t[0-9]+@';
    preg_match($pattern, $body, $match);
    $found = preg_match($pattern, $body, $match);
    $confirm_url = $match[0];
    $this
      ->assertTrue($found, t('Confirmation URL found: @url', array(
      '@url' => $confirm_url,
    )));
    $this
      ->drupalGet($confirm_url);
    $newsletter = taxonomy_get_term($tid);
    $this
      ->assertRaw(t('Are you sure you want to add %user to the %newsletter mailing list?', array(
      '%user' => simplenews_mask_mail($mail),
      '%newsletter' => $newsletter->name,
    )), t('Subscription confirmation found.'));
    $this
      ->drupalPost(NULL, array(), t('Subscribe'));
    $this
      ->assertRaw(t('%user was added to the %newsletter mailing list.', array(
      '%user' => $mail,
      '%newsletter' => $newsletter->name,
    )), t('Anonymous subscriber added to newsletter'));

    // 2. Subscribe anonymous via subscription page
    // Subscribe + submit
    // Assert confirmation message
    // Assert outgoing email
    //
    // Confirm using mail link
    // Confirm using mail link
    // Assert confirmation message
    $mail = $this
      ->randomEmail(8, 'testmail');
    $edit = array(
      "newsletters[{$tid}]" => '1',
      'mail' => $mail,
    );
    $this
      ->drupalPost('newsletter/subscriptions', $edit, t('Subscribe'));
    $this
      ->assertText(t('You will receive a confirmation email shortly containing further instructions on how to complete your subscription.'), t('Subscription confirmation e-mail sent.'));
    $mails = $this
      ->drupalGetMails();
    $body = $mails[1]['body'];
    $pattern = '@newsletter/confirm/add/[0-9,a-f]+t[0-9]+@';
    preg_match($pattern, $body, $match);
    $found = preg_match($pattern, $body, $match);
    $confirm_url = $match[0];
    $this
      ->assertTrue($found, t('Confirmation URL found: @url', array(
      '@url' => $confirm_url,
    )));
    $this
      ->drupalGet($confirm_url);
    $newsletter = taxonomy_get_term($tid);
    $this
      ->assertRaw(t('Are you sure you want to add %user to the %newsletter mailing list?', array(
      '%user' => simplenews_mask_mail($mail),
      '%newsletter' => $newsletter->name,
    )), t('Subscription confirmation found.'));
    $this
      ->drupalPost($confirm_url, NULL, t('Subscribe'));
    $this
      ->assertRaw(t('%user was added to the %newsletter mailing list.', array(
      '%user' => $mail,
      '%newsletter' => $newsletter->name,
    )), t('Anonymous subscriber added to newsletter'));

    // 3. Subscribe anonymous via multi block
    $this
      ->drupalLogin($admin_user);

    // Enable the multi-sign up block.
    $this
      ->setupSubscriptionBlock(0);

    // Disable the category block.
    $edit = array(
      'simplenews_' . $tid . '[region]' => -1,
    );
    $this
      ->drupalPost(NULL, $edit, t('Save blocks'));
    $this
      ->drupalLogout();

    // Try to submit multi-signup form without selecting a category.
    $mail = $this
      ->randomEmail(8, 'testmail');
    $edit = array(
      'mail' => $mail,
    );
    $this
      ->drupalPost(NULL, $edit, t('Subscribe'));
    $this
      ->assertText(t('You must select at least one newsletter.'));

    // Now fill out the form and try again. The e-mail should still be listed.
    $edit = array(
      'newsletters[' . $tid . ']' => TRUE,
    );
    $this
      ->drupalPost(NULL, $edit, t('Subscribe'));
    $this
      ->assertText(t('You will receive a confirmation email shortly containing further instructions on how to complete your subscription.'));
    $mails = $this
      ->drupalGetMails();
    $body = $mails[2]['body'];
    $pattern = '@newsletter/confirm/add/[0-9,a-f]+t[0-9]+@';
    preg_match($pattern, $body, $match);
    $found = preg_match($pattern, $body, $match);
    $confirm_url = $match[0];
    $this
      ->assertTrue($found, t('Confirmation URL found: @url', array(
      '@url' => $confirm_url,
    )));
    $this
      ->drupalGet($confirm_url);
    $newsletter = taxonomy_get_term($tid);
    $this
      ->assertRaw(t('Are you sure you want to add %user to the %newsletter mailing list?', array(
      '%user' => simplenews_mask_mail($mail),
      '%newsletter' => $newsletter->name,
    )), t('Subscription confirmation found.'));
    $this
      ->drupalPost($confirm_url, NULL, t('Subscribe'));
    $this
      ->assertRaw(t('%user was added to the %newsletter mailing list.', array(
      '%user' => $mail,
      '%newsletter' => $newsletter->name,
    )), t('Anonymous subscriber added to newsletter'));

    // Now the same with the newsletter/subscriptions page.
    $mail = $this
      ->randomEmail(8, 'testmail');
    $edit = array(
      'mail' => $mail,
    );
    $this
      ->drupalPost('newsletter/subscriptions', $edit, t('Subscribe'));
    $this
      ->assertText(t('You must select at least one newsletter.'));

    // Now fill out the form and try again.
    $edit = array(
      'newsletters[' . $tid . ']' => TRUE,
    );
    $this
      ->drupalPost(NULL, $edit, t('Subscribe'));
    $this
      ->assertText(t('You will receive a confirmation email shortly containing further instructions on how to complete your subscription.'));
    $mails = $this
      ->drupalGetMails();
    $body = $mails[3]['body'];
    $pattern = '@newsletter/confirm/add/[0-9,a-f]+t[0-9]+@';
    preg_match($pattern, $body, $match);
    $found = preg_match($pattern, $body, $match);
    $confirm_url = $match[0];
    $this
      ->assertTrue($found, t('Confirmation URL found: @url', array(
      '@url' => $confirm_url,
    )));
    $this
      ->drupalGet($confirm_url);
    $newsletter = taxonomy_get_term($tid);
    $this
      ->assertRaw(t('Are you sure you want to add %user to the %newsletter mailing list?', array(
      '%user' => simplenews_mask_mail($mail),
      '%newsletter' => $newsletter->name,
    )), t('Subscription confirmation found.'));
    $this
      ->drupalPost($confirm_url, NULL, t('Subscribe'));
    $this
      ->assertRaw(t('%user was added to the %newsletter mailing list.', array(
      '%user' => $mail,
      '%newsletter' => $newsletter->name,
    )), t('Anonymous subscriber added to newsletter'));
  }

  /**
   * Test anonymous subscription with single opt in.
   *
   * Steps performed:
   *   0. Preparation
   *   1. Subscribe anonymous via block
   */
  function testSubscribeAnonymousSingle() {

    // 0. Preparation
    // Login admin
    // Create single opt in newsletter.
    // Set permission for anonymous to subscribe
    // Enable newsletter block
    // Logout admin
    $admin_user = $this
      ->drupalCreateUser(array(
      'administer blocks',
      'administer content types',
      'administer nodes',
      'access administration pages',
      'administer permissions',
      'administer newsletters',
    ));
    $this
      ->drupalLogin($admin_user);
    $this
      ->setAnonymousUserSubscription(TRUE);

    // Setup subscription block with subscription form.
    $block_settings = array(
      'message' => $this
        ->randomName(4),
      'form' => '1',
      'link to previous' => FALSE,
      'previous issues' => FALSE,
      'rss feed' => TRUE,
    );
    $this
      ->drupalGet('admin/content/simplenews/types');
    $this
      ->clickLink(t('Add newsletter'));
    $edit = array(
      'name' => $this
        ->randomName(),
      'description' => $this
        ->randomString(20),
      'simplenews_opt_inout_' => 'single',
    );
    $this
      ->drupalPost(NULL, $edit, t('Save'));

    // @todo: Don't hardcode this.
    $tid = 2;
    $this
      ->setupSubscriptionBlock($tid, $block_settings);
    $this
      ->drupalLogout();

    // 1. Subscribe anonymous via block
    // Subscribe + submit
    // Assert confirmation message
    // Verify subscription state.
    $mail = $this
      ->randomEmail(8, 'testmail');
    $edit = array(
      'mail' => $mail,
    );
    $this
      ->drupalPost(NULL, $edit, t('Subscribe'));
    $this
      ->assertText(t('You have been subscribed.'), t('Anonymous subscriber added to newsletter'));
    $account = (object) array(
      'mail' => $mail,
    );
    $subscriber = simplenews_get_subscription($account);
  }

  /**
   * testSubscribeAuthenticated
   *
   * Steps performed:
   *   0. Preparation
   *   1. Subscribe authenticated via block
   *   2. Unsubscribe authenticated via subscription page
   *   3. Subscribe authenticated via subscription page
   *   4. Unsubscribe authenticated via account page
   *   5. Subscribe authenticated via account page
   *   6. Subscribe authenticated via multi block
   */
  function testSubscribeAuthenticated() {

    // 0. Preparation
    // Login admin
    // Set permission for anonymous to subscribe
    // Enable newsletter block
    // Logout admin
    // Login Subscriber
    $admin_user = $this
      ->drupalCreateUser(array(
      'administer blocks',
      'administer content types',
      'administer nodes',
      'access administration pages',
      'administer permissions',
    ));
    $this
      ->drupalLogin($admin_user);
    $this
      ->setAnonymousUserSubscription(TRUE);

    // Setup subscription block with subscription form.
    $block_settings = array(
      'message' => $this
        ->randomName(4),
      'form' => '1',
      'link to previous' => FALSE,
      'previous issues' => FALSE,
      'rss feed' => TRUE,
    );
    $tid = $this
      ->getRandomNewsletter();
    $this
      ->setupSubscriptionBlock($tid, $block_settings);
    $this
      ->drupalLogout();
    $subscriber_user = $this
      ->drupalCreateUser(array(
      'subscribe to newsletters',
    ));
    $this
      ->drupalLogin($subscriber_user);

    // 1. Subscribe authenticated via block
    // Subscribe + submit
    // Assert confirmation message
    $this
      ->drupalPost('', NULL, t('Subscribe'));
    $this
      ->assertText(t('You have been subscribed.'), t('Authenticated user subscribed using the subscription block.'));

    // 2. Unsubscribe authenticated via subscription page
    // Unsubscribe + submit
    // Assert confirmation message
    $edit = array(
      "newsletters[{$tid}]" => 0,
    );
    $this
      ->drupalPost('newsletter/subscriptions', $edit, t('Update'));
    $this
      ->assertRaw(t('The newsletter subscriptions for %mail have been updated.', array(
      '%mail' => $subscriber_user->mail,
    )), t('Authenticated user unsubscribed on the subscriptions page.'));

    // 3. Subscribe authenticated via subscription page
    // Subscribe + submit
    // Assert confirmation message
    $edit = array(
      "newsletters[{$tid}]" => '1',
    );
    $this
      ->drupalPost('newsletter/subscriptions', $edit, t('Update'));
    $this
      ->assertRaw(t('The newsletter subscriptions for %mail have been updated.', array(
      '%mail' => $subscriber_user->mail,
    )), t('Authenticated user subscribed on the subscriptions page.'));

    // 4. Unsubscribe authenticated via account page
    // Unsubscribe + submit
    // Assert confirmation message
    $edit = array(
      "newsletters[{$tid}]" => 0,
    );
    $url = 'user/' . $subscriber_user->uid . '/edit/newsletter';
    $this
      ->drupalPost($url, $edit, t('Save'));
    $this
      ->assertRaw(t('Your newsletter subscriptions have been updated.', array(
      '%mail' => $subscriber_user->mail,
    )), t('Authenticated user unsubscribed on the account page.'));

    // 5. Subscribe authenticated via account page
    // Subscribe + submit
    // Assert confirmation message
    $edit = array(
      "newsletters[{$tid}]" => '1',
    );
    $url = 'user/' . $subscriber_user->uid . '/edit/newsletter';
    $this
      ->drupalPost($url, $edit, t('Save'));
    $this
      ->assertRaw(t('Your newsletter subscriptions have been updated.', array(
      '%mail' => $subscriber_user->mail,
    )), t('Authenticated user unsubscribed on the account page.'));

    // Subscribe authenticated via multi block
    $this
      ->drupalLogin($admin_user);

    // Enable the multi-sign up block.
    $this
      ->setupSubscriptionBlock(0);

    // Disable the category block.
    $edit = array(
      'simplenews_' . $tid . '[region]' => -1,
    );
    $this
      ->drupalPost(NULL, $edit, t('Save blocks'));
    $this
      ->drupalLogout();

    // Try to submit multi-signup form without selecting a category.
    $subscriber_user2 = $this
      ->drupalCreateUser(array(
      'subscribe to newsletters',
    ));
    $this
      ->drupalLogin($subscriber_user2);
    $this
      ->assertNoField('mail');
    $this
      ->drupalPost(NULL, array(), t('Update'));
    $this
      ->assertText(t('The newsletter subscriptions for @mail have been updated.', array(
      '@mail' => $subscriber_user2->mail,
    )));

    // Nothing should have happened.
    $this
      ->assertNoFieldChecked('edit-newsletters-' . $tid);

    // Now fill out the form and try again.
    $edit = array(
      'newsletters[' . $tid . ']' => TRUE,
    );
    $this
      ->drupalPost(NULL, $edit, t('Update'));
    $this
      ->assertText(t('The newsletter subscriptions for @mail have been updated.', array(
      '@mail' => $subscriber_user2->mail,
    )));
    $this
      ->assertFieldChecked('edit-newsletters-' . $tid);

    // Unsubscribe.
    $edit = array(
      'newsletters[' . $tid . ']' => FALSE,
    );
    $this
      ->drupalPost(NULL, $edit, t('Update'));
    $this
      ->assertText(t('The newsletter subscriptions for @mail have been updated.', array(
      '@mail' => $subscriber_user2->mail,
    )));
    $this
      ->assertNoFieldChecked('edit-newsletters-' . $tid);

    // And now the same for the newsletter/subscriptions page.
    $subscriber_user3 = $this
      ->drupalCreateUser(array(
      'subscribe to newsletters',
    ));
    $this
      ->drupalLogin($subscriber_user3);
    $this
      ->assertNoField('mail');
    $this
      ->drupalPost('newsletter/subscriptions', array(), t('Update'));
    $this
      ->assertText(t('The newsletter subscriptions for @mail have been updated.', array(
      '@mail' => $subscriber_user3->mail,
    )));

    // Nothing should have happened.
    $this
      ->assertNoFieldChecked('edit-newsletters-' . $tid);

    // Now fill out the form and try again.
    $edit = array(
      'newsletters[' . $tid . ']' => TRUE,
    );
    $this
      ->drupalPost('newsletter/subscriptions', $edit, t('Update'));
    $this
      ->assertText(t('The newsletter subscriptions for @mail have been updated.', array(
      '@mail' => $subscriber_user3->mail,
    )));
    $this
      ->assertFieldChecked('edit-newsletters-' . $tid);

    // Unsubscribe.
    $edit = array(
      'newsletters[' . $tid . ']' => FALSE,
    );
    $this
      ->drupalPost('newsletter/subscriptions', $edit, t('Update'));
    $this
      ->assertText(t('The newsletter subscriptions for @mail have been updated.', array(
      '@mail' => $subscriber_user3->mail,
    )));
    $this
      ->assertNoFieldChecked('edit-newsletters-' . $tid);
  }

}

/**
 * @todo:
 * Newsletter node create, send draft, send final
 */
class SimpleNewsAdministrationTestCase extends SimplenewsTestCase {

  /**
   * Implementation of getInfo().
   */
  function getInfo() {
    return array(
      'name' => t('Simplenews administration'),
      'description' => t('Managing of newsletter categories and content types.'),
      'group' => t('Simplenews'),
    );
  }

  /**
   * Test various combinations of newsletter category settings.
   */
  function testCategorySettings() {

    // Allow registration of new accounts without approval.
    variable_set('user_register', 1);
    variable_set('user_email_verification', FALSE);

    // Allow authenticated users to subscribe.
    $this
      ->setAuthenticatedUserSubscription(TRUE);
    $admin_user = $this
      ->drupalCreateUser(array(
      'administer blocks',
      'administer content types',
      'administer nodes',
      'access administration pages',
      'administer permissions',
      'administer newsletters',
      'administer simplenews subscriptions',
    ));
    $this
      ->drupalLogin($admin_user);
    $this
      ->drupalGet('admin/content/simplenews/types');

    // Create a category for all possible setting combinations.
    $new_account = array(
      'none',
      'off',
      'on',
      'silent',
    );
    $opt_inout = array(
      'hidden',
      'single',
      'double',
    );
    foreach ($new_account as $new_account_setting) {
      foreach ($opt_inout as $opt_inout_setting) {
        $this
          ->clickLink(t('Add newsletter'));
        $edit = array(
          'name' => implode('-', array(
            $new_account_setting,
            $opt_inout_setting,
          )),
          'description' => $this
            ->randomString(20),
          'simplenews_new_account_' => $new_account_setting,
          'simplenews_opt_inout_' => $opt_inout_setting,
          'simplenews_from_name_' => $this
            ->randomName(),
          'simplenews_from_address_' => $this
            ->randomEmail(),
        );
        $this
          ->drupalPost(NULL, $edit, t('Save'));
      }
    }
    $categories = array();
    $result = db_query('SELECT * FROM {term_data} WHERE vid = %d', variable_get('simplenews_vid', ''));
    while ($category = db_fetch_object($result)) {
      $categories[$category->tid] = $category;
    }

    // Check block settings.
    $this
      ->drupalGet('admin/build/block');
    foreach ($categories as $category) {
      if (strpos($category->name, '-') === FALSE) {
        continue;
      }
      $opt_inout = variable_get('simplenews_opt_inout_' . $category->tid, 'double');
      if ($opt_inout != 'hidden') {
        $this
          ->assertField('simplenews_' . $category->tid . '[region]', t('Block is displayed for category'));
      }
      else {
        $this
          ->assertNoField('simplenews_' . $category->tid . '[region]', t('Block is not displayed for category'));
      }
    }

    // Check registration form.
    $this
      ->drupalLogout();
    $this
      ->drupalGet('user/register');
    foreach ($categories as $category) {
      if (strpos($category->name, '-') === FALSE) {
        continue;
      }

      // Explicitly subscribe to the off-double newsletter.
      if ($category->name == 'off-double') {
        $off_double_tid = $category->tid;
      }
      list($new_account_setting, $opt_inout_setting) = explode('-', $category->name);
      $new_account = variable_get('simplenews_new_account_' . $category->tid, 'on');
      $opt_inout = variable_get('simplenews_opt_inout_' . $category->tid, 'double');
      if ($new_account == 'on' && $opt_inout != 'hidden') {
        $this
          ->assertFieldChecked('edit-newsletters-' . $category->tid);
      }
      else {
        if ($new_account == 'off' && $opt_inout != 'hidden') {
          $this
            ->assertNoFieldChecked('edit-newsletters-' . $category->tid);
        }
        else {
          $this
            ->assertNoField('newsletters[' . $category->tid . ']', t('Hidden or silent newsletter category is not shown.'));
        }
      }
    }

    // Register a new user through the form.
    $edit = array(
      'name' => $this
        ->randomName(),
      'mail' => $this
        ->randomEmail(),
      'pass[pass1]' => $pass = $this
        ->randomName(),
      'pass[pass2]' => $pass,
      'newsletters[' . $off_double_tid . ']' => $off_double_tid,
    );
    $this
      ->drupalPost(NULL, $edit, t('Create new account'));

    // Verify confirmation messages.
    $this
      ->assertText(t('Registration successful. You are now logged in.'));
    foreach ($categories as $category) {
      if (strpos($category->name, '-') === FALSE) {
        continue;
      }

      // Check confirmation message for all on and non-hidden newsletters and
      // the one that was explicitly selected.
      $new_account = variable_get('simplenews_new_account_' . $category->tid, 'on');
      $opt_inout = variable_get('simplenews_opt_inout_' . $category->tid, 'double');
      if ($new_account == 'on' && $opt_inout != 'hidden' || $category->name == 'off-double') {
        $this
          ->assertText(t('You have been subscribed to @name.', array(
          '@name' => $category->name,
        )));
      }
      else {

        // All other newsletters must not show a message, e.g. those which were
        // subscribed silently.
        $this
          ->assertNoText(t('You have been subscribed to @name.', array(
          '@name' => $category->name,
        )));
      }
    }

    // Log out again.
    $this
      ->drupalLogout();

    // Get the user id and do a login through the drupalLogin() function.
    $uid = db_result(db_query("SELECT uid FROM {users} WHERE name = '%s'", $edit['name']));
    $user = user_load($uid);

    // Set the password so that the login works.
    $user->pass_raw = $edit['pass[pass1]'];

    // Verify newsletter subscription pages.
    $this
      ->drupalLogin($user);
    foreach (array(
      'newsletter/subscriptions',
      'user/' . $user->uid . '/edit/newsletter',
    ) as $path) {
      $this
        ->drupalGet($path);
      foreach ($categories as $category) {
        if (strpos($category->name, '-') === FALSE) {
          continue;
        }
        list($new_account_setting, $opt_inout_setting) = explode('-', $category->name);
        $new_account = variable_get('simplenews_new_account_' . $category->tid, 'on');
        $opt_inout = variable_get('simplenews_opt_inout_' . $category->tid, 'double');
        if ($opt_inout == 'hidden') {
          $this
            ->assertNoField('newsletters[' . $category->tid . ']', t('Hidden newsletter category is not shown.'));
        }
        else {
          if ($new_account == 'on' || $category->name == 'off-double' || $new_account == 'silent') {

            // All on, silent and the explicitly selected category should be checked.
            $this
              ->assertFieldChecked('edit-newsletters-' . $category->tid);
          }
          else {
            $this
              ->assertNoFieldChecked('edit-newsletters-' . $category->tid);
          }
        }
      }
    }

    // Unsubscribe from a newsletter category.
    $edit = array(
      'newsletters[' . $off_double_tid . ']' => FALSE,
    );
    $this
      ->drupalPost(NULL, $edit, t('Save'));
    $this
      ->assertNoFieldChecked('edit-newsletters-' . $off_double_tid);

    // Get a category which has the block enabled.
    foreach ($categories as $category) {

      // The default category is missing the from mail address. Use another one.
      if ($category->tid != 1) {
        $edit_category = $category;
        break;
      }
    }
  }

  /**
   * Test newsletter subscription management.
   *
   * Steps performed:
   *
   */
  function testSubscriptionManagement() {
    $admin_user = $this
      ->drupalCreateUser(array(
      'administer newsletters',
      'administer simplenews settings',
      'administer simplenews subscriptions',
      'administer taxonomy',
    ));
    $this
      ->drupalLogin($admin_user);

    // Create a second category.
    $edit = array(
      'name' => $name = $this
        ->randomName(),
    );
    $this
      ->drupalPost('admin/content/simplenews/types/add', $edit, t('Save'));

    // Add a number of users to each category separately and then add another
    // bunch to both.
    $subscribers = array();

    // Can't use the api function due to taxonomy static caches, assume id's.

    //$categories =simplenews_get_newsletters(variable_get('simplenews_vid', ''), TRUE, TRUE);
    $categories = array(
      1,
      2,
    );
    $groups = array();
    foreach ($categories as $tid) {
      $groups[$tid] = array(
        $tid,
      );
    }
    $groups['all'] = array_keys($groups);
    $subscribers_flat = array();
    foreach ($groups as $key => $group) {
      for ($i = 0; $i < 5; $i++) {
        $mail = $this
          ->randomEmail();
        $subscribers[$key][$mail] = $mail;
        $subscribers_flat[$mail] = $mail;
      }
    }

    // Create a user and assign him one of the mail addresses of the all group.
    $user = $this
      ->drupalCreateUser(array(
      'subscribe to newsletters',
    ));

    // Make sure that user_save() does not update the user object, as it will
    // override the pass_raw property which we'll need to log this user in
    // later on.
    $user_mail = current($subscribers['all']);
    user_save(clone $user, array(
      'mail' => $user_mail,
    ));
    $delimiters = array(
      ',',
      ' ',
      "\n",
    );
    $this
      ->drupalGet('admin/content/simplenews/users');
    $i = 0;
    foreach ($groups as $key => $group) {
      $this
        ->clickLink(t('Mass subscribe'));
      $edit = array(
        // Implode with a different, supported delimiter for each group.
        'emails' => implode($delimiters[$i++], $subscribers[$key]),
      );
      foreach ($group as $tid) {
        $edit['newsletters[' . $tid . ']'] = TRUE;
      }
      $this
        ->drupalPost(NULL, $edit, t('Subscribe'));
    }

    // 6.x-2.x does not redirect back to the list.
    $this
      ->clickLink('List');

    // The user to which the mail was assigned should be listed too.
    $this
      ->assertText($user->name);

    // Verify that all addresses are displayed in the table.
    $mail_addresses = $this
      ->xpath('//tr/td[2]');
    $this
      ->assertEqual(15, count($mail_addresses));
    foreach ($mail_addresses as $mail_address) {
      $mail_address = (string) $mail_address;
      $this
        ->assertTrue(isset($subscribers_flat[$mail_address]));
      unset($subscribers_flat[$mail_address]);
    }

    // All entries of the array should be removed by now.
    $this
      ->assertTrue(empty($subscribers_flat));

    // Limit list to subscribers of the first category only.
    reset($groups);
    $first = key($groups);

    // Build a flat list of the subscribers of this list.
    $subscribers_flat = array_merge($subscribers[$first], $subscribers['all']);
    $edit = array(
      'newsletter' => 'tid-' . $first,
    );
    $this
      ->drupalPost(NULL, $edit, t('Filter'));

    // Verify that all addresses are displayed in the table.
    $mail_addresses = $this
      ->xpath('//tr/td[2]');
    $this
      ->assertEqual(10, count($mail_addresses));
    foreach ($mail_addresses as $mail_address) {
      $mail_address = (string) $mail_address;
      $this
        ->assertTrue(isset($subscribers_flat[$mail_address]));
      unset($subscribers_flat[$mail_address]);
    }

    // All entries of the array should be removed by now.
    $this
      ->assertTrue(empty($subscribers_flat));

    // Filter a single mail address, the one assigned to a user.
    $edit = array(
      'email' => substr(current($subscribers['all']), 0, 4),
    );
    $this
      ->drupalPost(NULL, $edit, t('Filter'));
    $rows = $this
      ->xpath('//tbody/tr');
    $this
      ->assertEqual(1, count($rows));
    $this
      ->assertEqual(current($subscribers['all']), (string) $rows[0]->td[1]);
    $this
      ->assertEqual($user->name, (string) $rows[0]->td[2]->a);

    // Reset the filter.
    $this
      ->drupalPost(NULL, array(), t('Reset'));

    // Test mass-unsubscribe, unsubscribe one from the first group and one from
    // the all group, but only from the first newsletter category.
    $first_mail = array_rand($subscribers[$first]);
    $all_mail = array_rand($subscribers['all']);
    unset($subscribers[$first][$first_mail]);
    $edit = array(
      'emails' => $first_mail . ', ' . $all_mail,
      "newsletters[{$first}]" => TRUE,
    );
    $this
      ->clickLink(t('Mass unsubscribe'));
    $this
      ->drupalPost(NULL, $edit, t('Unsubscribe'));

    // The all mail is still displayed because it's still subscribed to the
    // second category. Reload the page to get rid of the confirmation
    // message.
    $this
      ->drupalGet('admin/content/simplenews/users');

    // @todo disabled.

    //$this->assertNoText($first_mail);
    $this
      ->assertText($all_mail);

    // Limit to first category, the all mail shouldn't be shown anymore.
    $edit = array(
      'newsletter' => 'tid-' . $first,
    );
    $this
      ->drupalPost(NULL, $edit, t('Filter'));
    $this
      ->assertNoText($first_mail);
    $this
      ->assertNoText($all_mail);

    // Check exporting.
    $this
      ->clickLink(t('Export'));
    $edit = array(
      'states[active]' => TRUE,
      'newsletters[' . $first . ']' => TRUE,
    );
    $this
      ->drupalPost(NULL, $edit, t('Export'));
    $export_field = $this
      ->xpath($this
      ->constructFieldXpath('name', 'emails'));
    $exported_mails = (string) $export_field[0];
    foreach ($subscribers[$first] as $mail) {
      $this
        ->assertTrue(strpos($exported_mails, $mail) !== FALSE, t('Mail address exported correctly.'));
    }
    foreach ($subscribers['all'] as $mail) {
      if ($mail != $all_mail) {
        $this
          ->assertTrue(strpos($exported_mails, $mail) !== FALSE, t('Mail address exported correctly.'));
      }
      else {
        $this
          ->assertFALSE(strpos($exported_mails, $mail) !== FALSE, t('Unsubscribed mail address not exported.'));
      }
    }

    // Delete newsletter category.
    $this
      ->drupalPost('admin/content/taxonomy/edit/term/' . $first, array(), t('Delete'));
    $this
      ->drupalPost(NULL, array(), t('Delete'));
    $this
      ->assertText(t('All subscriptions to newsletter Drupal newsletter have been deleted.'));

    // Verify that all related data has been deleted.
    $this
      ->assertFalse(db_result(db_query("SELECT * FROM {blocks} WHERE module = '%s' AND delta = %d", 'simplenews', $first)));

    // Verify that all subscriptions of that category have been removed.
    $this
      ->drupalGet('admin/content/simplenews/users');
    foreach ($subscribers[$first] as $mail) {
      $this
        ->assertNoText($mail);
    }

    // @todo Test Admin subscriber edit category
    // @todo Test Admin subscriber edit preferred language $subscription->language
    // @todo Test Admin subscriber edit Active / Inactive
    // Register a subscriber with an insecure e-mail address through the API
    // and make sure the address is correctly encoded.
    $xss_mail = "<script>alert('XSS');</script>";
    simplenews_subscribe_user($xss_mail, $this
      ->getRandomNewsletter(), FALSE);
    $this
      ->drupalGet('admin/content/simplenews/users');
    $this
      ->assertNoRaw($xss_mail);
    $this
      ->assertRaw(check_plain($xss_mail));
    $xss_subscriber = simplenews_get_subscription(_simplenews_user_load($xss_mail));
    $this
      ->drupalGet('admin/content/simplenews/users/edit/' . $xss_subscriber->snid);
    $this
      ->assertNoRaw($xss_mail);
    $this
      ->assertRaw(check_plain($xss_mail));
  }

}

/**
 * Test cases for creating and sending newsletters.
 */
class SimplenewsSendTestCase extends SimplenewsTestCase {

  /**
   * Implementation of getInfo().
   */
  function getInfo() {
    return array(
      'name' => t('Sending newsletters'),
      'description' => t('Creating and sending of newsletters, different send processes (with/without cron)'),
      'group' => t('Simplenews'),
    );
  }
  function setUp() {
    parent::setUp();
    $this->user = $this
      ->drupalCreateUser(array(
      'administer newsletters',
      'send newsletter',
      'administer nodes',
      'administer simplenews subscriptions',
      'create simplenews content',
      'edit any simplenews content',
      'delete any simplenews content',
    ));
    $this
      ->drupalLogin($this->user);

    // Subscribe a few users.
    $this->subscribers = array();
    for ($i = 0; $i < 5; $i++) {
      $mail = $this
        ->randomEmail();
      $this->subscribers[$mail] = $mail;
    }
    $delimiters = array(
      ',',
      ' ',
      "\n",
    );
    $this
      ->drupalGet('admin/content/simplenews/users');
    $this
      ->clickLink(t('Mass subscribe'));
    $edit = array(
      'emails' => implode(',', $this->subscribers),
      // @todo: Don't hardcode the default tid.
      'newsletters[1]' => TRUE,
    );
    $this
      ->drupalPost(NULL, $edit, t('Subscribe'));

    // Reset the static cache.
    module_load_include('inc', 'simplenews', 'includes/simplenews.mail');
    simplenews_mail(NULL, $message = NULL, $params = NULL, TRUE);
    simplenews_mail_mail(NULL, NULL, NULL, NULL, TRUE);
    token_get_values('global', NULL, TRUE);
  }

  /**
   * Send a newsletter using cron.
   */
  function testSendNowNoCron() {

    // Disable cron.
    variable_set('simplenews_use_cron', FALSE);

    // Verify that the newsletter settings are shown.
    $this
      ->drupalGet('node/add/simplenews');
    $this
      ->assertText(t('Newsletter'));
    $edit = array(
      'title' => $this
        ->randomName(),
      'taxonomy[' . variable_get('simplenews_vid', '') . ']' => $this
        ->getRandomNewsletter(),
    );
    $this
      ->drupalPost(NULL, $edit, 'Save');
    $this
      ->assertTrue(preg_match('|node/(\\d+)$|', $this
      ->getUrl(), $matches), 'Node created');
    $node = node_load($matches[1], NULL, TRUE);
    $this
      ->clickLink(t('Newsletter'));
    $this
      ->assertText(t('Send one test newsletter to the test address'));
    $this
      ->assertText(t('Send newsletter'));

    // Verify state.
    $this
      ->assertEqual(SIMPLENEWS_STATUS_SEND_NOT, $node->simplenews['s_status'], t('Newsletter not sent yet.'));

    // Send now.
    $this
      ->drupalPost(NULL, array(
      'simplenews[send]' => SIMPLENEWS_COMMAND_SEND_NOW,
    ), t('Submit'));

    // Verify state.
    $node = node_load($node->nid, NULL, TRUE);
    $this
      ->assertEqual(SIMPLENEWS_STATUS_SEND_READY, $node->simplenews['s_status'], t('Newsletter sending finished'));

    // Verify mails.
    $mails = $this
      ->drupalGetMails();
    $this
      ->assertEqual(5, count($mails), t('All mails were sent.'));
    foreach ($mails as $mail) {
      $this
        ->assertEqual($mail['subject'], '[Drupal newsletter] ' . $edit['title'], 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'));
  }

  /**
   * Send a newsletter using cron and a low throttle.
   */
  function testSendNowCronThrottle() {
    variable_set('simplenews_throttle', 3);

    // Verify that the newsletter settings are shown.
    $this
      ->drupalGet('node/add/simplenews');
    $this
      ->assertText(t('Newsletter'));
    $edit = array(
      'title' => $this
        ->randomName(),
      'taxonomy[' . variable_get('simplenews_vid', '') . ']' => $this
        ->getRandomNewsletter(),
    );
    $this
      ->drupalPost(NULL, $edit, 'Save');
    $this
      ->assertTrue(preg_match('|node/(\\d+)$|', $this
      ->getUrl(), $matches), 'Node created');
    $node = node_load($matches[1], NULL, TRUE);
    $this
      ->clickLink(t('Newsletter'));
    $this
      ->assertText(t('Send one test newsletter to the test address'));
    $this
      ->assertText(t('Send newsletter'));

    // Verify state.
    $this
      ->assertEqual(SIMPLENEWS_STATUS_SEND_NOT, $node->simplenews['s_status'], t('Newsletter not sent yet.'));

    // Send now.
    $this
      ->drupalPost(NULL, array(
      'simplenews[send]' => SIMPLENEWS_COMMAND_SEND_NOW,
    ), t('Submit'));

    // Verify state.
    $node = node_load($node->nid, NULL, TRUE);
    $this
      ->assertEqual(SIMPLENEWS_STATUS_SEND_PENDING, $node->simplenews['s_status'], t('Newsletter sending pending.'));

    // Verify that no mails have been sent yet.
    $mails = $this
      ->drupalGetMails();
    $this
      ->assertEqual(0, count($mails), t('No mails were sent yet.'));
    $spooled = db_result(db_query('SELECT COUNT(*) FROM {simplenews_mail_spool} WHERE nid = %d', $node->nid));
    $this
      ->assertEqual(5, $spooled, t('5 mails have been added to the mail spool'));

    // Run cron for the first time.
    simplenews_cron();

    // Verify state.
    $node = node_load($node->nid, NULL, TRUE);
    $this
      ->assertEqual(SIMPLENEWS_STATUS_SEND_PENDING, $node->simplenews['s_status'], t('Newsletter sending pending.'));
    $spooled = db_result(db_query('SELECT COUNT(*) FROM {simplenews_mail_spool} WHERE nid = %d', $node->nid));
    $this
      ->assertEqual(2, $spooled, t('2 mails remaining in spool.'));

    // Run cron for the second time.
    simplenews_cron();

    // Verify state.
    $node = node_load($node->nid, NULL, TRUE);
    $this
      ->assertEqual(SIMPLENEWS_STATUS_SEND_READY, $node->simplenews['s_status'], t('Newsletter sending finished.'));
    $spooled = db_result(db_query('SELECT COUNT(*) FROM {simplenews_mail_spool} WHERE nid = %d', $node->nid));
    $this
      ->assertEqual(0, $spooled, t('No mails remaining in spool.'));

    // Verify mails.
    $mails = $this
      ->drupalGetMails();
    $this
      ->assertEqual(5, count($mails), t('All mails were sent.'));
    foreach ($mails as $mail) {
      $this
        ->assertEqual($mail['subject'], '[Drupal newsletter] ' . $edit['title'], 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'));
  }

  /**
   * Send a newsletter without using cron.
   */
  function testSendNowCron() {

    // Verify that the newsletter settings are shown.
    $this
      ->drupalGet('node/add/simplenews');
    $this
      ->assertText(t('Newsletter'));
    $edit = array(
      'title' => $this
        ->randomName(),
      'taxonomy[' . variable_get('simplenews_vid', '') . ']' => $this
        ->getRandomNewsletter(),
    );
    $this
      ->drupalPost(NULL, $edit, 'Save');
    $this
      ->assertTrue(preg_match('|node/(\\d+)$|', $this
      ->getUrl(), $matches), 'Node created');
    $node = node_load($matches[1], NULL, TRUE);
    $this
      ->clickLink(t('Newsletter'));
    $this
      ->assertText(t('Send one test newsletter to the test address'));
    $this
      ->assertText(t('Send newsletter'));

    // Verify state.
    $this
      ->assertEqual(SIMPLENEWS_STATUS_SEND_NOT, $node->simplenews['s_status'], t('Newsletter not sent yet.'));

    // Send now.
    $this
      ->drupalPost(NULL, array(
      'simplenews[send]' => SIMPLENEWS_COMMAND_SEND_NOW,
    ), t('Submit'));

    // Verify state.
    $node = node_load($node->nid, NULL, TRUE);
    $this
      ->assertEqual(SIMPLENEWS_STATUS_SEND_PENDING, $node->simplenews['s_status'], t('Newsletter sending pending.'));

    // Verify that no mails have been sent yet.
    $mails = $this
      ->drupalGetMails();
    $this
      ->assertEqual(0, count($mails), t('No mails were sent yet.'));
    $spooled = db_result(db_query('SELECT COUNT(*) FROM {simplenews_mail_spool} WHERE nid = %d', $node->nid));
    $this
      ->assertEqual(5, $spooled, t('5 mails have been added to the mail spool'));

    // Run cron.
    simplenews_cron();

    // Verify state.
    $node = node_load($node->nid, NULL, TRUE);
    $this
      ->assertEqual(SIMPLENEWS_STATUS_SEND_READY, $node->simplenews['s_status'], t('Newsletter sending finished.'));
    $spooled = db_result(db_query('SELECT COUNT(*) FROM {simplenews_mail_spool} WHERE nid = %d', $node->nid));
    $this
      ->assertEqual(0, $spooled, t('No mails remaining in spool.'));

    // Verify mails.
    $mails = $this
      ->drupalGetMails();
    $this
      ->assertEqual(5, count($mails), t('All mails were sent.'));
    foreach ($mails as $mail) {
      $this
        ->assertEqual($mail['subject'], '[Drupal newsletter] ' . $edit['title'], 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'));
  }
  function testUpdateNewsletter() {

    // Create a second category.
    $this
      ->drupalGet('admin/content/simplenews/types');
    $this
      ->clickLink(t('Add newsletter'));
    $edit = array(
      'name' => $this
        ->randomName(),
      'description' => $this
        ->randomString(20),
    );
    $this
      ->drupalPost(NULL, $edit, t('Save'));
    $this
      ->drupalGet('node/add/simplenews');
    $this
      ->assertText(t('Newsletter'));
    $edit = array(
      'title' => $this
        ->randomName(),
      // @todo avoid hardcoding the term id.
      'taxonomy[' . variable_get('simplenews_vid', '') . ']' => 1,
    );
    $this
      ->drupalPost(NULL, $edit, 'Save');
    $this
      ->assertTrue(preg_match('|node/(\\d+)$|', $this
      ->getUrl(), $matches), 'Node created.');
    $node = node_load($matches[1], NULL, TRUE);

    // Verify newsletter.
    $this
      ->assertEqual(SIMPLENEWS_STATUS_SEND_NOT, $node->simplenews['s_status'], t('Newsletter sending not started.'));
    $this
      ->assertEqual(1, $node->simplenews['tid'], t('Newsletter has tid 1'));
    $this
      ->clickLink(t('Edit'));
    $update = array(
      'taxonomy[' . variable_get('simplenews_vid', '') . ']' => 2,
    );
    $this
      ->drupalPost(NULL, $update, t('Save'));

    // Verify newsletter.
    $node = node_load($node->nid, NULL, TRUE);
    $this
      ->assertEqual(SIMPLENEWS_STATUS_SEND_NOT, $node->simplenews['s_status'], t('Newsletter sending not started.'));
    $this
      ->assertEqual(2, $node->simplenews['tid'], t('Newsletter has tid 2.'));
  }

  /**
   * Create a newsletter, send mails and then delete.
   */
  function testDelete() {

    // Verify that the newsletter settings are shown.
    $this
      ->drupalGet('node/add/simplenews');
    $this
      ->assertText(t('Newsletter'));

    // Prevent deleting the mail spool entries automatically.
    variable_set('simplenews_spool_expire', 1);
    $edit = array(
      'title' => $this
        ->randomName(),
      'taxonomy[' . variable_get('simplenews_vid', '') . ']' => $this
        ->getRandomNewsletter(),
    );
    $this
      ->drupalPost(NULL, $edit, 'Save');
    $this
      ->assertTrue(preg_match('|node/(\\d+)$|', $this
      ->getUrl(), $matches), 'Node created');
    $node = node_load($matches[1], NULL, TRUE);
    $this
      ->clickLink(t('Newsletter'));
    $this
      ->assertText(t('Send one test newsletter to the test address'));
    $this
      ->assertText(t('Send newsletter'));

    // Verify state.
    $this
      ->assertEqual(SIMPLENEWS_STATUS_SEND_NOT, $node->simplenews['s_status'], t('Newsletter not sent yet.'));

    // Send now.
    $this
      ->drupalPost(NULL, array(
      'simplenews[send]' => SIMPLENEWS_COMMAND_SEND_NOW,
    ), t('Submit'));

    // Verify state.
    $node = node_load($node->nid, NULL, TRUE);
    $this
      ->assertEqual(SIMPLENEWS_STATUS_SEND_PENDING, $node->simplenews['s_status'], t('Newsletter sending pending.'));
    $spooled = db_result(db_query('SELECT COUNT(*) FROM {simplenews_mail_spool} WHERE nid = %d', $node->nid));
    $this
      ->assertEqual(5, $spooled, t('5 mails remaining in spool.'));

    // Verify that deleting isn't possible right now.
    // @todo: Feature not supported by 6.x-2.x.

    //$this->clickLink(t('Edit'));

    //$this->assertText(t("You can't delete this newsletter because it has not been sent to all its subscribers."));

    //$this->assertNoText(t('Delete'));

    // Send mails.
    simplenews_cron();

    // Verify state.
    $node = node_load($node->nid, NULL, TRUE);
    $this
      ->assertEqual(SIMPLENEWS_STATUS_SEND_READY, $node->simplenews['s_status'], t('Newsletter sending finished'));
    $spooled = db_result(db_query('SELECT COUNT(*) FROM {simplenews_mail_spool} WHERE nid = %d', $node->nid));
    $this
      ->assertEqual(5, $spooled, t('Mails are kept in simplenews_mail_spool after being sent.'));

    // Verify mails.
    $mails = $this
      ->drupalGetMails();
    $this
      ->assertEqual(5, count($mails), t('All mails were sent.'));
    foreach ($mails as $mail) {
      $this
        ->assertEqual($mail['subject'], '[Drupal newsletter] ' . $edit['title'], 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'));

    // Now delete.
    $this
      ->clickLink(t('Edit'));
    $this
      ->drupalPost(NULL, array(), t('Delete'));
    $this
      ->drupalPost(NULL, array(), t('Delete'));

    // Verify.
    $spooled = db_result(db_query('SELECT COUNT(*) FROM {simplenews_mail_spool} WHERE nid = %d', $node->nid));
    $this
      ->assertEqual(0, $spooled, t('No mails remaining in spool.'));
  }

}

/**
 * Unit tests for certain functions.
 *
 * @todo: This should be a unit test class, but the test bot seems to brake.
 */
class SimplenewsUnitTest extends SimplenewsTestCase {
  function getInfo() {
    return array(
      'name' => 'Unit tests',
      'description' => 'Unit tests for certain functions.',
      'group' => 'Simplenews',
    );
  }
  public function testMasking() {
    module_load_include('inc', 'simplenews', 'includes/simplenews.subscription');
    $this
      ->assertEqual('t*****@e*****.org', simplenews_mask_mail('test@example.org'));
    $this
      ->assertEqual('t*****@e*****.org', simplenews_mask_mail('t@example.org'));
    $this
      ->assertEqual('t*****@t*****.org', simplenews_mask_mail('t@test.example.org'));
    $this
      ->assertEqual('t*****@e*****', simplenews_mask_mail('t@example'));
  }

}

Classes

Namesort descending Description
SimpleNewsAdministrationTestCase @todo: Newsletter node create, send draft, send final
SimplenewsSendTestCase Test cases for creating and sending newsletters.
SimplenewsSubscribeTestCase
SimplenewsTestCase @file Simplenews test functions.
SimplenewsUnitTest Unit tests for certain functions.