drupal_web_test_case.php 90.2 KB
Newer Older
1
2
3
4
<?php
// $Id$

/**
5
6
7
 * Base class for Drupal tests.
 *
 * Do not extend this class, use one of the subclasses in this file.
8
 */
9
abstract class DrupalTestCase {
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
  /**
   * The test run ID.
   *
   * @var string
   */
  protected $testId;

  /**
   * The original database prefix, before it was changed for testing purposes.
   *
   * @var string
   */
  protected $originalPrefix = NULL;

  /**
   * The original file directory, before it was changed for testing purposes.
   *
   * @var string
   */
  protected $originalFileDirectory = NULL;

31
  /**
32
   * Time limit for the test.
33
   */
34
  protected $timeLimit = 500;
35

36
37
38
39
40
41
42
43
44
  /**
   * Current results of this test case.
   *
   * @var Array
   */
  public $results = array(
    '#pass' => 0,
    '#fail' => 0,
    '#exception' => 0,
45
    '#debug' => 0,
46
47
48
49
50
51
52
53
  );

  /**
   * Assertions thrown in that test case.
   *
   * @var Array
   */
  protected $assertions = array();
54

55
  /**
56
57
58
59
60
61
   * This class is skipped when looking for the source of an assertion.
   *
   * When displaying which function an assert comes from, it's not too useful
   * to see "drupalWebTestCase->drupalLogin()', we would like to see the test
   * that called it. So we need to skip the classes defining these helper
   * methods.
62
   */
63
  protected $skipClasses = array(__CLASS__ => TRUE);
64

65
66
67
  /**
   * Constructor for DrupalWebTestCase.
   *
68
   * @param $test_id
69
70
   *   Tests with the same id are reported together.
   */
71
72
  public function __construct($test_id = NULL) {
    $this->testId = $test_id;
73
74
75
  }

  /**
76
   * Internal helper: stores the assert.
77
78
   *
   * @param $status
79
80
   *   Can be 'pass', 'fail', 'exception'.
   *   TRUE is a synonym for 'pass', FALSE for 'fail'.
81
82
83
   * @param $message
   *   The message string.
   * @param $group
84
   *   Which group this assert belongs to.
85
   * @param $caller
86
   *   By default, the assert comes from a function whose name starts with
87
   *   'test'. Instead, you can specify where this assert originates from
88
   *   by passing in an associative array as $caller. Key 'file' is
89
90
91
   *   the name of the source file, 'line' is the line number and 'function'
   *   is the caller function itself.
   */
92
  protected function assert($status, $message = '', $group = 'Other', array $caller = NULL) {
93
    global $db_prefix;
94
95

    // Convert boolean status to string status.
96
97
98
    if (is_bool($status)) {
      $status = $status ? 'pass' : 'fail';
    }
99
100

    // Increment summary result counter.
101
    $this->results['#' . $status]++;
102
103
104
105

    // Get the function information about the call to the assertion method.
    if (!$caller) {
      $caller = $this->getAssertionCall();
106
    }
107
108

    // Switch to non-testing database to store results in.
109
    $current_db_prefix = $db_prefix;
110
    $db_prefix = $this->originalPrefix;
111
112

    // Creation assertion array that can be displayed while tests are running.
113
114
    $this->assertions[] = $assertion = array(
      'test_id' => $this->testId,
115
      'test_class' => get_class($this),
116
117
      'status' => $status,
      'message' => $message,
118
119
120
121
      'message_group' => $group,
      'function' => $caller['function'],
      'line' => $caller['line'],
      'file' => $caller['file'],
122
    );
123
124

    // Store assertion for display after the test has completed.
125
126
127
    db_insert('simpletest')
      ->fields($assertion)
      ->execute();
128
129

    // Return to testing prefix.
130
    $db_prefix = $current_db_prefix;
131
132
133
134
135
136
137
138
    // We do not use a ternary operator here to allow a breakpoint on
    // test failure.
    if ($status == 'pass') {
      return TRUE;
    }
    else {
      return FALSE;
    }
139
140
  }

141
  /**
142
143
144
145
146
147
148
149
   * Store an assertion from outside the testing context.
   *
   * This is useful for inserting assertions that can only be recorded after
   * the test case has been destroyed, such as PHP fatal errors. The caller
   * information is not automatically gathered since the caller is most likely
   * inserting the assertion on behalf of other code. In all other respects
   * the method behaves just like DrupalTestCase::assert() in terms of storing
   * the assertion.
150
   *
151
152
153
   * @return
   *   Message ID of the stored assertion.
   *
154
   * @see DrupalTestCase::assert()
155
   * @see DrupalTestCase::deleteAssert()
156
   */
157
  public static function insertAssert($test_id, $test_class, $status, $message = '', $group = 'Other', array $caller = array()) {
158
159
160
161
162
163
    // Convert boolean status to string status.
    if (is_bool($status)) {
      $status = $status ? 'pass' : 'fail';
    }

    $caller += array(
164
165
166
      'function' => t('Unknown'),
      'line' => 0,
      'file' => t('Unknown'),
167
168
169
170
171
172
173
174
175
176
177
178
179
    );

    $assertion = array(
      'test_id' => $test_id,
      'test_class' => $test_class,
      'status' => $status,
      'message' => $message,
      'message_group' => $group,
      'function' => $caller['function'],
      'line' => $caller['line'],
      'file' => $caller['file'],
    );

180
    return db_insert('simpletest')
181
182
183
184
      ->fields($assertion)
      ->execute();
  }

185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
  /**
   * Delete an assertion record by message ID.
   * 
   * @param $message_id
   *   Message ID of the assertion to delete.
   * @return
   *   TRUE if the assertion was deleted, FALSE otherwise.
   * 
   * @see DrupalTestCase::insertAssert()
   */
  public static function deleteAssert($message_id) {
    return (bool) db_delete('simpletest')
      ->condition('message_id', $message_id)
      ->execute();
  }

201
202
203
204
205
206
207
208
209
210
  /**
   * Cycles through backtrace until the first non-assertion method is found.
   *
   * @return
   *   Array representing the true caller.
   */
  protected function getAssertionCall() {
    $backtrace = debug_backtrace();

    // The first element is the call. The second element is the caller.
211
    // We skip calls that occurred in one of the methods of our base classes
212
    // or in an assertion function.
213
214
215
   while (($caller = $backtrace[1]) &&
         ((isset($caller['class']) && isset($this->skipClasses[$caller['class']])) ||
           substr($caller['function'], 0, 6) == 'assert')) {
216
217
218
219
220
221
222
      // We remove that call.
      array_shift($backtrace);
    }

    return _drupal_get_last_caller($backtrace);
  }

223
224
225
226
227
228
229
230
231
232
  /**
   * Check to see if a value is not false (not an empty string, 0, NULL, or FALSE).
   *
   * @param $value
   *   The value on which the assertion is to be done.
   * @param $message
   *   The message to display along with the assertion.
   * @param $group
   *   The type of assertion - examples are "Browser", "PHP".
   * @return
233
   *   TRUE if the assertion succeeded, FALSE otherwise.
234
235
   */
  protected function assertTrue($value, $message = '', $group = 'Other') {
236
    return $this->assert((bool) $value, $message ? $message : t('Value @value is TRUE.', array('@value' => var_export($value, TRUE))), $group);
237
238
239
240
241
242
243
244
245
246
247
248
  }

