Projet

Général

Profil

Paste
Télécharger (33,2 ko) Statistiques
| Branche: | Révision:

root / htmltest / modules / poll / poll.test @ 85ad3d82

1
<?php
2

    
3
/**
4
 * @file
5
 * Tests for poll.module.
6
 */
7

    
8
class PollTestCase extends DrupalWebTestCase {
9

    
10
  /**
11
   * Creates a poll.
12
   *
13
   * @param string $title
14
   *   The title of the poll.
15
   * @param array $choices
16
   *   A list of choice labels.
17
   * @param boolean $preview
18
   *   (optional) Whether to test if the preview is working or not. Defaults to
19
   *   TRUE.
20
   *
21
   * @return
22
   *   The node id of the created poll, or FALSE on error.
23
   */
24
  function pollCreate($title, $choices, $preview = TRUE) {
25
    $this->assertTrue(TRUE, 'Create a poll');
26

    
27
    $admin_user = $this->drupalCreateUser(array('create poll content', 'administer nodes'));
28
    $web_user = $this->drupalCreateUser(array('create poll content', 'access content', 'edit own poll content'));
29
    $this->drupalLogin($admin_user);
30

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

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

    
37
    // Verify that the vote count element only allows non-negative integers.
38
    $edit['choice[new:1][chvotes]'] = -1;
39
    $edit['choice[new:0][chvotes]'] = $this->randomString(7);
40
    $this->drupalPost(NULL, $edit, t('Save'));
41
    $this->assertText(t('Negative values are not allowed.'));
42
    $this->assertText(t('Vote count for new choice must be an integer.'));
43

    
44
    // Repeat steps for initializing the state of the internal browser.
45
    $this->drupalLogin($web_user);
46
    $this->drupalGet('node/add/poll');
47
    list($edit, $index) = $this->_pollGenerateEdit($title, $choices);
48

    
49
    // Re-submit the form until all choices are filled in.
50
    if (count($choices) > 2) {
51
      while ($index < count($choices)) {
52
        $this->drupalPost(NULL, $edit, t('More choices'));
53
        $this->assertPollChoiceOrder($choices, $index);
54
        list($edit, $index) = $this->_pollGenerateEdit($title, $choices, $index);
55
      }
56
    }
57

    
58
    if ($preview) {
59
      $this->drupalPost(NULL, $edit, t('Preview'));
60
      $this->assertPollChoiceOrder($choices, $index, TRUE);
61
      list($edit, $index) = $this->_pollGenerateEdit($title, $choices, $index);
62
    }
63

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

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

    
72
  /**
73
   * Generates POST values for the poll node form, specifically poll choices.
74
   *
75
   * @param $title
76
   *   The title for the poll node.
77
   * @param $choices
78
   *   An array containing poll choices, as generated by
79
   *   PollTestCase::_generateChoices().
80
   * @param $index
81
   *   (optional) The amount/number of already submitted poll choices. Defaults
82
   *   to 0.
83
   *
84
   * @return
85
   *   An indexed array containing:
86
   *   - The generated POST values, suitable for
87
   *     DrupalWebTestCase::drupalPost().
88
   *   - The number of poll choices contained in 'edit', for potential re-usage
89
   *     in subsequent invocations of this function.
90
   */
91
  function _pollGenerateEdit($title, array $choices, $index = 0) {
92
    $max_new_choices = ($index == 0 ? 2 : 5);
93
    $already_submitted_choices = array_slice($choices, 0, $index);
94
    $new_choices = array_values(array_slice($choices, $index, $max_new_choices));
95

    
96
    $edit = array(
97
      'title' => $title,
98
    );
99
    foreach ($already_submitted_choices as $k => $text) {
100
      $edit['choice[chid:' . $k . '][chtext]'] = $text;
101
    }
102
    foreach ($new_choices as $k => $text) {
103
      $edit['choice[new:' . $k . '][chtext]'] = $text;
104
    }
105
    return array($edit, count($already_submitted_choices) + count($new_choices));
106
  }
107

    
108
  function _generateChoices($count = 7) {
109
    $choices = array();
110
    for ($i = 1; $i <= $count; $i++) {
111
      $choices[] = $this->randomName();
112
    }
113
    return $choices;
114
  }
115

    
116
  /**
117
   * Assert correct poll choice order in the node form after submission.
118
   *
119
   * Verifies both the order in the DOM and in the 'weight' form elements.
120
   *
121
   * @param $choices
122
   *   An array containing poll choices, as generated by
123
   *   PollTestCase::_generateChoices().
124
   * @param $index
125
   *   (optional) The amount/number of already submitted poll choices. Defaults
126
   *   to 0.
127
   * @param $preview
128
   *   (optional) Whether to also check the poll preview.
129
   *
130
   * @see PollTestCase::_pollGenerateEdit()
131
   */
132
  function assertPollChoiceOrder(array $choices, $index = 0, $preview = FALSE) {
133
    $expected = array();
134
    $weight = 0;
135
    foreach ($choices as $id => $label) {
136
      if ($id < $index) {
137
        // The expected weight of each choice is higher than the previous one.
138
        $weight++;
139
        // Directly assert the weight form element value for this choice.
140
        $this->assertFieldByName('choice[chid:' . $id . '][weight]', $weight, format_string('Found choice @id with weight @weight.', array(
141
          '@id' => $id,
142
          '@weight' => $weight,
143
        )));
144
        // Append to our (to be reversed) stack of labels.
145
        $expected[$weight] = $label;
146
      }
147
    }
148
    ksort($expected);
149

    
150
    // Verify DOM order of poll choices (i.e., #weight of form elements).
151
    $elements = $this->xpath('//input[starts-with(@name, :prefix) and contains(@name, :suffix)]', array(
152
      ':prefix' => 'choice[chid:',
153
      ':suffix' => '][chtext]',
154
    ));
155
    $expected_order = $expected;
156
    foreach ($elements as $element) {
157
      $next_label = array_shift($expected_order);
158
      $this->assertEqual((string) $element['value'], $next_label);
159
    }
160

    
161
    // If requested, also verify DOM order in preview.
162
    if ($preview) {
163
      $elements = $this->xpath('//div[contains(@class, :teaser)]/descendant::div[@class=:text]', array(
164
        ':teaser' => 'node-teaser',
165
        ':text' => 'text',
166
      ));
167
      $expected_order = $expected;
168
      foreach ($elements as $element) {
169
        $next_label = array_shift($expected_order);
170
        $this->assertEqual((string) $element, $next_label, format_string('Found choice @label in preview.', array(
171
          '@label' => $next_label,
172
        )));
173
      }
174
    }
175
  }
176

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

    
184
class PollCreateTestCase extends PollTestCase {
185
  public static function getInfo() {
186
    return array(
187
      'name' => 'Poll create',
188
      'description' => 'Adds "more choices", previews and creates a poll.',
189
      'group' => 'Poll'
190
    );
191
  }
192

    
193
  function setUp() {
194
    parent::setUp('poll');
195
  }
196

    
197
  function testPollCreate() {
198
    $title = $this->randomName();
199
    $choices = $this->_generateChoices(7);
200
    $poll_nid = $this->pollCreate($title, $choices, TRUE);
201

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

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

    
211
    // Now add a new option to make sure that when we update the node the
212
    // option is displayed.
213
    $node = node_load($poll_nid);
214

    
215
    $new_option = $this->randomName();
216

    
217
    $vote_count = '2000';
218
    $node->choice[] = array(
219
      'chid' => '',
220
      'chtext' => $new_option,
221
      'chvotes' => (int) $vote_count,
222
      'weight' => 1000,
223
    );
224

    
225
    node_save($node);
226

    
227
    $this->drupalGet('poll');
228
    $this->clickLink($title);
229
    $this->assertText($new_option, 'New option found.');
230

    
231
    $option = $this->xpath('//div[@id="node-1"]//div[@class="poll"]//div[@class="text"]');
232
    $this->assertEqual(end($option), $new_option, 'Last item is equal to new option.');
233

    
234
    $votes = $this->xpath('//div[@id="node-1"]//div[@class="poll"]//div[@class="percent"]');
235
    $this->assertTrue(strpos(end($votes), $vote_count) > 0, "Votes saved.");
236
  }
237

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

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

    
247
    $this->drupalLogout();
248
    $this->drupalLogin($content_user);
249

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

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

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

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

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

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

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

    
290
class PollVoteTestCase extends PollTestCase {
291
  public static function getInfo() {
292
    return array(
293
      'name' => 'Poll vote',
294
      'description' => 'Vote on a poll',
295
      'group' => 'Poll'
296
    );
297
  }
298

    
299
  function setUp() {
300
    parent::setUp('poll');
301
  }
302

    
303
  function tearDown() {
304
    parent::tearDown();
305
  }
306

    
307
  function testPollVote() {
308
    $title = $this->randomName();
309
    $choices = $this->_generateChoices(7);
310
    $poll_nid = $this->pollCreate($title, $choices, FALSE);
311
    $this->drupalLogout();
312

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

    
316
    $this->drupalLogin($vote_user);
317

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

    
328
    $this->drupalGet("node/$poll_nid/votes");
329
    $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.');
330
    $this->assertText($choices[0], 'Vote recorded');
331

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

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

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

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

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

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

    
366
class PollBlockTestCase extends PollTestCase {
367
  public static function getInfo() {
368
    return array(
369
      'name' => 'Block availability',
370
      'description' => 'Check if the most recent poll block is available.',
371
      'group' => 'Poll',
372
    );
373
  }
374

    
375
  function setUp() {
376
    parent::setUp('poll');
377

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

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

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

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

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

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

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

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

    
433
/**
434
 * Test adding new choices.
435
 */
436
class PollJSAddChoice extends DrupalWebTestCase {
437

    
438
  public static function getInfo() {
439
    return array(
440
      'name' => 'Poll add choice',
441
      'description' => 'Submits a POST request for an additional poll choice.',
442
      'group' => 'Poll'
443
    );
444
  }
445

    
446
  function setUp() {
447
    parent::setUp('poll');
448
  }
449

    
450
  /**
451
   * Test adding a new choice.
452
   */
453
  function testAddChoice() {
454
    $web_user = $this->drupalCreateUser(array('create poll content', 'access content'));
455
    $this->drupalLogin($web_user);
456
    $this->drupalGet('node/add/poll');
457
    $edit = array(
458
      "title" => $this->randomName(),
459
      'choice[new:0][chtext]' => $this->randomName(),
460
      'choice[new:1][chtext]' => $this->randomName(),
461
    );
462

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

    
468
    $this->assertFieldByName('choice[chid:0][chtext]', $edit['choice[new:0][chtext]'], format_string('Field !i found', array('!i' => 0)));
469
    $this->assertFieldByName('choice[chid:1][chtext]', $edit['choice[new:1][chtext]'], format_string('Field !i found', array('!i' => 1)));
470
    $this->assertFieldByName('choice[new:0][chtext]', '', format_string('Field !i found', array('!i' => 2)));
471
  }
472
}
473

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

    
483
  function setUp() {
484
    parent::setUp('poll');
485

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

    
490
    // Allow anonymous users to vote on polls.
491
    user_role_change_permissions(DRUPAL_ANONYMOUS_RID, array(
492
      'access content' => TRUE,
493
      'vote on polls' => TRUE,
494
      'cancel own vote' => TRUE,
495
    ));
496

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

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

    
506
    $this->drupalLogout();
507

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

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

    
521
    $edit = array(
522
      'choice' => '1',
523
    );
524

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

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

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

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

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

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

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

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

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

    
574
    // Change host name for anonymous users.
575
    db_update('poll_vote')
576
      ->fields(array(
577
        'hostname' => '123.456.789.1',
578
      ))
579
      ->condition('hostname', '', '<>')
580
      ->execute();
581

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

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

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

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

    
614
/**
615
 * Test poll token replacement in strings.
616
 */
617
class PollTokenReplaceTestCase extends PollTestCase {
618
  public static function getInfo() {
619
    return array(
620
      'name' => 'Poll token replacement',
621
      'description' => 'Generates text using placeholders for dummy content to check poll token replacement.',
622
      'group' => 'Poll',
623
    );
624
  }
625

    
626
  function setUp() {
627
    parent::setUp('poll');
628
  }
629

    
630
  /**
631
   * Creates a poll, then tests the tokens generated from it.
632
   */
633
  function testPollTokenReplacement() {
634
    global $language;
635

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

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

    
651
    $vote_user2 = $this->drupalCreateUser(array('vote on polls', 'access content'));
652
    $this->drupalLogin($vote_user2);
653
    $edit = array(
654
      'choice' => '1',
655
    );
656
    $this->drupalPost('node/' . $poll_nid, $edit, t('Vote'));
657
    $this->drupalLogout();
658

    
659
    $vote_user3 = $this->drupalCreateUser(array('vote on polls', 'access content'));
660
    $this->drupalLogin($vote_user3);
661
    $edit = array(
662
      'choice' => '2',
663
    );
664
    $this->drupalPost('node/' . $poll_nid, $edit, t('Vote'));
665
    $this->drupalLogout();
666

    
667
    $vote_user4 = $this->drupalCreateUser(array('vote on polls', 'access content'));
668
    $this->drupalLogin($vote_user4);
669
    $edit = array(
670
      'choice' => '3',
671
    );
672
    $this->drupalPost('node/' . $poll_nid, $edit, t('Vote'));
673
    $this->drupalLogout();
674

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

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

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

    
688
    foreach ($tests as $input => $expected) {
689
      $output = token_replace($input, array('node' => $poll), array('language' => $language));
690
      $this->assertEqual($output, $expected, format_string('Sanitized poll token %token replaced.', array('%token' => $input)));
691
    }
692

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

    
696
    foreach ($tests as $input => $expected) {
697
      $output = token_replace($input, array('node' => $poll), array('language' => $language, 'sanitize' => FALSE));
698
      $this->assertEqual($output, $expected, format_string('Unsanitized poll token %token replaced.', array('%token' => $input)));
699
    }
700
  }
701
}
702

    
703
class PollExpirationTestCase extends PollTestCase {
704
  public static function getInfo() {
705
    return array(
706
      'name' => 'Poll expiration',
707
      'description' => 'Test the poll auto-expiration logic.',
708
      'group' => 'Poll',
709
    );
710
  }
711

    
712
  function setUp() {
713
    parent::setUp('poll');
714
  }
715

    
716
  function testAutoExpire() {
717
    // Set up a poll.
718
    $title = $this->randomName();
719
    $choices = $this->_generateChoices(2);
720
    $poll_nid = $this->pollCreate($title, $choices, FALSE);
721
    $this->assertTrue($poll_nid, 'Poll for auto-expire test created.');
722

    
723
    // Visit the poll edit page and verify that by default, expiration
724
    // is set to unlimited.
725
    $this->drupalGet("node/$poll_nid/edit");
726
    $this->assertField('runtime', 'Poll expiration setting found.');
727
    $elements = $this->xpath('//select[@id="edit-runtime"]/option[@selected="selected"]');
728
    $this->assertTrue(isset($elements[0]['value']) && $elements[0]['value'] == 0, 'Poll expiration set to unlimited.');
729

    
730
    // Set the expiration to one week.
731
    $edit = array();
732
    $poll_expiration = 604800; // One week.
733
    $edit['runtime'] = $poll_expiration;
734
    $this->drupalPost(NULL, $edit, t('Save'));
735
    $this->assertRaw(t('Poll %title has been updated.', array('%title' => $title)), 'Poll expiration settings saved.');
736

    
737
    // Make sure that the changed expiration settings is kept.
738
    $this->drupalGet("node/$poll_nid/edit");
739
    $elements = $this->xpath('//select[@id="edit-runtime"]/option[@selected="selected"]');
740
    $this->assertTrue(isset($elements[0]['value']) && $elements[0]['value'] == $poll_expiration, 'Poll expiration set to unlimited.');
741

    
742
    // Force a cron run. Since the expiration date has not yet been reached,
743
    // the poll should remain active.
744
    drupal_cron_run();
745
    $this->drupalGet("node/$poll_nid/edit");
746
    $elements = $this->xpath('//input[@id="edit-active-1"]');
747
    $this->assertTrue(isset($elements[0]) && !empty($elements[0]['checked']), 'Poll is still active.');
748

    
749
    // Test expiration. Since REQUEST_TIME is a constant and we don't
750
    // want to keep SimpleTest waiting until the moment of expiration arrives,
751
    // we forcibly change the expiration date in the database.
752
    $created = db_query('SELECT created FROM {node} WHERE nid = :nid', array(':nid' => $poll_nid))->fetchField();
753
    db_update('node')
754
      ->fields(array('created' => $created - ($poll_expiration * 1.01)))
755
      ->condition('nid', $poll_nid)
756
      ->execute();
757

    
758
    // Run cron and verify that the poll is now marked as "closed".
759
    drupal_cron_run();
760
    $this->drupalGet("node/$poll_nid/edit");
761
    $elements = $this->xpath('//input[@id="edit-active-0"]');
762
    $this->assertTrue(isset($elements[0]) && !empty($elements[0]['checked']), 'Poll has expired.');
763
  }
764
}
765

    
766
class PollDeleteChoiceTestCase extends PollTestCase {
767
  public static function getInfo() {
768
    return array(
769
      'name' => 'Poll choice deletion',
770
      'description' => 'Test the poll choice deletion logic.',
771
      'group' => 'Poll',
772
    );
773
  }
774

    
775
  function setUp() {
776
    parent::setUp('poll');
777
  }
778

    
779
  function testChoiceRemoval() {
780
    // Set up a poll with three choices.
781
    $title = $this->randomName();
782
    $choices = array('First choice', 'Second choice', 'Third choice');
783
    $poll_nid = $this->pollCreate($title, $choices, FALSE);
784
    $this->assertTrue($poll_nid, 'Poll for choice deletion logic test created.');
785

    
786
    // Edit the poll, and try to delete first poll choice.
787
    $this->drupalGet("node/$poll_nid/edit");
788
    $edit['choice[chid:1][chtext]'] = '';
789
    $this->drupalPost(NULL, $edit, t('Save'));
790

    
791
    // Click on the poll title to go to node page.
792
    $this->drupalGet('poll');
793
    $this->clickLink($title);
794

    
795
    // Check the first poll choice is deleted, while the others remain.
796
    $this->assertNoText('First choice', 'First choice removed.');
797
    $this->assertText('Second choice', 'Second choice remains.');
798
    $this->assertText('Third choice', 'Third choice remains.');
799
  }
800
}
801

    
802
/**
803
 * Tests poll translation logic.
804
 */
805
class PollTranslateTestCase extends PollTestCase {
806
  public static function getInfo() {
807
    return array(
808
      'name' => 'Poll translation',
809
      'description' => 'Test the poll translation logic.',
810
      'group' => 'Poll',
811
    );
812
  }
813

    
814
  function setUp() {
815
    parent::setUp('poll', 'translation');
816
  }
817

    
818
  /**
819
   * Tests poll creation and translation.
820
   *
821
   * Checks that the choice names get copied from the original poll and that
822
   * the vote count values are set to 0.
823
   */
824
  function testPollTranslate() {
825
    $admin_user = $this->drupalCreateUser(array('administer content types', 'administer languages', 'edit any poll content', 'create poll content', 'administer nodes', 'translate content'));
826

    
827
    // Set up a poll with two choices.
828
    $title = $this->randomName();
829
    $choices = array($this->randomName(), $this->randomName());
830
    $poll_nid = $this->pollCreate($title, $choices, FALSE);
831
    $this->assertTrue($poll_nid, 'Poll for translation logic test created.');
832

    
833
    $this->drupalLogout();
834
    $this->drupalLogin($admin_user);
835

    
836
    // Enable a second language.
837
    $this->drupalGet('admin/config/regional/language');
838
    $edit = array();
839
    $edit['langcode'] = 'nl';
840
    $this->drupalPost('admin/config/regional/language/add', $edit, t('Add language'));
841
    $this->assertRaw(t('The language %language has been created and can now be used.', array('%language' => 'Dutch')), 'Language Dutch has been created.');
842

    
843
    // Set "Poll" content type to use multilingual support with translation.
844
    $this->drupalGet('admin/structure/types/manage/poll');
845
    $edit = array();
846
    $edit['language_content_type'] = 2;
847
    $this->drupalPost('admin/structure/types/manage/poll', $edit, t('Save content type'));
848
    $this->assertRaw(t('The content type %type has been updated.', array('%type' => 'Poll')), 'Poll content type has been updated.');
849

    
850
    // Edit poll.
851
    $this->drupalGet("node/$poll_nid/edit");
852
    $edit = array();
853
    // Set the poll's first choice count to 200.
854
    $edit['choice[chid:1][chvotes]'] = 200;
855
    // Set the language to Dutch.
856
    $edit['language'] = 'nl';
857
    $this->drupalPost(NULL, $edit, t('Save'));
858

    
859
    // Translate the Dutch poll.
860
    $this->drupalGet('node/add/poll', array('query' => array('translation' => $poll_nid, 'target' => 'en')));
861

    
862
    $dutch_poll = node_load($poll_nid);
863

    
864
    // Check that the vote count values didn't get copied from the Dutch poll
865
    // and are set to 0.
866
    $this->assertFieldByName('choice[chid:1][chvotes]', '0', ('Found choice with vote count 0'));
867
    $this->assertFieldByName('choice[chid:2][chvotes]', '0', ('Found choice with vote count 0'));
868
    // Check that the choice names got copied from the Dutch poll.
869
    $this->assertFieldByName('choice[chid:1][chtext]', $dutch_poll->choice[1]['chtext'], format_string('Found choice with text @text', array('@text' => $dutch_poll->choice[1]['chtext'])));
870
    $this->assertFieldByName('choice[chid:2][chtext]', $dutch_poll->choice[2]['chtext'], format_string('Found choice with text @text', array('@text' => $dutch_poll->choice[2]['chtext'])));
871
  }
872
}