drupal_web_test_case.php 62.7 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 59 60 61 62 63 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 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
  /**
   * 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;

  /**
   * Whether a user is logged in the internal browser.
   *
   * @var bool
   */
  protected $isLoggedIn = 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 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;

  /**
   * 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();
111 112 113 114

  /**
   * Constructor for DrupalWebTestCase.
   *
115
   * @param $test_id
116 117
   *   Tests with the same id are reported together.
   */
118 119
  public function __construct($test_id = NULL) {
    $this->testId = $test_id;
120 121 122
  }

  /**
123
   * Internal helper: stores the assert.
124 125
   *
   * @param $status
126 127
   *   Can be 'pass', 'fail', 'exception'.
   *   TRUE is a synonym for 'pass', FALSE for 'fail'.
128 129 130 131
   * @param $message
   *   The message string.
   * @param $group
   *   WHich group this assert belongs to.
132
   * @param $caller
133 134
   *   By default, the assert comes from a function which names start with
   *   'test'. Instead, you can specify where this assert originates from
135
   *   by passing in an associative array as $caller. Key 'file' is
136 137 138
   *   the name of the source file, 'line' is the line number and 'function'
   *   is the caller function itself.
   */
139
  private function assert($status, $message = '', $group = 'Other', $caller = NULL) {
140
    global $db_prefix;
141 142

    // Convert boolean status to string status.
143 144 145
    if (is_bool($status)) {
      $status = $status ? 'pass' : 'fail';
    }
146 147

    // Increment summary result counter.
148
    $this->results['#' . $status]++;
149 150 151 152

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

    // Switch to non-testing database to store results in.
156
    $current_db_prefix = $db_prefix;
157
    $db_prefix = $this->originalPrefix;
158 159

    // Creation assertion array that can be displayed while tests are running.
160 161
    $this->assertions[] = $assertion = array(
      'test_id' => $this->testId,
162
      'test_class' => get_class($this),
163 164
      'status' => $status,
      'message' => $message,
165 166 167 168
      'message_group' => $group,
      'function' => $caller['function'],
      'line' => $caller['line'],
      'file' => $caller['file'],
169
    );
170 171 172 173 174

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

    // Return to testing prefix.
175
    $db_prefix = $current_db_prefix;
176
    return $status == 'pass' ? TRUE : FALSE;
177 178
  }

179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
  /**
   * 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.
    // We skip calls that occured in one of the methods of DrupalWebTestCase
    // 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);
  }

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

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

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

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

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

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

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

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

  /**
   * Fire an error assertion.
   *
   * @param $message
   *   The message to display along with the assertion.
   * @param $group
   *   The type of assertion - examples are "Browser", "PHP".
372
   * @param $caller
373
   *   The caller of the error.
374 375
   * @return
   *   FALSE.
376
   */
377
  protected function error($message = '', $group = 'Other', $caller = NULL) {
378
    return $this->assert('exception', $message, $group, $caller);
379 380 381 382
  }

  /**
   * Run all tests in this class.
383
   */
384
  public function run() {
385 386 387 388 389 390
    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') {
391
        $this->setUp();
392 393 394 395 396 397 398
        try {
          $this->$method();
          // Finish up.
        }
        catch (Exception $e) {
          $this->exceptionHandler($e);
        }
399
        $this->tearDown();
400 401
      }
    }
402 403
    // Clear out the error messages and restore error handler.
    drupal_get_messages();
404 405 406 407 408 409
    restore_error_handler();
  }

  /**
   * Handle errors.
   *
410
   * Because this is registered in set_error_handler(), it has to be public.
411
   * @see set_error_handler
412
   *
413
   */
414
  public function errorHandler($severity, $message, $file = NULL, $line = NULL) {
415
    if ($severity & error_reporting()) {
416 417 418 419 420 421 422 423 424 425 426
      $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',
      );
427 428 429

      $backtrace = debug_backtrace();
      $this->error($message, $error_map[$severity], _drupal_get_last_caller($backtrace));
430 431
    }
    return TRUE;