  /**
   * Check to see if a value is false (an empty string, 0, NULL, or FALSE).
   *
   * @param $value
   *   The value on which the assertion is to be done.
   * @param $message
   *   The message to display along with the assertion.
   * @param $group
   *   The type of assertion - examples are "Browser", "PHP".
   * @return
249
   *   TRUE if the assertion succeeded, FALSE otherwise.
250
251
   */
  protected function assertFalse($value, $message = '', $group = 'Other') {
252
    return $this->assert(!$value, $message ? $message : t('Value @value is FALSE.', array('@value' => var_export($value, TRUE))), $group);
253
254
255
256
257
258
259
260
261
262
263
264
  }

  /**
   * Check to see if a value is NULL.
   *
   * @param $value
   *   The value on which the assertion is to be done.
   * @param $message
   *   The message to display along with the assertion.
   * @param $group
   *   The type of assertion - examples are "Browser", "PHP".
   * @return
265
   *   TRUE if the assertion succeeded, FALSE otherwise.
266
267
   */
  protected function assertNull($value, $message = '', $group = 'Other') {
268
    return $this->assert(!isset($value), $message ? $message : t('Value @value is NULL.', array('@value' => var_export($value, TRUE))), $group);
269
270
271
272
273
274
275
276
277
278
279
280
  }

  /**
   * Check to see if a value is not NULL.
   *
   * @param $value
   *   The value on which the assertion is to be done.
   * @param $message
   *   The message to display along with the assertion.
   * @param $group
   *   The type of assertion - examples are "Browser", "PHP".
   * @return
281
   *   TRUE if the assertion succeeded, FALSE otherwise.
282
283
   */
  protected function assertNotNull($value, $message = '', $group = 'Other') {
284
    return $this->assert(isset($value), $message ? $message : t('Value @value is not NULL.', array('@value' => var_export($value, TRUE))), $group);
285
286
287
288
289
290
291
292
293
294
295
296
297
298
  }

  /**
   * Check to see if two values are equal.
   *
   * @param $first
   *   The first value to check.
   * @param $second
   *   The second value to check.
   * @param $message
   *   The message to display along with the assertion.
   * @param $group
   *   The type of assertion - examples are "Browser", "PHP".
   * @return
299
   *   TRUE if the assertion succeeded, FALSE otherwise.
300
301
   */
  protected function assertEqual($first, $second, $message = '', $group = 'Other') {
302
    return $this->assert($first == $second, $message ? $message : t('Value @first is equal to value @second.', array('@first' => var_export($first, TRUE), '@second' => var_export($second, TRUE))), $group);
303
304
305
306
307
308
309
310
311
312
313
314
315
316
  }

  /**
   * Check to see if two values are not equal.
   *
   * @param $first
   *   The first value to check.
   * @param $second
   *   The second value to check.
   * @param $message
   *   The message to display along with the assertion.
   * @param $group
   *   The type of assertion - examples are "Browser", "PHP".
   * @return
317
   *   TRUE if the assertion succeeded, FALSE otherwise.
318
319
   */
  protected function assertNotEqual($first, $second, $message = '', $group = 'Other') {
320
    return $this->assert($first != $second, $message ? $message : t('Value @first is not equal to value @second.', array('@first' => var_export($first, TRUE), '@second' => var_export($second, TRUE))), $group);
321
322
323
324
325
326
327
328
329
330
331
332
333
334
  }

