<?php
// $Id: poll.test,v 1.33 2010/04/22 23:59:04 dries Exp $

/**
 * @file
 * Tests for the poll module.
 */

class PollTestCase extends DrupalWebTestCase {

  /**
   * Creates a poll.
   *
   * @param string $title The title of the poll.
   * @param array $choices Choices.
   * @param boolean $test_preview Whether to test if the preview is working or not.
   * @return integer The nid of the created poll, or FALSE on error.
   */
  function pollCreate($title, $choices, $test_preview = TRUE) {
    $this->assertTrue(TRUE, 'Create a poll');

    $web_user = $this->drupalCreateUser(array('create poll content', 'access content'));
    $this->drupalLogin($web_user);

    // Get the form first to initialize the state of the internal browser
    $this->drupalGet('node/add/poll');

    // Prepare a form with two choices
    list($edit, $index) = $this->_pollGenerateEdit($title, $choices);

    if (count($choices) > 2) {
      // Re-submit the form while the choices are all in
      while ($index < count($choices)) {
        $this->drupalPost(NULL, $edit, t('More choices'));
        list($edit, $index) = $this->_pollGenerateEdit($title, $choices, $index);
      }
    }

    if ($test_preview) {
      $this->drupalPost(NULL, $edit, t('Preview'));
      foreach ($choices as $k => $choice_text) {
        $this->assertRaw($choice_text, t('Choice @choice found was in preview.', array('@choice' => $k)));
      }
      list($edit, $index) = $this->_pollGenerateEdit($title, $choices, $index);
    }

    $this->drupalPost(NULL, $edit, t('Save'));
    $node = $this->drupalGetNodeByTitle($title);
    $this->assertText(t('@type @title has been created.', array('@type' => node_type_get_name('poll'), '@title' => $title)), 'Poll has been created.');
    $this->assertTrue($node->nid, t('Poll has been found in the database.'));

    return isset($node->nid) ? $node->nid : FALSE;
  }

  function _pollGenerateEdit($title, $choices, $index = 0) {
    $max_new_choices = $index == 0 ? 2 : 5;
    $already_submitted_choices = array_slice($choices, 0, $index);
    $new_choices = array_values(array_slice($choices, $index, $max_new_choices));

    $langcode = LANGUAGE_NONE;
    $edit = array(
      "title" => $title
    );
    foreach ($already_submitted_choices as $k => $text) {
      $edit['choice[chid:' . $k . '][chtext]'] = $text;
    }
    foreach ($new_choices as $k => $text) {
      $edit['choice[new:' . $k . '][chtext]'] = $text;
    }
    return array($edit, count($already_submitted_choices) + count($new_choices));
  }

  function _generateChoices($count = 7) {
    $choices = array();
    for ($i = 1; $i <= $count; $i++) {
      $choices[] = $this->randomName();
    }
    return $choices;
  }

  function pollUpdate($nid, $title, $edit) {
    // Edit the poll node.
    $this->drupalPost('node/' . $nid . '/edit', $edit, t('Save'));
    $this->assertText(t('@type @title has been updated.', array('@type' => node_type_get_name('poll'), '@title' => $title)), 'Poll has been updated.');
  }
}

