drupal_web_test_case.php 82.7 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
   *
   * @see DrupalTestCase::assert()
   */
153
  public static function insertAssert($test_id, $test_class, $status, $message = '', $group = 'Other', array $caller = array()) {
154
155
156
157
158
159
    // Convert boolean status to string status.
    if (is_bool($status)) {
      $status = $status ? 'pass' : 'fail';
    }

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

    $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'],
    );

    db_insert('simpletest')
      ->fields($assertion)
      ->execute();
  }

181
182
183
184
185
186
187
188
189
190
  /**
   * 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.
191
    // We skip calls that occurred in one of the methods of our base classes
192
    // or in an assertion function.
193
194
195
   while (($caller = $backtrace[1]) &&
         ((isset($caller['class']) && isset($this->skipClasses[$caller['class']])) ||
           substr($caller['function'], 0, 6) == 'assert')) {
196
197
198
199
200
201
202
      // We remove that call.
      array_shift($backtrace);
    }

    return _drupal_get_last_caller($backtrace);
  }

203
204
205
206
207
208
209
210
211
212
  /**
   * 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
213
   *   TRUE if the assertion succeeded, FALSE otherwise.
214
215
   */
  protected function assertTrue($value, $message = '', $group = 'Other') {
216
    return $this->assert((bool) $value, $message ? $message : t('Value is TRUE'), $group);
217
218
219
220
221
222
223
224
225
226
227
228
  }

  /**
   * 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
229
   *   TRUE if the assertion succeeded, FALSE otherwise.
230
231
   */
  protected function assertFalse($value, $message = '', $group = 'Other') {
232
    return $this->assert(!$value, $message ? $message : t('Value is FALSE'), $group);
233
234
235
236
237
238
239
240
241
242
243
244
  }

  /**
   * 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
245
   *   TRUE if the assertion succeeded, FALSE otherwise.
246
247
   */
  protected function assertNull($value, $message = '', $group = 'Other') {
248
    return $this->assert(!isset($value), $message ? $message : t('Value is NULL'), $group);
249
250
251
252
253
254
255
256
257
258
259
260
  }

  /**
   * 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
261
   *   TRUE if the assertion succeeded, FALSE otherwise.
262
263
   */
  protected function assertNotNull($value, $message = '', $group = 'Other') {
264
    return $this->assert(isset($value), $message ? $message : t('Value is not NULL'), $group);
265
266
267
268
269
270
271
272
273
274
275
276
277
278
  }

  /**
   * 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
279
   *   TRUE if the assertion succeeded, FALSE otherwise.
280
281
   */
  protected function assertEqual($first, $second, $message = '', $group = 'Other') {
282
    return $this->assert($first == $second, $message ? $message : t('First value is equal to second value'), $group);
283
284
285
286
287
288
289
290
291
292
293
294
295
296
  }

  /**
   * 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
297
   *   TRUE if the assertion succeeded, FALSE otherwise.
298
299
   */
  protected function assertNotEqual($first, $second, $message = '', $group = 'Other') {
300
    return $this->assert($first != $second, $message ? $message : t('First value is not equal to second value'), $group);
301
302
303
304
305
306
307
308
309
310
311
312
313
314
  }

  /**
   * 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
315
   *   TRUE if the assertion succeeded, FALSE otherwise.
316
317
   */
  protected function assertIdentical($first, $second, $message = '', $group = 'Other') {
318
    return $this->assert($first === $second, $message ? $message : t('First value is identical to second value'), $group);
319
320
321
322
323
324
325
326
327
328
329
330
331
332
  }

  /**
   * 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
333
   *   TRUE if the assertion succeeded, FALSE otherwise.
334
335
   */
  protected function assertNotIdentical($first, $second, $message = '', $group = 'Other') {
336
    return $this->assert($first !== $second, $message ? $message : t('First value is not identical to second value'), $group);
337
338
339
340
341
342
343
344
345
346
347
348
349
  }

  /**
   * 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') {
350
    return $this->assert(TRUE, $message, $group);
351
352
  }

353
  /**
354
   * Fire an assertion that is always negative.
355
   *
356
357
358
359
360
361
362
363
   * @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') {
364
    return $this->assert(FALSE, $message, $group);
365
366
367
368
369
370
371
372
373
  }

  /**
   * Fire an error assertion.
   *
   * @param $message
   *   The message to display along with the assertion.
   * @param $group
   *   The type of assertion - examples are "Browser", "PHP".
374
   * @param $caller
375
   *   The caller of the error.
376
377
   * @return
   *   FALSE.
378
   */