  /**
   * Check to see if two values are identical.
   *
   * @param $first
   *   The first value to check.
   * @param $second
   *   The second value to check.
   * @param $message
   *   The message to display along with the assertion.
   * @param $group
   *   The type of assertion - examples are "Browser", "PHP".
   * @return
335
   *   TRUE if the assertion succeeded, FALSE otherwise.
336
337
   */
  protected function assertIdentical($first, $second, $message = '', $group = 'Other') {
338
    return $this->assert($first === $second, $message ? $message : t('Value @first is identical to value @second.', array('@first' => var_export($first, TRUE), '@second' => var_export($second, TRUE))), $group);
339
340
341
342
343
344
345
346
347
348
349
350
351
352
  }

  /**
   * Check to see if two values are not identical.
   *
   * @param $first
   *   The first value to check.
   * @param $second
   *   The second value to check.
   * @param $message
   *   The message to display along with the assertion.
   * @param $group
   *   The type of assertion - examples are "Browser", "PHP".
   * @return
353
   *   TRUE if the assertion succeeded, FALSE otherwise.
354
355
   */
  protected function assertNotIdentical($first, $second, $message = '', $group = 'Other') {
356
    return $this->assert($first !== $second, $message ? $message : t('Value @first is not identical to value @second.', array('@first' => var_export($first, TRUE), '@second' => var_export($second, TRUE))), $group);
357
358
359
360
361
362
363
364
365
366
367
368
369
  }

  /**
   * Fire an assertion that is always positive.
   *
   * @param $message
   *   The message to display along with the assertion.
   * @param $group
   *   The type of assertion - examples are "Browser", "PHP".
   * @return
   *   TRUE.
   */
  protected function pass($message = NULL, $group = 'Other') {
370
    return $this->assert(TRUE, $message, $group);
371
372
  }

373
  /**
374
   * Fire an assertion that is always negative.
375
   *
376
377
378
379
380
381
382
383
   * @param $message
   *   The message to display along with the assertion.
   * @param $group
   *   The type of assertion - examples are "Browser", "PHP".
   * @return
   *   FALSE.
   */
  protected function fail($message = NULL, $group = 'Other') {
384
    return $this->assert(FALSE, $message, $group);
385
386
387
388
389
390
391
392
393
  }

  /**
   * Fire an error assertion.
   *
   * @param $message
   *   The message to display along with the assertion.
   * @param $group
   *   The type of assertion - examples are "Browser", "PHP".
394
   * @param $caller
395
   *   The caller of the error.
396
397
   * @return
   *   FALSE.
398
   */
399
  protected function error($message = '', $group = 'Other', array $caller = NULL) {
400
401
402
403
404
405
    if ($group == 'User notice') {
      // Since 'User notice' is set by trigger_error() which is used for debug
      // set the message to a status of 'debug'.
      return $this->assert('debug', $message, 'Debug', $caller);
    }

406
    return $this->assert('exception', $message, $group, $caller);
407
408
409
410
  }

  /**
   * Run all tests in this class.
411
   */
412
  public function run() {
413
    // Initialize verbose debugging.
414
    simpletest_verbose(NULL, file_directory_path(), get_class($this));
415

416
417
    // HTTP auth settings (<username>:<password>) for the simpletest browser
    // when sending requests to the test site.
418
419
420
421
422
    $username = variable_get('simpletest_username', NULL);
    $password = variable_get('simpletest_password', NULL);
    if ($username && $password) {
      $this->httpauth_credentials = $username . ':' . $password;
    }
423

424
    set_error_handler(array($this, 'errorHandler'));
425
    $class = get_class($this);
426
    // Iterate through all the methods in this class.
427
    foreach (get_class_methods($class) as $method) {
428
429
      // If the current method starts with "test", run it - it's a test.
      if (strtolower(substr($method, 0, 4)) == 'test') {
430
431
432
433
434
435
436
437
438
        // Insert a fail record. This will be deleted on completion to ensure
        // that testing completed.
        $method_info = new ReflectionMethod($class, $method);
        $caller = array(
          'file' => $method_info->getFileName(),
          'line' => $method_info->getStartLine(),
          'function' => $class . '->' . $method . '()',
        );
        $completion_check_id = DrupalTestCase::insertAssert($this->testId, $class, FALSE, t('The test did not complete due to a fatal error.'), 'Completion check', $caller);
439
        $this->setUp();
440
441
442
443
444
445
446
        try {
          $this->$method();
          // Finish up.
        }
        catch (Exception $e) {
          $this->exceptionHandler($e);
        }
447
        $this->tearDown();
448
449
        // Remove the completion check record.
        DrupalTestCase::deleteAssert($completion_check_id);
450
451
      }
    }
452
453
    // Clear out the error messages and restore error handler.
    drupal_get_messages();
454
455
456
457
    restore_error_handler();
  }