class PollCreateTestCase extends PollTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Poll create',
      'description' => 'Adds "more choices", previews and creates a poll.',
      'group' => 'Poll'
    );
  }

  function setUp() {
    parent::setUp('poll');
  }

  function testPollCreate() {
    $title = $this->randomName();
    $choices = $this->_generateChoices(7);
    $this->pollCreate($title, $choices, TRUE);

    // Verify poll appears on 'poll' page.
    $this->drupalGet('poll');
    $this->assertText($title, 'Poll appears in poll list.');
    $this->assertText('open', 'Poll is active.');

    // Click on the poll title to go to node page.
    $this->clickLink($title);
    $this->assertText('Total votes: 0', 'Link to poll correct.');
  }

  function testPollClose() {
    $content_user = $this->drupalCreateUser(array('create poll content', 'edit any poll content', 'access content'));
    $vote_user = $this->drupalCreateUser(array('cancel own vote', 'inspect all votes', 'vote on polls', 'access content'));

    // Create poll.
    $title = $this->randomName();
    $choices = $this->_generateChoices(7);
    $poll_nid = $this->pollCreate($title, $choices, FALSE);

    $this->drupalLogout();
    $this->drupalLogin($content_user);

    // Edit the poll node and close the poll.
    $close_edit = array('active' => 0);
    $this->pollUpdate($poll_nid, $title, $close_edit);

    // Verify 'Vote' button no longer appears.
    $this->drupalGet('node/' . $poll_nid);
    $elements = $this->xpath('//input[@id="edit-vote"]');
    $this->assertTrue(empty($elements), t("Vote button doesn't appear."));

    // Verify status on 'poll' page is 'closed'.
    $this->drupalGet('poll');
    $this->assertText($title, 'Poll appears in poll list.');
    $this->assertText('closed', 'Poll is closed.');

    // Edit the poll node and re-activate.
    $open_edit = array('active' => 1);
    $this->pollUpdate($poll_nid, $title, $open_edit);

    // Vote on the poll.
    $this->drupalLogout();
    $this->drupalLogin($vote_user);
    $vote_edit = array('choice' => '1');
    $this->drupalPost('node/' . $poll_nid, $vote_edit, t('Vote'));
    $this->assertText('Your vote was recorded.', 'Your vote was recorded.');
    $elements = $this->xpath('//input[@value="Cancel your vote"]');
    $this->assertTrue(isset($elements[0]), t("'Cancel your vote' button appears."));

    // Edit the poll node and close the poll.
    $this->drupalLogout();
    $this->drupalLogin($content_user);
    $close_edit = array('active' => 0);
    $this->pollUpdate($poll_nid, $title, $close_edit);

    // Verify 'Cancel your vote' button no longer appears.
    $this->drupalGet('node/' . $poll_nid);
    $elements = $this->xpath('//input[@value="Cancel your vote"]');
    $this->assertTrue(empty($elements), t("'Cancel your vote' button no longer appears."));
  }
}

class PollVoteTestCase extends PollTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Poll vote',
      'description' => 'Vote on a poll',
      'group' => 'Poll'
    );
  }

  function setUp() {
    parent::setUp('poll');
  }

  function tearDown() {
    parent::tearDown();
  }

  function testPollVote() {
    $title = $this->randomName();
    $choices = $this->_generateChoices(7);
    $poll_nid = $this->pollCreate($title, $choices, FALSE);
    $this->drupalLogout();

    $vote_user = $this->drupalCreateUser(array('cancel own vote', 'inspect all votes', 'vote on polls', 'access content'));
    $restricted_vote_user = $this->drupalCreateUser(array('vote on polls', 'access content'));

    $this->drupalLogin($vote_user);

    // Record a vote for the first choice.
    $edit = array(
      'choice' => '1',
    );
    $this->drupalPost('node/' . $poll_nid, $edit, t('Vote'));
    $this->assertText('Your vote was recorded.', 'Your vote was recorded.');
    $this->assertText('Total votes: 1', 'Vote count updated correctly.');
    $elements = $this->xpath('//input[@value="Cancel your vote"]');
    $this->assertTrue(isset($elements[0]), t("'Cancel your vote' button appears."));

    $this->drupalGet("node/$poll_nid/votes");
    $this->assertText(t('This table lists all the recorded votes for this poll. If anonymous users are allowed to vote, they will be identified by the IP address of the computer they used when they voted.'), 'Vote table text.');
    $this->assertText($choices[0], 'Vote recorded');

    // Ensure poll listing page has correct number of votes.
    $this->drupalGet('poll');
    $this->assertText($title, 'Poll appears in poll list.');
    $this->assertText('1 vote', 'Poll has 1 vote.');

    // Cancel a vote.
    $this->drupalPost('node/' . $poll_nid, array(), t('Cancel your vote'));
    $this->assertText('Your vote was cancelled.', 'Your vote was cancelled.');
    $this->assertNoText('Cancel your vote', "Cancel vote button doesn't appear.");

    $this->drupalGet("node/$poll_nid/votes");
    $this->assertNoText($choices[0], 'Vote cancelled');

    // Ensure poll listing page has correct number of votes.
    $this->drupalGet('poll');
    $this->assertText($title, 'Poll appears in poll list.');
    $this->assertText('0 votes', 'Poll has 0 votes.');

    // Log in as a user who can only vote on polls.
    $this->drupalLogout();
    $this->drupalLogin($restricted_vote_user);

    // Vote on a poll.
    $edit = array(
      'choice' => '1',
    );
    $this->drupalPost('node/' . $poll_nid, $edit, t('Vote'));
    $this->assertText('Your vote was recorded.', 'Your vote was recorded.');
    $this->assertText('Total votes: 1', 'Vote count updated correctly.');
    $elements = $this->xpath('//input[@value="Cancel your vote"]');
    $this->assertTrue(empty($elements), t("'Cancel your vote' button does not appear."));
  }
}