432 433
  }

434 435 436 437 438
  /**
   * Handle exceptions.
   *
   * @see set_exception_handler
   */
439
  protected function exceptionHandler($exception) {
440 441 442 443 444 445 446 447 448
    $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));
  }

449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
  /**
   * 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;
  }

465 466 467
  /**
   * Creates a node based on default settings.
   *
468 469
   * @param $settings
   *   An associative array of settings to change from the defaults, keys are
470
   *   node properties, for example 'body' => 'Hello, world!'.
471 472
   * @return
   *   Created node object.
473
   */
474
  protected function drupalCreateNode($settings = array()) {
475 476 477 478 479
    // Populate defaults array
    $defaults = array(
      'body'      => $this->randomName(32),
      'title'     => $this->randomName(8),
      'comment'   => 2,
480
      'changed'   => REQUEST_TIME,
481 482 483 484 485 486 487 488 489 490 491 492 493
      'format'    => FILTER_FORMAT_DEFAULT,
      'moderate'  => 0,
      'promote'   => 0,
      'revision'  => 1,
      'log'       => '',
      'status'    => 1,
      'sticky'    => 0,
      'type'      => 'page',
      'revisions' => NULL,
      'taxonomy'  => NULL,
    );
    $defaults['teaser'] = $defaults['body'];
    // If we already have a node, we use the original node's created time, and this
494 495
    if (isset($defaults['created'])) {
      $defaults['date'] = format_date($defaults['created'], 'custom', 'Y-m-d H:i:s O');
496 497 498 499 500 501 502 503 504 505 506
    }
    if (empty($settings['uid'])) {
      global $user;
      $defaults['uid'] = $user->uid;
    }
    $node = ($settings + $defaults);
    $node = (object)$node;

    node_save($node);

    // small hack to link revisions to our test user
507
    db_query('UPDATE {node_revision} SET uid = %d WHERE vid = %d', $node->uid, $node->vid);
508 509 510 511 512 513
    return $node;
  }

  /**
   * Creates a custom content type based on default settings.
   *
514
   * @param $settings
515 516
   *   An array of settings to change from the defaults.
   *   Example: 'type' => 'foo'.
517 518
   * @return
   *   Created content type.
519
   */
520
  protected function drupalCreateContentType($settings = array()) {
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
    // find a non-existent random type name.
    do {
      $name = strtolower($this->randomName(3, 'type_'));
    } 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;

550
    $saved_type = node_type_save($type);
551 552
    node_types_rebuild();

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

555 556 557
    // Reset permissions so that permissions for this content type are available.
    $this->checkPermissions(array(), TRUE);

558 559 560 561 562 563
    return $type;
  }

  /**
   * Get a list files that can be used in tests.
   *
564 565 566 567 568 569
   * @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.
570
   */
571
  protected function drupalGetTestFiles($type, $size = NULL) {
572 573 574 575 576
    $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().
577
      $path = $this->originalFileDirectory . '/simpletest';
578
      $files = file_scan_directory($path, '/' . $type . '\-.*/');
579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594

      // If size is set then remove any files that are not of that size.
      if ($size !== NULL) {
        foreach ($files as $file) {
          $stats = stat($file->filename);
          if ($stats['size'] != $size) {
            unset($files[$file->filename]);
          }
        }
      }
    }
    usort($files, array($this, 'drupalCompareFiles'));
    return $files;
  }

  /**
595
   * Compare two files based on size and file name.
596
   */
597
  protected function drupalCompareFiles($file1, $file2) {
598 599 600 601 602 603 604 605 606
    // Determine which file is larger.
    $compare_size = (filesize($file1->filename) > filesize($file2->filename));
    if (!$compare_size) {
      // Both files were the same size, so return whichever one is alphabetically greater.
      return strnatcmp($file1->name, $file2->name);
    }
    else {
      // Return TRUE if $file1 is larger than $file2.
      return $compare_size;
607 608 609 610 611 612
    }
  }

  /**
   * Generates a random string.
   *
613 614 615 616 617 618
   * @param $number
   *   Number of characters in length to append to the prefix.
   * @param $prefix
   *   Prefix to use.
   * @return
   *   Randomly generated string.
619
   */