379
  protected function error($message = '', $group = 'Other', array $caller = NULL) {
380
381
382
383
384
385
    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);
    }

386
    return $this->assert('exception', $message, $group, $caller);
387
388
389
390
  }

  /**
   * Run all tests in this class.
391
   */
392
  public function run() {
393
    // Initialize verbose debugging.
394
    simpletest_verbose(NULL, file_directory_path(), get_class($this));
395

396
397
    // HTTP auth settings (<username>:<password>) for the simpletest browser
    // when sending requests to the test site.
398
399
400
401
402
    $username = variable_get('simpletest_username', NULL);
    $password = variable_get('simpletest_password', NULL);
    if ($username && $password) {
      $this->httpauth_credentials = $username . ':' . $password;
    }
403

404
405
406
407
408
409
    set_error_handler(array($this, 'errorHandler'));
    $methods = array();
    // Iterate through all the methods in this class.
    foreach (get_class_methods(get_class($this)) as $method) {
      // If the current method starts with "test", run it - it's a test.
      if (strtolower(substr($method, 0, 4)) == 'test') {
410
        $this->setUp();
411
412
413
414
415
416
417
        try {
          $this->$method();
          // Finish up.
        }
        catch (Exception $e) {
          $this->exceptionHandler($e);
        }
418
        $this->tearDown();
419
420
      }
    }
421
422
    // Clear out the error messages and restore error handler.
    drupal_get_messages();
423
424
425
426
427
428
    restore_error_handler();
  }

  /**
   * Handle errors.
   *
429
   * Because this is registered in set_error_handler(), it has to be public.
430
   * @see set_error_handler
431
   *
432
   */
433
  public function errorHandler($severity, $message, $file = NULL, $line = NULL) {
434
    if ($severity & error_reporting()) {
435
436
437
438
439
440
441
442
443
444
445
      $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',
      );
446
447
448

      $backtrace = debug_backtrace();
      $this->error($message, $error_map[$severity], _drupal_get_last_caller($backtrace));
449
450
    }
    return TRUE;
451
452
  }

453
454
455
456
457
  /**
   * Handle exceptions.
   *
   * @see set_exception_handler
   */
458
  protected function exceptionHandler($exception) {
459
460
461
462
463
464
465
466
467
    $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));
  }

468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
  /**
   * 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
522
 * watchdog(), function_exists(), module_implements(),
523
524
525
526
527
528
529
530
531
532
533
 * module_invoke_all() etc.
 */
class DrupalUnitTestCase extends DrupalTestCase {

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

535
536
537
538
539
540
541
542
543
  function setUp() {
    global $db_prefix, $conf;

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

    // Generate temporary prefixed database to ensure that tests have a clean starting point.
    $db_prefix = Database::getConnection()->prefixTables('{simpletest' . mt_rand(1000, 1000000) . '}');
544
    $conf['file_public_path'] = $this->originalFileDirectory . '/' . $db_prefix;
545
546
547
548
549
550
551

    // 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']);
552
      module_list(TRUE, FALSE, FALSE, $module_list);
553
554
555
556
557
558
    }
  }

  function tearDown() {
    global $db_prefix, $conf;
    if (preg_match('/simpletest\d+/', $db_prefix)) {
559
      $conf['file_public_path'] = $this->originalFileDirectory;
560
561
562
563
      // Return the database prefix to the original.
      $db_prefix = $this->originalPrefix;
      // Restore modules if necessary.
      if (isset($this->originalModuleList)) {
564
        module_list(TRUE, FALSE, FALSE, $this->originalModuleList);
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
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
      }
    }
  }
}