  /**
458
   * Handle errors during test runs.
459
   *
460
   * Because this is registered in set_error_handler(), it has to be public.
461
462
   * @see set_error_handler
   */
463
  public function errorHandler($severity, $message, $file = NULL, $line = NULL) {
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
    if ($severity & error_reporting()) {
      $error_map = array(
        E_STRICT => 'Run-time notice',
        E_WARNING => 'Warning',
        E_NOTICE => 'Notice',
        E_CORE_ERROR => 'Core error',
        E_CORE_WARNING => 'Core warning',
        E_USER_ERROR => 'User error',
        E_USER_WARNING => 'User warning',
        E_USER_NOTICE => 'User notice',
        E_RECOVERABLE_ERROR => 'Recoverable error',
      );

      $backtrace = debug_backtrace();
      $this->error($message, $error_map[$severity], _drupal_get_last_caller($backtrace));
    }
480
    return TRUE;
481
482
  }

483
484
485
486
487
  /**
   * Handle exceptions.
   *
   * @see set_exception_handler
   */
488
  protected function exceptionHandler($exception) {
489
490
491
492
493
494
495
496
497
    $backtrace = $exception->getTrace();
    // Push on top of the backtrace the call that generated the exception.
    array_unshift($backtrace, array(
      'line' => $exception->getLine(),
      'file' => $exception->getFile(),
    ));
    $this->error($exception->getMessage(), 'Uncaught exception', _drupal_get_last_caller($backtrace));
  }

498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
  /**
   * Generates a random string of ASCII characters of codes 32 to 126.
   *
   * The generated string includes alpha-numeric characters and common misc
   * characters. Use this method when testing general input where the content
   * is not restricted.
   *
   * @param $length
   *   Length of random string to generate which will be appended to $db_prefix.
   * @return
   *   Randomly generated string.
   */
  public static function randomString($length = 8) {
    global $db_prefix;

    $str = '';
    for ($i = 0; $i < $length; $i++) {
      $str .= chr(mt_rand(32, 126));
    }
    return str_replace('simpletest', 's', $db_prefix) . $str;
  }

  /**
   * Generates a random string containing letters and numbers.
   *
   * The letters may be upper or lower case. This method is better for
   * restricted inputs that do not accept certain characters. For example,
   * when testing input fields that require machine readable values (ie without
   * spaces and non-standard characters) this method is best.
   *
   * @param $length
   *   Length of random string to generate which will be appended to $db_prefix.
   * @return
   *   Randomly generated string.
   */
  public static function randomName($length = 8) {
    global $db_prefix;

    $values = array_merge(range(65, 90), range(97, 122), range(48, 57));
    $max = count($values) - 1;
    $str = '';
    for ($i = 0; $i < $length; $i++) {
      $str .= chr($values[mt_rand(0, $max)]);
    }
    return str_replace('simpletest', 's', $db_prefix) . $str;
  }

}

/**
 * Test case for Drupal unit tests.
 *
 * These tests can not access the database nor files. Calling any Drupal
 * function that needs the database will throw exceptions. These include
552
 * watchdog(), function_exists(), module_implements(),
553
554
555
556
557
558
559
560
561
562
563
 * module_invoke_all() etc.
 */
class DrupalUnitTestCase extends DrupalTestCase {

  /**
   * Constructor for DrupalUnitTestCase.
   */
  function __construct($test_id = NULL) {
    parent::__construct($test_id);
    $this->skipClasses[__CLASS__] = TRUE;
  }
564

565
  protected function setUp() {
566
567
568
569
570
571
    global $db_prefix, $conf;

    // Store necessary current values before switching to prefixed database.
    $this->originalPrefix = $db_prefix;
    $this->originalFileDirectory = file_directory_path();

572
573
574
    // Reset all statics so that test is performed with a clean environment.
    drupal_static_reset();

575
576
    // Generate temporary prefixed database to ensure that tests have a clean starting point.
    $db_prefix = Database::getConnection()->prefixTables('{simpletest' . mt_rand(1000, 1000000) . '}');
577
    $conf['file_public_path'] = $this->originalFileDirectory . '/' . $db_prefix;
578
579
580
581
582
583
584

    // If locale is enabled then t() will try to access the database and
    // subsequently will fail as the database is not accessible.
    $module_list = module_list();
    if (isset($module_list['locale'])) {
      $this->originalModuleList = $module_list;
      unset($module_list['locale']);
585
      module_list(TRUE, FALSE, FALSE, $module_list);
586
587
588
    }
  }

589
  protected function tearDown() {
590
591
    global $db_prefix, $conf;
    if (preg_match('/simpletest\d+/', $db_prefix)) {
592
      $conf['file_public_path'] = $this->originalFileDirectory;
593
594
595
596
      // Return the database prefix to the original.
      $db_prefix = $this->originalPrefix;
      // Restore modules if necessary.
      if (isset($this->originalModuleList)) {
597
        module_list(TRUE, FALSE, FALSE, $this->originalModuleList);
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
      }
    }
  }
}

/**
 * Test case for typical Drupal tests.
 */
class DrupalWebTestCase extends DrupalTestCase {
  /**
   * The URL currently loaded in the internal browser.
   *
   * @var string
   */
  protected $url;

  /**
   * The handle of the current cURL connection.
   *
   * @var resource
   */
  protected $curlHandle;

  /**
   * The headers of the page currently loaded in the internal browser.
   *
   * @var Array
   */
  protected $headers;

  /**
   * The content of the page currently loaded in the internal browser.
   *
   * @var string
   */
  protected $content;

  /**
   * The content of the page currently loaded in the internal browser (plain text version).
   *
   * @var string
   */
  protected $plainTextContent;

  /**
   * The parsed version of the page.
   *
   * @var SimpleXMLElement
   */
  protected $elements = NULL;

