PageRenderTime 73ms CodeModel.GetById 20ms app.highlight 39ms RepoModel.GetById 1ms app.codeStats 1ms

/modules/simpletest/drupal_web_test_case.php

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

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