class PollBlockTestCase extends PollTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Block availability',
      'description' => 'Check if the most recent poll block is available.',
      'group' => 'Poll',
    );
  }

  function setUp() {
    parent::setUp('poll');

    // Create and login user
    $admin_user = $this->drupalCreateUser(array('administer blocks'));
    $this->drupalLogin($admin_user);
  }

  function testRecentBlock() {
    // Set block title to confirm that the interface is available.
    $this->drupalPost('admin/structure/block/manage/poll/recent/configure', array('title' => $this->randomName(8)), t('Save block'));
    $this->assertText(t('The block configuration has been saved.'), t('Block configuration set.'));

    // Set the block to a region to confirm block is available.
    $edit = array();
    $edit['poll_recent[region]'] = 'footer';
    $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
    $this->assertText(t('The block settings have been updated.'), t('Block successfully move to footer region.'));

    // Create a poll which should appear in recent polls block.
    $title = $this->randomName();
    $choices = $this->_generateChoices(7);
    $poll_nid = $this->pollCreate($title, $choices, TRUE);

    // Verify poll appears in a block.
    // View user page so we're not matching the poll node on front page.
    $this->drupalGet('user');
    // If a 'block' view not generated, this title would not appear even though
    // the choices might.
    $this->assertText($title, 'Poll appears in block.');

    // Logout and login back in as a user who can vote.
    $this->drupalLogout();
    $vote_user = $this->drupalCreateUser(array('cancel own vote', 'inspect all votes', 'vote on polls', 'access content'));
    $this->drupalLogin($vote_user);

    // Verify we can vote via the block.
    $edit = array(
      'choice' => '1',
    );
    $this->drupalPost('user/' . $vote_user->uid, $edit, t('Vote'));
    $this->assertText('Your vote was recorded.', 'Your vote was recorded.');
    $this->assertText('Total votes: 1', 'Vote count updated correctly.');
    $this->assertText('Older polls', 'Link to older polls appears.');
    $this->clickLink('Older polls');
    $this->assertText('1 vote - open', 'Link to poll listing correct.');

    // Close the poll and verify block doesn't appear.
    $content_user = $this->drupalCreateUser(array('create poll content', 'edit any poll content', 'access content'));
    $this->drupalLogout();
    $this->drupalLogin($content_user);
    $close_edit = array('active' => 0);
    $this->pollUpdate($poll_nid, $title, $close_edit);
    $this->drupalGet('user/' . $content_user->uid);
    $this->assertNoText($title, 'Poll no longer appears in block.');
  }
}

/**
 * Test adding new choices.
 */
class PollJSAddChoice extends DrupalWebTestCase {

  public static function getInfo() {
    return array(
      'name' => 'Poll add choice',
      'description' => 'Submits a POST request for an additional poll choice.',
      'group' => 'Poll'
    );
  }

  function setUp() {
    parent::setUp('poll');
  }

  /**
   * Test adding a new choice.
   */
  function testAddChoice() {
    $web_user = $this->drupalCreateUser(array('create poll content', 'access content'));
    $this->drupalLogin($web_user);
    $this->drupalGet('node/add/poll');
    $langcode = LANGUAGE_NONE;
    $edit = array(
      "title" => $this->randomName(),
      'choice[new:0][chtext]' => $this->randomName(),
      'choice[new:1][chtext]' => $this->randomName(),
    );

    // Press 'add choice' button through AJAX, and place the expected HTML result
    // as the tested content.
    $commands = $this->drupalPostAJAX(NULL, $edit, array('op' => t('More choices')));
    $this->content = $commands[1]['data'];

    $this->assertFieldByName('choice[chid:0][chtext]', $edit['choice[new:0][chtext]'], t('Field !i found', array('!i' => 0)));
    $this->assertFieldByName('choice[chid:1][chtext]', $edit['choice[new:1][chtext]'], t('Field !i found', array('!i' => 1)));
    $this->assertFieldByName('choice[new:0][chtext]', '', t('Field !i found', array('!i' => 2)));
  }
}

class PollVoteCheckHostname extends PollTestCase {
  public static function getInfo() {
    return array(
      'name' => 'User poll vote capability.',
      'description' => 'Check that users and anonymous users from specified ip-address can only vote once.',
      'group' => 'Poll'
    );
  }

