drupal_web_test_case.php 69.1 KB
Newer Older
1 2 3 4 5 6
<?php
// $Id$

/**
 * Test case for typical Drupal tests.
 */
7
class DrupalWebTestCase {
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29

  /**
   * The test run ID.
   *
   * @var string
   */
  protected $testId;

  /**
   * The URL currently loaded in the internal browser.
   *
   * @var string
   */
  protected $url;

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

30 31 32 33 34 35 36
  /**
   * The headers of the page currently loaded in the internal browser.
   *
   * @var Array
   */
  protected $headers;

37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
  /**
   * 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;

  /**
59
   * The current user logged in using the internal browser.
60 61 62
   *
   * @var bool
   */
63
  protected $loggedInUser = FALSE;
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93

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

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

101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
  /**
   * Current results of this test case.
   *
   * @var Array
   */
  public $results = array(
    '#pass' => 0,
    '#fail' => 0,
    '#exception' => 0,
  );

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

119 120 121 122
  /**
   * Time limit for the test.
   */
  protected $timeLimit = 180;
123

124 125 126 127
  /**
   * HTTP authentication credentials (<username>:<password>).
   */
  protected $httpauth_credentials = NULL;
128 129


130 131 132
  /**
   * Constructor for DrupalWebTestCase.
   *
133
   * @param $test_id
134 135
   *   Tests with the same id are reported together.
   */
136 137
  public function __construct($test_id = NULL) {
    $this->testId = $test_id;
138 139 140
  }

  /**
141
   * Internal helper: stores the assert.
142 143
   *
   * @param $status
144 145
   *   Can be 'pass', 'fail', 'exception'.
   *   TRUE is a synonym for 'pass', FALSE for 'fail'.
146 147 148
   * @param $message
   *   The message string.
   * @param $group
149
   *   Which group this assert belongs to.
150
   * @param $caller
151
   *   By default, the assert comes from a function whose name starts with
152
   *   'test'. Instead, you can specify where this assert originates from
153
   *   by passing in an associative array as $caller. Key 'file' is
154 155 156
   *   the name of the source file, 'line' is the line number and 'function'
   *   is the caller function itself.
   */
157
  private function assert($status, $message = '', $group = 'Other', array $caller = NULL) {
158
    global $db_prefix;
159 160

    // Convert boolean status to string status.
161 162 163
    if (is_bool($status)) {
      $status = $status ? 'pass' : 'fail';
    }
164 165

    // Increment summary result counter.
166
    $this->results['#' . $status]++;
167 168 169 170

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

    // Switch to non-testing database to store results in.
174
    $current_db_prefix = $db_prefix;
175
    $db_prefix = $this->originalPrefix;
176 177

    // Creation assertion array that can be displayed while tests are running.
178 179
    $this->assertions[] = $assertion = array(
      'test_id' => $this->testId,
180
      'test_class' => get_class($this),
181 182
      'status' => $status,
      'message' => $message,
183 184 185 186
      'message_group' => $group,
      'function' => $caller['function'],
      'line' => $caller['line'],
      'file' => $caller['file'],
187
    );
188 189 190 191 192

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

    // Return to testing prefix.
193
    $db_prefix = $current_db_prefix;
194
    return $status == 'pass' ? TRUE : FALSE;
195 196
  }

197 198 199 200 201 202 203 204 205 206
  /**
   * 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.
207
    // We skip calls that occurred in one of the methods of DrupalWebTestCase
208 209 210 211 212 213 214 215 216 217 218
    // or in an assertion function.
    while (($caller = $backtrace[1]) &&
          ((isset($caller['class']) && $caller['class'] == 'DrupalWebTestCase') ||
            substr($caller['function'], 0, 6) == 'assert')) {
      // We remove that call.
      array_shift($backtrace);
    }

    return _drupal_get_last_caller($backtrace);
  }

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

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

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

  /**
   * 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
277
   *   TRUE if the assertion succeeded, FALSE otherwise.
278 279
   */
  protected function assertNotNull($value, $message = '', $group = 'Other') {
280
    return $this->assert(isset($value), $message ? $message : t('Value is not NULL'), $group);
281 282 283 284 285 286 287 288 289 290 291 292 293 294
  }

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

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

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