  /**
   * The current user logged in using the internal browser.
   *
   * @var bool
   */
  protected $loggedInUser = FALSE;

  /**
   * The current cookie file used by cURL.
   *
   * We do not reuse the cookies in further runs, so we do not need a file
   * but we still need cookie handling, so we set the jar to NULL.
   */
  protected $cookieFile = NULL;

  /**
   * Additional cURL options.
   *
   * DrupalWebTestCase itself never sets this but always obeys what is set.
   */
  protected $additionalCurlOptions = array();

  /**
   * The original user, before it was changed to a clean uid = 1 for testing purposes.
   *
   * @var object
   */
  protected $originalUser = NULL;

  /**
   * HTTP authentication credentials (<username>:<password>).
   */
  protected $httpauth_credentials = NULL;

683
684
685
686
687
688
689
690
691
692
  /**
   * The current session name, if available.
   */
  protected $session_name = NULL;

  /**
   * The current session ID, if available.
   */
  protected $session_id = NULL;

693
694
695
696
697
698
699
700
  /**
   * Constructor for DrupalWebTestCase.
   */
  function __construct($test_id = NULL) {
    parent::__construct($test_id);
    $this->skipClasses[__CLASS__] = TRUE;
  }

701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
  /**
   * Get a node from the database based on its title.
   *
   * @param title
   *   A node title, usually generated by $this->randomName().
   *
   * @return
   *   A node object matching $title.
   */
  function drupalGetNodeByTitle($title) {
    $nodes = node_load_multiple(array(), array('title' => $title));
    // Load the first node returned from the database.
    $returned_node = reset($nodes);
    return $returned_node;
  }

717
718
719
  /**
   * Creates a node based on default settings.
   *
720
721
   * @param $settings
   *   An associative array of settings to change from the defaults, keys are
722
   *   node properties, for example 'title' => 'Hello, world!'.
723
724
   * @return
   *   Created node object.
725
   */
726
  protected function drupalCreateNode($settings = array()) {
727
    // Populate defaults array.
728
    $settings += array(
729
730
      'body'      => array(LANGUAGE_NONE => array(array())),
      'title'     => array(LANGUAGE_NONE => array(array('value' => $this->randomName(8)))),
731
      'comment'   => 2,
732
      'changed'   => REQUEST_TIME,
733
734
735
736
737
738
739
740
741
      'moderate'  => 0,
      'promote'   => 0,
      'revision'  => 1,
      'log'       => '',
      'status'    => 1,
      'sticky'    => 0,
      'type'      => 'page',
      'revisions' => NULL,
      'taxonomy'  => NULL,
742
      'language'  => LANGUAGE_NONE,
743
    );
744
745
746
747

    // Use the original node's created time for existing nodes.
    if (isset($settings['created']) && !isset($settings['date'])) {
      $settings['date'] = format_date($settings['created'], 'custom', 'Y-m-d H:i:s O');
748
    }
749
750
751
752
753
754
755
756
757
758
759
760
761

    // If the node's user uid is not specified manually, use the currently
    // logged in user if available, or else the user running the test.
    if (!isset($settings['uid'])) {
      if ($this->loggedInUser) {
        $settings['uid'] = $this->loggedInUser->uid;
      }
      else {
        global $user;
        $settings['uid'] = $user->uid;
      }
    }

762
763
764
    // Merge body field value and format separately.
    $body = array(
      'value' => $this->randomName(32),
765
      'format' => filter_default_format(),
766
    );
767
    $settings['body'][$settings['language']][0] += $body;
768

769
    $node = (object) $settings;
770
771
    node_save($node);

772
    // Small hack to link revisions to our test user.
773
774
775
776
    db_update('node_revision')
      ->fields(array('uid' => $node->uid))
      ->condition('vid', $node->vid)
      ->execute();
777
778
779
780
781
782
    return $node;
  }

  /**
   * Creates a custom content type based on default settings.
   *
783
   * @param $settings
784
785
   *   An array of settings to change from the defaults.
   *   Example: 'type' => 'foo'.
786
787
   * @return
   *   Created content type.
788
   */
789
  protected function drupalCreateContentType($settings = array()) {
790
    // Find a non-existent random type name.
791
    do {
792
      $name = strtolower($this->randomName(8));
793
    } while (node_type_get_type($name));
794

795
    // Populate defaults array.
796
797
798
    $defaults = array(
      'type' => $name,
      'name' => $name,
799
      'base' => 'node_content',
800
801
802
803
804
805
806
      'description' => '',
      'help' => '',
      'title_label' => 'Title',
      'body_label' => 'Body',
      'has_title' => 1,
      'has_body' => 1,
    );
807
    // Imposed values for a custom type.
808
809
810
811
812
813
814
815
816
817
818
    $forced = array(
      'orig_type' => '',
      'old_type' => '',
      'module' => 'node',
      'custom' => 1,
      'modified' => 1,
      'locked' => 0,
    );
    $type = $forced + $settings + $defaults;
    $type = (object)$type;

819
    $saved_type = node_type_save($type);
820
    node_types_rebuild();
821
    menu_rebuild();
822

823
    $this->assertEqual($saved_type, SAVED_NEW, t('Created content type %type.', array('%type' => $type->type)));
824

825
826
827
    // Reset permissions so that permissions for this content type are available.
    $this->checkPermissions(array(), TRUE);

828
829
830
831
832
833
    return $type;
  }