620
  public static function randomName($number = 4, $prefix = 'simpletest_') {
621 622 623 624 625 626 627 628 629 630 631 632 633 634
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_';
    for ($x = 0; $x < $number; $x++) {
      $prefix .= $chars{mt_rand(0, strlen($chars) - 1)};
      if ($x == 0) {
        $chars .= '0123456789';
      }
    }
    return $prefix;
  }

  /**
   * Create a user with a given set of permissions. The permissions correspond to the
   * names given on the privileges page.
   *
635 636 637 638
   * @param $permissions
   *   Array of permission names to assign to user.
   * @return
   *   A fully loaded user object with pass_raw property, or FALSE if account
639 640
   *   creation fails.
   */
641
  protected function drupalCreateUser($permissions = NULL) {
642
    // Create a role with the given permission set.
643
    if (!($rid = $this->_drupalCreateRole($permissions))) {
644 645 646 647 648 649
      return FALSE;
    }

    // Create a user assigned to that role.
    $edit = array();
    $edit['name']   = $this->randomName();
650
    $edit['mail']   = $edit['name'] . '@example.com';
651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669
    $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.
   *
670 671 672 673
   * @param $permissions
   *   Array of permission names to assign to role.
   * @return
   *   Role ID of newly created role, or FALSE if role creation failed.
674
   */
675
  protected function _drupalCreateRole(Array $permissions = NULL) {
676 677
    // Generate string version of permissions list.
    if ($permissions === NULL) {
678
      $permissions = array('access comments', 'access content', 'post comments', 'post comments without approval');
679 680
    }

681 682 683 684
    if (!$this->checkPermissions($permissions)) {
      return FALSE;
    }

685 686 687 688 689 690 691
    // 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.
692 693 694 695 696
      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'));
697 698 699 700 701 702 703
      return $role->rid;
    }
    else {
      return FALSE;
    }
  }

704 705 706
  /**
   * Check to make sure that the array of permissions are valid.
   *
707 708 709 710 711 712
   * @param $permissions
   *   Permissions to check.
   * @param $reset
   *   Reset cached available permissions.
   * @return
   *   TRUE or FALSE depending on whether the permissions are valid.
713
   */
714
  protected function checkPermissions(Array $permissions, $reset = FALSE) {
715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730
    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;
  }

731 732 733 734 735
  /**
   * Logs in a user with the internal browser. If already logged in then logs the current
   * user out before logging in the specified user. If no user is specified then a new
   * user will be created and logged in.
   *
736 737 738 739 740
   * @param $user
   *   User object representing the user to login.
   * @return
   *   User that was logged in. Useful if no user was passed in order to retrieve
   *   the created user.
741
   */
742 743
  protected function drupalLogin($user = NULL) {
    if ($this->isLoggedIn) {
744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760
      $this->drupalLogout();
    }

    if (!isset($user)) {
      $user = $this->_drupalCreateRole();
    }

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

761
    $this->isLoggedIn = $pass;
762 763 764 765 766 767 768

    return $user;
  }

  /*
   * Logs a user out of the internal browser, then check the login page to confirm logout.
   */
769
  protected function drupalLogout() {
770
    // Make a request to the logout page.
771
    $this->drupalGet('user/logout');
772 773 774 775 776 777

    // 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'));

778
    $this->isLoggedIn = !$pass;
779 780 781
  }

  /**
782 783 784 785
   * 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
786
   * is created with the same name as the database prefix.
787
   *
788
   * @param ...
789
   *   List of modules to enable for the duration of the test.
790
   */