/**
 * 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;

650
651
652
653
654
655
656
657
658
659
  /**
   * The current session name, if available.
   */
  protected $session_name = NULL;

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

660
661
662
663
664
665
666
667
  /**
   * Constructor for DrupalWebTestCase.
   */
  function __construct($test_id = NULL) {
    parent::__construct($test_id);
    $this->skipClasses[__CLASS__] = TRUE;
  }

668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
  /**
   * 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;
  }

684
685
686
  /**
   * Creates a node based on default settings.
   *
687
688
   * @param $settings
   *   An associative array of settings to change from the defaults, keys are
689
   *   node properties, for example 'title' => 'Hello, world!'.
690
691
   * @return
   *   Created node object.
692
   */
693
  protected function drupalCreateNode($settings = array()) {
694
    // Populate defaults array.
695
    $settings += array(
696
      'body'      => array(FIELD_LANGUAGE_NONE => array(array())),
697
      'title'     => array(FIELD_LANGUAGE_NONE => array(array('value' => $this->randomName(8)))),
698
      'comment'   => 2,
699
      'changed'   => REQUEST_TIME,
700
701
702
703
704
705
706
707
708
709
      'moderate'  => 0,
      'promote'   => 0,
      'revision'  => 1,
      'log'       => '',
      'status'    => 1,
      'sticky'    => 0,
      'type'      => 'page',
      'revisions' => NULL,
      'taxonomy'  => NULL,
    );
710
711
712
713

    // 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');
714
    }
715
716
717
718
719
720
721
722
723
724
725
726
727

    // 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;
      }
    }

728
729
730
    // Merge body field value and format separately.
    $body = array(
      'value' => $this->randomName(32),
731
      'format' => filter_default_format(),
732
    );
733
    $settings['body'][FIELD_LANGUAGE_NONE][0] += $body;
734

735
    $node = (object) $settings;
736
737
    node_save($node);

738
    // Small hack to link revisions to our test user.
739
740
741
742
    db_update('node_revision')
      ->fields(array('uid' => $node->uid))
      ->condition('vid', $node->vid)
      ->execute();
743
744
745
746
747
748
    return $node;
  }

  /**
   * Creates a custom content type based on default settings.
   *
749
   * @param $settings
750
751
   *   An array of settings to change from the defaults.
   *   Example: 'type' => 'foo'.
752
753
   * @return
   *   Created content type.
754
   */
755
  protected function drupalCreateContentType($settings = array()) {
756
    // Find a non-existent random type name.
757
    do {
758
      $name = strtolower($this->randomName(8));
759
    } while (node_type_get_type($name));
760

761
    // Populate defaults array.
762
763
764
    $defaults = array(
      'type' => $name,
      'name' => $name,
765
      'base' => 'node_content',
766
767
768
769
770
771
772
      'description' => '',
      'help' => '',
      'title_label' => 'Title',
      'body_label' => 'Body',
      'has_title' => 1,
      'has_body' => 1,
    );
773
    // Imposed values for a custom type.
774
775
776
777
778
779
780
781
782
783
784
    $forced = array(
      'orig_type' => '',
      'old_type' => '',
      'module' => 'node',
      'custom' => 1,
      'modified' => 1,
      'locked' => 0,
    );
    $type = $forced + $settings + $defaults;
    $type = (object)$type;

785
    $saved_type = node_type_save($type);
786
    node_types_rebuild();
787
    menu_rebuild();
788

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

791
792
793
    // Reset permissions so that permissions for this content type are available.
    $this->checkPermissions(array(), TRUE);

794
795
796
797
798
799
    return $type;
  }

  /**
   * Get a list files that can be used in tests.
   *
800
801
802
803
804
805
   * @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.
806
   */