  function setUp() {
    parent::setUp('poll');

    // Create and login user.
    $this->admin_user = $this->drupalCreateUser(array('administer permissions', 'create poll content'));
    $this->drupalLogin($this->admin_user);

    // Allow anonymous users to vote on polls.
    user_role_change_permissions(DRUPAL_ANONYMOUS_RID, array(
      'access content' => TRUE,
      'vote on polls' => TRUE,
      'cancel own vote' => TRUE,
    ));

    // Enable page cache to verify that the result page is not saved in the
    // cache when anonymous voting is allowed.
    variable_set('cache', CACHE_NORMAL);

    // Create poll.
    $title = $this->randomName();
    $choices = $this->_generateChoices(3);
    $this->poll_nid = $this->pollCreate($title, $choices, FALSE);

    $this->drupalLogout();

    // Create web users.
    $this->web_user1 = $this->drupalCreateUser(array('access content', 'vote on polls', 'cancel own vote'));
    $this->web_user2 = $this->drupalCreateUser(array('access content', 'vote on polls'));
  }

  /**
   * Check that anonymous users with same ip cannot vote on poll more than once
   * unless user is logged in.
   */
  function testHostnamePollVote() {
    // Login User1.
    $this->drupalLogin($this->web_user1);

    $edit = array(
      'choice' => '1',
    );

    // User1 vote on Poll.
    $this->drupalPost('node/' . $this->poll_nid, $edit, t('Vote'));
    $this->assertText(t('Your vote was recorded.'), t('%user vote was recorded.', array('%user' => $this->web_user1->name)));
    $this->assertText(t('Total votes: @votes', array('@votes' => 1)), t('Vote count updated correctly.'));

    // Check to make sure User1 cannot vote again.
    $this->drupalGet('node/' . $this->poll_nid);
    $elements = $this->xpath('//input[@value="Vote"]');
    $this->assertTrue(empty($elements), t("%user is not able to vote again.", array('%user' => $this->web_user1->name)));
    $elements = $this->xpath('//input[@value="Cancel your vote"]');
    $this->assertTrue(!empty($elements), t("'Cancel your vote' button appears."));

    // Logout User1.
    $this->drupalLogout();

    // Fill the page cache by requesting the poll.
    $this->drupalGet('node/' . $this->poll_nid);
    $this->assertEqual($this->drupalGetHeader('x-drupal-cache'), 'MISS', t('Page was cacheable but was not in the cache.'));
    $this->drupalGet('node/' . $this->poll_nid);
    $this->assertEqual($this->drupalGetHeader('x-drupal-cache'), 'HIT', t('Page was cached.'));

    // Anonymous user vote on Poll.
    $this->drupalPost(NULL, $edit, t('Vote'));
    $this->assertText(t('Your vote was recorded.'), t('Anonymous vote was recorded.'));
    $this->assertText(t('Total votes: @votes', array('@votes' => 2)), t('Vote count updated correctly.'));
    $elements = $this->xpath('//input[@value="Cancel your vote"]');
    $this->assertTrue(!empty($elements), t("'Cancel your vote' button appears."));

    // Check to make sure Anonymous user cannot vote again.
    $this->drupalGet('node/' . $this->poll_nid);
    $this->assertFalse($this->drupalGetHeader('x-drupal-cache'), t('Page was not cacheable.'));
    $elements = $this->xpath('//input[@value="Vote"]');
    $this->assertTrue(empty($elements), t("Anonymous is not able to vote again."));
    $elements = $this->xpath('//input[@value="Cancel your vote"]');
    $this->assertTrue(!empty($elements), t("'Cancel your vote' button appears."));

    // Login User2.
    $this->drupalLogin($this->web_user2);

    // User2 vote on poll.
    $this->drupalPost('node/' . $this->poll_nid, $edit, t('Vote'));
    $this->assertText(t('Your vote was recorded.'), t('%user vote was recorded.', array('%user' => $this->web_user2->name)));
    $this->assertText(t('Total votes: @votes', array('@votes' => 3)), 'Vote count updated correctly.');
    $elements = $this->xpath('//input[@value="Cancel your vote"]');
    $this->assertTrue(empty($elements), t("'Cancel your vote' button does not appear."));

    // Logout User2.
    $this->drupalLogout();

    // Change host name for anonymous users.
    db_update('poll_vote')
      ->fields(array(
        'hostname' => '123.456.789.1',
      ))
      ->condition('hostname', '', '<>')
      ->execute();

    // Check to make sure Anonymous user can vote again with a new session after
    // a hostname change.
    $this->drupalGet('node/' . $this->poll_nid);
    $this->assertEqual($this->drupalGetHeader('x-drupal-cache'), 'MISS', t('Page was cacheable but was not in the cache.'));
    $this->drupalPost(NULL, $edit, t('Vote'));
    $this->assertText(t('Your vote was recorded.'), t('%user vote was recorded.', array('%user' => $this->web_user2->name)));
    $this->assertText(t('Total votes: @votes', array('@votes' => 4)), 'Vote count updated correctly.');
    $elements = $this->xpath('//input[@value="Cancel your vote"]');
    $this->assertTrue(!empty($elements), t("'Cancel your vote' button appears."));

    // Check to make sure Anonymous user cannot vote again with a new session,
    // and that the vote from the previous session cannot be cancelledd.
    $this->curlClose();
    $this->drupalGet('node/' . $this->poll_nid);
    $this->assertEqual($this->drupalGetHeader('x-drupal-cache'), 'MISS', t('Page was cacheable but was not in the cache.'));
    $elements = $this->xpath('//input[@value="Vote"]');
    $this->assertTrue(empty($elements), t('Anonymous is not able to vote again.'));
    $elements = $this->xpath('//input[@value="Cancel your vote"]');
    $this->assertTrue(empty($elements), t("'Cancel your vote' button does not appear."));

    // Login User1.
    $this->drupalLogin($this->web_user1);

    // Check to make sure User1 still cannot vote even after hostname changed.
    $this->drupalGet('node/' . $this->poll_nid);
    $elements = $this->xpath('//input[@value="Vote"]');
    $this->assertTrue(empty($elements), t("%user is not able to vote again.", array('%user' => $this->web_user1->name)));
    $elements = $this->xpath('//input[@value="Cancel your vote"]');
    $this->assertTrue(!empty($elements), t("'Cancel your vote' button appears."));
  }
}