791
  protected function setUp() {
792
    global $db_prefix;
793 794

    // Store necessary current values before switching to prefixed database.
795
    $this->originalPrefix = $db_prefix;
796
    $clean_url_original = variable_get('clean_url', 0);
797 798

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

801
    include_once DRUPAL_ROOT . '/includes/install.inc';
802
    drupal_install_system();
803

804 805
    $this->preloadRegistry();

806
    // Add the specified modules to the list of modules in the default profile.
807
    $args = func_get_args();
808
    $modules = array_unique(array_merge(drupal_get_profile_modules('default', 'en'), $args));
809
    drupal_install_modules($modules);
810

811 812 813 814 815
    // Because the schema is static cached, we need to flush
    // it between each run.  If we don't, then it will contain
    // stale data for the previous run's database prefix and all
    // calls to it will fail.
    drupal_get_schema(NULL, TRUE);
816

817
    // Run default profile tasks.
818 819
    $task = 'profile';
    default_profile_tasks($task, '');
820 821

    // Rebuild caches.
822 823
    actions_synchronize();
    _drupal_flush_css_js();
824
    $this->refreshVariables();
825
    $this->checkPermissions(array(), TRUE);
826 827

    // Restore necessary variables.
828 829 830
    variable_set('install_profile', 'default');
    variable_set('install_task', 'profile-finished');
    variable_set('clean_url', $clean_url_original);
831
    variable_set('site_mail', 'simpletest@example.com');
832 833

    // Use temporary files directory with the same prefix as database.
834
    $this->originalFileDirectory = file_directory_path();
835
    variable_set('file_directory_path', file_directory_path() . '/' . $db_prefix);
836
    $directory = file_directory_path();
837
    file_check_directory($directory, FILE_CREATE_DIRECTORY); // Create the files directory.
838 839
  }

840 841 842 843 844 845 846 847 848 849
  /**
   * 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 the a clean environment for the current test run. 
   */ 
  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');
  }

850 851 852 853 854 855 856 857 858 859 860 861
  /**
   * 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.
   */
862
  protected function refreshVariables() {
863 864 865 866 867
    global $conf;
    cache_clear_all('variables', 'cache');
    $conf = variable_init();
  }

868 869 870 871
  /**
   * Delete created files and temporary files directory, delete the tables created by setUp(),
   * and reset the database prefix.
   */
872
  protected function tearDown() {
873 874 875
    global $db_prefix;
    if (preg_match('/simpletest\d+/', $db_prefix)) {
      // Delete temporary files directory and reset files directory path.
876
      simpletest_clean_temporary_directory(file_directory_path());
877
      variable_set('file_directory_path', $this->originalFileDirectory);
878

879
      // Remove all prefixed tables (all the tables in the schema).
880 881 882 883 884
      $schema = drupal_get_schema(NULL, TRUE);
      $ret = array();
      foreach ($schema as $name => $table) {
        db_drop_table($ret, $name);
      }
885 886

      // Return the database prefix to the original.
887
      $db_prefix = $this->originalPrefix;
888 889

      // Ensure that the internal logged in variable is reset.
890
      $this->isLoggedIn = FALSE;
891

892 893
      // Reload module list and implementations to ensure that test module hooks
      // aren't called after tests.
894
      module_list(TRUE);
895
      module_implements(MODULE_IMPLEMENTS_CLEAR_CACHE);
896 897 898 899

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

900
      // Close the CURL handler.
901 902 903 904 905
      $this->curlClose();
    }
  }

  /**
906
   * Initializes the cURL connection.
907
   *
908 909 910
   * This function will add authentication headers as specified in the
   * simpletest_httpauth_username and simpletest_httpauth_pass variables. Also,
   * see the description of $curl_options among the properties.
911
   */