  /**
   * Get a list files that can be used in tests.
   *
834
835
836
837
838
839
   * @param $type
   *   File type, possible values: 'binary', 'html', 'image', 'javascript', 'php', 'sql', 'text'.
   * @param $size
   *   File size in bytes to match. Please check the tests/files folder.
   * @return
   *   List of files that match filter.
840
   */
841
  protected function drupalGetTestFiles($type, $size = NULL) {
842
843
844
845
    $files = array();

    // Make sure type is valid.
    if (in_array($type, array('binary', 'html', 'image', 'javascript', 'php', 'sql', 'text'))) {
846
      // Use original file directory instead of one created during setUp().
847
      $path = $this->originalFileDirectory . '/simpletest';
848
      $files = file_scan_directory($path, '/' . $type . '\-.*/');
849
850
851
852

      // If size is set then remove any files that are not of that size.
      if ($size !== NULL) {
        foreach ($files as $file) {
853
          $stats = stat($file->uri);
854
          if ($stats['size'] != $size) {
855
            unset($files[$file->uri]);
856
857
858
859
860
861
862
863
864
          }
        }
      }
    }
    usort($files, array($this, 'drupalCompareFiles'));
    return $files;
  }

  /**
865
   * Compare two files based on size and file name.
866
   */
867
  protected function drupalCompareFiles($file1, $file2) {
868
    $compare_size = filesize($file1->uri) - filesize($file2->uri);
869
870
871
    if ($compare_size) {
      // Sort by file size.
      return $compare_size;
872
873
    }
    else {
874
875
      // The files were the same size, so sort alphabetically.
      return strnatcmp($file1->name, $file2->name);
876
877
878
879
880
881
882
    }
  }

  /**
   * Create a user with a given set of permissions. The permissions correspond to the
   * names given on the privileges page.
   *
883
884
885
886
   * @param $permissions
   *   Array of permission names to assign to user.
   * @return
   *   A fully loaded user object with pass_raw property, or FALSE if account
887
888
   *   creation fails.
   */
889
  protected function drupalCreateUser($permissions = array('access comments', 'access content', 'post comments', 'post comments without approval')) {
890
    // Create a role with the given permission set.
891
    if (!($rid = $this->drupalCreateRole($permissions))) {
892
893
894
895
896
897
      return FALSE;
    }

    // Create a user assigned to that role.
    $edit = array();
    $edit['name']   = $this->randomName();
898
    $edit['mail']   = $edit['name'] . '@example.com';
899
900
901
902
    $edit['roles']  = array($rid => $rid);
    $edit['pass']   = user_password();
    $edit['status'] = 1;

903
    $account = user_save(drupal_anonymous_user(), $edit);
904
905
906
907
908
909
910
911
912
913
914
915
916
917

    $this->assertTrue(!empty($account->uid), t('User created with name %name and pass %pass', array('%name' => $edit['name'], '%pass' => $edit['pass'])), t('User login'));
    if (empty($account->uid)) {
      return FALSE;
    }

    // Add the raw password so that we can log in as this user.
    $account->pass_raw = $edit['pass'];
    return $account;
  }