  /**
   * 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
349
   *   TRUE if the assertion succeeded, FALSE otherwise.
350 351
   */
  protected function assertNotIdentical($first, $second, $message = '', $group = 'Other') {
352
    return $this->assert($first !== $second, $message ? $message : t('First value is not identical to second value'), $group);
353 354 355 356 357 358 359 360 361 362 363 364 365
  }

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

369
  /**
370
   * Fire an assertion that is always negative.
371
   *
372 373 374 375 376 377 378 379
   * @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') {
380
    return $this->assert(FALSE, $message, $group);
381 382 383 384 385 386 387 388 389
  }

  /**
   * Fire an error assertion.
   *
   * @param $message
   *   The message to display along with the assertion.
   * @param $group
   *   The type of assertion - examples are "Browser", "PHP".
390
   * @param $caller
391
   *   The caller of the error.
392 393
   * @return
   *   FALSE.
394
   */
395
  protected function error($message = '', $group = 'Other', array $caller = NULL) {
396
    return $this->assert('exception', $message, $group, $caller);
397 398 399 400
  }

  /**
   * Run all tests in this class.
401
   */
402
  public function run() {
403 404 405 406
    // HTTP auth settings (<username>:<password>) for the simpletest browser
    // when sending requests to the test site.
    $this->httpauth_credentials = variable_get('simpletest_httpauth_credentials', NULL);

407 408 409 410 411 412
    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') {
413
        $this->setUp();
414 415 416 417 418 419 420
        try {
          $this->$method();
          // Finish up.
        }
        catch (Exception $e) {
          $this->exceptionHandler($e);
        }
421
        $this->tearDown();
422 423
      }
    }
424 425
    // Clear out the error messages and restore error handler.
    drupal_get_messages();
426 427 428 429 430 431
    restore_error_handler();
  }

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

      $backtrace = debug_backtrace();
      $this->error($message, $error_map[$severity], _drupal_get_last_caller($backtrace));
452 453
    }
    return TRUE;
454 455
  }

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

471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
  /**
   * 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;
  }

487 488 489
  /**
   * Creates a node based on default settings.
   *
490 491
   * @param $settings
   *   An associative array of settings to change from the defaults, keys are
492
   *   node properties, for example 'body' => 'Hello, world!'.
493 494
   * @return
   *   Created node object.
495
   */
496
  protected function drupalCreateNode($settings = array()) {
497
    // Populate defaults array
498
    $settings += array(
499 500 501
      'body'      => $this->randomName(32),
      'title'     => $this->randomName(8),
      'comment'   => 2,
502
      'changed'   => REQUEST_TIME,
503 504 505 506 507 508 509 510 511 512 513
      'format'    => FILTER_FORMAT_DEFAULT,
      'moderate'  => 0,
      'promote'   => 0,
      'revision'  => 1,
      'log'       => '',
      'status'    => 1,
      'sticky'    => 0,
      'type'      => 'page',
      'revisions' => NULL,
      'taxonomy'  => NULL,
    );
514 515 516 517

    // 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');
518
    }
519 520 521

    // Add the default teaser.
    if (!isset($settings['teaser'])) {
522
      $settings['teaser'] = $settings['body'];
523 524
    }

525 526 527 528 529 530 531 532 533 534 535 536 537
    // 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;
      }
    }

    $node = (object) $settings;
538 539 540
    node_save($node);

    // small hack to link revisions to our test user
541
    db_query('UPDATE {node_revision} SET uid = %d WHERE vid = %d', $node->uid, $node->vid);
542 543 544 545 546 547
    return $node;
  }

  /**
   * Creates a custom content type based on default settings.
   *
548
   * @param $settings
549 550
   *   An array of settings to change from the defaults.
   *   Example: 'type' => 'foo'.
551 552
   * @return
   *   Created content type.
553
   */
