You are here

class SimpleNewsAdministrationTestCase in Simplenews 7

Same name and namespace in other branches
  1. 6.2 tests/simplenews.test \SimpleNewsAdministrationTestCase
  2. 7.2 tests/simplenews.test \SimpleNewsAdministrationTestCase

@todo: Newsletter node create, send draft, send final

Hierarchy

Expanded class hierarchy of SimpleNewsAdministrationTestCase

File

tests/simplenews.test, line 986
Simplenews test functions.

View source
class SimpleNewsAdministrationTestCase extends SimplenewsTestCase {

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

  /**
   * Overrides SimplenewsTestCase::setUp().
   */
  public function setUp() {
    parent::setUp(array(
      'block',
    ));
  }

  /**
   * 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',
      'create simplenews content',
      'send newsletter',
    ));
    $this
      ->drupalLogin($admin_user);
    $this
      ->drupalGet('admin/config/services/simplenews');

    // Create a category for all possible setting combinations.
    $new_account = array(
      'none',
      'off',
      'on',
      'silent',
    );
    $opt_inout = array(
      'hidden',
      'single',
      'double',
    );
    $block = array(
      'block' => TRUE,
      'noblock' => FALSE,
    );
    foreach ($new_account as $new_account_setting) {
      foreach ($opt_inout as $opt_inout_setting) {
        foreach ($block as $name => $value) {
          $this
            ->clickLink(t('Add newsletter category'));
          $edit = array(
            'name' => implode('-', array(
              $new_account_setting,
              $opt_inout_setting,
              $name,
            )),
            'description' => $this
              ->randomString(20),
            'new_account' => $new_account_setting,
            'opt_inout' => $opt_inout_setting,
            'block' => $value,
            'priority' => rand(0, 5),
            'receipt' => rand(0, 1) ? TRUE : FALSE,
            'from_name' => $this
              ->randomName(),
            'from_address' => $this
              ->randomEmail(),
          );
          $this
            ->drupalPost(NULL, $edit, t('Save'));
        }
      }
    }
    drupal_static_reset('simplenews_categories_load_multiple');
    $categories = simplenews_categories_load_multiple();

    // Check block settings.
    $this
      ->drupalGet('admin/structure/block');

    //blocks[simplenews_42][region]
    foreach ($categories as $category) {
      if (strpos($category->name, '-') === FALSE) {
        continue;
      }
      list($new_account_setting, $opt_inout_setting, $block) = explode('-', $category->name);
      if ($block == 'block' && $opt_inout_setting != 'hidden') {
        $this
          ->assertField('blocks[simplenews_' . $category->tid . '][region]', t('Block is displayed for category'));
      }
      else {
        $this
          ->assertNoField('blocks[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-block newsletter.
      if ($category->name == 'off-double-block') {
        $off_double_block_tid = $category->tid;
      }
      list($new_account_setting, $opt_inout_setting, $block) = explode('-', $category->name);
      if ($category->new_account == 'on' && $category->opt_inout != 'hidden') {
        $this
          ->assertFieldChecked('edit-newsletters-' . $category->tid);
      }
      elseif ($category->new_account == 'off' && $category->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_block_tid . ']' => $off_double_block_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) {

      // Check confirmation message for all on and non-hidden newsletters and
      // the one that was explicitly selected.
      if ($category->new_account == 'on' && $category->opt_inout != 'hidden' || $category->name == 'off-double-block') {
        $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_query('SELECT uid FROM {users} WHERE name = :name', array(
      ':name' => $edit['name'],
    ))
      ->fetchField();
    $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/simplenews',
    ) as $path) {
      $this
        ->drupalGet($path);
      foreach ($categories as $category) {
        if (strpos($category->name, '-') === FALSE) {
          continue;
        }
        list($new_account_setting, $opt_inout_setting, $block) = explode('-', $category->name);
        if ($category->opt_inout == 'hidden') {
          $this
            ->assertNoField('newsletters[' . $category->tid . ']', t('Hidden newsletter category is not shown.'));
        }
        elseif ($category->new_account == 'on' || $category->name == 'off-double-block' || $category->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_block_tid . ']' => FALSE,
    );
    $this
      ->drupalPost(NULL, $edit, t('Save'));
    $this
      ->assertNoFieldChecked('edit-newsletters-' . $off_double_block_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->block == TRUE && $category->tid != 1 && $category->opt_inout != 'hidden') {
        $edit_category = $category;
        break;
      }
    }
    $this
      ->drupalLogin($admin_user);
    $this
      ->setupSubscriptionBlock($edit_category->tid, $settings = array(
      'issue count' => 2,
      'previous issues' => 1,
    ));

    // Create a bunch of newsletters.
    $generated_names = array();
    $date = strtotime('monday this week');
    for ($index = 0; $index < 3; $index++) {
      $name = $this
        ->randomName();
      $generated_names[] = $name;
      $this
        ->drupalGet('node/add/simplenews');
      $edit = array(
        'title' => $name,
        'field_simplenews_term[und]' => $edit_category->tid,
        'date' => date('c', strtotime('+' . $index . ' day', $date)),
      );
      $this
        ->drupalPost(NULL, $edit, 'Save');
      $this
        ->clickLink(t('Newsletter'));
      $this
        ->drupalPost(NULL, array(
        'simplenews[send]' => SIMPLENEWS_COMMAND_SEND_NOW,
      ), t('Submit'));
    }

    // Display the two recent issues.
    $this
      ->drupalGet('');
    $this
      ->assertText(t('Previous issues'), 'Should display recent issues.');
    $displayed_issues = $this
      ->xpath("//div[@class='issues-list']/div/ul/li/a");
    $this
      ->assertEqual(count($displayed_issues), 2, 'Displys two recent issues.');
    $this
      ->assertFalse(in_array($generated_names[0], $displayed_issues));
    $this
      ->assertTrue(in_array($generated_names[1], $displayed_issues));
    $this
      ->assertTrue(in_array($generated_names[2], $displayed_issues));
    $this
      ->drupalGet('admin/config/services/simplenews/categories/' . $edit_category->tid . '/edit');
    $this
      ->assertFieldByName('name', $edit_category->name, t('Category name is displayed when editing'));
    $this
      ->assertFieldByName('description', $edit_category->description, t('Category description is displayed when editing'));
    $edit = array(
      'block' => FALSE,
    );
    $this
      ->drupalPost(NULL, $edit, t('Save'));
    $updated_category = simplenews_category_load($edit_category->tid);
    $this
      ->assertEqual(0, $updated_category->block, t('Block for category disabled'));
    $this
      ->drupalGet('admin/structure/block');
    $this
      ->assertNoText($edit_category->name, t('Category block was removed'));

    // Delete a category.
    $this
      ->drupalGet('admin/config/services/simplenews/categories/' . $edit_category->tid . '/edit');
    $edit = array();
    $this
      ->drupalPost(NULL, $edit, t('Delete'));
    $this
      ->drupalPost(NULL, $edit, t('Delete'));

    // Verify that the category has been deleted.
    $this
      ->assertFalse(simplenews_category_load($edit_category->tid));
    $this
      ->assertFalse(db_query('SELECT tid FROM {simplenews_category} WHERE tid = :tid', array(
      ':tid' => $edit_category->tid,
    ))
      ->fetchField());
  }

  /**
   * 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/config/services/simplenews/add', $edit, t('Save'));

    // Add a number of users to each category separately and then add another
    // bunch to both.
    $subscribers = array();
    drupal_static_reset('simplenews_categories_load_multiple');
    $categories = simplenews_categories_load_multiple();
    $groups = array();
    foreach (array_keys($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/people/simplenews');
    $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'));
    }

    // 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(
      'list' => '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' => drupal_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/people/simplenews');
    $this
      ->assertNoText($first_mail);
    $this
      ->assertText($all_mail);

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

    // Check exporting.
    $this
      ->clickLink(t('Export'));
    $this
      ->drupalPost(NULL, array(
      'newsletters[' . $first . ']' => TRUE,
    ), 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.'));
      }
    }

    // Only export unsubscribed mail addresses.
    $edit = array(
      'subscribed[subscribed]' => FALSE,
      'subscribed[unsubscribed]' => TRUE,
      'newsletters[' . $first . ']' => TRUE,
    );
    $this
      ->drupalPost(NULL, $edit, t('Export'));
    $export_field = $this
      ->xpath($this
      ->constructFieldXpath('name', 'emails'));
    $exported_mails = (string) $export_field[0];
    $exported_mails = explode(', ', $exported_mails);
    $this
      ->assertEqual(2, count($exported_mails));
    $this
      ->assertTrue(in_array($all_mail, $exported_mails));
    $this
      ->assertTrue(in_array($first_mail, $exported_mails));

    // Make sure there are unconfirmed subscriptions.
    $unconfirmed = array();
    $unconfirmed[] = $this
      ->randomEmail();
    $unconfirmed[] = $this
      ->randomEmail();
    foreach ($unconfirmed as $mail) {
      simplenews_subscribe_user($mail, $first, TRUE);
    }

    // Only export unconfirmed mail addresses.
    $edit = array(
      'subscribed[subscribed]' => FALSE,
      'subscribed[unconfirmed]' => TRUE,
      'subscribed[unsubscribed]' => FALSE,
      'newsletters[' . $first . ']' => TRUE,
    );
    $this
      ->drupalPost(NULL, $edit, t('Export'));
    $export_field = $this
      ->xpath($this
      ->constructFieldXpath('name', 'emails'));
    $exported_mails = (string) $export_field[0];
    $exported_mails = explode(', ', $exported_mails);
    $this
      ->assertEqual(2, count($exported_mails));
    $this
      ->assertTrue(in_array($unconfirmed[0], $exported_mails));
    $this
      ->assertTrue(in_array($unconfirmed[1], $exported_mails));

    // Make sure the user is subscribed to the first tid.
    simplenews_subscribe_user($user_mail, $first, FALSE);
    module_load_include('inc', 'simplenews', 'includes/simplenews.admin');
    $before_count = simplenews_count_subscriptions($first);

    // Block the user.
    user_save(clone $user, array(
      'status' => 0,
    ));
    $this
      ->drupalGet('admin/people/simplenews');

    // Verify updated subscriptions count.
    drupal_static_reset('simplenews_count_subscriptions');
    $after_count = simplenews_count_subscriptions($first);
    $this
      ->assertEqual($before_count - 1, $after_count, t('Blocked users are not counted in subscription count.'));

    // Test mass subscribe with previously unsubscribed users.
    for ($i = 0; $i < 3; $i++) {
      $tested_subscribers[] = $this
        ->randomEmail();
    }
    simplenews_subscribe_user($tested_subscribers[0], $first, FALSE);
    simplenews_subscribe_user($tested_subscribers[1], $first, FALSE);
    simplenews_unsubscribe_user($tested_subscribers[0], $first, FALSE);
    simplenews_unsubscribe_user($tested_subscribers[1], $first, FALSE);
    $unsubscribed = implode(', ', array_slice($tested_subscribers, 0, 2));
    $edit = array(
      'emails' => implode(', ', $tested_subscribers),
      'newsletters[' . $first . ']' => TRUE,
    );
    $this
      ->drupalPost('admin/people/simplenews/import', $edit, t('Subscribe'));
    drupal_static_reset('simplenews_subscriber_load_multiple');
    drupal_static_reset('simplenews_user_is_subscribed');
    $this
      ->assertFalse(simplenews_user_is_subscribed($tested_subscribers[0], $first, t('Subscriber not resubscribed through mass subscription.')));
    $this
      ->assertFalse(simplenews_user_is_subscribed($tested_subscribers[1], $first, t('Subscriber not resubscribed through mass subscription.')));
    $this
      ->assertTrue(simplenews_user_is_subscribed($tested_subscribers[2], $first, t('Subscriber subscribed through mass subscription.')));
    $substitutes = array(
      '@name' => check_plain(_simplenews_newsletter_name(simplenews_category_load($first))),
      '@mail' => $unsubscribed,
    );
    $this
      ->assertText(t('The following addresses were skipped because they have previously unsubscribed from @name: @mail.', $substitutes));
    $this
      ->assertText(t("If you would like to resubscribe them, use the 'Force resubscription' option."));

    // Test mass subscribe with previously unsubscribed users and force
    // resubscription.
    $tested_subscribers[2] = $this
      ->randomEmail();
    $edit = array(
      'emails' => implode(', ', $tested_subscribers),
      'newsletters[' . $first . ']' => TRUE,
      'resubscribe' => TRUE,
    );
    $this
      ->drupalPost('admin/people/simplenews/import', $edit, t('Subscribe'));
    drupal_static_reset('simplenews_subscriber_load_multiple');
    drupal_static_reset('simplenews_user_is_subscribed');
    $this
      ->assertTrue(simplenews_user_is_subscribed($tested_subscribers[0], $first, t('Subscriber resubscribed trough mass subscription.')));
    $this
      ->assertTrue(simplenews_user_is_subscribed($tested_subscribers[1], $first, t('Subscriber resubscribed trough mass subscription.')));
    $this
      ->assertTrue(simplenews_user_is_subscribed($tested_subscribers[2], $first, t('Subscriber subscribed trough mass subscription.')));

    // Delete newsletter category.
    $this
      ->drupalPost('taxonomy/term/' . $first . '/edit', array(), t('Delete'));
    $this
      ->assertText(t('This taxonomy term is part of simplenews newsletter category @name. Deleting this term will delete the newsletter category and all subscriptions to category @name. This action cannot be undone.', array(
      '@name' => $categories[$first]->name,
    )), t('Confirmation message displayed.'));
    $this
      ->drupalPost(NULL, array(), t('Delete'));
    $this
      ->assertText(t('All subscriptions to newsletter @newsletter have been deleted.', array(
      '@newsletter' => $categories[$first]->name,
    )));

    // Verify that all related data has been deleted.
    $this
      ->assertFalse(simplenews_category_load($first));
    $this
      ->assertFalse(db_query('SELECT tid FROM {simplenews_category} WHERE tid = :tid', array(
      ':tid' => $first,
    ))
      ->fetchField());
    $this
      ->assertFalse(db_query('SELECT * FROM {block} WHERE module = :module AND delta = :tid', array(
      ':module' => 'simplenews',
      ':tid' => $first,
    ))
      ->fetchField());

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

    // Reset list and click on the first subscriber.
    $this
      ->drupalPost(NULL, array(), t('Reset'));
    $this
      ->clickLink(t('edit'));

    // Get the subscriber id from the path.
    $this
      ->assertTrue(preg_match('|admin/people/simplenews/users/edit/(\\d+)$|', $this
      ->getUrl(), $matches), 'Subscriber found');
    $subscriber = simplenews_subscriber_load($matches[1]);
    $this
      ->assertText(t('Subscriptions for @mail', array(
      '@mail' => $subscriber->mail,
    )));
    $this
      ->assertFieldChecked('edit-activated--2');

    // Disable account.
    $edit = array(
      'activated' => FALSE,
    );
    $this
      ->drupalPost(NULL, $edit, t('Update'));
    drupal_static_reset('simplenews_subscriber_load_multiple');
    drupal_static_reset('simplenews_user_is_subscribed');
    $this
      ->assertFalse(simplenews_user_is_subscribed($subscriber->mail, $this
      ->getRandomNewsletter(), t('Subscriber is not active')));

    // Re-enable account.
    $this
      ->drupalGet('admin/people/simplenews/users/edit/' . $subscriber->snid);
    $this
      ->assertText(t('Subscriptions for @mail', array(
      '@mail' => $subscriber->mail,
    )));
    $this
      ->assertNoFieldChecked('edit-activated--2');
    $edit = array(
      'activated' => TRUE,
    );
    $this
      ->drupalPost(NULL, $edit, t('Update'));
    drupal_static_reset('simplenews_subscriber_load_multiple');
    drupal_static_reset('simplenews_user_is_subscribed');
    $this
      ->assertTrue(simplenews_user_is_subscribed($subscriber->mail, $this
      ->getRandomNewsletter(), t('Subscriber is active again.')));

    // Remove the category.
    $this
      ->drupalGet('admin/people/simplenews/users/edit/' . $subscriber->snid);
    $this
      ->assertText(t('Subscriptions for @mail', array(
      '@mail' => $subscriber->mail,
    )));
    $edit = array(
      'newsletters[' . reset($subscriber->tids) . ']' => FALSE,
    );
    $this
      ->drupalPost(NULL, $edit, t('Update'));
    drupal_static_reset('simplenews_subscriber_load_multiple');
    drupal_static_reset('simplenews_user_is_subscribed');
    $this
      ->assertFalse(simplenews_user_is_subscribed($subscriber->mail, reset($subscriber->tids), t('Subscriber not subscribed anymore.')));

    // @todo Test Admin subscriber edit preferred language $subscription->language
    // 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/people/simplenews');
    $this
      ->assertNoRaw($xss_mail);
    $this
      ->assertRaw(check_plain($xss_mail));
    $xss_subscriber = simplenews_subscriber_load_by_mail($xss_mail);
    $this
      ->drupalGet('admin/people/simplenews/users/edit/' . $xss_subscriber->snid);
    $this
      ->assertNoRaw($xss_mail);
    $this
      ->assertRaw(check_plain($xss_mail));
  }

  /**
   * Test content type configuration.
   */
  function testContentTypes() {
    $admin_user = $this
      ->drupalCreateUser(array(
      'administer blocks',
      'administer content types',
      'administer nodes',
      'access administration pages',
      'administer permissions',
      'administer newsletters',
      'administer simplenews subscriptions',
      'bypass node access',
      'send newsletter',
    ));
    $this
      ->drupalLogin($admin_user);
    $this
      ->drupalGet('admin/structure/types');
    $this
      ->clickLink(t('Add content type'));
    $edit = array(
      'name' => $name = $this
        ->randomName(),
      'type' => $type = drupal_strtolower($name),
      'simplenews_content_type' => TRUE,
    );
    $this
      ->drupalPost(NULL, $edit, t('Save content type'));

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

    // Create an issue.
    $edit = array(
      'title' => $this
        ->randomName(),
    );
    $this
      ->drupalPost(NULL, $edit, 'Save');

    // Send newsletter.
    $this
      ->clickLink(t('Newsletter'));
    $this
      ->assertText(t('Send newsletter'));
    $this
      ->drupalPost(NULL, array(), t('Submit'));
    $mails = $this
      ->drupalGetMails();
    $this
      ->assertEqual('simplenews_test', $mails[0]['id']);

    // @todo: Test with a custom test mail address.
    $this
      ->assertEqual('user@example.com', $mails[0]['to']);
    $this
      ->assertEqual(t('[Drupal newsletter] @title', array(
      '@title' => $edit['title'],
    )), $mails[0]['subject']);

    // Update the content type, remove the simpletest checkbox.
    $edit = array(
      'simplenews_content_type' => FALSE,
    );
    $this
      ->drupalPost('admin/structure/types/manage/' . $type, $edit, t('Save content type'));

    // Verify that the newsletter settings are still shown.
    // Note: Previously the field got autoremoved. We leave it remaining due to potential data loss.
    $this
      ->drupalGet('node/add/' . $type);
    $this
      ->assertNoText(t('Replacement patterns'));
    $this
      ->assertText(t('Newsletter category'));

    // @todo: Test node update/delete.
    // Delete content type.
    // @todo: Add assertions.
    $this
      ->drupalPost('admin/structure/types/manage/' . $type . '/delete', array(), t('Delete'));
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DrupalTestCase::$assertions protected property Assertions thrown in that test case.
DrupalTestCase::$databasePrefix protected property The database prefix of this test run.
DrupalTestCase::$originalFileDirectory protected property The original file directory, before it was changed for testing purposes.
DrupalTestCase::$results public property Current results of this test case.
DrupalTestCase::$setup protected property Flag to indicate whether the test has been set up.
DrupalTestCase::$setupDatabasePrefix protected property
DrupalTestCase::$setupEnvironment protected property
DrupalTestCase::$skipClasses protected property This class is skipped when looking for the source of an assertion.
DrupalTestCase::$testId protected property The test run ID.
DrupalTestCase::$timeLimit protected property Time limit for the test.
DrupalTestCase::$useSetupInstallationCache public property Whether to cache the installation part of the setUp() method.
DrupalTestCase::$useSetupModulesCache public property Whether to cache the modules installation part of the setUp() method.
DrupalTestCase::$verboseDirectoryUrl protected property URL to the verbose output file directory.
DrupalTestCase::assert protected function Internal helper: stores the assert.
DrupalTestCase::assertEqual protected function Check to see if two values are equal.
DrupalTestCase::assertFalse protected function Check to see if a value is false (an empty string, 0, NULL, or FALSE).
DrupalTestCase::assertIdentical protected function Check to see if two values are identical.
DrupalTestCase::assertNotEqual protected function Check to see if two values are not equal.
DrupalTestCase::assertNotIdentical protected function Check to see if two values are not identical.
DrupalTestCase::assertNotNull protected function Check to see if a value is not NULL.
DrupalTestCase::assertNull protected function Check to see if a value is NULL.
DrupalTestCase::assertTrue protected function Check to see if a value is not false (not an empty string, 0, NULL, or FALSE).
DrupalTestCase::deleteAssert public static function Delete an assertion record by message ID.
DrupalTestCase::error protected function Fire an error assertion. 1
DrupalTestCase::errorHandler public function Handle errors during test runs. 1
DrupalTestCase::exceptionHandler protected function Handle exceptions.
DrupalTestCase::fail protected function Fire an assertion that is always negative.
DrupalTestCase::generatePermutations public static function Converts a list of possible parameters into a stack of permutations.
DrupalTestCase::getAssertionCall protected function Cycles through backtrace until the first non-assertion method is found.
DrupalTestCase::getDatabaseConnection public static function Returns the database connection to the site running Simpletest.
DrupalTestCase::insertAssert public static function Store an assertion from outside the testing context.
DrupalTestCase::pass protected function Fire an assertion that is always positive.
DrupalTestCase::randomName public static function Generates a random string containing letters and numbers.
DrupalTestCase::randomString public static function Generates a random string of ASCII characters of codes 32 to 126.
DrupalTestCase::run public function Run all tests in this class.
DrupalTestCase::verbose protected function Logs a verbose message in a text file.
DrupalWebTestCase::$additionalCurlOptions protected property Additional cURL options.
DrupalWebTestCase::$content protected property The content of the page currently loaded in the internal browser.
DrupalWebTestCase::$cookieFile protected property The current cookie file used by cURL.
DrupalWebTestCase::$cookies protected property The cookies of the page currently loaded in the internal browser.
DrupalWebTestCase::$curlHandle protected property The handle of the current cURL connection.
DrupalWebTestCase::$drupalSettings protected property The value of the Drupal.settings JavaScript variable for the page currently loaded in the internal browser.
DrupalWebTestCase::$elements protected property The parsed version of the page.
DrupalWebTestCase::$generatedTestFiles protected property Whether the files were copied to the test files directory.
DrupalWebTestCase::$headers protected property The headers of the page currently loaded in the internal browser.
DrupalWebTestCase::$httpauth_credentials protected property HTTP authentication credentials (<username>:<password>).
DrupalWebTestCase::$httpauth_method protected property HTTP authentication method
DrupalWebTestCase::$loggedInUser protected property The current user logged in using the internal browser.
DrupalWebTestCase::$originalShutdownCallbacks protected property The original shutdown handlers array, before it was cleaned for testing purposes.
DrupalWebTestCase::$originalUser protected property The original user, before it was changed to a clean uid = 1 for testing purposes.
DrupalWebTestCase::$plainTextContent protected property The content of the page currently loaded in the internal browser (plain text version).
DrupalWebTestCase::$redirect_count protected property The number of redirects followed during the handling of a request.
DrupalWebTestCase::$session_id protected property The current session ID, if available.
DrupalWebTestCase::$session_name protected property The current session name, if available.
DrupalWebTestCase::$url protected property The URL currently loaded in the internal browser.
DrupalWebTestCase::assertField protected function Asserts that a field exists with the given name or ID.
DrupalWebTestCase::assertFieldById protected function Asserts that a field exists in the current page with the given ID and value.
DrupalWebTestCase::assertFieldByName protected function Asserts that a field exists in the current page with the given name and value.
DrupalWebTestCase::assertFieldByXPath protected function Asserts that a field exists in the current page by the given XPath.
DrupalWebTestCase::assertFieldChecked protected function Asserts that a checkbox field in the current page is checked.
DrupalWebTestCase::assertLink protected function Pass if a link with the specified label is found, and optional with the specified index.
DrupalWebTestCase::assertLinkByHref protected function Pass if a link containing a given href (part) is found.
DrupalWebTestCase::assertMail protected function Asserts that the most recently sent e-mail message has the given value.
DrupalWebTestCase::assertMailPattern protected function Asserts that the most recently sent e-mail message has the pattern in it.
DrupalWebTestCase::assertMailString protected function Asserts that the most recently sent e-mail message has the string in it.
DrupalWebTestCase::assertNoDuplicateIds protected function Asserts that each HTML ID is used for just a single element.
DrupalWebTestCase::assertNoField protected function Asserts that a field does not exist with the given name or ID.
DrupalWebTestCase::assertNoFieldById protected function Asserts that a field does not exist with the given ID and value.
DrupalWebTestCase::assertNoFieldByName protected function Asserts that a field does not exist with the given name and value.
DrupalWebTestCase::assertNoFieldByXPath protected function Asserts that a field doesn't exist or its value doesn't match, by XPath.
DrupalWebTestCase::assertNoFieldChecked protected function Asserts that a checkbox field in the current page is not checked.
DrupalWebTestCase::assertNoLink protected function Pass if a link with the specified label is not found.
DrupalWebTestCase::assertNoLinkByHref protected function Pass if a link containing a given href (part) is not found.
DrupalWebTestCase::assertNoOptionSelected protected function Asserts that a select option in the current page is not checked.
DrupalWebTestCase::assertNoPattern protected function Will trigger a pass if the perl regex pattern is not present in raw content.
DrupalWebTestCase::assertNoRaw protected function Pass if the raw text is NOT found on the loaded page, fail otherwise. Raw text refers to the raw HTML that the page generated.
DrupalWebTestCase::assertNoResponse protected function Asserts the page did not return the specified response code.
DrupalWebTestCase::assertNoText protected function Pass if the text is NOT found on the text version of the page. The text version is the equivalent of what a user would see when viewing through a web browser. In other words the HTML has been filtered out of the contents.
DrupalWebTestCase::assertNoTitle protected function Pass if the page title is not the given string.
DrupalWebTestCase::assertNoUniqueText protected function Pass if the text is found MORE THAN ONCE on the text version of the page.
DrupalWebTestCase::assertOptionSelected protected function Asserts that a select option in the current page is checked.
DrupalWebTestCase::assertPattern protected function Will trigger a pass if the Perl regex pattern is found in the raw content.
DrupalWebTestCase::assertRaw protected function Pass if the raw text IS found on the loaded page, fail otherwise. Raw text refers to the raw HTML that the page generated.
DrupalWebTestCase::assertResponse protected function Asserts the page responds with the specified response code.
DrupalWebTestCase::assertText protected function Pass if the text IS found on the text version of the page. The text version is the equivalent of what a user would see when viewing through a web browser. In other words the HTML has been filtered out of the contents.
DrupalWebTestCase::assertTextHelper protected function Helper for assertText and assertNoText.
DrupalWebTestCase::assertThemeOutput protected function Asserts themed output.
DrupalWebTestCase::assertTitle protected function Pass if the page title is the given string.
DrupalWebTestCase::assertUniqueText protected function Pass if the text is found ONLY ONCE on the text version of the page.
DrupalWebTestCase::assertUniqueTextHelper protected function Helper for assertUniqueText and assertNoUniqueText.
DrupalWebTestCase::assertUrl protected function Pass if the internal browser's URL matches the given path.
DrupalWebTestCase::buildXPathQuery protected function Builds an XPath query.
DrupalWebTestCase::changeDatabasePrefix protected function Changes the database connection to the prefixed one.
DrupalWebTestCase::checkForMetaRefresh protected function Check for meta refresh tag and if found call drupalGet() recursively. This function looks for the http-equiv attribute to be set to "Refresh" and is case-sensitive.
DrupalWebTestCase::checkPermissions protected function Check to make sure that the array of permissions are valid.
DrupalWebTestCase::clickLink protected function Follows a link by name.
DrupalWebTestCase::constructFieldXpath protected function Helper function: construct an XPath for the given set of attributes and value.
DrupalWebTestCase::copySetupCache protected function Copy the setup cache from/to another table and files directory.
DrupalWebTestCase::cronRun protected function Runs cron in the Drupal installed by Simpletest.
DrupalWebTestCase::curlClose protected function Close the cURL handler and unset the handler.
DrupalWebTestCase::curlExec protected function Initializes and executes a cURL request.
DrupalWebTestCase::curlHeaderCallback protected function Reads headers and registers errors received from the tested site.
DrupalWebTestCase::curlInitialize protected function Initializes the cURL connection.
DrupalWebTestCase::drupalCompareFiles protected function Compare two files based on size and file name.
DrupalWebTestCase::drupalCreateContentType protected function Creates a custom content type based on default settings.
DrupalWebTestCase::drupalCreateNode protected function Creates a node based on default settings.
DrupalWebTestCase::drupalCreateRole protected function Creates a role with specified permissions.
DrupalWebTestCase::drupalCreateUser protected function Create a user with a given set of permissions.
DrupalWebTestCase::drupalGet protected function Retrieves a Drupal path or an absolute path.
DrupalWebTestCase::drupalGetAJAX protected function Retrieve a Drupal path or an absolute path and JSON decode the result.
DrupalWebTestCase::drupalGetContent protected function Gets the current raw HTML of requested page.
DrupalWebTestCase::drupalGetHeader protected function Gets the value of an HTTP response header. If multiple requests were required to retrieve the page, only the headers from the last request will be checked by default. However, if TRUE is passed as the second argument, all requests will be processed…
DrupalWebTestCase::drupalGetHeaders protected function Gets the HTTP response headers of the requested page. Normally we are only interested in the headers returned by the last request. However, if a page is redirected or HTTP authentication is in use, multiple requests will be required to retrieve the…
DrupalWebTestCase::drupalGetMails protected function Gets an array containing all e-mails sent during this test case.
DrupalWebTestCase::drupalGetNodeByTitle function Get a node from the database based on its title.
DrupalWebTestCase::drupalGetSettings protected function Gets the value of the Drupal.settings JavaScript variable for the currently loaded page.
DrupalWebTestCase::drupalGetTestFiles protected function Get a list files that can be used in tests.
DrupalWebTestCase::drupalGetToken protected function Generate a token for the currently logged in user.
DrupalWebTestCase::drupalHead protected function Retrieves only the headers for a Drupal path or an absolute path.
DrupalWebTestCase::drupalLogin protected function Log in a user with the internal browser.
DrupalWebTestCase::drupalLogout protected function
DrupalWebTestCase::drupalPost protected function Execute a POST request on a Drupal page. It will be done as usual POST request with SimpleBrowser.
DrupalWebTestCase::drupalPostAJAX protected function Execute an Ajax submission.
DrupalWebTestCase::drupalSetContent protected function Sets the raw HTML content. This can be useful when a page has been fetched outside of the internal browser and assertions need to be made on the returned page.
DrupalWebTestCase::drupalSetSettings protected function Sets the value of the Drupal.settings JavaScript variable for the currently loaded page.
DrupalWebTestCase::getAbsoluteUrl protected function Takes a path and returns an absolute path.
DrupalWebTestCase::getAllOptions protected function Get all option elements, including nested options, in a select.
DrupalWebTestCase::getSelectedItem protected function Get the selected value from a select field.
DrupalWebTestCase::getSetupCacheKey protected function Returns the cache key used for the setup caching.
DrupalWebTestCase::getUrl protected function Get the current URL from the cURL handler.
DrupalWebTestCase::handleForm protected function Handle form input related to drupalPost(). Ensure that the specified fields exist and attempt to create POST data in the correct manner for the particular field type.
DrupalWebTestCase::loadSetupCache protected function Copies the cached tables and files for a cached installation setup.
DrupalWebTestCase::parse protected function Parse content returned from curlExec using DOM and SimpleXML.
DrupalWebTestCase::preloadRegistry protected function Preload the registry from the testing site.
DrupalWebTestCase::prepareDatabasePrefix protected function Generates a database prefix for running tests.
DrupalWebTestCase::prepareEnvironment protected function Prepares the current environment for running the test.
DrupalWebTestCase::recursiveDirectoryCopy protected function Recursively copy one directory to another.
DrupalWebTestCase::refreshVariables protected function Refresh the in-memory set of variables. Useful after a page request is made that changes a variable in a different thread. 1
DrupalWebTestCase::resetAll protected function Reset all data structures after having enabled new modules.
DrupalWebTestCase::storeSetupCache protected function Store the installation setup to a cache.
DrupalWebTestCase::tearDown protected function Delete created files and temporary files directory, delete the tables created by setUp(), and reset the database prefix. 6
DrupalWebTestCase::verboseEmail protected function Outputs to verbose the most recent $count emails sent.
DrupalWebTestCase::xpath protected function Perform an xpath search on the contents of the internal browser. The search is relative to the root element (HTML tag normally) of the page.
DrupalWebTestCase::__construct function Constructor for DrupalWebTestCase. Overrides DrupalTestCase::__construct 1
SimpleNewsAdministrationTestCase::getInfo static function Implement getInfo().
SimpleNewsAdministrationTestCase::setUp public function Overrides SimplenewsTestCase::setUp(). Overrides SimplenewsTestCase::setUp
SimpleNewsAdministrationTestCase::testCategorySettings function Test various combinations of newsletter category settings.
SimpleNewsAdministrationTestCase::testContentTypes function Test content type configuration.
SimpleNewsAdministrationTestCase::testSubscriptionManagement function Test newsletter subscription management.
SimplenewsTestCase::$mailadress_cache protected property
SimplenewsTestCase::$profile protected property The profile to install as a basis for testing. Overrides DrupalWebTestCase::$profile
SimplenewsTestCase::getRandomNewsletter function Select randomly one of the available newsletters.
SimplenewsTestCase::randomEmail function Generates a random email address.
SimplenewsTestCase::setAnonymousUserSubscription function Set anonymous user permission to subscribe.
SimplenewsTestCase::setAuthenticatedUserSubscription function Set authenticated user permission to subscribe.
SimplenewsTestCase::setUpSubscribers function
SimplenewsTestCase::setupSubscriptionBlock function Enable newsletter subscription block.