PageRenderTime 89ms CodeModel.GetById 17ms app.highlight 59ms RepoModel.GetById 1ms app.codeStats 1ms

/modules/simpletest/drupal_web_test_case.php

https://github.com/jacobSingh/drupal
PHP | 2767 lines | 1188 code | 228 blank | 1351 comment | 181 complexity | e68609ca32c0feefd59967f83425a5e1 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   1<?php
   2// $Id: drupal_web_test_case.php,v 1.188 2010-01-04 23:08:34 webchick Exp $
   3
   4/**
   5 * Base class for Drupal tests.
   6 *
   7 * Do not extend this class, use one of the subclasses in this file.
   8 */
   9abstract class DrupalTestCase {
  10  /**
  11   * The test run ID.
  12   *
  13   * @var string
  14   */
  15  protected $testId;
  16
  17  /**
  18   * The original database prefix, before it was changed for testing purposes.
  19   *
  20   * @var string
  21   */
  22  protected $originalPrefix = NULL;
  23
  24  /**
  25   * The original file directory, before it was changed for testing purposes.
  26   *
  27   * @var string
  28   */
  29  protected $originalFileDirectory = NULL;
  30
  31  /**
  32   * Time limit for the test.
  33   */
  34  protected $timeLimit = 500;
  35
  36  /**
  37   * Current results of this test case.
  38   *
  39   * @var Array
  40   */
  41  public $results = array(
  42    '#pass' => 0,
  43    '#fail' => 0,
  44    '#exception' => 0,
  45    '#debug' => 0,
  46  );
  47
  48  /**
  49   * Assertions thrown in that test case.
  50   *
  51   * @var Array
  52   */
  53  protected $assertions = array();
  54
  55  /**
  56   * This class is skipped when looking for the source of an assertion.
  57   *
  58   * When displaying which function an assert comes from, it's not too useful
  59   * to see "drupalWebTestCase->drupalLogin()', we would like to see the test
  60   * that called it. So we need to skip the classes defining these helper
  61   * methods.
  62   */
  63  protected $skipClasses = array(__CLASS__ => TRUE);
  64
  65  /**
  66   * Constructor for DrupalWebTestCase.
  67   *
  68   * @param $test_id
  69   *   Tests with the same id are reported together.
  70   */
  71  public function __construct($test_id = NULL) {
  72    $this->testId = $test_id;
  73  }
  74
  75  /**
  76   * Internal helper: stores the assert.
  77   *
  78   * @param $status
  79   *   Can be 'pass', 'fail', 'exception'.
  80   *   TRUE is a synonym for 'pass', FALSE for 'fail'.
  81   * @param $message
  82   *   The message string.
  83   * @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   *   the name of the source file, 'line' is the line number and 'function'
  90   *   is the caller function itself.
  91   */
  92  protected function assert($status, $message = '', $group = 'Other', array $caller = NULL) {
  93    global $db_prefix;
  94
  95    // Convert boolean status to string status.
  96    if (is_bool($status)) {
  97      $status = $status ? 'pass' : 'fail';
  98    }
  99
 100    // Increment summary result counter.
 101    $this->results['#' . $status]++;
 102
 103    // Get the function information about the call to the assertion method.
 104    if (!$caller) {
 105      $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    $this->assertions[] = $assertion = array(
 114      'test_id' => $this->testId,
 115      'test_class' => get_class($this),
 116      'status' => $status,
 117      'message' => $message,
 118      'message_group' => $group,
 119      'function' => $caller['function'],
 120      'line' => $caller['line'],
 121      'file' => $caller['file'],
 122    );
 123
 124    // Store assertion for display after the test has completed.
 125    db_insert('simpletest')
 126      ->fields($assertion)
 127      ->execute();
 128
 129    // Return to testing prefix.
 130    $db_prefix = $current_db_prefix;
 131    // We do not use a ternary operator here to allow a breakpoint on
 132    // test failure.
 133    if ($status == 'pass') {
 134      return TRUE;
 135    }
 136    else {
 137      return FALSE;
 138    }
 139  }
 140
 141  /**
 142   * Store an assertion from outside the testing context.
 143   *
 144   * This is useful for inserting assertions that can only be recorded after
 145   * the test case has been destroyed, such as PHP fatal errors. The caller
 146   * information is not automatically gathered since the caller is most likely
 147   * inserting the assertion on behalf of other code. In all other respects
 148   * the method behaves just like DrupalTestCase::assert() in terms of storing
 149   * the assertion.
 150   *
 151   * @return
 152   *   Message ID of the stored assertion.
 153   *
 154   * @see DrupalTestCase::assert()
 155   * @see DrupalTestCase::deleteAssert()
 156   */
 157  public static function insertAssert($test_id, $test_class, $status, $message = '', $group = 'Other', array $caller = array()) {
 158    // Convert boolean status to string status.
 159    if (is_bool($status)) {
 160      $status = $status ? 'pass' : 'fail';
 161    }
 162
 163    $caller += array(
 164      'function' => t('Unknown'),
 165      'line' => 0,
 166      'file' => t('Unknown'),
 167    );
 168
 169    $assertion = array(
 170      'test_id' => $test_id,
 171      'test_class' => $test_class,
 172      'status' => $status,
 173      'message' => $message,
 174      'message_group' => $group,
 175      'function' => $caller['function'],
 176      'line' => $caller['line'],
 177      'file' => $caller['file'],
 178    );
 179
 180    return db_insert('simpletest')
 181      ->fields($assertion)
 182      ->execute();
 183  }
 184
 185  /**
 186   * Delete an assertion record by message ID.
 187   *
 188   * @param $message_id
 189   *   Message ID of the assertion to delete.
 190   * @return
 191   *   TRUE if the assertion was deleted, FALSE otherwise.
 192   *
 193   * @see DrupalTestCase::insertAssert()
 194   */
 195  public static function deleteAssert($message_id) {
 196    return (bool) db_delete('simpletest')
 197      ->condition('message_id', $message_id)
 198      ->execute();
 199  }
 200
 201  /**
 202   * Cycles through backtrace until the first non-assertion method is found.
 203   *
 204   * @return
 205   *   Array representing the true caller.
 206   */
 207  protected function getAssertionCall() {
 208    $backtrace = debug_backtrace();
 209
 210    // The first element is the call. The second element is the caller.
 211    // We skip calls that occurred in one of the methods of our base classes
 212    // or in an assertion function.
 213   while (($caller = $backtrace[1]) &&
 214         ((isset($caller['class']) && isset($this->skipClasses[$caller['class']])) ||
 215           substr($caller['function'], 0, 6) == 'assert')) {
 216      // We remove that call.
 217      array_shift($backtrace);
 218    }
 219
 220    return _drupal_get_last_caller($backtrace);
 221  }
 222
 223  /**
 224   * Check to see if a value is not false (not an empty string, 0, NULL, or FALSE).
 225   *
 226   * @param $value
 227   *   The value on which the assertion is to be done.
 228   * @param $message
 229   *   The message to display along with the assertion.
 230   * @param $group
 231   *   The type of assertion - examples are "Browser", "PHP".
 232   * @return
 233   *   TRUE if the assertion succeeded, FALSE otherwise.
 234   */
 235  protected function assertTrue($value, $message = '', $group = 'Other') {
 236    return $this->assert((bool) $value, $message ? $message : t('Value @value is TRUE.', array('@value' => var_export($value, TRUE))), $group);
 237  }
 238
 239  /**
 240   * Check to see if a value is false (an empty string, 0, NULL, or FALSE).
 241   *
 242   * @param $value
 243   *   The value on which the assertion is to be done.
 244   * @param $message
 245   *   The message to display along with the assertion.
 246   * @param $group
 247   *   The type of assertion - examples are "Browser", "PHP".
 248   * @return
 249   *   TRUE if the assertion succeeded, FALSE otherwise.
 250   */
 251  protected function assertFalse($value, $message = '', $group = 'Other') {
 252    return $this->assert(!$value, $message ? $message : t('Value @value is FALSE.', array('@value' => var_export($value, TRUE))), $group);
 253  }
 254
 255  /**
 256   * Check to see if a value is NULL.
 257   *
 258   * @param $value
 259   *   The value on which the assertion is to be done.
 260   * @param $message
 261   *   The message to display along with the assertion.
 262   * @param $group
 263   *   The type of assertion - examples are "Browser", "PHP".
 264   * @return
 265   *   TRUE if the assertion succeeded, FALSE otherwise.
 266   */
 267  protected function assertNull($value, $message = '', $group = 'Other') {
 268    return $this->assert(!isset($value), $message ? $message : t('Value @value is NULL.', array('@value' => var_export($value, TRUE))), $group);
 269  }
 270
 271  /**
 272   * Check to see if a value is not NULL.
 273   *
 274   * @param $value
 275   *   The value on which the assertion is to be done.
 276   * @param $message
 277   *   The message to display along with the assertion.
 278   * @param $group
 279   *   The type of assertion - examples are "Browser", "PHP".
 280   * @return
 281   *   TRUE if the assertion succeeded, FALSE otherwise.
 282   */
 283  protected function assertNotNull($value, $message = '', $group = 'Other') {
 284    return $this->assert(isset($value), $message ? $message : t('Value @value is not NULL.', array('@value' => var_export($value, TRUE))), $group);
 285  }
 286
 287  /**
 288   * Check to see if two values are equal.
 289   *
 290   * @param $first
 291   *   The first value to check.
 292   * @param $second
 293   *   The second value to check.
 294   * @param $message
 295   *   The message to display along with the assertion.
 296   * @param $group
 297   *   The type of assertion - examples are "Browser", "PHP".
 298   * @return
 299   *   TRUE if the assertion succeeded, FALSE otherwise.
 300   */
 301  protected function assertEqual($first, $second, $message = '', $group = 'Other') {
 302    return $this->assert($first == $second, $message ? $message : t('Value @first is equal to value @second.', array('@first' => var_export($first, TRUE), '@second' => var_export($second, TRUE))), $group);
 303  }
 304
 305  /**
 306   * Check to see if two values are not equal.
 307   *
 308   * @param $first
 309   *   The first value to check.
 310   * @param $second
 311   *   The second value to check.
 312   * @param $message
 313   *   The message to display along with the assertion.
 314   * @param $group
 315   *   The type of assertion - examples are "Browser", "PHP".
 316   * @return
 317   *   TRUE if the assertion succeeded, FALSE otherwise.
 318   */
 319  protected function assertNotEqual($first, $second, $message = '', $group = 'Other') {
 320    return $this->assert($first != $second, $message ? $message : t('Value @first is not equal to value @second.', array('@first' => var_export($first, TRUE), '@second' => var_export($second, TRUE))), $group);
 321  }
 322
 323  /**
 324   * Check to see if two values are identical.
 325   *
 326   * @param $first
 327   *   The first value to check.
 328   * @param $second
 329   *   The second value to check.
 330   * @param $message
 331   *   The message to display along with the assertion.
 332   * @param $group
 333   *   The type of assertion - examples are "Browser", "PHP".
 334   * @return
 335   *   TRUE if the assertion succeeded, FALSE otherwise.
 336   */
 337  protected function assertIdentical($first, $second, $message = '', $group = 'Other') {
 338    return $this->assert($first === $second, $message ? $message : t('Value @first is identical to value @second.', array('@first' => var_export($first, TRUE), '@second' => var_export($second, TRUE))), $group);
 339  }
 340
 341  /**
 342   * Check to see if two values are not identical.
 343   *
 344   * @param $first
 345   *   The first value to check.
 346   * @param $second
 347   *   The second value to check.
 348   * @param $message
 349   *   The message to display along with the assertion.
 350   * @param $group
 351   *   The type of assertion - examples are "Browser", "PHP".
 352   * @return
 353   *   TRUE if the assertion succeeded, FALSE otherwise.
 354   */
 355  protected function assertNotIdentical($first, $second, $message = '', $group = 'Other') {
 356    return $this->assert($first !== $second, $message ? $message : t('Value @first is not identical to value @second.', array('@first' => var_export($first, TRUE), '@second' => var_export($second, TRUE))), $group);
 357  }
 358
 359  /**
 360   * Fire an assertion that is always positive.
 361   *
 362   * @param $message
 363   *   The message to display along with the assertion.
 364   * @param $group
 365   *   The type of assertion - examples are "Browser", "PHP".
 366   * @return
 367   *   TRUE.
 368   */
 369  protected function pass($message = NULL, $group = 'Other') {
 370    return $this->assert(TRUE, $message, $group);
 371  }
 372
 373  /**
 374   * Fire an assertion that is always negative.
 375   *
 376   * @param $message
 377   *   The message to display along with the assertion.
 378   * @param $group
 379   *   The type of assertion - examples are "Browser", "PHP".
 380   * @return
 381   *   FALSE.
 382   */
 383  protected function fail($message = NULL, $group = 'Other') {
 384    return $this->assert(FALSE, $message, $group);
 385  }
 386
 387  /**
 388   * Fire an error assertion.
 389   *
 390   * @param $message
 391   *   The message to display along with the assertion.
 392   * @param $group
 393   *   The type of assertion - examples are "Browser", "PHP".
 394   * @param $caller
 395   *   The caller of the error.
 396   * @return
 397   *   FALSE.
 398   */
 399  protected function error($message = '', $group = 'Other', array $caller = NULL) {
 400    if ($group == 'User notice') {
 401      // Since 'User notice' is set by trigger_error() which is used for debug
 402      // set the message to a status of 'debug'.
 403      return $this->assert('debug', $message, 'Debug', $caller);
 404    }
 405
 406    return $this->assert('exception', $message, $group, $caller);
 407  }
 408
 409  /**
 410   * Run all tests in this class.
 411   */
 412  public function run() {
 413    // Initialize verbose debugging.
 414    simpletest_verbose(NULL, file_directory_path(), get_class($this));
 415
 416    // HTTP auth settings (<username>:<password>) for the simpletest browser
 417    // when sending requests to the test site.
 418    $this->httpauth_method = variable_get('simpletest_httpauth_method', CURLAUTH_BASIC);
 419    $username = variable_get('simpletest_httpauth_username', NULL);
 420    $password = variable_get('simpletest_httpauth_password', NULL);
 421    if ($username && $password) {
 422      $this->httpauth_credentials = $username . ':' . $password;
 423    }
 424
 425    set_error_handler(array($this, 'errorHandler'));
 426    $class = get_class($this);
 427    // Iterate through all the methods in this class.
 428    foreach (get_class_methods($class) as $method) {
 429      // If the current method starts with "test", run it - it's a test.
 430      if (strtolower(substr($method, 0, 4)) == 'test') {
 431        // Insert a fail record. This will be deleted on completion to ensure
 432        // that testing completed.
 433        $method_info = new ReflectionMethod($class, $method);
 434        $caller = array(
 435          'file' => $method_info->getFileName(),
 436          'line' => $method_info->getStartLine(),
 437          'function' => $class . '->' . $method . '()',
 438        );
 439        $completion_check_id = DrupalTestCase::insertAssert($this->testId, $class, FALSE, t('The test did not complete due to a fatal error.'), 'Completion check', $caller);
 440        $this->setUp();
 441        try {
 442          $this->$method();
 443          // Finish up.
 444        }
 445        catch (Exception $e) {
 446          $this->exceptionHandler($e);
 447        }
 448        $this->tearDown();
 449        // Remove the completion check record.
 450        DrupalTestCase::deleteAssert($completion_check_id);
 451      }
 452    }
 453    // Clear out the error messages and restore error handler.
 454    drupal_get_messages();
 455    restore_error_handler();
 456  }
 457
 458  /**
 459   * Handle errors during test runs.
 460   *
 461   * Because this is registered in set_error_handler(), it has to be public.
 462   * @see set_error_handler
 463   */
 464  public function errorHandler($severity, $message, $file = NULL, $line = NULL) {
 465    if ($severity & error_reporting()) {
 466      $error_map = array(
 467        E_STRICT => 'Run-time notice',
 468        E_WARNING => 'Warning',
 469        E_NOTICE => 'Notice',
 470        E_CORE_ERROR => 'Core error',
 471        E_CORE_WARNING => 'Core warning',
 472        E_USER_ERROR => 'User error',
 473        E_USER_WARNING => 'User warning',
 474        E_USER_NOTICE => 'User notice',
 475        E_RECOVERABLE_ERROR => 'Recoverable error',
 476      );
 477
 478      $backtrace = debug_backtrace();
 479      $this->error($message, $error_map[$severity], _drupal_get_last_caller($backtrace));
 480    }
 481    return TRUE;
 482  }
 483
 484  /**
 485   * Handle exceptions.
 486   *
 487   * @see set_exception_handler
 488   */
 489  protected function exceptionHandler($exception) {
 490    $backtrace = $exception->getTrace();
 491    // Push on top of the backtrace the call that generated the exception.
 492    array_unshift($backtrace, array(
 493      'line' => $exception->getLine(),
 494      'file' => $exception->getFile(),
 495    ));
 496    $this->error($exception->getMessage(), 'Uncaught exception', _drupal_get_last_caller($backtrace));
 497  }
 498
 499  /**
 500   * Generates a random string of ASCII characters of codes 32 to 126.
 501   *
 502   * The generated string includes alpha-numeric characters and common misc
 503   * characters. Use this method when testing general input where the content
 504   * is not restricted.
 505   *
 506   * @param $length
 507   *   Length of random string to generate which will be appended to $db_prefix.
 508   * @return
 509   *   Randomly generated string.
 510   */
 511  public static function randomString($length = 8) {
 512    global $db_prefix;
 513
 514    $str = '';
 515    for ($i = 0; $i < $length; $i++) {
 516      $str .= chr(mt_rand(32, 126));
 517    }
 518    return str_replace('simpletest', 's', $db_prefix) . $str;
 519  }
 520
 521  /**
 522   * Generates a random string containing letters and numbers.
 523   *
 524   * The letters may be upper or lower case. This method is better for
 525   * restricted inputs that do not accept certain characters. For example,
 526   * when testing input fields that require machine readable values (ie without
 527   * spaces and non-standard characters) this method is best.
 528   *
 529   * @param $length
 530   *   Length of random string to generate which will be appended to $db_prefix.
 531   * @return
 532   *   Randomly generated string.
 533   */
 534  public static function randomName($length = 8) {
 535    global $db_prefix;
 536
 537    $values = array_merge(range(65, 90), range(97, 122), range(48, 57));
 538    $max = count($values) - 1;
 539    $str = '';
 540    for ($i = 0; $i < $length; $i++) {
 541      $str .= chr($values[mt_rand(0, $max)]);
 542    }
 543    return str_replace('simpletest', 's', $db_prefix) . $str;
 544  }
 545
 546}
 547
 548/**
 549 * Test case for Drupal unit tests.
 550 *
 551 * These tests can not access the database nor files. Calling any Drupal
 552 * function that needs the database will throw exceptions. These include
 553 * watchdog(), function_exists(), module_implements(),
 554 * module_invoke_all() etc.
 555 */
 556class DrupalUnitTestCase extends DrupalTestCase {
 557
 558  /**
 559   * Constructor for DrupalUnitTestCase.
 560   */
 561  function __construct($test_id = NULL) {
 562    parent::__construct($test_id);
 563    $this->skipClasses[__CLASS__] = TRUE;
 564  }
 565
 566  protected function setUp() {
 567    global $db_prefix, $conf;
 568
 569    // Store necessary current values before switching to prefixed database.
 570    $this->originalPrefix = $db_prefix;
 571    $this->originalFileDirectory = file_directory_path();
 572
 573    // Reset all statics so that test is performed with a clean environment.
 574    drupal_static_reset();
 575
 576    // Generate temporary prefixed database to ensure that tests have a clean starting point.
 577    $db_prefix = Database::getConnection()->prefixTables('{simpletest' . mt_rand(1000, 1000000) . '}');
 578    $conf['file_public_path'] = $this->originalFileDirectory . '/' . $db_prefix;
 579
 580    // If locale is enabled then t() will try to access the database and
 581    // subsequently will fail as the database is not accessible.
 582    $module_list = module_list();
 583    if (isset($module_list['locale'])) {
 584      $this->originalModuleList = $module_list;
 585      unset($module_list['locale']);
 586      module_list(TRUE, FALSE, FALSE, $module_list);
 587    }
 588  }
 589
 590  protected function tearDown() {
 591    global $db_prefix, $conf;
 592    if (preg_match('/simpletest\d+/', $db_prefix)) {
 593      $conf['file_public_path'] = $this->originalFileDirectory;
 594      // Return the database prefix to the original.
 595      $db_prefix = $this->originalPrefix;
 596      // Restore modules if necessary.
 597      if (isset($this->originalModuleList)) {
 598        module_list(TRUE, FALSE, FALSE, $this->originalModuleList);
 599      }
 600    }
 601  }
 602}
 603
 604/**
 605 * Test case for typical Drupal tests.
 606 */
 607class DrupalWebTestCase extends DrupalTestCase {
 608  /**
 609   * The URL currently loaded in the internal browser.
 610   *
 611   * @var string
 612   */
 613  protected $url;
 614
 615  /**
 616   * The handle of the current cURL connection.
 617   *
 618   * @var resource
 619   */
 620  protected $curlHandle;
 621
 622  /**
 623   * The headers of the page currently loaded in the internal browser.
 624   *
 625   * @var Array
 626   */
 627  protected $headers;
 628
 629  /**
 630   * The content of the page currently loaded in the internal browser.
 631   *
 632   * @var string
 633   */
 634  protected $content;
 635
 636  /**
 637   * The content of the page currently loaded in the internal browser (plain text version).
 638   *
 639   * @var string
 640   */
 641  protected $plainTextContent;
 642
 643  /**
 644   * The parsed version of the page.
 645   *
 646   * @var SimpleXMLElement
 647   */
 648  protected $elements = NULL;
 649
 650  /**
 651   * The current user logged in using the internal browser.
 652   *
 653   * @var bool
 654   */
 655  protected $loggedInUser = FALSE;
 656
 657  /**
 658   * The current cookie file used by cURL.
 659   *
 660   * We do not reuse the cookies in further runs, so we do not need a file
 661   * but we still need cookie handling, so we set the jar to NULL.
 662   */
 663  protected $cookieFile = NULL;
 664
 665  /**
 666   * Additional cURL options.
 667   *
 668   * DrupalWebTestCase itself never sets this but always obeys what is set.
 669   */
 670  protected $additionalCurlOptions = array();
 671
 672  /**
 673   * The original user, before it was changed to a clean uid = 1 for testing purposes.
 674   *
 675   * @var object
 676   */
 677  protected $originalUser = NULL;
 678
 679  /**
 680   * HTTP authentication method
 681   */
 682  protected $httpauth_method = CURLAUTH_BASIC;
 683
 684  /**
 685   * HTTP authentication credentials (<username>:<password>).
 686   */
 687  protected $httpauth_credentials = NULL;
 688
 689  /**
 690   * The current session name, if available.
 691   */
 692  protected $session_name = NULL;
 693
 694  /**
 695   * The current session ID, if available.
 696   */
 697  protected $session_id = NULL;
 698
 699  /**
 700   * Whether the files were copied to the test files directory.
 701   */
 702  protected $generatedTestFiles = FALSE;
 703
 704  /**
 705   * Constructor for DrupalWebTestCase.
 706   */
 707  function __construct($test_id = NULL) {
 708    parent::__construct($test_id);
 709    $this->skipClasses[__CLASS__] = TRUE;
 710  }
 711
 712  /**
 713   * Get a node from the database based on its title.
 714   *
 715   * @param title
 716   *   A node title, usually generated by $this->randomName().
 717   *
 718   * @return
 719   *   A node object matching $title.
 720   */
 721  function drupalGetNodeByTitle($title) {
 722    $nodes = node_load_multiple(array(), array('title' => $title));
 723    // Load the first node returned from the database.
 724    $returned_node = reset($nodes);
 725    return $returned_node;
 726  }
 727
 728  /**
 729   * Creates a node based on default settings.
 730   *
 731   * @param $settings
 732   *   An associative array of settings to change from the defaults, keys are
 733   *   node properties, for example 'title' => 'Hello, world!'.
 734   * @return
 735   *   Created node object.
 736   */
 737  protected function drupalCreateNode($settings = array()) {
 738    // Populate defaults array.
 739    $settings += array(
 740      'body'      => array(LANGUAGE_NONE => array(array())),
 741      'title'     => array(LANGUAGE_NONE => array(array('value' => $this->randomName(8)))),
 742      'comment'   => 2,
 743      'changed'   => REQUEST_TIME,
 744      'moderate'  => 0,
 745      'promote'   => 0,
 746      'revision'  => 1,
 747      'log'       => '',
 748      'status'    => 1,
 749      'sticky'    => 0,
 750      'type'      => 'page',
 751      'revisions' => NULL,
 752      'taxonomy'  => NULL,
 753      'language'  => LANGUAGE_NONE,
 754    );
 755
 756    // Use the original node's created time for existing nodes.
 757    if (isset($settings['created']) && !isset($settings['date'])) {
 758      $settings['date'] = format_date($settings['created'], 'custom', 'Y-m-d H:i:s O');
 759    }
 760
 761    // If the node's user uid is not specified manually, use the currently
 762    // logged in user if available, or else the user running the test.
 763    if (!isset($settings['uid'])) {
 764      if ($this->loggedInUser) {
 765        $settings['uid'] = $this->loggedInUser->uid;
 766      }
 767      else {
 768        global $user;
 769        $settings['uid'] = $user->uid;
 770      }
 771    }
 772
 773    // Merge body field value and format separately.
 774    $body = array(
 775      'value' => $this->randomName(32),
 776      'format' => filter_default_format(),
 777    );
 778    $settings['body'][$settings['language']][0] += $body;
 779
 780    $node = (object) $settings;
 781    node_save($node);
 782
 783    // Small hack to link revisions to our test user.
 784    db_update('node_revision')
 785      ->fields(array('uid' => $node->uid))
 786      ->condition('vid', $node->vid)
 787      ->execute();
 788    return $node;
 789  }
 790
 791  /**
 792   * Creates a custom content type based on default settings.
 793   *
 794   * @param $settings
 795   *   An array of settings to change from the defaults.
 796   *   Example: 'type' => 'foo'.
 797   * @return
 798   *   Created content type.
 799   */
 800  protected function drupalCreateContentType($settings = array()) {
 801    // Find a non-existent random type name.
 802    do {
 803      $name = strtolower($this->randomName(8));
 804    } while (node_type_get_type($name));
 805
 806    // Populate defaults array.
 807    $defaults = array(
 808      'type' => $name,
 809      'name' => $name,
 810      'base' => 'node_content',
 811      'description' => '',
 812      'help' => '',
 813      'title_label' => 'Title',
 814      'body_label' => 'Body',
 815      'has_title' => 1,
 816      'has_body' => 1,
 817    );
 818    // Imposed values for a custom type.
 819    $forced = array(
 820      'orig_type' => '',
 821      'old_type' => '',
 822      'module' => 'node',
 823      'custom' => 1,
 824      'modified' => 1,
 825      'locked' => 0,
 826    );
 827    $type = $forced + $settings + $defaults;
 828    $type = (object)$type;
 829
 830    $saved_type = node_type_save($type);
 831    node_types_rebuild();
 832    menu_rebuild();
 833
 834    $this->assertEqual($saved_type, SAVED_NEW, t('Created content type %type.', array('%type' => $type->type)));
 835
 836    // Reset permissions so that permissions for this content type are available.
 837    $this->checkPermissions(array(), TRUE);
 838
 839    return $type;
 840  }
 841
 842  /**
 843   * Get a list files that can be used in tests.
 844   *
 845   * @param $type
 846   *   File type, possible values: 'binary', 'html', 'image', 'javascript', 'php', 'sql', 'text'.
 847   * @param $size
 848   *   File size in bytes to match. Please check the tests/files folder.
 849   * @return
 850   *   List of files that match filter.
 851   */
 852  protected function drupalGetTestFiles($type, $size = NULL) {
 853    if (empty($this->generatedTestFiles)) {
 854      // Generate binary test files.
 855      $lines = array(64, 1024);
 856      $count = 0;
 857      foreach ($lines as $line) {
 858        simpletest_generate_file('binary-' . $count++, 64, $line, 'binary');
 859      }
 860
 861      // Generate text test files.
 862      $lines = array(16, 256, 1024, 2048, 20480);
 863      $count = 0;
 864      foreach ($lines as $line) {
 865        simpletest_generate_file('text-' . $count++, 64, $line);
 866      }
 867
 868      // Copy other test files from simpletest.
 869      $original = drupal_get_path('module', 'simpletest') . '/files';
 870      $files = file_scan_directory($original, '/(html|image|javascript|php|sql)-.*/');
 871      $destination_path = file_directory_path('public');
 872      foreach ($files as $file) {
 873        file_unmanaged_copy($file->uri, $destination_path);
 874      }
 875
 876      $this->generatedTestFiles = TRUE;
 877    }
 878
 879    $files = array();
 880    // Make sure type is valid.
 881    if (in_array($type, array('binary', 'html', 'image', 'javascript', 'php', 'sql', 'text'))) {
 882      $files = file_scan_directory(file_directory_path('public'), '/' . $type . '\-.*/');
 883
 884      // If size is set then remove any files that are not of that size.
 885      if ($size !== NULL) {
 886        foreach ($files as $file) {
 887          $stats = stat($file->uri);
 888          if ($stats['size'] != $size) {
 889            unset($files[$file->uri]);
 890          }
 891        }
 892      }
 893    }
 894    usort($files, array($this, 'drupalCompareFiles'));
 895    return $files;
 896  }
 897
 898  /**
 899   * Compare two files based on size and file name.
 900   */
 901  protected function drupalCompareFiles($file1, $file2) {
 902    $compare_size = filesize($file1->uri) - filesize($file2->uri);
 903    if ($compare_size) {
 904      // Sort by file size.
 905      return $compare_size;
 906    }
 907    else {
 908      // The files were the same size, so sort alphabetically.
 909      return strnatcmp($file1->name, $file2->name);
 910    }
 911  }
 912
 913  /**
 914   * Create a user with a given set of permissions. The permissions correspond to the
 915   * names given on the privileges page.
 916   *
 917   * @param $permissions
 918   *   Array of permission names to assign to user.
 919   * @return
 920   *   A fully loaded user object with pass_raw property, or FALSE if account
 921   *   creation fails.
 922   */
 923  protected function drupalCreateUser($permissions = array('access comments', 'access content', 'post comments', 'post comments without approval')) {
 924    // Create a role with the given permission set.
 925    if (!($rid = $this->drupalCreateRole($permissions))) {
 926      return FALSE;
 927    }
 928
 929    // Create a user assigned to that role.
 930    $edit = array();
 931    $edit['name']   = $this->randomName();
 932    $edit['mail']   = $edit['name'] . '@example.com';
 933    $edit['roles']  = array($rid => $rid);
 934    $edit['pass']   = user_password();
 935    $edit['status'] = 1;
 936
 937    $account = user_save(drupal_anonymous_user(), $edit);
 938
 939    $this->assertTrue(!empty($account->uid), t('User created with name %name and pass %pass', array('%name' => $edit['name'], '%pass' => $edit['pass'])), t('User login'));
 940    if (empty($account->uid)) {
 941      return FALSE;
 942    }
 943
 944    // Add the raw password so that we can log in as this user.
 945    $account->pass_raw = $edit['pass'];
 946    return $account;
 947  }
 948
 949  /**
 950   * Internal helper function; Create a role with specified permissions.
 951   *
 952   * @param $permissions
 953   *   Array of permission names to assign to role.
 954   * @param $name
 955   *   (optional) String for the name of the role.  Defaults to a random string.
 956   * @return
 957   *   Role ID of newly created role, or FALSE if role creation failed.
 958   */
 959  protected function drupalCreateRole(array $permissions, $name = NULL) {
 960    // Generate random name if it was not passed.
 961    if (!$name) {
 962      $name = $this->randomName();
 963    }
 964
 965    // Check the all the permissions strings are valid.
 966    if (!$this->checkPermissions($permissions)) {
 967      return FALSE;
 968    }
 969
 970    // Create new role.
 971    $role = new stdClass();
 972    $role->name = $name;
 973    user_role_save($role);
 974    user_role_grant_permissions($role->rid, $permissions);
 975
 976    $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'));
 977    if ($role && !empty($role->rid)) {
 978      $count = db_query('SELECT COUNT(*) FROM {role_permission} WHERE rid = :rid', array(':rid' => $role->rid))->fetchField();
 979      $this->assertTrue($count == count($permissions), t('Created permissions: @perms', array('@perms' => implode(', ', $permissions))), t('Role'));
 980      return $role->rid;
 981    }
 982    else {
 983      return FALSE;
 984    }
 985  }
 986
 987  /**
 988   * Check to make sure that the array of permissions are valid.
 989   *
 990   * @param $permissions
 991   *   Permissions to check.
 992   * @param $reset
 993   *   Reset cached available permissions.
 994   * @return
 995   *   TRUE or FALSE depending on whether the permissions are valid.
 996   */
 997  protected function checkPermissions(array $permissions, $reset = FALSE) {
 998    $available = &drupal_static(__FUNCTION__);
 999
1000    if (!isset($available) || $reset) {
1001      $available = array_keys(module_invoke_all('permission'));
1002    }
1003
1004    $valid = TRUE;
1005    foreach ($permissions as $permission) {
1006      if (!in_array($permission, $available)) {
1007        $this->fail(t('Invalid permission %permission.', array('%permission' => $permission)), t('Role'));
1008        $valid = FALSE;
1009      }
1010    }
1011    return $valid;
1012  }
1013
1014  /**
1015   * Log in a user with the internal browser.
1016   *
1017   * If a user is already logged in, then the current user is logged out before
1018   * logging in the specified user.
1019   *
1020   * Please note that neither the global $user nor the passed in user object is
1021   * populated with data of the logged in user. If you need full access to the
1022   * user object after logging in, it must be updated manually. If you also need
1023   * access to the plain-text password of the user (set by drupalCreateUser()),
1024   * e.g. to login the same user again, then it must be re-assigned manually.
1025   * For example:
1026   * @code
1027   *   // Create a user.
1028   *   $account = $this->drupalCreateUser(array());
1029   *   $this->drupalLogin($account);
1030   *   // Load real user object.
1031   *   $pass_raw = $account->pass_raw;
1032   *   $account = user_load($account->uid);
1033   *   $account->pass_raw = $pass_raw;
1034   * @endcode
1035   *
1036   * @param $user
1037   *   User object representing the user to login.
1038   *
1039   * @see drupalCreateUser()
1040   */
1041  protected function drupalLogin(stdClass $user) {
1042    if ($this->loggedInUser) {
1043      $this->drupalLogout();
1044    }
1045
1046    $edit = array(
1047      'name' => $user->name,
1048      'pass' => $user->pass_raw
1049    );
1050    $this->drupalPost('user', $edit, t('Log in'));
1051
1052    // If a "log out" link appears on the page, it is almost certainly because
1053    // the login was successful.
1054    $pass = $this->assertLink(t('Log out'), 0, t('User %name successfully logged in.', array('%name' => $user->name)), t('User login'));
1055
1056    if ($pass) {
1057      $this->loggedInUser = $user;
1058    }
1059  }
1060
1061  /**
1062   * Generate a token for the currently logged in user.
1063   */
1064  protected function drupalGetToken($value = '') {
1065    $private_key = drupal_get_private_key();
1066    return md5($this->session_id . $value . $private_key);
1067  }
1068
1069  /*
1070   * Logs a user out of the internal browser, then check the login page to confirm logout.
1071   */
1072  protected function drupalLogout() {
1073    // Make a request to the logout page, and redirect to the user page, the
1074    // idea being if you were properly logged out you should be seeing a login
1075    // screen.
1076    $this->drupalGet('user/logout', array('query' => array('destination' => 'user')));
1077    $pass = $this->assertField('name', t('Username field found.'), t('Logout'));
1078    $pass = $pass && $this->assertField('pass', t('Password field found.'), t('Logout'));
1079
1080    if ($pass) {
1081      $this->loggedInUser = FALSE;
1082    }
1083  }
1084
1085  /**
1086   * Generates a random database prefix, runs the install scripts on the
1087   * prefixed database and enable the specified modules. After installation
1088   * many caches are flushed and the internal browser is setup so that the
1089   * page requests will run on the new prefix. A temporary files directory
1090   * is created with the same name as the database prefix.
1091   *
1092   * @param ...
1093   *   List of modules to enable for the duration of the test.
1094   */
1095  protected function setUp() {
1096    global $db_prefix, $user, $language;
1097
1098    // Store necessary current values before switching to prefixed database.
1099    $this->originalLanguage = $language;
1100    $this->originalLanguageDefault = variable_get('language_default');
1101    $this->originalPrefix = $db_prefix;
1102    $this->originalFileDirectory = file_directory_path();
1103    $this->originalProfile = drupal_get_profile();
1104    $clean_url_original = variable_get('clean_url', 0);
1105
1106    // Generate temporary prefixed database to ensure that tests have a clean starting point.
1107    $db_prefix_new = Database::getConnection()->prefixTables('{simpletest' . mt_rand(1000, 1000000) . '}');
1108    db_update('simpletest_test_id')
1109      ->fields(array('last_prefix' => $db_prefix_new))
1110      ->condition('test_id', $this->testId)
1111      ->execute();
1112    $db_prefix = $db_prefix_new;
1113
1114    // Create test directory ahead of installation so fatal errors and debug
1115    // information can be logged during installation process.
1116    // Use temporary files directory with the same prefix as the database.
1117    $public_files_directory  = $this->originalFileDirectory . '/simpletest/' . substr($db_prefix, 10);
1118    $private_files_directory = $public_files_directory . '/private';
1119    $temp_files_directory    = $private_files_directory . '/temp';
1120
1121    // Create the directories
1122    file_prepare_directory($public_files_directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
1123    file_prepare_directory($private_files_directory, FILE_CREATE_DIRECTORY);
1124    file_prepare_directory($temp_files_directory, FILE_CREATE_DIRECTORY);
1125    $this->generatedTestFiles = FALSE;
1126
1127    // Log fatal errors.
1128    ini_set('log_errors', 1);
1129    ini_set('error_log', $public_files_directory . '/error.log');
1130
1131    // Reset all statics so that test is performed with a clean environment.
1132    drupal_static_reset();
1133
1134    include_once DRUPAL_ROOT . '/includes/install.inc';
1135    drupal_install_system();
1136
1137    $this->preloadRegistry();
1138
1139    // Include the default profile
1140    variable_set('install_profile', 'standard');
1141    $profile_details = install_profile_info('standard', 'en');
1142
1143    // Install the modules specified by the default profile.
1144    drupal_install_modules($profile_details['dependencies'], TRUE);
1145
1146    drupal_static_reset('_node_types_build');
1147
1148    if ($modules = func_get_args()) {
1149      // Install modules needed for this test.
1150      drupal_install_modules($modules, TRUE);
1151    }
1152
1153    // Because the schema is static cached, we need to flush
1154    // it between each run. If we don't, then it will contain
1155    // stale data for the previous run's database prefix and all
1156    // calls to it will fail.
1157    drupal_get_schema(NULL, TRUE);
1158
1159    // Run default profile tasks.
1160    $install_state = array();
1161    drupal_install_modules(array('standard'), TRUE);
1162
1163    // Rebuild caches.
1164    node_types_rebuild();
1165    actions_synchronize();
1166    _drupal_flush_css_js();
1167    $this->refreshVariables();
1168    $this->checkPermissions(array(), TRUE);
1169
1170    // Log in with a clean $user.
1171    $this->originalUser = $user;
1172    drupal_save_session(FALSE);
1173    $user = user_load(1);
1174
1175    // Restore necessary variables.
1176    variable_set('install_task', 'done');
1177    variable_set('clean_url', $clean_url_original);
1178    variable_set('site_mail', 'simpletest@example.com');
1179    // Set up English language.
1180    unset($GLOBALS['conf']['language_default']);
1181    $language = language_default();
1182
1183    // Set path variables
1184    variable_set('file_public_path', $public_files_directory);
1185    variable_set('file_private_path', $private_files_directory);
1186    variable_set('file_temporary_path', $temp_files_directory);
1187
1188    // Use the test mail class instead of the default mail handler class.
1189    variable_set('mail_system', array('default-system' => 'TestingMailSystem'));
1190
1191    drupal_set_time_limit($this->timeLimit);
1192  }
1193
1194  /**
1195   * This method is called by DrupalWebTestCase::setUp, and preloads the
1196   * registry from the testing site to cut down on the time it takes to
1197   * setup a clean environment for the current test run.
1198   */
1199  protected function preloadRegistry() {
1200    db_query('INSERT INTO {registry} SELECT * FROM ' . $this->originalPrefix . 'registry');
1201    db_query('INSERT INTO {registry_file} SELECT * FROM ' . $this->originalPrefix . 'registry_file');
1202  }
1203
1204  /**
1205   * Refresh the in-memory set of variables. Useful after a page request is made
1206   * that changes a variable in a different thread.
1207   *
1208   * In other words calling a settings page with $this->drupalPost() with a changed
1209   * value would update a variable to reflect that change, but in the thread that
1210   * made the call (thread running the test) the changed variable would not be
1211   * picked up.
1212   *
1213   * This method clears the variables cache and loads a fresh copy from the database
1214   * to ensure that the most up-to-date set of variables is loaded.
1215   */
1216  protected function refreshVariables() {
1217    global $conf;
1218    cache_clear_all('variables', 'cache_bootstrap');
1219    $conf = variable_initialize();
1220  }
1221
1222  /**
1223   * Delete created files and temporary files directory, delete the tables created by setUp(),
1224   * and reset the database prefix.
1225   */
1226  protected function tearDown() {
1227    global $db_prefix, $user, $language;
1228
1229    // In case a fatal error occured that was not in the test process read the
1230    // log to pick up any fatal errors.
1231    $db_prefix_temp = $db_prefix;
1232    $db_prefix = $this->originalPrefix;
1233    simpletest_log_read($this->testId, $db_prefix, get_class($this), TRUE);
1234    $db_prefix = $db_prefix_temp;
1235
1236    $emailCount = count(variable_get('drupal_test_email_collector', array()));
1237    if ($emailCount) {
1238      $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));
1239      $this->pass($message, t('E-mail'));
1240    }
1241
1242    if (preg_match('/simpletest\d+/', $db_prefix)) {
1243      // Delete temporary files directory.
1244      file_unmanaged_delete_recursive($this->originalFileDirectory . '/simpletest/' . substr($db_prefix, 10));
1245
1246      // Remove all prefixed tables (all the tables in the schema).
1247      $schema = drupal_get_schema(NULL, TRUE);
1248      $ret = array();
1249      foreach ($schema as $name => $table) {
1250        db_drop_table($name);
1251      }
1252
1253      // Return the database prefix to the original.
1254      $db_prefix = $this->originalPrefix;
1255
1256      // Return the user to the original one.
1257      $user = $this->originalUser;
1258      drupal_save_session(TRUE);
1259
1260      // Ensure that internal logged in variable and cURL options are reset.
1261      $this->loggedInUser = FALSE;
1262      $this->additionalCurlOptions = array();
1263
1264      // Reload module list and implementations to ensure that test module hooks
1265      // aren't called after tests.
1266      module_list(TRUE);
1267      module_implements('', FALSE, TRUE);
1268
1269      // Reset the Field API.
1270      field_cache_clear();
1271
1272      // Rebuild caches.
1273      $this->refreshVariables();
1274
1275      // Reset language.
1276      $language = $this->originalLanguage;
1277      if ($this->originalLanguageDefault) {
1278        $GLOBALS['conf']['language_default'] = $this->originalLanguageDefault;
1279      }
1280
1281      // Close the CURL handler.
1282      $this->curlClose();
1283    }
1284  }
1285
1286  /**
1287   * Initializes the cURL connection.
1288   *
1289   * If the simpletest_httpauth_credentials variable is set, this function will
1290   * add HTTP authentication headers. This is necessary for testing sites that
1291   * are protected by login credentials from public access.
1292   * See the description of $curl_options for other options.
1293   */
1294  protected function curlInitialize() {
1295    global $base_url, $db_prefix;
1296
1297    if (!isset($this->curlHandle)) {
1298      $this->curlHandle = curl_init();
1299      $curl_options = $this->additionalCurlOptions + array(
1300        CURLOPT_COOKIEJAR => $this->cookieFile,
1301        CURLOPT_URL => $base_url,
1302        CURLOPT_FOLLOWLOCATION => TRUE,
1303        CURLOPT_MAXREDIRS => 5,
1304        CURLOPT_RETURNTRANSFER => TRUE,
1305        CURLOPT_SSL_VERIFYPEER => FALSE, // Required to make the tests run on https.
1306        CURLOPT_SSL_VERIFYHOST => FALSE, // Required to make the tests run on https.
1307        CURLOPT_HEADERFUNCTION => array(&$this, 'curlHeaderCallback'),
1308      );
1309      if (isset($this->httpauth_credentials)) {
1310        $curl_options[CURLOPT_HTTPAUTH] = $this->httpauth_method;
1311        $curl_options[CURLOPT_USERPWD] = $this->httpauth_credentials;
1312      }
1313      curl_setopt_array($this->curlHandle, $this->additionalCurlOptions + $curl_options);
1314
1315      // By default, the child session name should be the same as the parent.
1316      $this->session_name = session_name();
1317    }
1318    // We set the user agent header on each request so as to use the current
1319    // time and a new uniqid.
1320    if (preg_match('/simpletest\d+/', $db_prefix, $matches)) {
1321      curl_setopt($this->curlHandle, CURLOPT_USERAGENT, drupal_generate_test_ua($matches[0]));
1322    }
1323  }
1324
1325  /**
1326   * Performs a cURL exec with the specified options after calling curlConnect().
1327   *
1328   * @param $curl_options
1329   *   Custom cURL options.
1330   * @return
1331   *   Content returned from the exec.
1332   */
1333  protected function curlExec($curl_options) {
1334    $this->curlInitialize();
1335    $url = empty($curl_options[CURLOPT_URL]) ? curl_getinfo($this->curlHandle, CURLINFO_EFFECTIVE_URL) : $curl_options[CURLOPT_URL];
1336    if (!empty($curl_options[CURLOPT_POST])) {
1337      // This is a fix for the Curl library to prevent Expect: 100-continue
1338      // headers in POST requests, that may cause unexpected HTTP response
1339      // codes from some webservers (like lighttpd that returns a 417 error
1340      // code). It is done by setting an empty "Expect" header field that is
1341      // not overwritten by Curl.
1342      $curl_options[CURLOPT_HTTPHEADER][] = 'Expect:';
1343    }
1344    curl_setopt_array($this->curlHandle, $this->additionalCurlOptions + $curl_options);
1345
1346    // Reset headers and the session ID.
1347    $this->session_id = NULL;
1348    $this->headers = array();
1349
1350    $this->drupalSetContent(curl_exec($this->curlHandle), curl_getinfo($this->curlHandle, CURLINFO_EFFECTIVE_URL));
1351    $message_vars = array(
1352      '!method' => !empty($curl_options[CURLOPT_NOBODY]) ? 'HEAD' : (empty($curl_options[CURLOPT_POSTFIELDS]) ? 'GET' : 'POST'),
1353      '@url' => $url,
1354      '@status' => curl_getinfo($this->curlHandle, CURLINFO_HTTP_CODE),
1355      '!length' => format_size(strlen($this->content))
1356    );
1357    $message = t('!method @url returned @status (!length).', $message_vars);
1358    $this->assertTrue($this->content !== FALSE, $message, t('Browser'));
1359    return $this->drupalGetContent();
1360  }
1361
1362  /**
1363   * Reads headers and registers errors received from the tested site.
1364   *
1365   * @see _drupal_log_error().
1366   *
1367   * @param $curlHandler
1368   *   The cURL handler.
1369   * @param $header
1370   *   An header.
1371   */
1372  protected function curlHeaderCallback($curlHandler, $header) {
1373    $this->headers[] = $header;
1374
1375    // Errors are being sent via X-Drupal-Assertion-* headers,
1376    // generated by _drupal_log_error() in the exact form required
1377    // by DrupalWebTestCase::error().
1378    if (preg_match('/^X-Drupal-Assertion-[0-9]+: (.*)$/', $header, $matches)) {
1379      // Call DrupalWebTestCase::error() with the parameters from the header.
1380      call_user_func_array(array(&$this, 'error'), unserialize(urldecode($matches[1])));
1381    }
1382
1383    // Save cookies.
1384    if (preg_match('/^Set-Cookie: ([^=]+)=(.+)/', $header, $matches)) {
1385      $name = $matches[1];
1386      $parts = array_map('trim', explode(';', $matches[2]));
1387      $value = array_shift($parts);
1388      $this->cookies[$name] = array('value' => $value, 'secure' => in_array('secure', $parts));
1389      if ($name == $this->session_name) {
1390        if ($value != 'deleted') {
1391          $this->session_id = $value;
1392        }
1393        else {
1394          $this->session_id = NULL;
1395        }
1396      }
1397    }
1398
1399    // This is required by cURL.
1400    return strlen($header);
1401  }
1402
1403  /**
1404   * Close the cURL handler and unset the handler.
1405   */
1406  protected function curlClose() {
1407    if (isset($this->curlHandle)) {
1408      curl_close($this->curlHandle);
1409      unset($this->curlHandle);
1410    }
1411  }
1412
1413  /**
1414   * Parse content returned from curlExec using DOM and SimpleXML.
1415   *
1416   * @return
1417   *   A SimpleXMLElement or FALSE on failure.
1418   */
1419  protected function parse() {
1420    if (!$this->elements) {
1421      // DOM can load HTML soup. But, HTML soup can throw warnings, suppress
1422      // them.
1423      @$htmlDom = DOMDocument::loadHTML($this->content);
1424      if ($htmlDom) {
1425        $this->pass(t('Valid HTML found on "@path"', array('@path' => $this->getUrl())), t('Browser'));
1426        // It's much easier to work with simplexml than DOM, luckily enough
1427        // we can just simply import our DOM tree.
1428        $this->elements = simplexml_import_dom($htmlDom);
1429      }
1430    }
1431    if (!$this->elements) {
1432      $this->fail(t('Parsed page successfully.'), t('Browser'));
1433    }
1434
1435    return $this->elements;
1436  }
1437
1438  /**
1439   * Retrieves a Drupal path or an absolute path.
1440   *
1441   * @param $path
1442   *   Drupal path or URL to load into internal browser
1443   * @param $options
1444   *   Options to be forwarded to url().
1445   * @param $headers
1446   *   An array containing additional HTTP request headers, each formatted as
1447   *   "name: value".
1448   * @return
1449   *   The retrieved HTML string, also available as $this->drupalGetContent()
1450   */
1451  protected function drupalGet($path, array $options = array(), array $headers = array()) {
1452    $options['absolute'] = TRUE;
1453
1454    // We re-using a CURL connection here. If that connection still has certain
1455    // options set, it might change the GET into a POST. Make sure we clear out
1456    // previous options.
1457    $out = $this->curlExec(array(CURLOPT_HTTPGET => TRUE, CURLOPT_URL => url($path, $options), CURLOPT_NOBODY => FALSE, CURLOPT_HTTPHEADER => $headers));
1458    $this->refreshVariables(); // Ensure that any changes to variables in the other thread are picked up.
1459
1460    // Replace original page output with new output from redirected page(s).
1461    if ($new = $this->checkForMetaRefresh()) {
1462      $out = $new;
1463    }
1464    $this->verbose('GET request to: ' . $path .
1465                   '<hr />Ending URL: ' . $this->getUrl() .
1466                   '<hr />' . $out);
1467    return $out;
1468  }
1469
1470  /**
1471   * Retrieve a Drupal path or an absolute path and JSON decode the result.
1472   */
1473  protected function drupalGetAJAX($path, array $options = array(), array $headers = array()) {
1474    return drupal_json_decode($this->drupalGet($path, $options, $headers));
1475  }
1476
1477  /**
1478   * Execute a POST request on a Drupal page.
1479   * It will be done as usual POST request with SimpleBrowser.
1480   *
1481   * @param $path
1482   *   Location of the post form. Either a Drupal path or an absolute path or
1483   *   NULL to post to the current page. For multi-stage forms you can set the
1484   *   path to NULL and have it post to the last received page. Example:
1485   *
1486   *   @code
1487   *   // First step in form.
1488   *   $edit = array(...);
1489   *   $this->drupalPost('some_url', $edit, t('Save'));
1490   *
1491   *   // Second step in form.
1492   *   $edit = array(...);
1493   *   $this->drupalPost(NULL, $edit, t('Save'));
1494   *   @endcode
1495   * @param  $edit
1496   *   Field data in an associative array. Changes the current input fields
1497   *   (where possible) to the values indicated. A checkbox can be set to
1498   *   TRUE to be checked and FALSE to be unchecked. Note that when a form
1499   *   contains file upload fields, other fields cannot start with the '@'
1500   *   character.
1501   *
1502   *   Multiple select fields can be set using name[] and setting each of the
1503   *   possible values. Example:
1504   *   @code
1505   *   $edit = array();
1506   *   $edit['name[]'] = array('value1', 'value2');
1507   *   @endcode
1508   * @param $submit
1509   *   Value of the submit button whose click is to be emulated. For example,
1510   *   t('Save'). The processing of the request depends on this value. For
1511 

Large files files are truncated, but you can click here to view the full file