554
  protected function drupalCreateContentType($settings = array()) {
555 556
    // find a non-existent random type name.
    do {
557
      $name = strtolower($this->randomName(8));
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583
    } while (node_get_types('type', $name));

    // Populate defaults array
    $defaults = array(
      'type' => $name,
      'name' => $name,
      'description' => '',
      'help' => '',
      'min_word_count' => 0,
      'title_label' => 'Title',
      'body_label' => 'Body',
      'has_title' => 1,
      'has_body' => 1,
    );
    // imposed values for a custom type
    $forced = array(
      'orig_type' => '',
      'old_type' => '',
      'module' => 'node',
      'custom' => 1,
      'modified' => 1,
      'locked' => 0,
    );
    $type = $forced + $settings + $defaults;
    $type = (object)$type;

584
    $saved_type = node_type_save($type);
585 586
    node_types_rebuild();

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

589 590 591
    // Reset permissions so that permissions for this content type are available.
    $this->checkPermissions(array(), TRUE);

592 593 594 595 596 597
    return $type;
  }

  /**
   * Get a list files that can be used in tests.
   *
598 599 600 601 602 603
   * @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.
604
   */
605
  protected function drupalGetTestFiles($type, $size = NULL) {
606 607 608 609 610
    $files = array();

    // Make sure type is valid.
    if (in_array($type, array('binary', 'html', 'image', 'javascript', 'php', 'sql', 'text'))) {
     // Use original file directory instead of one created during setUp().
611
      $path = $this->originalFileDirectory . '/simpletest';
612
      $files = file_scan_directory($path, '/' . $type . '\-.*/');
613 614 615 616

      // If size is set then remove any files that are not of that size.
      if ($size !== NULL) {
        foreach ($files as $file) {
617
          $stats = stat($file->filepath);
618
          if ($stats['size'] != $size) {
619
            unset($files[$file->filepath]);
620 621 622 623 624 625 626 627 628
          }
        }
      }
    }
    usort($files, array($this, 'drupalCompareFiles'));
    return $files;
  }

  /**
629
   * Compare two files based on size and file name.
630
   */
631
  protected function drupalCompareFiles($file1, $file2) {
632 633 634 635
    $compare_size = filesize($file1->filepath) - filesize($file2->filepath);
    if ($compare_size) {
      // Sort by file size.
      return $compare_size;
636 637
    }
    else {
638 639
      // The files were the same size, so sort alphabetically.
      return strnatcmp($file1->name, $file2->name);
640 641 642 643
    }
  }

  /**
644 645 646
   * Generates a random string of ASCII characters of codes 32 to 126.
   *
   * The generated string includes alpha-numeric characters and common misc
647 648
   * characters. Use this method when testing general input where the content
   * is not restricted.
649
   *
650
   * @param $length
651
   *   Length of random string to generate which will be appended to $db_prefix.
652 653
   * @return
   *   Randomly generated string.
654
   */