912
  protected function curlInitialize() {
913
    global $base_url, $db_prefix;
914 915 916 917
    if (!isset($this->curlHandle)) {
      $this->curlHandle = curl_init();
      $curl_options = $this->additionalCurlOptions + array(
        CURLOPT_COOKIEJAR => $this->cookieFile,
918 919 920
        CURLOPT_URL => $base_url,
        CURLOPT_FOLLOWLOCATION => TRUE,
        CURLOPT_RETURNTRANSFER => TRUE,
921 922
        CURLOPT_SSL_VERIFYPEER => FALSE,  // Required to make the tests run on https://
        CURLOPT_SSL_VERIFYHOST => FALSE,  // Required to make the tests run on https://
923
        CURLOPT_HEADERFUNCTION => array(&$this, 'curlHeaderCallback'),
924
      );
925 926
      if (preg_match('/simpletest\d+/', $db_prefix, $matches)) {
        $curl_options[CURLOPT_USERAGENT] = $matches[0];
927 928 929
      }
      if (!isset($curl_options[CURLOPT_USERPWD]) && ($auth = variable_get('simpletest_httpauth_username', ''))) {
        if ($pass = variable_get('simpletest_httpauth_pass', '')) {
930
          $auth .= ':' . $pass;
931 932 933
        }
        $curl_options[CURLOPT_USERPWD] = $auth;
      }
934
      curl_setopt_array($this->curlHandle, $this->additionalCurlOptions + $curl_options);
935 936 937 938
    }
  }

  /**
939
   * Performs a cURL exec with the specified options after calling curlConnect().
940
   *
941 942
   * @param $curl_options
   *   Custom cURL options.
943 944
   * @return
   *   Content returned from the exec.
945 946
   */
  protected function curlExec($curl_options) {
947
    $this->curlInitialize();
948 949
    $url = empty($curl_options[CURLOPT_URL]) ? curl_getinfo($this->curlHandle, CURLINFO_EFFECTIVE_URL) : $curl_options[CURLOPT_URL];
    curl_setopt_array($this->curlHandle, $this->additionalCurlOptions + $curl_options);
950
    $this->headers = array();
951 952
    $this->drupalSetContent(curl_exec($this->curlHandle), curl_getinfo($this->curlHandle, CURLINFO_EFFECTIVE_URL));
    $this->assertTrue($this->content !== FALSE, t('!method to !url, response is !length bytes.', array('!method' => !empty($curl_options[CURLOPT_NOBODY]) ? 'HEAD' : (empty($curl_options[CURLOPT_POSTFIELDS]) ? 'GET' : 'POST'), '!url' => $url, '!length' => strlen($this->content))), t('Browser'));
953
    return $this->drupalGetContent();
954 955
  }

956 957 958 959 960
  /**
   * Reads headers and registers errors received from the tested site.
   *
   * @see _drupal_log_error().
   *
961 962 963 964
   * @param $curlHandler
   *   The cURL handler.
   * @param $header
   *   An header.
965
   */
966
  protected function curlHeaderCallback($curlHandler, $header) {
967
    $this->headers[] = $header;
968 969 970 971 972 973 974 975 976 977 978
    // 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);
  }

979 980 981 982
  /**
   * Close the cURL handler and unset the handler.
   */
  protected function curlClose() {
983 984 985
    if (isset($this->curlHandle)) {
      curl_close($this->curlHandle);
      unset($this->curlHandle);
986 987 988 989
    }
  }

  /**
990
   * Parse content returned from curlExec using DOM and SimpleXML.
991
   *
992 993
   * @return
   *   A SimpleXMLElement or FALSE on failure.
994 995 996 997 998
   */
  protected function parse() {
    if (!$this->elements) {
      // DOM can load HTML soup. But, HTML soup can throw warnings, supress
      // them.
999
      @$htmlDom = DOMDocument::loadHTML($this->content);
1000
      if ($htmlDom) {
1001
        $this->pass(t('Valid HTML found on "@path"', array('@path' => $this->getUrl())), t('Browser'));
1002 1003 1004 1005 1006
        // 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);
      }
    }
1007 1008 1009
    if (!$this->elements) {
      $this->fail(t('Parsed page successfully.'), t('Browser'));
    }
1010

1011 1012 1013 1014 1015 1016
    return $this->elements;
  }

  /**
   * Retrieves a Drupal path or an absolute path.
   *
1017
   * @param $path
1018
   *   Drupal path or URL to load into internal browser
1019
   * @param $options
1020
   *   Options to be forwarded to url().
1021 1022 1023
   * @param $headers
   *   An array containing additional HTTP request headers, each formatted as
   *   "name: value".
1024
   * @return
1025
   *   The retrieved HTML string, also available as $this->drupalGetContent()
1026
   */