/**
 * Test poll token replacement in strings.
 */
class PollTokenReplaceTestCase extends PollTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Poll token replacement',
      'description' => 'Generates text using placeholders for dummy content to check poll token replacement.',
      'group' => 'Poll',
    );
  }

  function setUp() {
    parent::setUp('poll');
  }

  /**
   * Creates a poll, then tests the tokens generated from it.
   */
  function testPollTokenReplacement() {
    global $language;

    // Craete a poll with three choices.
    $title = $this->randomName();
    $choices = $this->_generateChoices(3);
    $poll_nid = $this->pollCreate($title, $choices, FALSE);
    $this->drupalLogout();

    // Create four users and have each of them vote.
    $vote_user1 = $this->drupalCreateUser(array('vote on polls', 'access content'));
    $this->drupalLogin($vote_user1);
    $edit = array(
      'choice' => '1',
    );
    $this->drupalPost('node/' . $poll_nid, $edit, t('Vote'));
    $this->drupalLogout();

    $vote_user2 = $this->drupalCreateUser(array('vote on polls', 'access content'));
    $this->drupalLogin($vote_user2);
    $edit = array(
      'choice' => '1',
    );
    $this->drupalPost('node/' . $poll_nid, $edit, t('Vote'));
    $this->drupalLogout();

    $vote_user3 = $this->drupalCreateUser(array('vote on polls', 'access content'));
    $this->drupalLogin($vote_user3);
    $edit = array(
      'choice' => '2',
    );
    $this->drupalPost('node/' . $poll_nid, $edit, t('Vote'));
    $this->drupalLogout();

    $vote_user4 = $this->drupalCreateUser(array('vote on polls', 'access content'));
    $this->drupalLogin($vote_user4);
    $edit = array(
      'choice' => '3',
    );
    $this->drupalPost('node/' . $poll_nid, $edit, t('Vote'));
    $this->drupalLogout();

    $poll = node_load($poll_nid, NULL, TRUE);

    // Generate and test sanitized tokens.
    $tests = array();
    $tests['[node:poll-votes]'] = 4;
    $tests['[node:poll-winner]'] = filter_xss($poll->choice[1]['chtext']);
    $tests['[node:poll-winner-votes]'] = 2;
    $tests['[node:poll-winner-percent]'] = 50;
    $tests['[node:poll-duration]'] = format_interval($poll->runtime, 1, $language->language);

    // Test to make sure that we generated something for each token.
    $this->assertFalse(in_array(0, array_map('strlen', $tests)), t('No empty tokens generated.'));

    foreach ($tests as $input => $expected) {
      $output = token_replace($input, array('node' => $poll), array('language' => $language));
      $this->assertFalse(strcmp($output, $expected), t('Sanitized poll token %token replaced.', array('%token' => $input)));
    }

    // Generate and test unsanitized tokens.
    $tests['[node:poll-winner]'] = $poll->choice[1]['chtext'];

    foreach ($tests as $input => $expected) {
      $output = token_replace($input, array('node' => $poll), array('language' => $language, 'sanitize' => FALSE));
      $this->assertFalse(strcmp($output, $expected), t('Unsanitized poll token %token replaced.', array('%token' => $input)));
    }
  }
}