807
  protected function drupalGetTestFiles($type, $size = NULL) {
808
809
810
811
    $files = array();

    // Make sure type is valid.
    if (in_array($type, array('binary', 'html', 'image', 'javascript', 'php', 'sql', 'text'))) {
812
      // Use original file directory instead of one created during setUp().
813
      $path = $this->originalFileDirectory . '/simpletest';
814
      $files = file_scan_directory($path, '/' . $type . '\-.*/');
815
816
817
818

      // If size is set then remove any files that are not of that size.
      if ($size !== NULL) {
        foreach ($files as $file) {
819
          $stats = stat($file->uri);
820
          if ($stats['size'] != $size) {
821
            unset($files[$file->uri]);
822
823
824
825
826
827
828
829
830
          }
        }
      }
    }
    usort($files, array($this, 'drupalCompareFiles'));
    return $files;
  }

  /**
831
   * Compare two files based on size and file name.
832
   */
833
  protected function drupalCompareFiles($file1, $file2) {
834
    $compare_size = filesize($file1->uri) - filesize($file2->uri);
835
836
837
    if ($compare_size) {
      // Sort by file size.
      return $compare_size;
838
839
    }
    else {
840
841
      // The files were the same size, so sort alphabetically.
      return strnatcmp($file1->name, $file2->name);
842
843
844
845
846
847
848
    }
  }

  /**
   * Create a user with a given set of permissions. The permissions correspond to the
   * names given on the privileges page.
   *
849
850
851
852
   * @param $permissions
   *   Array of permission names to assign to user.
   * @return
   *   A fully loaded user object with pass_raw property, or FALSE if account
853
854
   *   creation fails.
   */