1027
  protected function drupalGet($path, Array $options = array(), Array $headers = array()) {
1028
    $options['absolute'] = TRUE;
1029 1030 1031 1032

    // 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
    // previous options.
1033
    $out = $this->curlExec(array(CURLOPT_HTTPGET => TRUE, CURLOPT_URL => url($path, $options), CURLOPT_NOBODY => FALSE, CURLOPT_HTTPHEADER => $headers));
1034
    $this->refreshVariables(); // Ensure that any changes to variables in the other thread are picked up.
1035 1036 1037 1038 1039

    // Replace original page output with new output from redirected page(s).
    if (($new = $this->checkForMetaRefresh())) {
      $out = $new;
    }
1040
    return $out;
1041 1042 1043
  }

  /**
1044 1045
   * Execute a POST request on a Drupal page.
   * It will be done as usual POST request with SimpleBrowser.
1046
   *
1047
   * @param $path
1048
   *   Location of the post form. Either a Drupal path or an absolute path or
1049 1050 1051 1052 1053 1054 1055 1056 1057 1058
   *   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'));
1059
   * @param  $edit
1060 1061
   *   Field data in an assocative array. Changes the current input fields
   *   (where possible) to the values indicated. A checkbox can be set to
1062 1063 1064
   *   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.
1065 1066 1067 1068 1069
   *
   *   Multiple select fields can be set using name[] and setting each of the
   *   possible values. Example:
   *   $edit = array();
   *   $edit['name[]'] = array('value1', 'value2');
1070
   * @param $submit
1071
   *   Value of the submit button.
1072 1073
   * @param $options
   *   Options to be forwarded to url().
1074 1075 1076
   * @param $headers
   *   An array containing additional HTTP request headers, each formatted as
   *   "name: value".
1077
   */
1078
  protected function drupalPost($path, $edit, $submit, Array $options = array(), Array $headers = array()) {
1079 1080
    $submit_matches = FALSE;
    if (isset($path)) {
1081
      $html = $this->drupalGet($path, $options);
1082 1083 1084 1085
    }
    if ($this->parse()) {
      $edit_save = $edit;
      // Let's iterate over all the forms.
1086
      $forms = $this->xpath('//form');
1087
      foreach ($forms as $form) {
1088 1089 1090 1091 1092 1093
        // 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();
1094

1095
        // We post only if we managed to handle every field in edit and the
1096
        // submit button matches.
1097
        if (!$edit && $submit_matches) {
1098 1099 1100 1101 1102
          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) {
1103 1104 1105 1106
              $file = realpath($file);
              if ($file && is_file($file)) {
                $post[$key] = '@' . $file;
              }
1107 1108 1109 1110 1111 1112 1113 1114 1115 1116
            }
          }
          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);
1117
          }
1118
          $out = $this->curlExec(array(CURLOPT_URL => $action, CURLOPT_POST => TRUE, CURLOPT_POSTFIELDS => $post, CURLOPT_HTTPHEADER => $headers));
1119
          // Ensure that any changes to variables in the other thread are picked up.
1120
          $this->refreshVariables();
1121 1122 1123 1124 1125

          // Replace original page output with new output from redirected page(s).
          if (($new = $this->checkForMetaRefresh())) {
            $out = $new;
          }
1126
          return $out;
1127 1128 1129 1130 1131 1132
        }
      }
      // 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)));
      }
1133 1134
      $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)));
1135 1136 1137
    }
  }

1138 1139 1140 1141 1142 1143 1144 1145
  /**
   * 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.
   */
1146
  protected function checkForMetaRefresh() {
1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159
    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;
  }

1160 1161 1162 1163 1164 1165 1166
  /**
   * 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().
1167 1168 1169
   * @param $headers
   *   An array containing additional HTTP request headers, each formatted as
   *   "name: value".
1170 1171