  /**
   * Internal helper function; Create a role with specified permissions.
   *
918
919
   * @param $permissions
   *   Array of permission names to assign to role.
920
921
   * @param $name
   *   (optional) String for the name of the role.  Defaults to a random string.
922
923
   * @return
   *   Role ID of newly created role, or FALSE if role creation failed.
924
   */
925
926
927
928
929
930
  protected function drupalCreateRole(array $permissions, $name = NULL) {
    // Generate random name if it was not passed.
    if (!$name) {
      $name = $this->randomName();
    }

931
    // Check the all the permissions strings are valid.
932
933
934
935
    if (!$this->checkPermissions($permissions)) {
      return FALSE;
    }

936
    // Create new role.
937
938
939
    $role = new stdClass();
    $role->name = $name;
    user_role_save($role);
940
    user_role_grant_permissions($role->rid, $permissions);
941

942
    $this->assertTrue(isset($role->rid), t('Created role of name: @name, id: @rid', array('@name' => $name, '@rid' => (isset($role->rid) ? $role->rid : t('-n/a-')))), t('Role'));
943
    if ($role && !empty($role->rid)) {
944
      $count = db_query('SELECT COUNT(*) FROM {role_permission} WHERE rid = :rid', array(':rid' => $role->rid))->fetchField();
945
      $this->assertTrue($count == count($permissions), t('Created permissions: @perms', array('@perms' => implode(', ', $permissions))), t('Role'));
946
947
948
949
950
951
952
      return $role->rid;
    }
    else {
      return FALSE;
    }
  }

953
954
955
  /**
   * Check to make sure that the array of permissions are valid.
   *
956
957
958
959
960
961
   * @param $permissions
   *   Permissions to check.
   * @param $reset
   *   Reset cached available permissions.
   * @return
   *   TRUE or FALSE depending on whether the permissions are valid.
962
   */
963
  protected function checkPermissions(array $permissions, $reset = FALSE) {
964
    $available = &drupal_static(__FUNCTION__);
965
966

    if (!isset($available) || $reset) {
967
      $available = array_keys(module_invoke_all('permission'));
968
969
970
971
972
973
974
975
976
977
978
979
    }

    $valid = TRUE;
    foreach ($permissions as $permission) {
      if (!in_array($permission, $available)) {
        $this->fail(t('Invalid permission %permission.', array('%permission' => $permission)), t('Role'));
        $valid = FALSE;
      }
    }
    return $valid;
  }

980
  /**
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
   * Log in a user with the internal browser.
   *
   * If a user is already logged in, then the current user is logged out before
   * logging in the specified user.
   *
   * Please note that neither the global $user nor the passed in user object is
   * populated with data of the logged in user. If you need full access to the
   * user object after logging in, it must be updated manually. If you also need
   * access to the plain-text password of the user (set by drupalCreateUser()),
   * e.g. to login the same user again, then it must be re-assigned manually.
   * For example:
   * @code
   *   // Create a user.
   *   $account = $this->drupalCreateUser(array());
   *   $this->drupalLogin($account);
   *   // Load real user object.
   *   $pass_raw = $account->pass_raw;
   *   $account = user_load($account->uid);
   *   $account->pass_raw = $pass_raw;
   * @endcode
1001
   *
1002
1003
   * @param $user
   *   User object representing the user to login.
1004
1005
   *
   * @see drupalCreateUser()
1006
   */
1007
  protected function drupalLogin(stdClass $user) {
1008
    if ($this->loggedInUser) {
1009
1010
1011
1012
1013
1014
1015
1016
1017
      $this->drupalLogout();
    }

    $edit = array(
      'name' => $user->name,
      'pass' => $user->pass_raw
    );
    $this->drupalPost('user', $edit, t('Log in'));

1018
1019
1020
    // If a "log out" link appears on the page, it is almost certainly because
    // the login was successful.
    $pass = $this->assertLink(t('Log out'), 0, t('User %name successfully logged in.', array('%name' => $user->name)), t('User login'));
1021

1022
1023
1024
    if ($pass) {
      $this->loggedInUser = $user;
    }
1025
1026
  }

1027
1028
1029
1030
1031
1032
1033
1034
  /**
   * Generate a token for the currently logged in user.
   */
  protected function drupalGetToken($value = '') {
    $private_key = drupal_get_private_key();
    return md5($this->session_id . $value . $private_key);
  }

1035
1036
1037
  /*
   * Logs a user out of the internal browser, then check the login page to confirm logout.
   */
1038
  protected function drupalLogout() {
1039
1040
1041
    // Make a request to the logout page, and redirect to the user page, the
    // idea being if you were properly logged out you should be seeing a login
    // screen.
1042
    $this->drupalGet('user/logout', array('query' => array('destination' => 'user')));
1043
1044
1045
    $pass = $this->assertField('name', t('Username field found.'), t('Logout'));
    $pass = $pass && $this->assertField('pass', t('Password field found.'), t('Logout'));

1046
1047
1048
    if ($pass) {
      $this->loggedInUser = FALSE;
    }
1049
1050
1051
  }