855
  protected function drupalCreateUser($permissions = array('access comments', 'access content', 'post comments', 'post comments without approval')) {
856
    // Create a role with the given permission set.
857
    if (!($rid = $this->drupalCreateRole($permissions))) {
858
859
860
861
862
863
      return FALSE;
    }

    // Create a user assigned to that role.
    $edit = array();
    $edit['name']   = $this->randomName();
864
    $edit['mail']   = $edit['name'] . '@example.com';
865
866
867
868
    $edit['roles']  = array($rid => $rid);
    $edit['pass']   = user_password();
    $edit['status'] = 1;

869
    $account = user_save(drupal_anonymous_user(), $edit);
870
871
872
873
874
875
876
877
878
879
880
881
882
883

    $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.
   *
884
885
   * @param $permissions
   *   Array of permission names to assign to role.
886
887
   * @param $name
   *   (optional) String for the name of the role.  Defaults to a random string.
888
889
   * @return
   *   Role ID of newly created role, or FALSE if role creation failed.
890
   */
891
892
893
894
895
896
  protected function drupalCreateRole(array $permissions, $name = NULL) {
    // Generate random name if it was not passed.
    if (!$name) {
      $name = $this->randomName();
    }

897
    // Check the all the permissions strings are valid.
898
899
900
901
    if (!$this->checkPermissions($permissions)) {
      return FALSE;
    }

902
    // Create new role.
903
904
905
    $role = new stdClass();
    $role->name = $name;
    user_role_save($role);
906
    user_role_grant_permissions($role->rid, $permissions);
907

908
    $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'));
909
    if ($role && !empty($role->rid)) {
910
      $count = db_query('SELECT COUNT(*) FROM {role_permission} WHERE rid = :rid', array(':rid' => $role->rid))->fetchField();
911
      $this->assertTrue($count == count($permissions), t('Created permissions: @perms', array('@perms' => implode(', ', $permissions))), t('Role'));
912
913
914
915
916
917
918
      return $role->rid;
    }
    else {
      return FALSE;
    }
  }

919
920
921
  /**
   * Check to make sure that the array of permissions are valid.
   *
922
923
924
925
926
927
   * @param $permissions
   *   Permissions to check.
   * @param $reset
   *   Reset cached available permissions.
   * @return
   *   TRUE or FALSE depending on whether the permissions are valid.
928
   */
929
  protected function checkPermissions(array $permissions, $reset = FALSE) {
930
    $available = &drupal_static(__FUNCTION__);
931
932

    if (!isset($available) || $reset) {
933
      $available = array_keys(module_invoke_all('permission'));
934
935
936
937
938
939
940
941
942
943
944
945
    }

    $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;
  }

946
  /**
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
   * 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
967
   *
968
969
   * @param $user
   *   User object representing the user to login.
970
971
   *
   * @see drupalCreateUser()
972
   */
973
  protected function drupalLogin(stdClass $user) {
974
    if ($this->loggedInUser) {
975
976
977
978
979
980
981
982
983
      $this->drupalLogout();
    }

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

984
985
986
    // 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'));
987

988
989
990
    if ($pass) {
      $this->loggedInUser = $user;
    }
991
992
  }

993
994
995
996
997
998
999
1000
  /**
   * 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);
  }

1001
1002
1003
  /*
   * Logs a user out of the internal browser, then check the login page to confirm logout.
   */
1004
  protected function drupalLogout() {
1005
1006
1007
    // 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.
1008
    $this->drupalGet('user/logout', array('query' => array('destination' => 'user')));
1009
1010
1011
    $pass = $this->assertField('name', t('Username field found.'), t('Logout'));
    $pass = $pass && $this->assertField('pass', t('Password field found.'), t('Logout'));

1012
1013
1014
    if ($pass) {
      $this->loggedInUser = FALSE;
    }
1015
1016
1017
  }

  /**
1018
1019
1020
1021
   * 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
1022
   * is created with the same name as the database prefix.
1023
   *
1024
   * @param ...
1025
   *   List of modules to enable for the duration of the test.
1026
   */
1027
  protected function setUp() {
1028
    global $db_prefix, $user, $language;
1029
1030

    // Store necessary current values before switching to prefixed database.
1031
1032
    $this->originalLanguage = $language;
    $this->originalLanguageDefault = variable_get('language_default');
1033
    $this->originalPrefix = $db_prefix;
1034
    $this->originalFileDirectory = file_directory_path();
1035
    $this->originalProfile = drupal_get_profile();
1036
    $clean_url_original = variable_get('clean_url', 0);
1037
1038

    // Generate temporary prefixed database to ensure that tests have a clean starting point.
1039
1040
1041
1042
1043
1044
    $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;
1045

1046
1047
1048
    // Create test directory ahead of installation so fatal errors and debug
    // information can be logged during installation process.
    $directory = $this->originalFileDirectory . '/simpletest/' . substr($db_prefix, 10);
1049
    file_prepare_directory($directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
1050
1051
1052
1053
1054

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

1055
    include_once DRUPAL_ROOT . '/includes/install.inc';
1056
    drupal_install_system();
1057

1058
1059
    $this->preloadRegistry();

1060
    // Include the default profile
1061
    variable_set('install_profile', 'default');
1062
1063
    $profile_details = install_profile_info('default', 'en');

1064
    // Add the specified modules to the list of modules in the default profile.
1065
    // Install the modules specified by the default profile.
1066
    drupal_install_modules($profile_details['dependencies'], TRUE);
1067

1068
    drupal_static_reset('_node_types_build');
1069
1070
1071
1072
1073
1074
1075

    // 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);
    }
1076

1077
    // Because the schema is static cached, we need to flush
1078
    // it between each run. If we don't, then it will contain
1079
1080
1081
    // stale data for the previous run's database prefix and all
    // calls to it will fail.
    drupal_get_schema(NULL, TRUE);
1082

1083
    // Run default profile tasks.
1084
    $install_state = array();
1085
    drupal_install_modules(array('default'), TRUE);
1086
1087

    // Rebuild caches.
1088
    node_types_rebuild();
1089
1090
    actions_synchronize();
    _drupal_flush_css_js();
1091
    $this->refreshVariables();
1092
    $this->checkPermissions(array(), TRUE);
1093

1094
1095
1096
    // Log in with a clean $user.
    $this->originalUser = $user;
    drupal_save_session(FALSE);
1097
    $user = user_load(1);
1098

1099
    // Restore necessary variables.
1100
    variable_set('install_profile', 'default');
1101
    variable_set('install_task', 'done');
1102
    variable_set('clean_url', $clean_url_original);
1103
    variable_set('site_mail', 'simpletest@example.com');
1104
1105
1106
    // Set up English language.
    unset($GLOBALS['conf']['language_default']);
    $language = language_default();
1107

1108
1109
    // Use the test mail class instead of the default mail handler class.
    variable_set('mail_sending_system', array('default-system' => 'TestingMailSystem'));
1110

1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
    // Use temporary files directory with the same prefix as the database.
    $public_files_directory  = $this->originalFileDirectory . '/' . $db_prefix;
    $private_files_directory = $public_files_directory . '/private';

    // Set path variables
    variable_set('file_public_path', $public_files_directory);
    variable_set('file_private_path', $private_files_directory);

    // Create the directories
    $directory = file_directory_path('public');
    file_prepare_directory($directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
    file_prepare_directory($private_files_directory, FILE_CREATE_DIRECTORY);
1123

1124
    drupal_set_time_limit($this->timeLimit);
1125
1126
  }

1127
  /**
1128
1129
1130
1131
   * 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.
   */
1132
1133
1134
1135
1136
  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');
  }

1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
  /**
   * 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.
   */
1149
  protected function refreshVariables() {
1150
1151
    global $conf;
    cache_clear_all('variables', 'cache');
1152
    $conf = variable_initialize();
1153
1154
  }

1155
1156
1157
1158
  /**
   * Delete created files and temporary files directory, delete the tables created by setUp(),
   * and reset the database prefix.
   */
1159
  protected function tearDown() {
1160
    global $db_prefix, $user, $language;
1161

1162
1163
1164
1165
1166
1167
1168
    // 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;

1169
    $emailCount = count(variable_get('drupal_test_email_collector', array()));
1170
1171
1172
1173
1174
    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'));
    }

1175
    if (preg_match('/simpletest\d+/', $db_prefix)) {
1176
      // Delete temporary files directory.
1177
      file_unmanaged_delete_recursive(file_directory_path());
1178

1179
      // Remove all prefixed tables (all the tables in the schema).
1180
1181
1182
      $schema = drupal_get_schema(NULL, TRUE);
      $ret = array();
      foreach ($schema as $name => $table) {
1183
        db_drop_table($name);
1184
      }
1185
1186

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

1189
1190
1191
1192
      // Return the user to the original one.
      $user = $this->originalUser;
      drupal_save_session(TRUE);

1193
      // Ensure that internal logged in variable and cURL options are reset.
1194
      $this->loggedInUser = FALSE;
1195
      $this->additionalCurlOptions = array();
1196

1197
1198
      // Reload module list and implementations to ensure that test module hooks
      // aren't called after tests.
1199
      module_list(TRUE);
1200
      module_implements('', FALSE, TRUE);
1201

1202
1203
1204
      // Reset the Field API.
      field_cache_clear();

1205
1206
      // Rebuild caches.
      $this->refreshVariables();
1207

1208
      // Reset language.
1209
1210
1211
1212
      $language = $this->originalLanguage;
      if ($this->originalLanguageDefault) {
        $GLOBALS['conf']['language_default'] = $this->originalLanguageDefault;
      }
1213

1214
      // Close the CURL handler.
1215
1216
1217
1218
1219
      $this->curlClose();
    }
  }

  /**
1220
   * Initializes the cURL connection.
1221
   *
1222
1223
1224
1225
   * If the simpletest_httpauth_credentials variable is set, this function will
   * add HTTP authentication headers. This is necessary for testing sites that
   * are protected by login credentials from public access.
   * See the description of $curl_options for other options.
1226
   */
1227
  protected function curlInitialize() {
1228
    global $base_url, $db_prefix;
1229

1230
1231
1232
1233
    if (!isset($this->curlHandle)) {
      $this->curlHandle = curl_init();
      $curl_options = $this->additionalCurlOptions + array(
        CURLOPT_COOKIEJAR => $this->cookieFile,
1234
        CURLOPT_URL => $base_url,
1235
1236
        CURLOPT_FOLLOWLOCATION => TRUE,
        CURLOPT_MAXREDIRS => 5,
1237
        CURLOPT_RETURNTRANSFER => TRUE,
1238
1239
        CURLOPT_SSL_VERIFYPEER => FALSE, // Required to make the tests run on https.
        CURLOPT_SSL_VERIFYHOST => FALSE, // Required to make the tests run on https.
1240
        CURLOPT_HEADERFUNCTION => array(&$this, 'curlHeaderCallback'),
1241
      );