655 656 657 658 659 660
  public static function randomString($length = 8) {
    global $db_prefix;

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

665
  /**
666 667 668
   * Generates a random string containing letters and numbers.
   *
   * The letters may be upper or lower case. This method is better for
669 670 671
   * 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.
672 673
   *
   * @param $length
674
   *   Length of random string to generate which will be appended to $db_prefix.
675 676 677 678 679 680 681 682 683 684 685 686 687
   * @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;
688
  }
689

690 691 692 693
  /**
   * Create a user with a given set of permissions. The permissions correspond to the
   * names given on the privileges page.
   *
694 695 696 697
   * @param $permissions
   *   Array of permission names to assign to user.
   * @return
   *   A fully loaded user object with pass_raw property, or FALSE if account
698 699
   *   creation fails.
   */
700
  protected function drupalCreateUser($permissions = array('access comments', 'access content', 'post comments', 'post comments without approval')) {
701
    // Create a role with the given permission set.
702
    if (!($rid = $this->drupalCreateRole($permissions))) {
703 704 705 706 707 708
      return FALSE;
    }

    // Create a user assigned to that role.
    $edit = array();
    $edit['name']   = $this->randomName();
709
    $edit['mail']   = $edit['name'] . '@example.com';
710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
    $edit['roles']  = array($rid => $rid);
    $edit['pass']   = user_password();
    $edit['status'] = 1;

    $account = user_save('', $edit);

    $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.
   *
729 730 731 732
   * @param $permissions
   *   Array of permission names to assign to role.
   * @return
   *   Role ID of newly created role, or FALSE if role creation failed.
733
   */
734
  protected function drupalCreateRole(array $permissions) {
735 736 737 738
    if (!$this->checkPermissions($permissions)) {
      return FALSE;
    }

739 740 741 742 743 744 745
    // Create new role.
    $role_name = $this->randomName();
    db_query("INSERT INTO {role} (name) VALUES ('%s')", $role_name);
    $role = db_fetch_object(db_query("SELECT * FROM {role} WHERE name = '%s'", $role_name));
    $this->assertTrue($role, t('Created role of name: @role_name, id: @rid', array('@role_name' => $role_name, '@rid' => (isset($role->rid) ? $role->rid : t('-n/a-')))), t('Role'));
    if ($role && !empty($role->rid)) {
      // Assign permissions to role and mark it for clean-up.
746 747 748 749 750
      foreach ($permissions as $permission_string) {
        db_query("INSERT INTO {role_permission} (rid, permission) VALUES (%d, '%s')", $role->rid, $permission_string);
      }
      $count = db_result(db_query("SELECT COUNT(*) FROM {role_permission} WHERE rid = %d", $role->rid));
      $this->assertTrue($count == count($permissions), t('Created permissions: @perms', array('@perms' => implode(', ', $permissions))), t('Role'));
751 752 753 754 755 756 757
      return $role->rid;
    }
    else {
      return FALSE;
    }
  }

758 759 760
  /**
   * Check to make sure that the array of permissions are valid.
   *
761 762 763 764 765 766
   * @param $permissions
   *   Permissions to check.
   * @param $reset
   *   Reset cached available permissions.
   * @return
   *   TRUE or FALSE depending on whether the permissions are valid.
767
   */
768
  protected function checkPermissions(array $permissions, $reset = FALSE) {
769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784
    static $available;

    if (!isset($available) || $reset) {
      $available = array_keys(module_invoke_all('perm'));
    }

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

785
  /**
786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805
   * 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
806
   *
807 808
   * @param $user
   *   User object representing the user to login.
809 810
   *
   * @see drupalCreateUser()
811
   */
812
  protected function drupalLogin(stdClass $user) {
813
    if ($this->loggedInUser) {
814 815 816 817 818 819 820 821 822 823 824 825 826
      $this->drupalLogout();
    }

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

    $pass = $this->assertText($user->name, t('Found name: %name', array('%name' => $user->name)), t('User login'));
    $pass = $pass && $this->assertNoText(t('The username %name has been blocked.', array('%name' => $user->name)), t('No blocked message at login page'), t('User login'));
    $pass = $pass && $this->assertNoText(t('The name %name is a reserved username.', array('%name' => $user->name)), t('No reserved message at login page'), t('User login'));

827 828 829
    if ($pass) {
      $this->loggedInUser = $user;
    }
830 831 832 833 834
  }

  /*
   * Logs a user out of the internal browser, then check the login page to confirm logout.
   */
835
  protected function drupalLogout() {
836
    // Make a request to the logout page.
837
    $this->drupalGet('user/logout');
838 839 840 841 842 843

    // Load the user page, the idea being if you were properly logged out you should be seeing a login screen.
    $this->drupalGet('user');
    $pass = $this->assertField('name', t('Username field found.'), t('Logout'));
    $pass = $pass && $this->assertField('pass', t('Password field found.'), t('Logout'));

844 845 846
    if ($pass) {
      $this->loggedInUser = FALSE;
    }
847 848 849
  }

  /**
850 851 852 853
   * 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
854
   * is created with the same name as the database prefix.
855
   *
856
   * @param ...
857
   *   List of modules to enable for the duration of the test.
858
   */
859
  protected function setUp() {
860
    global $db_prefix, $user;
861 862

    // Store necessary current values before switching to prefixed database.
863
    $this->originalPrefix = $db_prefix;
864
    $this->originalFileDirectory = file_directory_path();
865
    $clean_url_original = variable_get('clean_url', 0);
866 867

    // Generate temporary prefixed database to ensure that tests have a clean starting point.
868
    $db_prefix = Database::getConnection()->prefixTables('{simpletest' . mt_rand(1000, 1000000) . '}');
869

870
    include_once DRUPAL_ROOT . '/includes/install.inc';
871
    drupal_install_system();
872

873 874
    $this->preloadRegistry();

875
    // Add the specified modules to the list of modules in the default profile.
876
    $args = func_get_args();
877
    $modules = array_unique(array_merge(drupal_get_profile_modules('default', 'en'), $args));
878
    drupal_install_modules($modules, TRUE);
879

880
    // Because the schema is static cached, we need to flush
881
    // it between each run. If we don't, then it will contain
882 883 884
    // stale data for the previous run's database prefix and all
    // calls to it will fail.
    drupal_get_schema(NULL, TRUE);
885

886
    // Run default profile tasks.
887 888
    $task = 'profile';
    default_profile_tasks($task, '');
889 890

    // Rebuild caches.
891 892
    actions_synchronize();
    _drupal_flush_css_js();
893
    $this->refreshVariables();
894
    $this->checkPermissions(array(), TRUE);
895

896 897 898
    // Log in with a clean $user.
    $this->originalUser = $user;
    drupal_save_session(FALSE);
899
    $user = user_load(1);
900

901
    // Restore necessary variables.
902 903 904
    variable_set('install_profile', 'default');
    variable_set('install_task', 'profile-finished');
    variable_set('clean_url', $clean_url_original);
905
    variable_set('site_mail', 'simpletest@example.com');
906 907

    // Use temporary files directory with the same prefix as database.
908
    variable_set('file_directory_path', $this->originalFileDirectory . '/' . $db_prefix);
909
    $directory = file_directory_path();
910 911 912
    // Create the files directory.
    file_check_directory($directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);

913
    set_time_limit($this->timeLimit);
914 915
  }

916
  /**
917 918 919 920
   * 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.
   */
921 922 923 924 925
  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');
  }

926 927 928 929 930 931 932 933 934 935 936 937
  /**
   * 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.
   */
938
  protected function refreshVariables() {
939 940 941 942 943
    global $conf;
    cache_clear_all('variables', 'cache');
    $conf = variable_init();
  }

944 945 946 947
  /**
   * Delete created files and temporary files directory, delete the tables created by setUp(),
   * and reset the database prefix.
   */
948
  protected function tearDown() {
949
    global $db_prefix, $user;
950 951
    if (preg_match('/simpletest\d+/', $db_prefix)) {
      // Delete temporary files directory and reset files directory path.
952
      file_unmanaged_delete_recursive(file_directory_path());
953
      variable_set('file_directory_path', $this->originalFileDirectory);
954

955
      // Remove all prefixed tables (all the tables in the schema).
956 957 958 959 960
      $schema = drupal_get_schema(NULL, TRUE);
      $ret = array();
      foreach ($schema as $name => $table) {
        db_drop_table($ret, $name);
      }
961 962

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

965 966 967 968
      // Return the user to the original one.
      $user = $this->originalUser;
      drupal_save_session(TRUE);

969
      // Ensure that internal logged in variable and cURL options are reset.
970
      $this->loggedInUser = FALSE;
971
      $this->additionalCurlOptions = array();
972

973 974
      // Reload module list and implementations to ensure that test module hooks
      // aren't called after tests.
975
      module_list(TRUE);
976
      module_implements(MODULE_IMPLEMENTS_CLEAR_CACHE);
977

978 979 980
      // Reset the Field API.
      field_cache_clear();

981 982 983
      // Rebuild caches.
      $this->refreshVariables();

984
      // Close the CURL handler.
985 986 987 988 989
      $this->curlClose();
    }
  }

  /**
990
   * Initializes the cURL connection.
991
   *
992 993 994 995
   * 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.
996
   */
997
  protected function curlInitialize() {
998
    global $base_url, $db_prefix;
999 1000 1001 1002
    if (!isset($this->curlHandle)) {
      $this->curlHandle = curl_init();
      $curl_options = $this->additionalCurlOptions + array(
        CURLOPT_COOKIEJAR => $this->cookieFile,
1003 1004
        CURLOPT_URL => $base_url,
        CURLOPT_FOLLOWLOCATION => TRUE,
1005
        CURLOPT_MAXREDIRS => 5,
1006
        CURLOPT_RETURNTRANSFER => TRUE,
1007 1008
        CURLOPT_SSL_VERIFYPEER => FALSE,  // Required to make the tests run on https://
        CURLOPT_SSL_VERIFYHOST => FALSE,  // Required to make the tests run on https://
1009
        CURLOPT_HEADERFUNCTION => array(&$this, 'curlHeaderCallback'),
1010
      );
1011 1012
      if (preg_match('/simpletest\d+/', $db_prefix, $matches)) {
        $curl_options[CURLOPT_USERAGENT] = $matches[0];
1013
      }
1014 1015
      if (isset($this->httpauth_credentials)) {
        $curl_options[CURLOPT_USERPWD] = $this->httpauth_credentials;
1016
      }
1017
      curl_setopt_array($this->curlHandle, $this->additionalCurlOptions + $curl_options);
1018 1019 1020 1021
    }
  }

  /**
1022
   * Performs a cURL exec with the specified options after calling curlConnect().
1023
   *
1024 1025
   * @param $curl_options
   *   Custom cURL options.
1026 1027
   * @return
   *   Content returned from the exec.
1028 1029
   */
  protected function curlExec($curl_options) {
1030
    $this->curlInitialize();
1031
    $url = empty($curl_options[CURLOPT_URL]) ? curl_getinfo($this->curlHandle, CURLINFO_EFFECTIVE_URL) : $curl_options[CURLOPT_URL];
1032 1033 1034 1035 1036 1037 1038 1039
    if (!empty($curl_options[CURLOPT_POST])) {
      // This is a fix for the Curl library to prevent Expect: 100-continue
      // headers in POST requests, that may cause unexpected HTTP response
      // codes from some webservers (like lighttpd that returns a 417 error
      // code). It is done by setting an empty "Expect" header field that is
      // not overwritten by Curl.
      $curl_options[CURLOPT_HTTPHEADER][] = 'Expect:';
    }
1040
    curl_setopt_array($this->curlHandle, $this->additionalCurlOptions + $curl_options);
1041
    $this->headers = array();
1042
    $this->drupalSetContent(curl_exec($this->curlHandle), curl_getinfo($this->curlHandle, CURLINFO_EFFECTIVE_URL));
1043 1044 1045 1046 1047 1048 1049 1050
    $message_vars = array(
      '!method' => !empty($curl_options[CURLOPT_NOBODY]) ? 'HEAD' : (empty($curl_options[CURLOPT_POSTFIELDS]) ? 'GET' : 'POST'),
      '@url' => $url,
      '@status' => curl_getinfo($this->curlHandle, CURLINFO_HTTP_CODE),
      '!length' => format_size(strlen($this->content))
    );
    $message = t('!method @url returned @status (!length).', $message_vars);
    $this->assertTrue($this->content !== FALSE, $message, t('Browser'));
1051
    return $this->drupalGetContent();
1052 1053
  }

1054 1055 1056 1057 1058
  /**
   * Reads headers and registers errors received from the tested site.
   *
   * @see _drupal_log_error().
   *
1059 1060 1061 1062
   * @param $curlHandler
   *   The cURL handler.
   * @param $header
   *   An header.
1063
   */
1064
  protected function curlHeaderCallback($curlHandler, $header) {
1065
    $this->headers[] = $header;
1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
    // Errors are being sent via X-Drupal-Assertion-* headers,
    // generated by _drupal_log_error() in the exact form required
    // by DrupalWebTestCase::error().
    if (preg_match('/^X-Drupal-Assertion-[0-9]+: (.*)$/', $header, $matches)) {
      // Call DrupalWebTestCase::error() with the parameters from the header.
      call_user_func_array(array(&$this, 'error'), unserialize(urldecode($matches[1])));
    }
    // This is required by cURL.
    return strlen($header);
  }

1077 1078 1079 1080
  /**
   * Close the cURL handler and unset the handler.
   */
  protected function curlClose() {
1081 1082 1083
    if (isset($this->curlHandle)) {
      curl_close($this->curlHandle);
      unset($this->curlHandle);
1084 1085 1086 1087
    }
  }

  /**
1088
   * Parse content returned from curlExec using DOM and SimpleXML.
1089
   *
1090 1091
   * @return
   *   A SimpleXMLElement or FALSE on failure.
1092 1093 1094
   */
  protected function parse() {
    if (!$this->elements) {
1095
      // DOM can load HTML soup. But, HTML soup can throw warnings, suppress
1096
      // them.
1097
      @$htmlDom = DOMDocument::loadHTML($this->content);
1098
      if ($htmlDom) {
1099
        $this->pass(t('Valid HTML found on "@path"', array('@path' => $this->getUrl())), t('Browser'));
1100 1101 1102 1103 1104
        // It's much easier to work with simplexml than DOM, luckily enough
        // we can just simply import our DOM tree.
        $this->elements = simplexml_import_dom($htmlDom);
      }
    }
1105 1106 1107
    if (!$this->elements) {
      $this->fail(t('Parsed page successfully.'), t('Browser'));
    }
1108

1109 1110 1111 1112 1113 1114
    return $this->elements;
  }

  /**
   * Retrieves a Drupal path or an absolute path.
   *
1115
   * @param $path
1116
   *   Drupal path or URL to load into internal browser
1117
   * @param $options
1118
   *   Options to be forwarded to url().
1119 1120 1121
   * @param $headers
   *   An array containing additional HTTP request headers, each formatted as
   *   "name: value".
1122
   * @return
1123
   *   The retrieved HTML string, also available as $this->drupalGetContent()
1124
   */
1125
  protected function drupalGet($path, array $options = array(), array $headers = array()) {
1126
    $options['absolute'] = TRUE;
1127

1128 1129
    // We re-using a CURL connection here. If that connection still has certain
    // options set, it might change the GET into a POST. Make sure we clear out
1130
    // previous options.
1131
    $out = $this->curlExec(array(CURLOPT_HTTPGET => TRUE, CURLOPT_URL => url($path, $options), CURLOPT_NOBODY => FALSE, CURLOPT_HTTPHEADER => $headers));
1132
    $this->refreshVariables(); // Ensure that any changes to variables in the other thread are picked up.
1133 1134 1135 1136 1137

    // Replace original page output with new output from redirected page(s).
    if (($new = $this->checkForMetaRefresh())) {
      $out = $new;
    }
1138
    return $out;
1139 1140 1141
  }

  /**
1142 1143
   * Execute a POST request on a Drupal page.
   * It will be done as usual POST request with SimpleBrowser.
1144
   *
1145
   * @param $path
1146
   *   Location of the post form. Either a Drupal path or an absolute path or
1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
   *   NULL to post to the current page. For multi-stage forms you can set the
   *   path to NULL and have it post to the last received page. Example:
   *
   *   // First step in form.
   *   $edit = array(...);
   *   $this->drupalPost('some_url', $edit, t('Save'));
   *
   *   // Second step in form.
   *   $edit = array(...);
   *   $this->drupalPost(NULL, $edit, t('Save'));
1157
   * @param  $edit
1158
   *   Field data in an associative array. Changes the current input fields
1159
   *   (where possible) to the values indicated. A checkbox can be set to
1160 1161 1162
   *   TRUE to be checked and FALSE to be unchecked. Note that when a form
   *   contains file upload fields, other fields cannot start with the '@'
   *   character.
1163 1164 1165 1166 1167
   *
   *   Multiple select fields can be set using name[] and setting each of the
   *   possible values. Example:
   *   $edit = array();
   *   $edit['name[]'] = array('value1', 'value2');
1168
   * @param $submit
1169
   *   Value of the submit button.
1170 1171
   * @param $options
   *   Options to be forwarded to url().
1172 1173 1174
   * @param $headers
   *   An array containing additional HTTP request headers, each formatted as
   *   "name: value".
1175
   */
1176
  protected function drupalPost($path, $edit, $submit, array $options = array(), array $headers = array()) {
1177 1178
    $submit_matches = FALSE;
    if (isset($path)) {
1179
      $html = $this->drupalGet($path, $options);
1180 1181 1182 1183
    }
    if ($this->parse()) {
      $edit_save = $edit;
      // Let's iterate over all the forms.
1184
      $forms = $this->xpath('//form');
1185
      foreach ($forms as $form) {
1186 1187 1188 1189 1190 1191
        // We try to set the fields of this form as specified in $edit.
        $edit = $edit_save;
        $post = array();
        $upload = array();
        $submit_matches = $this->handleForm($post, $edit, $upload, $submit, $form);
        $action = isset($form['action']) ? $this->getAbsoluteUrl($form['action']) : $this->getUrl();
1192

1193
        // We post only if we managed to handle every field in edit and the
1194
        // submit button matches.
1195
        if (!$edit && $submit_matches) {
1196 1197 1198 1199 1200
          if ($upload) {
            // TODO: cURL handles file uploads for us, but the implementation
            // is broken. This is a less than elegant workaround. Alternatives
            // are being explored at #253506.
            foreach ($upload as $key => $file) {
1201 1202 1203 1204
              $file = realpath($file);
              if ($file && is_file($file)) {
                $post[$key] = '@' . $file;
              }
1205 1206 1207 1208 1209 1210 1211 1212 1213 1214
            }
          }
          else {
            foreach ($post as $key => $value) {
              // Encode according to application/x-www-form-urlencoded
              // Both names and values needs to be urlencoded, according to
              // http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.1
              $post[$key] = urlencode($key) . '=' . urlencode($value);
            }
            $post = implode('&', $post);
1215
          }
1216
          $out = $this->curlExec(array(CURLOPT_URL => $action, CURLOPT_POST => TRUE, CURLOPT_POSTFIELDS => $post, CURLOPT_HTTPHEADER => $headers));
1217
          // Ensure that any changes to variables in the other thread are picked up.
1218
          $this->refreshVariables();
1219 1220 1221 1222 1223

          // Replace original page output with new output from redirected page(s).
          if (($new = $this->checkForMetaRefresh())) {
            $out = $new;
          }
1224
          return $out;
1225 1226 1227 1228 1229 1230
        }
      }
      // We have not found a form which contained all fields of $edit.
      foreach ($edit as $name => $value) {
        $this->fail(t('Failed to set field @name to @value', array('@name' => $name, '@value' => $value)));
      }
1231 1232
      $this->assertTrue($submit_matches, t('Found the @submit button', array('@submit' => $submit)));
      $this->fail(t('Found the requested form fields at @path', array('@path' => $path)));
1233 1234 1235
    }
  }

1236 1237 1238 1239 1240 1241 1242 1243
  /**
   * Check for meta refresh tag and if found call drupalGet() recursively. This
   * function looks for the http-equiv attribute to be set to "Refresh"
   * and is case-sensitive.
   *
   * @return
   *   Either the new page content or FALSE.
   */
1244
  protected function checkForMetaRefresh() {
1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257
    if ($this->drupalGetContent() != '' && $this->parse()) {
      $refresh = $this->xpath('//meta[@http-equiv="Refresh"]');
      if (!empty($refresh)) {
        // Parse the content attribute of the meta tag for the format:
        // "[delay]: URL=[page_to_redirect_to]".
        if (preg_match('/\d+;\s*URL=(?P<url>.*)/i', $refresh[0]['content'], $match)) {
          return $this->drupalGet($this->getAbsoluteUrl(decode_entities($match['url'])));
        }
      }
    }
    return FALSE;
  }

1258 1259 1260 1261 1262 1263 1264
  /**
   * Retrieves only the headers for a Drupal path or an absolute path.
   *
   * @param $path
   *   Drupal path or URL to load into internal browser
   * @param $options
   *   Options to be forwarded to url().
1265 1266 1267
   * @param $headers
   *   An array containing additional HTTP request headers, each formatted as
   *   "name: value".
1268 1269 1270
   * @return
   *   The retrieved headers, also available as $this->drupalGetContent()
   */