  /**
1052
1053
1054
1055
   * Generates a random database prefix, runs the install scripts on the
   * prefixed database and enable the specified modules. After installation
   * many caches are flushed and the internal browser is setup so that the
   * page requests will run on the new prefix. A temporary files directory
1056
   * is created with the same name as the database prefix.
1057
   *
1058
   * @param ...
1059
   *   List of modules to enable for the duration of the test.
1060
   */
1061
  protected function setUp() {
1062
    global $db_prefix, $user, $language;
1063
1064

    // Store necessary current values before switching to prefixed database.
1065
1066
    $this->originalLanguage = $language;
    $this->originalLanguageDefault = variable_get('language_default');
1067
    $this->originalPrefix = $db_prefix;
1068
    $this->originalFileDirectory = file_directory_path();
1069
    $this->originalProfile = drupal_get_profile();
1070
    $clean_url_original = variable_get('clean_url', 0);
1071
1072

    // Generate temporary prefixed database to ensure that tests have a clean starting point.
1073
1074
1075
1076
1077
1078
    $db_prefix_new = Database::getConnection()->prefixTables('{simpletest' . mt_rand(1000, 1000000) . '}');
    db_update('simpletest_test_id')
      ->fields(array('last_prefix' => $db_prefix_new))
      ->condition('test_id', $this->testId)
      ->execute();
    $db_prefix = $db_prefix_new;
1079

1080
1081
    // Create test directory ahead of installation so fatal errors and debug
    // information can be logged during installation process.
1082
1083
1084
1085
1086
1087
1088
    // Use temporary files directory with the same prefix as the database.
    $public_files_directory  = $this->originalFileDirectory . '/simpletest/' . substr($db_prefix, 10);
    $private_files_directory = $public_files_directory . '/private';

    // Create the directories
    file_prepare_directory($public_files_directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
    file_prepare_directory($private_files_directory, FILE_CREATE_DIRECTORY);
1089
1090
1091

    // Log fatal errors.
    ini_set('log_errors', 1);
1092
    ini_set('error_log', $public_files_directory . '/error.log');
1093

1094
1095
1096
    // Reset all statics so that test is performed with a clean environment.
    drupal_static_reset();

1097
    include_once DRUPAL_ROOT . '/includes/install.inc';
1098
    drupal_install_system();
1099

1100
1101
    $this->preloadRegistry();

1102
    // Include the default profile
1103
    variable_set('install_profile', 'default');
1104
1105
    $profile_details = install_profile_info('default', 'en');

1106
    // Add the specified modules to the list of modules in the default profile.
1107
    // Install the modules specified by the default profile.
1108
    drupal_install_modules($profile_details['dependencies'], TRUE);
1109

1110
    drupal_static_reset('_node_types_build');
1111
1112
1113
1114
1115
1116
1117

    // Install additional modules one at a time in order to make sure that the
    // list of modules is updated between each module's installation.
    $modules = func_get_args();
    foreach ($modules as $module) {
      drupal_install_modules(array($module), TRUE);
    }
1118

1119
    // Because the schema is static cached, we need to flush
1120
    // it between each run. If we don't, then it will contain
1121
1122
1123
    // stale data for the previous run's database prefix and all
    // calls to it will fail.
    drupal_get_schema(NULL, TRUE);
1124

1125
    // Run default profile tasks.
1126
    $install_state = array();
1127
    drupal_install_modules(array('default'), TRUE);
1128
1129

    // Rebuild caches.
1130
    node_types_rebuild();
1131
1132
    actions_synchronize();
    _drupal_flush_css_js();
1133
    $this->refreshVariables();
1134
    $this->checkPermissions(array(), TRUE);
1135

1136
1137
1138
    // Log in with a clean $user.
    $this->originalUser = $user;
    drupal_save_session(FALSE);
1139
    $user = user_load(1);
1140

1141
    // Restore necessary variables.
1142
    variable_set('install_profile', 'default');
1143
    variable_set('install_task', 'done');
1144
    variable_set('clean_url', $clean_url_original);
1145
    variable_set('site_mail', 'simpletest@example.com');
1146
1147
1148
    // Set up English language.
    unset($GLOBALS['conf']['language_default']);
    $language = language_default();
1149

1150
1151
1152
1153
    // Set path variables
    variable_set('file_public_path', $public_files_directory);
    variable_set('file_private_path', $private_files_directory);

1154
1155
    // Use the test mail class instead of the default mail handler class.
    variable_set('mail_system', array('default-system' => 'TestingMailSystem'));
1156

1157
    drupal_set_time_limit($this->timeLimit);
1158
1159
  }

1160
  /**
1161
1162
1163
1164
   * This method is called by DrupalWebTestCase::setUp, and preloads the
   * registry from the testing site to cut down on the time it takes to
   * setup a clean environment for the current test run.
   */
1165
1166
1167
1168
1169
  protected function preloadRegistry() {
    db_query('INSERT INTO {registry} SELECT * FROM ' . $this->originalPrefix . 'registry');
    db_query('INSERT INTO {registry_file} SELECT * FROM ' . $this->originalPrefix . 'registry_file');
  }

1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
  /**
   * Refresh the in-memory set of variables. Useful after a page request is made
   * that changes a variable in a different thread.
   *
   * In other words calling a settings page with $this->drupalPost() with a changed
   * value would update a variable to reflect that change, but in the thread that
   * made the call (thread running the test) the changed variable would not be
   * picked up.
   *
   * This method clears the variables cache and loads a fresh copy from the database
   * to ensure that the most up-to-date set of variables is loaded.
   */
1182
  protected function refreshVariables() {
1183
    global $conf;
1184
    cache_clear_all('variables', 'cache_bootstrap');
1185
    $conf = variable_initialize();
1186
1187
  }

1188
1189
1190
1191
  /**
   * Delete created files and temporary files directory, delete the tables created by setUp(),
   * and reset the database prefix.
   */
1192
  protected function tearDown() {
1193
    global $db_prefix, $user, $language;
1194

1195
1196
1197
1198
1199
1200
1201
    // In case a fatal error occured that was not in the test process read the
    // log to pick up any fatal errors.
    $db_prefix_temp = $db_prefix;
    $db_prefix = $this->originalPrefix;
    simpletest_log_read($this->testId, $db_prefix, get_class($this), TRUE);
    $db_prefix = $db_prefix_temp;

1202
    $emailCount = count(variable_get('drupal_test_email_collector', array()));
1203
1204
1205
1206
1207
    if ($emailCount) {
      $message = format_plural($emailCount, t('!count e-mail was sent during this test.'), t('!count e-mails were sent during this test.'), array('!count' => $emailCount));
      $this->pass($message, t('E-mail'));
    }

1208
    if (preg_match('/simpletest\d+/', $db_prefix)) {
1209
      // Delete temporary files directory.
1210
      file_unmanaged_delete_recursive($this->originalFileDirectory . '/simpletest/' . substr($db_prefix, 10));
1211

1212
      // Remove all prefixed tables (all the tables in the schema).
1213
1214
1215
      $schema = drupal_get_schema(NULL, TRUE);
      $ret = array();
      foreach ($schema as $name => $table) {
1216
        db_drop_table($name);
1217
      }
1218
1219

      // Return the database prefix to the original.
1220
      $db_prefix = $this->originalPrefix;
1221

1222
1223
1224
1225
      // Return the user to the original one.
      $user = $this->originalUser;
      drupal_save_session(TRUE);

1226
      // Ensure that internal logged in variable and cURL options are reset.
1227
      $this->loggedInUser = FALSE;
1228
      $this->additionalCurlOptions = array();
1229

1230
1231
      // Reload module list and implementations to ensure that test module hooks
      // aren't called after tests.
1232
      module_list(TRUE);
1233
      module_implements('', FALSE, TRUE);
1234

webchick's avatar