Drupal PHP Cross Reference Content Management Systems

Source: /modules/simpletest/drupal_web_test_case.php - 3650 lines - 129162 bytes - Summary - Text - Print

Description: Global variable that holds information about the tests being run. An array, with the following keys: - 'test_run_id': the ID of the test being run, in the form 'simpletest_%" - 'in_child_site': TRUE if the current request is a cURL request from the parent site.

   1  <?php
   2  
   3  /**
   4   * Global variable that holds information about the tests being run.
   5   *
   6   * An array, with the following keys:
   7   *  - 'test_run_id': the ID of the test being run, in the form 'simpletest_%"
   8   *  - 'in_child_site': TRUE if the current request is a cURL request from
   9   *     the parent site.
  10   *
  11   * @var array
  12   */
  13  global $drupal_test_info;
  14  
  15  /**
  16   * Base class for Drupal tests.
  17   *
  18   * Do not extend this class, use one of the subclasses in this file.
  19   */
  20  abstract class DrupalTestCase {
  21    /**
  22     * The test run ID.
  23     *
  24     * @var string
  25     */
  26    protected $testId;
  27  
  28    /**
  29     * The database prefix of this test run.
  30     *
  31     * @var string
  32     */
  33    protected $databasePrefix = 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 = 500;
  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     * Flag to indicate whether the test has been set up.
  78     *
  79     * The setUp() method isolates the test from the parent Drupal site by
  80     * creating a random prefix for the database and setting up a clean file
  81     * storage directory. The tearDown() method then cleans up this test
  82     * environment. We must ensure that setUp() has been run. Otherwise,
  83     * tearDown() will act on the parent Drupal site rather than the test
  84     * environment, destroying live data.
  85     */
  86    protected $setup = FALSE;
  87  
  88    protected $setupDatabasePrefix = FALSE;
  89  
  90    protected $setupEnvironment = FALSE;
  91  
  92    /**
  93     * Constructor for DrupalTestCase.
  94     *
  95     * @param $test_id
  96     *   Tests with the same id are reported together.
  97     */
  98    public function __construct($test_id = NULL) {
  99      $this->testId = $test_id;
 100    }
 101  
 102    /**
 103     * Internal helper: stores the assert.
 104     *
 105     * @param $status
 106     *   Can be 'pass', 'fail', 'exception'.
 107     *   TRUE is a synonym for 'pass', FALSE for 'fail'.
 108     * @param $message
 109     *   The message string.
 110     * @param $group
 111     *   Which group this assert belongs to.
 112     * @param $caller
 113     *   By default, the assert comes from a function whose name starts with
 114     *   'test'. Instead, you can specify where this assert originates from
 115     *   by passing in an associative array as $caller. Key 'file' is
 116     *   the name of the source file, 'line' is the line number and 'function'
 117     *   is the caller function itself.
 118     */
 119    protected function assert($status, $message = '', $group = 'Other', array $caller = NULL) {
 120      // Convert boolean status to string status.
 121      if (is_bool($status)) {
 122        $status = $status ? 'pass' : 'fail';
 123      }
 124  
 125      // Increment summary result counter.
 126      $this->results['#' . $status]++;
 127  
 128      // Get the function information about the call to the assertion method.
 129      if (!$caller) {
 130        $caller = $this->getAssertionCall();
 131      }
 132  
 133      // Creation assertion array that can be displayed while tests are running.
 134      $this->assertions[] = $assertion = array(
 135        'test_id' => $this->testId,
 136        'test_class' => get_class($this),
 137        'status' => $status,
 138        'message' => $message,
 139        'message_group' => $group,
 140        'function' => $caller['function'],
 141        'line' => $caller['line'],
 142        'file' => $caller['file'],
 143      );
 144  
 145      // Store assertion for display after the test has completed.
 146      try {
 147        $connection = Database::getConnection('default', 'simpletest_original_default');
 148      }
 149      catch (DatabaseConnectionNotDefinedException $e) {
 150        // If the test was not set up, the simpletest_original_default
 151        // connection does not exist.
 152        $connection = Database::getConnection('default', 'default');
 153      }
 154      $connection
 155        ->insert('simpletest')
 156        ->fields($assertion)
 157        ->execute();
 158  
 159      // We do not use a ternary operator here to allow a breakpoint on
 160      // test failure.
 161      if ($status == 'pass') {
 162        return TRUE;
 163      }
 164      else {
 165        return FALSE;
 166      }
 167    }
 168  
 169    /**
 170     * Store an assertion from outside the testing context.
 171     *
 172     * This is useful for inserting assertions that can only be recorded after
 173     * the test case has been destroyed, such as PHP fatal errors. The caller
 174     * information is not automatically gathered since the caller is most likely
 175     * inserting the assertion on behalf of other code. In all other respects
 176     * the method behaves just like DrupalTestCase::assert() in terms of storing
 177     * the assertion.
 178     *
 179     * @return
 180     *   Message ID of the stored assertion.
 181     *
 182     * @see DrupalTestCase::assert()
 183     * @see DrupalTestCase::deleteAssert()
 184     */
 185    public static function insertAssert($test_id, $test_class, $status, $message = '', $group = 'Other', array $caller = array()) {
 186      // Convert boolean status to string status.
 187      if (is_bool($status)) {
 188        $status = $status ? 'pass' : 'fail';
 189      }
 190  
 191      $caller += array(
 192        'function' => t('Unknown'),
 193        'line' => 0,
 194        'file' => t('Unknown'),
 195      );
 196  
 197      $assertion = array(
 198        'test_id' => $test_id,
 199        'test_class' => $test_class,
 200        'status' => $status,
 201        'message' => $message,
 202        'message_group' => $group,
 203        'function' => $caller['function'],
 204        'line' => $caller['line'],
 205        'file' => $caller['file'],
 206      );
 207  
 208      return db_insert('simpletest')
 209        ->fields($assertion)
 210        ->execute();
 211    }
 212  
 213    /**
 214     * Delete an assertion record by message ID.
 215     *
 216     * @param $message_id
 217     *   Message ID of the assertion to delete.
 218     * @return
 219     *   TRUE if the assertion was deleted, FALSE otherwise.
 220     *
 221     * @see DrupalTestCase::insertAssert()
 222     */
 223    public static function deleteAssert($message_id) {
 224      return (bool) db_delete('simpletest')
 225        ->condition('message_id', $message_id)
 226        ->execute();
 227    }
 228  
 229    /**
 230     * Cycles through backtrace until the first non-assertion method is found.
 231     *
 232     * @return
 233     *   Array representing the true caller.
 234     */
 235    protected function getAssertionCall() {
 236      $backtrace = debug_backtrace();
 237  
 238      // The first element is the call. The second element is the caller.
 239      // We skip calls that occurred in one of the methods of our base classes
 240      // or in an assertion function.
 241     while (($caller = $backtrace[1]) &&
 242           ((isset($caller['class']) && isset($this->skipClasses[$caller['class']])) ||
 243             substr($caller['function'], 0, 6) == 'assert')) {
 244        // We remove that call.
 245        array_shift($backtrace);
 246      }
 247  
 248      return _drupal_get_last_caller($backtrace);
 249    }
 250  
 251    /**
 252     * Check to see if a value is not false (not an empty string, 0, NULL, or FALSE).
 253     *
 254     * @param $value
 255     *   The value on which the assertion is to be done.
 256     * @param $message
 257     *   The message to display along with the assertion.
 258     * @param $group
 259     *   The type of assertion - examples are "Browser", "PHP".
 260     * @return
 261     *   TRUE if the assertion succeeded, FALSE otherwise.
 262     */
 263    protected function assertTrue($value, $message = '', $group = 'Other') {
 264      return $this->assert((bool) $value, $message ? $message : t('Value @value is TRUE.', array('@value' => var_export($value, TRUE))), $group);
 265    }
 266  
 267    /**
 268     * Check to see if a value is false (an empty string, 0, NULL, or FALSE).
 269     *
 270     * @param $value
 271     *   The value on which the assertion is to be done.
 272     * @param $message
 273     *   The message to display along with the assertion.
 274     * @param $group
 275     *   The type of assertion - examples are "Browser", "PHP".
 276     * @return
 277     *   TRUE if the assertion succeeded, FALSE otherwise.
 278     */
 279    protected function assertFalse($value, $message = '', $group = 'Other') {
 280      return $this->assert(!$value, $message ? $message : t('Value @value is FALSE.', array('@value' => var_export($value, TRUE))), $group);
 281    }
 282  
 283    /**
 284     * Check to see if a value is NULL.
 285     *
 286     * @param $value
 287     *   The value on which the assertion is to be done.
 288     * @param $message
 289     *   The message to display along with the assertion.
 290     * @param $group
 291     *   The type of assertion - examples are "Browser", "PHP".
 292     * @return
 293     *   TRUE if the assertion succeeded, FALSE otherwise.
 294     */
 295    protected function assertNull($value, $message = '', $group = 'Other') {
 296      return $this->assert(!isset($value), $message ? $message : t('Value @value is NULL.', array('@value' => var_export($value, TRUE))), $group);
 297    }
 298  
 299    /**
 300     * Check to see if a value is not NULL.
 301     *
 302     * @param $value
 303     *   The value on which the assertion is to be done.
 304     * @param $message
 305     *   The message to display along with the assertion.
 306     * @param $group
 307     *   The type of assertion - examples are "Browser", "PHP".
 308     * @return
 309     *   TRUE if the assertion succeeded, FALSE otherwise.
 310     */
 311    protected function assertNotNull($value, $message = '', $group = 'Other') {
 312      return $this->assert(isset($value), $message ? $message : t('Value @value is not NULL.', array('@value' => var_export($value, TRUE))), $group);
 313    }
 314  
 315    /**
 316     * Check to see if two values are equal.
 317     *
 318     * @param $first
 319     *   The first value to check.
 320     * @param $second
 321     *   The second value to check.
 322     * @param $message
 323     *   The message to display along with the assertion.
 324     * @param $group
 325     *   The type of assertion - examples are "Browser", "PHP".
 326     * @return
 327     *   TRUE if the assertion succeeded, FALSE otherwise.
 328     */
 329    protected function assertEqual($first, $second, $message = '', $group = 'Other') {
 330      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);
 331    }
 332  
 333    /**
 334     * Check to see if two values are not equal.
 335     *
 336     * @param $first
 337     *   The first value to check.
 338     * @param $second
 339     *   The second value to check.
 340     * @param $message
 341     *   The message to display along with the assertion.
 342     * @param $group
 343     *   The type of assertion - examples are "Browser", "PHP".
 344     * @return
 345     *   TRUE if the assertion succeeded, FALSE otherwise.
 346     */
 347    protected function assertNotEqual($first, $second, $message = '', $group = 'Other') {
 348      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);
 349    }
 350  
 351    /**
 352     * Check to see if two values are identical.
 353     *
 354     * @param $first
 355     *   The first value to check.
 356     * @param $second
 357     *   The second value to check.
 358     * @param $message
 359     *   The message to display along with the assertion.
 360     * @param $group
 361     *   The type of assertion - examples are "Browser", "PHP".
 362     * @return
 363     *   TRUE if the assertion succeeded, FALSE otherwise.
 364     */
 365    protected function assertIdentical($first, $second, $message = '', $group = 'Other') {
 366      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);
 367    }
 368  
 369    /**
 370     * Check to see if two values are not identical.
 371     *
 372     * @param $first
 373     *   The first value to check.
 374     * @param $second
 375     *   The second value to check.
 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     *   TRUE if the assertion succeeded, FALSE otherwise.
 382     */
 383    protected function assertNotIdentical($first, $second, $message = '', $group = 'Other') {
 384      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);
 385    }
 386  
 387    /**
 388     * Fire an assertion that is always positive.
 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     * @return
 395     *   TRUE.
 396     */
 397    protected function pass($message = NULL, $group = 'Other') {
 398      return $this->assert(TRUE, $message, $group);
 399    }
 400  
 401    /**
 402     * Fire an assertion that is always negative.
 403     *
 404     * @param $message
 405     *   The message to display along with the assertion.
 406     * @param $group
 407     *   The type of assertion - examples are "Browser", "PHP".
 408     * @return
 409     *   FALSE.
 410     */
 411    protected function fail($message = NULL, $group = 'Other') {
 412      return $this->assert(FALSE, $message, $group);
 413    }
 414  
 415    /**
 416     * Fire an error assertion.
 417     *
 418     * @param $message
 419     *   The message to display along with the assertion.
 420     * @param $group
 421     *   The type of assertion - examples are "Browser", "PHP".
 422     * @param $caller
 423     *   The caller of the error.
 424     * @return
 425     *   FALSE.
 426     */
 427    protected function error($message = '', $group = 'Other', array $caller = NULL) {
 428      if ($group == 'User notice') {
 429        // Since 'User notice' is set by trigger_error() which is used for debug
 430        // set the message to a status of 'debug'.
 431        return $this->assert('debug', $message, 'Debug', $caller);
 432      }
 433  
 434      return $this->assert('exception', $message, $group, $caller);
 435    }
 436  
 437    /**
 438     * Logs verbose message in a text file.
 439     *
 440     * The a link to the vebose message will be placed in the test results via
 441     * as a passing assertion with the text '[verbose message]'.
 442     *
 443     * @param $message
 444     *   The verbose message to be stored.
 445     *
 446     * @see simpletest_verbose()
 447     */
 448    protected function verbose($message) {
 449      if ($id = simpletest_verbose($message)) {
 450        $url = file_create_url($this->originalFileDirectory . '/simpletest/verbose/' . get_class($this) . '-' . $id . '.html');
 451        $this->error(l(t('Verbose message'), $url, array('attributes' => array('target' => '_blank'))), 'User notice');
 452      }
 453    }
 454  
 455    /**
 456     * Run all tests in this class.
 457     *
 458     * Regardless of whether $methods are passed or not, only method names
 459     * starting with "test" are executed.
 460     *
 461     * @param $methods
 462     *   (optional) A list of method names in the test case class to run; e.g.,
 463     *   array('testFoo', 'testBar'). By default, all methods of the class are
 464     *   taken into account, but it can be useful to only run a few selected test
 465     *   methods during debugging.
 466     */
 467    public function run(array $methods = array()) {
 468      // Initialize verbose debugging.
 469      simpletest_verbose(NULL, variable_get('file_public_path', conf_path() . '/files'), get_class($this));
 470  
 471      // HTTP auth settings (<username>:<password>) for the simpletest browser
 472      // when sending requests to the test site.
 473      $this->httpauth_method = variable_get('simpletest_httpauth_method', CURLAUTH_BASIC);
 474      $username = variable_get('simpletest_httpauth_username', NULL);
 475      $password = variable_get('simpletest_httpauth_password', NULL);
 476      if ($username && $password) {
 477        $this->httpauth_credentials = $username . ':' . $password;
 478      }
 479  
 480      set_error_handler(array($this, 'errorHandler'));
 481      $class = get_class($this);
 482      // Iterate through all the methods in this class, unless a specific list of
 483      // methods to run was passed.
 484      $class_methods = get_class_methods($class);
 485      if ($methods) {
 486        $class_methods = array_intersect($class_methods, $methods);
 487      }
 488      foreach ($class_methods as $method) {
 489        // If the current method starts with "test", run it - it's a test.
 490        if (strtolower(substr($method, 0, 4)) == 'test') {
 491          // Insert a fail record. This will be deleted on completion to ensure
 492          // that testing completed.
 493          $method_info = new ReflectionMethod($class, $method);
 494          $caller = array(
 495            'file' => $method_info->getFileName(),
 496            'line' => $method_info->getStartLine(),
 497            'function' => $class . '->' . $method . '()',
 498          );
 499          $completion_check_id = DrupalTestCase::insertAssert($this->testId, $class, FALSE, t('The test did not complete due to a fatal error.'), 'Completion check', $caller);
 500          $this->setUp();
 501          if ($this->setup) {
 502            try {
 503              $this->$method();
 504              // Finish up.
 505            }
 506            catch (Exception $e) {
 507              $this->exceptionHandler($e);
 508            }
 509            $this->tearDown();
 510          }
 511          else {
 512            $this->fail(t("The test cannot be executed because it has not been set up properly."));
 513          }
 514          // Remove the completion check record.
 515          DrupalTestCase::deleteAssert($completion_check_id);
 516        }
 517      }
 518      // Clear out the error messages and restore error handler.
 519      drupal_get_messages();
 520      restore_error_handler();
 521    }
 522  
 523    /**
 524     * Handle errors during test runs.
 525     *
 526     * Because this is registered in set_error_handler(), it has to be public.
 527     * @see set_error_handler
 528     */
 529    public function errorHandler($severity, $message, $file = NULL, $line = NULL) {
 530      if ($severity & error_reporting()) {
 531        $error_map = array(
 532          E_STRICT => 'Run-time notice',
 533          E_WARNING => 'Warning',
 534          E_NOTICE => 'Notice',
 535          E_CORE_ERROR => 'Core error',
 536          E_CORE_WARNING => 'Core warning',
 537          E_USER_ERROR => 'User error',
 538          E_USER_WARNING => 'User warning',
 539          E_USER_NOTICE => 'User notice',
 540          E_RECOVERABLE_ERROR => 'Recoverable error',
 541        );
 542  
 543        $backtrace = debug_backtrace();
 544        $this->error($message, $error_map[$severity], _drupal_get_last_caller($backtrace));
 545      }
 546      return TRUE;
 547    }
 548  
 549    /**
 550     * Handle exceptions.
 551     *
 552     * @see set_exception_handler
 553     */
 554    protected function exceptionHandler($exception) {
 555      $backtrace = $exception->getTrace();
 556      // Push on top of the backtrace the call that generated the exception.
 557      array_unshift($backtrace, array(
 558        'line' => $exception->getLine(),
 559        'file' => $exception->getFile(),
 560      ));
 561      require_once  DRUPAL_ROOT . '/includes/errors.inc';
 562      // The exception message is run through check_plain() by _drupal_decode_exception().
 563      $this->error(t('%type: !message in %function (line %line of %file).', _drupal_decode_exception($exception)), 'Uncaught exception', _drupal_get_last_caller($backtrace));
 564    }
 565  
 566    /**
 567     * Generates a random string of ASCII characters of codes 32 to 126.
 568     *
 569     * The generated string includes alpha-numeric characters and common
 570     * miscellaneous characters. Use this method when testing general input
 571     * where the content is not restricted.
 572     *
 573     * Do not use this method when special characters are not possible (e.g., in
 574     * machine or file names that have already been validated); instead,
 575     * use DrupalWebTestCase::randomName().
 576     *
 577     * @param $length
 578     *   Length of random string to generate.
 579     *
 580     * @return
 581     *   Randomly generated string.
 582     *
 583     * @see DrupalWebTestCase::randomName()
 584     */
 585    public static function randomString($length = 8) {
 586      $str = '';
 587      for ($i = 0; $i < $length; $i++) {
 588        $str .= chr(mt_rand(32, 126));
 589      }
 590      return $str;
 591    }
 592  
 593    /**
 594     * Generates a random string containing letters and numbers.
 595     *
 596     * The string will always start with a letter. The letters may be upper or
 597     * lower case. This method is better for restricted inputs that do not
 598     * accept certain characters. For example, when testing input fields that
 599     * require machine readable values (i.e. without spaces and non-standard
 600     * characters) this method is best.
 601     *
 602     * Do not use this method when testing unvalidated user input. Instead, use
 603     * DrupalWebTestCase::randomString().
 604     *
 605     * @param $length
 606     *   Length of random string to generate.
 607     *
 608     * @return
 609     *   Randomly generated string.
 610     *
 611     * @see DrupalWebTestCase::randomString()
 612     */
 613    public static function randomName($length = 8) {
 614      $values = array_merge(range(65, 90), range(97, 122), range(48, 57));
 615      $max = count($values) - 1;
 616      $str = chr(mt_rand(97, 122));
 617      for ($i = 1; $i < $length; $i++) {
 618        $str .= chr($values[mt_rand(0, $max)]);
 619      }
 620      return $str;
 621    }
 622  
 623    /**
 624     * Converts a list of possible parameters into a stack of permutations.
 625     *
 626     * Takes a list of parameters containing possible values, and converts all of
 627     * them into a list of items containing every possible permutation.
 628     *
 629     * Example:
 630     * @code
 631     * $parameters = array(
 632     *   'one' => array(0, 1),
 633     *   'two' => array(2, 3),
 634     * );
 635     * $permutations = DrupalTestCase::generatePermutations($parameters)
 636     * // Result:
 637     * $permutations == array(
 638     *   array('one' => 0, 'two' => 2),
 639     *   array('one' => 1, 'two' => 2),
 640     *   array('one' => 0, 'two' => 3),
 641     *   array('one' => 1, 'two' => 3),
 642     * )
 643     * @endcode
 644     *
 645     * @param $parameters
 646     *   An associative array of parameters, keyed by parameter name, and whose
 647     *   values are arrays of parameter values.
 648     *
 649     * @return
 650     *   A list of permutations, which is an array of arrays. Each inner array
 651     *   contains the full list of parameters that have been passed, but with a
 652     *   single value only.
 653     */
 654    public static function generatePermutations($parameters) {
 655      $all_permutations = array(array());
 656      foreach ($parameters as $parameter => $values) {
 657        $new_permutations = array();
 658        // Iterate over all values of the parameter.
 659        foreach ($values as $value) {
 660          // Iterate over all existing permutations.
 661          foreach ($all_permutations as $permutation) {
 662            // Add the new parameter value to existing permutations.
 663            $new_permutations[] = $permutation + array($parameter => $value);
 664          }
 665        }
 666        // Replace the old permutations with the new permutations.
 667        $all_permutations = $new_permutations;
 668      }
 669      return $all_permutations;
 670    }
 671  }
 672  
 673  /**
 674   * Test case for Drupal unit tests.
 675   *
 676   * These tests can not access the database nor files. Calling any Drupal
 677   * function that needs the database will throw exceptions. These include
 678   * watchdog(), module_implements(), module_invoke_all() etc.
 679   */
 680  class DrupalUnitTestCase extends DrupalTestCase {
 681  
 682    /**
 683     * Constructor for DrupalUnitTestCase.
 684     */
 685    function __construct($test_id = NULL) {
 686      parent::__construct($test_id);
 687      $this->skipClasses[__CLASS__] = TRUE;
 688    }
 689  
 690    /**
 691     * Sets up unit test environment.
 692     *
 693     * Unlike DrupalWebTestCase::setUp(), DrupalUnitTestCase::setUp() does not
 694     * install modules because tests are performed without accessing the database.
 695     * Any required files must be explicitly included by the child class setUp()
 696     * method.
 697     */
 698    protected function setUp() {
 699      global $conf;
 700  
 701      // Store necessary current values before switching to the test environment.
 702      $this->originalFileDirectory = variable_get('file_public_path', conf_path() . '/files');
 703  
 704      // Reset all statics so that test is performed with a clean environment.
 705      drupal_static_reset();
 706  
 707      // Generate temporary prefixed database to ensure that tests have a clean starting point.
 708      $this->databasePrefix = Database::getConnection()->prefixTables('{simpletest' . mt_rand(1000, 1000000) . '}');
 709  
 710      // Create test directory.
 711      $public_files_directory = $this->originalFileDirectory . '/simpletest/' . substr($this->databasePrefix, 10);
 712      file_prepare_directory($public_files_directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
 713      $conf['file_public_path'] = $public_files_directory;
 714  
 715      // Clone the current connection and replace the current prefix.
 716      $connection_info = Database::getConnectionInfo('default');
 717      Database::renameConnection('default', 'simpletest_original_default');
 718      foreach ($connection_info as $target => $value) {
 719        $connection_info[$target]['prefix'] = array(
 720          'default' => $value['prefix']['default'] . $this->databasePrefix,
 721        );
 722      }
 723      Database::addConnectionInfo('default', 'default', $connection_info['default']);
 724  
 725      // Set user agent to be consistent with web test case.
 726      $_SERVER['HTTP_USER_AGENT'] = $this->databasePrefix;
 727  
 728      // If locale is enabled then t() will try to access the database and
 729      // subsequently will fail as the database is not accessible.
 730      $module_list = module_list();
 731      if (isset($module_list['locale'])) {
 732        $this->originalModuleList = $module_list;
 733        unset($module_list['locale']);
 734        module_list(TRUE, FALSE, FALSE, $module_list);
 735      }
 736      $this->setup = TRUE;
 737    }
 738  
 739    protected function tearDown() {
 740      global $conf;
 741  
 742      // Get back to the original connection.
 743      Database::removeConnection('default');
 744      Database::renameConnection('simpletest_original_default', 'default');
 745  
 746      $conf['file_public_path'] = $this->originalFileDirectory;
 747      // Restore modules if necessary.
 748      if (isset($this->originalModuleList)) {
 749        module_list(TRUE, FALSE, FALSE, $this->originalModuleList);
 750      }
 751    }
 752  }
 753  
 754  /**
 755   * Test case for typical Drupal tests.
 756   */
 757  class DrupalWebTestCase extends DrupalTestCase {
 758    /**
 759     * The profile to install as a basis for testing.
 760     *
 761     * @var string
 762     */
 763    protected $profile = 'standard';
 764  
 765    /**
 766     * The URL currently loaded in the internal browser.
 767     *
 768     * @var string
 769     */
 770    protected $url;
 771  
 772    /**
 773     * The handle of the current cURL connection.
 774     *
 775     * @var resource
 776     */
 777    protected $curlHandle;
 778  
 779    /**
 780     * The headers of the page currently loaded in the internal browser.
 781     *
 782     * @var Array
 783     */
 784    protected $headers;
 785  
 786    /**
 787     * The content of the page currently loaded in the internal browser.
 788     *
 789     * @var string
 790     */
 791    protected $content;
 792  
 793    /**
 794     * The content of the page currently loaded in the internal browser (plain text version).
 795     *
 796     * @var string
 797     */
 798    protected $plainTextContent;
 799  
 800    /**
 801     * The value of the Drupal.settings JavaScript variable for the page currently loaded in the internal browser.
 802     *
 803     * @var Array
 804     */
 805    protected $drupalSettings;
 806  
 807    /**
 808     * The parsed version of the page.
 809     *
 810     * @var SimpleXMLElement
 811     */
 812    protected $elements = NULL;
 813  
 814    /**
 815     * The current user logged in using the internal browser.
 816     *
 817     * @var bool
 818     */
 819    protected $loggedInUser = FALSE;
 820  
 821    /**
 822     * The current cookie file used by cURL.
 823     *
 824     * We do not reuse the cookies in further runs, so we do not need a file
 825     * but we still need cookie handling, so we set the jar to NULL.
 826     */
 827    protected $cookieFile = NULL;
 828  
 829    /**
 830     * Additional cURL options.
 831     *
 832     * DrupalWebTestCase itself never sets this but always obeys what is set.
 833     */
 834    protected $additionalCurlOptions = array();
 835  
 836    /**
 837     * The original user, before it was changed to a clean uid = 1 for testing purposes.
 838     *
 839     * @var object
 840     */
 841    protected $originalUser = NULL;
 842  
 843    /**
 844     * The original shutdown handlers array, before it was cleaned for testing purposes.
 845     *
 846     * @var array
 847     */
 848    protected $originalShutdownCallbacks = array();
 849  
 850    /**
 851     * HTTP authentication method
 852     */
 853    protected $httpauth_method = CURLAUTH_BASIC;
 854  
 855    /**
 856     * HTTP authentication credentials (<username>:<password>).
 857     */
 858    protected $httpauth_credentials = NULL;
 859  
 860    /**
 861     * The current session name, if available.
 862     */
 863    protected $session_name = NULL;
 864  
 865    /**
 866     * The current session ID, if available.
 867     */
 868    protected $session_id = NULL;
 869  
 870    /**
 871     * Whether the files were copied to the test files directory.
 872     */
 873    protected $generatedTestFiles = FALSE;
 874  
 875    /**
 876     * The number of redirects followed during the handling of a request.
 877     */
 878    protected $redirect_count;
 879  
 880    /**
 881     * Constructor for DrupalWebTestCase.
 882     */
 883    function __construct($test_id = NULL) {
 884      parent::__construct($test_id);
 885      $this->skipClasses[__CLASS__] = TRUE;
 886    }
 887  
 888    /**
 889     * Get a node from the database based on its title.
 890     *
 891     * @param $title
 892     *   A node title, usually generated by $this->randomName().
 893     * @param $reset
 894     *   (optional) Whether to reset the internal node_load() cache.
 895     *
 896     * @return
 897     *   A node object matching $title.
 898     */
 899    function drupalGetNodeByTitle($title, $reset = FALSE) {
 900      $nodes = node_load_multiple(array(), array('title' => $title), $reset);
 901      // Load the first node returned from the database.
 902      $returned_node = reset($nodes);
 903      return $returned_node;
 904    }
 905  
 906    /**
 907     * Creates a node based on default settings.
 908     *
 909     * @param $settings
 910     *   An associative array of settings to change from the defaults, keys are
 911     *   node properties, for example 'title' => 'Hello, world!'.
 912     * @return
 913     *   Created node object.
 914     */
 915    protected function drupalCreateNode($settings = array()) {
 916      // Populate defaults array.
 917      $settings += array(
 918        'body'      => array(LANGUAGE_NONE => array(array())),
 919        'title'     => $this->randomName(8),
 920        'comment'   => 2,
 921        'changed'   => REQUEST_TIME,
 922        'moderate'  => 0,
 923        'promote'   => 0,
 924        'revision'  => 1,
 925        'log'       => '',
 926        'status'    => 1,
 927        'sticky'    => 0,
 928        'type'      => 'page',
 929        'revisions' => NULL,
 930        'language'  => LANGUAGE_NONE,
 931      );
 932  
 933      // Use the original node's created time for existing nodes.
 934      if (isset($settings['created']) && !isset($settings['date'])) {
 935        $settings['date'] = format_date($settings['created'], 'custom', 'Y-m-d H:i:s O');
 936      }
 937  
 938      // If the node's user uid is not specified manually, use the currently
 939      // logged in user if available, or else the user running the test.
 940      if (!isset($settings['uid'])) {
 941        if ($this->loggedInUser) {
 942          $settings['uid'] = $this->loggedInUser->uid;
 943        }
 944        else {
 945          global $user;
 946          $settings['uid'] = $user->uid;
 947        }
 948      }
 949  
 950      // Merge body field value and format separately.
 951      $body = array(
 952        'value' => $this->randomName(32),
 953        'format' => filter_default_format(),
 954      );
 955      $settings['body'][$settings['language']][0] += $body;
 956  
 957      $node = (object) $settings;
 958      node_save($node);
 959  
 960      // Small hack to link revisions to our test user.
 961      db_update('node_revision')
 962        ->fields(array('uid' => $node->uid))
 963        ->condition('vid', $node->vid)
 964        ->execute();
 965      return $node;
 966    }
 967  
 968    /**
 969     * Creates a custom content type based on default settings.
 970     *
 971     * @param $settings
 972     *   An array of settings to change from the defaults.
 973     *   Example: 'type' => 'foo'.
 974     * @return
 975     *   Created content type.
 976     */
 977    protected function drupalCreateContentType($settings = array()) {
 978      // Find a non-existent random type name.
 979      do {
 980        $name = strtolower($this->randomName(8));
 981      } while (node_type_get_type($name));
 982  
 983      // Populate defaults array.
 984      $defaults = array(
 985        'type' => $name,
 986        'name' => $name,
 987        'base' => 'node_content',
 988        'description' => '',
 989        'help' => '',
 990        'title_label' => 'Title',
 991        'body_label' => 'Body',
 992        'has_title' => 1,
 993        'has_body' => 1,
 994      );
 995      // Imposed values for a custom type.
 996      $forced = array(
 997        'orig_type' => '',
 998        'old_type' => '',
 999        'module' => 'node',
1000        'custom' => 1,
1001        'modified' => 1,
1002        'locked' => 0,
1003      );
1004      $type = $forced + $settings + $defaults;
1005      $type = (object) $type;
1006  
1007      $saved_type = node_type_save($type);
1008      node_types_rebuild();
1009      menu_rebuild();
1010      node_add_body_field($type);
1011  
1012      $this->assertEqual($saved_type, SAVED_NEW, t('Created content type %type.', array('%type' => $type->type)));
1013  
1014      // Reset permissions so that permissions for this content type are available.
1015      $this->checkPermissions(array(), TRUE);
1016  
1017      return $type;
1018    }
1019  
1020    /**
1021     * Get a list files that can be used in tests.
1022     *
1023     * @param $type
1024     *   File type, possible values: 'binary', 'html', 'image', 'javascript', 'php', 'sql', 'text'.
1025     * @param $size
1026     *   File size in bytes to match. Please check the tests/files folder.
1027     * @return
1028     *   List of files that match filter.
1029     */
1030    protected function drupalGetTestFiles($type, $size = NULL) {
1031      if (empty($this->generatedTestFiles)) {
1032        // Generate binary test files.
1033        $lines = array(64, 1024);
1034        $count = 0;
1035        foreach ($lines as $line) {
1036          simpletest_generate_file('binary-' . $count++, 64, $line, 'binary');
1037        }
1038  
1039        // Generate text test files.
1040        $lines = array(16, 256, 1024, 2048, 20480);
1041        $count = 0;
1042        foreach ($lines as $line) {
1043          simpletest_generate_file('text-' . $count++, 64, $line);
1044        }
1045  
1046        // Copy other test files from simpletest.
1047        $original = drupal_get_path('module', 'simpletest') . '/files';
1048        $files = file_scan_directory($original, '/(html|image|javascript|php|sql)-.*/');
1049        foreach ($files as $file) {
1050          file_unmanaged_copy($file->uri, variable_get('file_public_path', conf_path() . '/files'));
1051        }
1052  
1053        $this->generatedTestFiles = TRUE;
1054      }
1055  
1056      $files = array();
1057      // Make sure type is valid.
1058      if (in_array($type, array('binary', 'html', 'image', 'javascript', 'php', 'sql', 'text'))) {
1059        $files = file_scan_directory('public://', '/' . $type . '\-.*/');
1060  
1061        // If size is set then remove any files that are not of that size.
1062        if ($size !== NULL) {
1063          foreach ($files as $file) {
1064            $stats = stat($file->uri);
1065            if ($stats['size'] != $size) {
1066              unset($files[$file->uri]);
1067            }
1068          }
1069        }
1070      }
1071      usort($files, array($this, 'drupalCompareFiles'));
1072      return $files;
1073    }
1074  
1075    /**
1076     * Compare two files based on size and file name.
1077     */
1078    protected function drupalCompareFiles($file1, $file2) {
1079      $compare_size = filesize($file1->uri) - filesize($file2->uri);
1080      if ($compare_size) {
1081        // Sort by file size.
1082        return $compare_size;
1083      }
1084      else {
1085        // The files were the same size, so sort alphabetically.
1086        return strnatcmp($file1->name, $file2->name);
1087      }
1088    }
1089  
1090    /**
1091     * Create a user with a given set of permissions.
1092     *
1093     * @param array $permissions
1094     *   Array of permission names to assign to user. Note that the user always
1095     *   has the default permissions derived from the "authenticated users" role.
1096     *
1097     * @return object|false
1098     *   A fully loaded user object with pass_raw property, or FALSE if account
1099     *   creation fails.
1100     */
1101    protected function drupalCreateUser(array $permissions = array()) {
1102      // Create a role with the given permission set, if any.
1103      $rid = FALSE;
1104      if ($permissions) {
1105        $rid = $this->drupalCreateRole($permissions);
1106        if (!$rid) {
1107          return FALSE;
1108        }
1109      }
1110  
1111      // Create a user assigned to that role.
1112      $edit = array();
1113      $edit['name']   = $this->randomName();
1114      $edit['mail']   = $edit['name'] . '@example.com';
1115      $edit['pass']   = user_password();
1116      $edit['status'] = 1;
1117      if ($rid) {
1118        $edit['roles'] = array($rid => $rid);
1119      }
1120  
1121      $account = user_save(drupal_anonymous_user(), $edit);
1122  
1123      $this->assertTrue(!empty($account->uid), t('User created with name %name and pass %pass', array('%name' => $edit['name'], '%pass' => $edit['pass'])), t('User login'));
1124      if (empty($account->uid)) {
1125        return FALSE;
1126      }
1127  
1128      // Add the raw password so that we can log in as this user.
1129      $account->pass_raw = $edit['pass'];
1130      return $account;
1131    }
1132  
1133    /**
1134     * Internal helper function; Create a role with specified permissions.
1135     *
1136     * @param $permissions
1137     *   Array of permission names to assign to role.
1138     * @param $name
1139     *   (optional) String for the name of the role.  Defaults to a random string.
1140     * @return
1141     *   Role ID of newly created role, or FALSE if role creation failed.
1142     */
1143    protected function drupalCreateRole(array $permissions, $name = NULL) {
1144      // Generate random name if it was not passed.
1145      if (!$name) {
1146        $name = $this->randomName();
1147      }
1148  
1149      // Check the all the permissions strings are valid.
1150      if (!$this->checkPermissions($permissions)) {
1151        return FALSE;
1152      }
1153  
1154      // Create new role.
1155      $role = new stdClass();
1156      $role->name = $name;
1157      user_role_save($role);
1158      user_role_grant_permissions($role->rid, $permissions);
1159  
1160      $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'));
1161      if ($role && !empty($role->rid)) {
1162        $count = db_query('SELECT COUNT(*) FROM {role_permission} WHERE rid = :rid', array(':rid' => $role->rid))->fetchField();
1163        $this->assertTrue($count == count($permissions), t('Created permissions: @perms', array('@perms' => implode(', ', $permissions))), t('Role'));
1164        return $role->rid;
1165      }
1166      else {
1167        return FALSE;
1168      }
1169    }
1170  
1171    /**
1172     * Check to make sure that the array of permissions are valid.
1173     *
1174     * @param $permissions
1175     *   Permissions to check.
1176     * @param $reset
1177     *   Reset cached available permissions.
1178     * @return
1179     *   TRUE or FALSE depending on whether the permissions are valid.
1180     */
1181    protected function checkPermissions(array $permissions, $reset = FALSE) {
1182      $available = &drupal_static(__FUNCTION__);
1183  
1184      if (!isset($available) || $reset) {
1185        $available = array_keys(module_invoke_all('permission'));
1186      }
1187  
1188      $valid = TRUE;
1189      foreach ($permissions as $permission) {
1190        if (!in_array($permission, $available)) {
1191          $this->fail(t('Invalid permission %permission.', array('%permission' => $permission)), t('Role'));
1192          $valid = FALSE;
1193        }
1194      }
1195      return $valid;
1196    }
1197  
1198    /**
1199     * Log in a user with the internal browser.
1200     *
1201     * If a user is already logged in, then the current user is logged out before
1202     * logging in the specified user.
1203     *
1204     * Please note that neither the global $user nor the passed-in user object is
1205     * populated with data of the logged in user. If you need full access to the
1206     * user object after logging in, it must be updated manually. If you also need
1207     * access to the plain-text password of the user (set by drupalCreateUser()),
1208     * e.g. to log in the same user again, then it must be re-assigned manually.
1209     * For example:
1210     * @code
1211     *   // Create a user.
1212     *   $account = $this->drupalCreateUser(array());
1213     *   $this->drupalLogin($account);
1214     *   // Load real user object.
1215     *   $pass_raw = $account->pass_raw;
1216     *   $account = user_load($account->uid);
1217     *   $account->pass_raw = $pass_raw;
1218     * @endcode
1219     *
1220     * @param $user
1221     *   User object representing the user to log in.
1222     *
1223     * @see drupalCreateUser()
1224     */
1225    protected function drupalLogin(stdClass $user) {
1226      if ($this->loggedInUser) {
1227        $this->drupalLogout();
1228      }
1229  
1230      $edit = array(
1231        'name' => $user->name,
1232        'pass' => $user->pass_raw
1233      );
1234      $this->drupalPost('user', $edit, t('Log in'));
1235  
1236      // If a "log out" link appears on the page, it is almost certainly because
1237      // the login was successful.
1238      $pass = $this->assertLink(t('Log out'), 0, t('User %name successfully logged in.', array('%name' => $user->name)), t('User login'));
1239  
1240      if ($pass) {
1241        $this->loggedInUser = $user;
1242      }
1243    }
1244  
1245    /**
1246     * Generate a token for the currently logged in user.
1247     */
1248    protected function drupalGetToken($value = '') {
1249      $private_key = drupal_get_private_key();
1250      return drupal_hmac_base64($value, $this->session_id . $private_key);
1251    }
1252  
1253    /*
1254     * Logs a user out of the internal browser, then check the login page to confirm logout.
1255     */
1256    protected function drupalLogout() {
1257      // Make a request to the logout page, and redirect to the user page, the
1258      // idea being if you were properly logged out you should be seeing a login
1259      // screen.
1260      $this->drupalGet('user/logout');
1261      $this->drupalGet('user');
1262      $pass = $this->assertField('name', t('Username field found.'), t('Logout'));
1263      $pass = $pass && $this->assertField('pass', t('Password field found.'), t('Logout'));
1264  
1265      if ($pass) {
1266        $this->loggedInUser = FALSE;
1267      }
1268    }
1269  
1270    /**
1271     * Generates a database prefix for running tests.
1272     *
1273     * The generated database table prefix is used for the Drupal installation
1274     * being performed for the test. It is also used as user agent HTTP header
1275     * value by the cURL-based browser of DrupalWebTestCase, which is sent
1276     * to the Drupal installation of the test. During early Drupal bootstrap, the
1277     * user agent HTTP header is parsed, and if it matches, all database queries
1278     * use the database table prefix that has been generated here.
1279     *
1280     * @see DrupalWebTestCase::curlInitialize()
1281     * @see drupal_valid_test_ua()
1282     * @see DrupalWebTestCase::setUp()
1283     */
1284    protected function prepareDatabasePrefix() {
1285      $this->databasePrefix = 'simpletest' . mt_rand(1000, 1000000);
1286  
1287      // As soon as the database prefix is set, the test might start to execute.
1288      // All assertions as well as the SimpleTest batch operations are associated
1289      // with the testId, so the database prefix has to be associated with it.
1290      db_update('simpletest_test_id')
1291        ->fields(array('last_prefix' => $this->databasePrefix))
1292        ->condition('test_id', $this->testId)
1293        ->execute();
1294    }
1295  
1296    /**
1297     * Changes the database connection to the prefixed one.
1298     *
1299     * @see DrupalWebTestCase::setUp()
1300     */
1301    protected function changeDatabasePrefix() {
1302      if (empty($this->databasePrefix)) {
1303        $this->prepareDatabasePrefix();
1304        // If $this->prepareDatabasePrefix() failed to work, return without
1305        // setting $this->setupDatabasePrefix to TRUE, so setUp() methods will
1306        // know to bail out.
1307        if (empty($this->databasePrefix)) {
1308          return;
1309        }
1310      }
1311  
1312      // Clone the current connection and replace the current prefix.
1313      $connection_info = Database::getConnectionInfo('default');
1314      Database::renameConnection('default', 'simpletest_original_default');
1315      foreach ($connection_info as $target => $value) {
1316        $connection_info[$target]['prefix'] = array(
1317          'default' => $value['prefix']['default'] . $this->databasePrefix,
1318        );
1319      }
1320      Database::addConnectionInfo('default', 'default', $connection_info['default']);
1321  
1322      // Indicate the database prefix was set up correctly.
1323      $this->setupDatabasePrefix = TRUE;
1324    }
1325  
1326    /**
1327     * Prepares the current environment for running the test.
1328     *
1329     * Backups various current environment variables and resets them, so they do
1330     * not interfere with the Drupal site installation in which tests are executed
1331     * and can be restored in tearDown().
1332     *
1333     * Also sets up new resources for the testing environment, such as the public
1334     * filesystem and configuration directories.
1335     *
1336     * @see DrupalWebTestCase::setUp()
1337     * @see DrupalWebTestCase::tearDown()
1338     */
1339    protected function prepareEnvironment() {
1340      global $user, $language, $conf;
1341  
1342      // Store necessary current values before switching to prefixed database.
1343      $this->originalLanguage = $language;
1344      $this->originalLanguageDefault = variable_get('language_default');
1345      $this->originalFileDirectory = variable_get('file_public_path', conf_path() . '/files');
1346      $this->originalProfile = drupal_get_profile();
1347      $this->originalCleanUrl = variable_get('clean_url', 0);
1348      $this->originalUser = $user;
1349  
1350      // Set to English to prevent exceptions from utf8_truncate() from t()
1351      // during install if the current language is not 'en'.
1352      // The following array/object conversion is copied from language_default().
1353      $language = (object) array('language' => 'en', 'name' => 'English', 'native' => 'English', 'direction' => 0, 'enabled' => 1, 'plurals' => 0, 'formula' => '', 'domain' => '', 'prefix' => '', 'weight' => 0, 'javascript' => '');
1354  
1355      // Save and clean the shutdown callbacks array because it is static cached
1356      // and will be changed by the test run. Otherwise it will contain callbacks
1357      // from both environments and the testing environment will try to call the
1358      // handlers defined by the original one.
1359      $callbacks = &drupal_register_shutdown_function();
1360      $this->originalShutdownCallbacks = $callbacks;
1361      $callbacks = array();
1362  
1363      // Create test directory ahead of installation so fatal errors and debug
1364      // information can be logged during installation process.
1365      // Use temporary files directory with the same prefix as the database.
1366      $this->public_files_directory = $this->originalFileDirectory . '/simpletest/' . substr($this->databasePrefix, 10);
1367      $this->private_files_directory = $this->public_files_directory . '/private';
1368      $this->temp_files_directory = $this->private_files_directory . '/temp';
1369  
1370      // Create the directories
1371      file_prepare_directory($this->public_files_directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
1372      file_prepare_directory($this->private_files_directory, FILE_CREATE_DIRECTORY);
1373      file_prepare_directory($this->temp_files_directory, FILE_CREATE_DIRECTORY);
1374      $this->generatedTestFiles = FALSE;
1375  
1376      // Log fatal errors.
1377      ini_set('log_errors', 1);
1378      ini_set('error_log', $this->public_files_directory . '/error.log');
1379  
1380      // Set the test information for use in other parts of Drupal.
1381      $test_info = &$GLOBALS['drupal_test_info'];
1382      $test_info['test_run_id'] = $this->databasePrefix;
1383      $test_info['in_child_site'] = FALSE;
1384  
1385      // Indicate the environment was set up correctly.
1386      $this->setupEnvironment = TRUE;
1387    }
1388  
1389    /**
1390     * Sets up a Drupal site for running functional and integration tests.
1391     *
1392     * Generates a random database prefix and installs Drupal with the specified
1393     * installation profile in DrupalWebTestCase::$profile into the
1394     * prefixed database. Afterwards, installs any additional modules specified by
1395     * the test.
1396     *
1397     * After installation all caches are flushed and several configuration values
1398     * are reset to the values of the parent site executing the test, since the
1399     * default values may be incompatible with the environment in which tests are
1400     * being executed.
1401     *
1402     * @param ...
1403     *   List of modules to enable for the duration of the test. This can be
1404     *   either a single array or a variable number of string arguments.
1405     *
1406     * @see DrupalWebTestCase::prepareDatabasePrefix()
1407     * @see DrupalWebTestCase::changeDatabasePrefix()
1408     * @see DrupalWebTestCase::prepareEnvironment()
1409     */
1410    protected function setUp() {
1411      global $user, $language, $conf;
1412  
1413      // Create the database prefix for this test.
1414      $this->prepareDatabasePrefix();
1415  
1416      // Prepare the environment for running tests.
1417      $this->prepareEnvironment();
1418      if (!$this->setupEnvironment) {
1419        return FALSE;
1420      }
1421  
1422      // Reset all statics and variables to perform tests in a clean environment.
1423      $conf = array();
1424      drupal_static_reset();
1425  
1426      // Change the database prefix.
1427      // All static variables need to be reset before the database prefix is
1428      // changed, since DrupalCacheArray implementations attempt to
1429      // write back to persistent caches when they are destructed.
1430      $this->changeDatabasePrefix();
1431      if (!$this->setupDatabasePrefix) {
1432        return FALSE;
1433      }
1434  
1435      // Preset the 'install_profile' system variable, so the first call into
1436      // system_rebuild_module_data() (in drupal_install_system()) will register
1437      // the test's profile as a module. Without this, the installation profile of
1438      // the parent site (executing the test) is registered, and the test
1439      // profile's hook_install() and other hook implementations are never invoked.
1440      $conf['install_profile'] = $this->profile;
1441  
1442      // Perform the actual Drupal installation.
1443      include_once  DRUPAL_ROOT . '/includes/install.inc';
1444      drupal_install_system();
1445  
1446      $this->preloadRegistry();
1447  
1448      // Set path variables.
1449      variable_set('file_public_path', $this->public_files_directory);
1450      variable_set('file_private_path', $this->private_files_directory);
1451      variable_set('file_temporary_path', $this->temp_files_directory);
1452  
1453      // Set the 'simpletest_parent_profile' variable to add the parent profile's
1454      // search path to the child site's search paths.
1455      // @see drupal_system_listing()
1456      // @todo This may need to be primed like 'install_profile' above.
1457      variable_set('simpletest_parent_profile', $this->originalProfile);
1458  
1459      // Include the testing profile.
1460      variable_set('install_profile', $this->profile);
1461      $profile_details = install_profile_info($this->profile, 'en');
1462  
1463      // Install the modules specified by the testing profile.
1464      module_enable($profile_details['dependencies'], FALSE);
1465  
1466      // Install modules needed for this test. This could have been passed in as
1467      // either a single array argument or a variable number of string arguments.
1468      // @todo Remove this compatibility layer in Drupal 8, and only accept
1469      // $modules as a single array argument.
1470      $modules = func_get_args();
1471      if (isset($modules[0]) && is_array($modules[0])) {
1472        $modules = $modules[0];
1473      }
1474      if ($modules) {
1475        $success = module_enable($modules, TRUE);
1476        $this->assertTrue($success, t('Enabled modules: %modules', array('%modules' => implode(', ', $modules))));
1477      }
1478  
1479      // Run the profile tasks.
1480      $install_profile_module_exists = db_query("SELECT 1 FROM {system} WHERE type = 'module' AND name = :name", array(
1481        ':name' => $this->profile,
1482      ))->fetchField();
1483      if ($install_profile_module_exists) {
1484        module_enable(array($this->profile), FALSE);
1485      }
1486  
1487      // Reset/rebuild all data structures after enabling the modules.
1488      $this->resetAll();
1489  
1490      // Run cron once in that environment, as install.php does at the end of
1491      // the installation process.
1492      drupal_cron_run();
1493  
1494      // Ensure that the session is not written to the new environment and replace
1495      // the global $user session with uid 1 from the new test site.
1496      drupal_save_session(FALSE);
1497      // Login as uid 1.
1498      $user = user_load(1);
1499  
1500      // Restore necessary variables.
1501      variable_set('install_task', 'done');
1502      variable_set('clean_url', $this->originalCleanUrl);
1503      variable_set('site_mail', 'simpletest@example.com');
1504      variable_set('date_default_timezone', date_default_timezone_get());
1505  
1506      // Set up English language.
1507      unset($conf['language_default']);
1508      $language = language_default();
1509  
1510      // Use the test mail class instead of the default mail handler class.
1511      variable_set('mail_system', array('default-system' => 'TestingMailSystem'));
1512  
1513      drupal_set_time_limit($this->timeLimit);
1514      $this->setup = TRUE;
1515    }
1516  
1517    /**
1518     * Preload the registry from the testing site.
1519     *
1520     * This method is called by DrupalWebTestCase::setUp(), and preloads the
1521     * registry from the testing site to cut down on the time it takes to
1522     * set up a clean environment for the current test run.
1523     */
1524    protected function preloadRegistry() {
1525      // Use two separate queries, each with their own connections: copy the
1526      // {registry} and {registry_file} tables over from the parent installation
1527      // to the child installation.
1528      $original_connection = Database::getConnection('default', 'simpletest_original_default');
1529      $test_connection = Database::getConnection();
1530  
1531      foreach (array('registry', 'registry_file') as $table) {
1532        // Find the records from the parent database.
1533        $source_query = $original_connection
1534          ->select($table, array(), array('fetch' => PDO::FETCH_ASSOC))
1535          ->fields($table);
1536  
1537        $dest_query = $test_connection->insert($table);
1538  
1539        $first = TRUE;
1540        foreach ($source_query->execute() as $row) {
1541          if ($first) {
1542            $dest_query->fields(array_keys($row));
1543            $first = FALSE;
1544          }
1545          // Insert the records into the child database.
1546          $dest_query->values($row);
1547        }
1548  
1549        $dest_query->execute();
1550      }
1551    }
1552  
1553    /**
1554     * Reset all data structures after having enabled new modules.
1555     *
1556     * This method is called by DrupalWebTestCase::setUp() after enabling
1557     * the requested modules. It must be called again when additional modules
1558     * are enabled later.
1559     */
1560    protected function resetAll() {
1561      // Reset all static variables.
1562      drupal_static_reset();
1563      // Reset the list of enabled modules.
1564      module_list(TRUE);
1565  
1566      // Reset cached schema for new database prefix. This must be done before
1567      // drupal_flush_all_caches() so rebuilds can make use of the schema of
1568      // modules enabled on the cURL side.
1569      drupal_get_schema(NULL, TRUE);
1570  
1571      // Perform rebuilds and flush remaining caches.
1572      drupal_flush_all_caches();
1573  
1574      // Reload global $conf array and permissions.
1575      $this->refreshVariables();
1576      $this->checkPermissions(array(), TRUE);
1577    }
1578  
1579    /**
1580     * Refresh the in-memory set of variables. Useful after a page request is made
1581     * that changes a variable in a different thread.
1582     *
1583     * In other words calling a settings page with $this->drupalPost() with a changed
1584     * value would update a variable to reflect that change, but in the thread that
1585     * made the call (thread running the test) the changed variable would not be
1586     * picked up.
1587     *
1588     * This method clears the variables cache and loads a fresh copy from the database
1589     * to ensure that the most up-to-date set of variables is loaded.
1590     */
1591    protected function refreshVariables() {
1592      global $conf;
1593      cache_clear_all('variables', 'cache_bootstrap');
1594      $conf = variable_initialize();
1595    }
1596  
1597    /**
1598     * Delete created files and temporary files directory, delete the tables created by setUp(),
1599     * and reset the database prefix.
1600     */
1601    protected function tearDown() {
1602      global $user, $language;
1603  
1604      // In case a fatal error occurred that was not in the test process read the
1605      // log to pick up any fatal errors.
1606      simpletest_log_read($this->testId, $this->databasePrefix, get_class($this), TRUE);
1607  
1608      $emailCount = count(variable_get('drupal_test_email_collector', array()));
1609      if ($emailCount) {
1610        $message = format_plural($emailCount, '1 e-mail was sent during this test.', '@count e-mails were sent during this test.');
1611        $this->pass($message, t('E-mail'));
1612      }
1613  
1614      // Delete temporary files directory.
1615      file_unmanaged_delete_recursive($this->originalFileDirectory . '/simpletest/' . substr($this->databasePrefix, 10));
1616  
1617      // Remove all prefixed tables.
1618      $tables = db_find_tables($this->databasePrefix . '%');
1619      $connection_info = Database::getConnectionInfo('default');
1620      $tables = db_find_tables($connection_info['default']['prefix']['default'] . '%');
1621      if (empty($tables)) {
1622        $this->fail('Failed to find test tables to drop.');
1623      }
1624      $prefix_length = strlen($connection_info['default']['prefix']['default']);
1625      foreach ($tables as $table) {
1626        if (db_drop_table(substr($table, $prefix_length))) {
1627          unset($tables[$table]);
1628        }
1629      }
1630      if (!empty($tables)) {
1631        $this->fail('Failed to drop all prefixed tables.');
1632      }
1633  
1634      // Get back to the original connection.
1635      Database::removeConnection('default');
1636      Database::renameConnection('simpletest_original_default', 'default');
1637  
1638      // Restore original shutdown callbacks array to prevent original
1639      // environment of calling handlers from test run.
1640      $callbacks = &drupal_register_shutdown_function();
1641      $callbacks = $this->originalShutdownCallbacks;
1642  
1643      // Return the user to the original one.
1644      $user = $this->originalUser;
1645      drupal_save_session(TRUE);
1646  
1647      // Ensure that internal logged in variable and cURL options are reset.
1648      $this->loggedInUser = FALSE;
1649      $this->additionalCurlOptions = array();
1650  
1651      // Reload module list and implementations to ensure that test module hooks
1652      // aren't called after tests.
1653      module_list(TRUE);
1654      module_implements('', FALSE, TRUE);
1655  
1656      // Reset the Field API.
1657      field_cache_clear();
1658  
1659      // Rebuild caches.
1660      $this->refreshVariables();
1661  
1662      // Reset public files directory.
1663      $GLOBALS['conf']['file_public_path'] = $this->originalFileDirectory;
1664  
1665      // Reset language.
1666      $language = $this->originalLanguage;
1667      if ($this->originalLanguageDefault) {
1668        $GLOBALS['conf']['language_default'] = $this->originalLanguageDefault;
1669      }
1670  
1671      // Close the CURL handler.
1672      $this->curlClose();
1673    }
1674  
1675    /**
1676     * Initializes the cURL connection.
1677     *
1678     * If the simpletest_httpauth_credentials variable is set, this function will
1679     * add HTTP authentication headers. This is necessary for testing sites that
1680     * are protected by login credentials from public access.
1681     * See the description of $curl_options for other options.
1682     */
1683    protected function curlInitialize() {
1684      global $base_url;
1685  
1686      if (!isset($this->curlHandle)) {
1687        $this->curlHandle = curl_init();
1688  
1689        // Some versions/configurations of cURL break on a NULL cookie jar, so
1690        // supply a real file.
1691        if (empty($this->cookieFile)) {
1692          $this->cookieFile = $this->public_files_directory . '/cookie.jar';
1693        }
1694  
1695        $curl_options = array(
1696          CURLOPT_COOKIEJAR => $this->cookieFile,
1697          CURLOPT_URL => $base_url,
1698          CURLOPT_FOLLOWLOCATION => FALSE,
1699          CURLOPT_RETURNTRANSFER => TRUE,
1700          CURLOPT_SSL_VERIFYPEER => FALSE, // Required to make the tests run on HTTPS.
1701          CURLOPT_SSL_VERIFYHOST => FALSE, // Required to make the tests run on HTTPS.
1702          CURLOPT_HEADERFUNCTION => array(&$this, 'curlHeaderCallback'),
1703          CURLOPT_USERAGENT => $this->databasePrefix,
1704        );
1705        if (isset($this->httpauth_credentials)) {
1706          $curl_options[CURLOPT_HTTPAUTH] = $this->httpauth_method;
1707          $curl_options[CURLOPT_USERPWD] = $this->httpauth_credentials;
1708        }
1709        // curl_setopt_array() returns FALSE if any of the specified options
1710        // cannot be set, and stops processing any further options.
1711        $result = curl_setopt_array($this->curlHandle, $this->additionalCurlOptions + $curl_options);
1712        if (!$result) {
1713          throw new Exception('One or more cURL options could not be set.');
1714        }
1715  
1716        // By default, the child session name should be the same as the parent.
1717        $this->session_name = session_name();
1718      }
1719      // We set the user agent header on each request so as to use the current
1720      // time and a new uniqid.
1721      if (preg_match('/simpletest\d+/', $this->databasePrefix, $matches)) {
1722        curl_setopt($this->curlHandle, CURLOPT_USERAGENT, drupal_generate_test_ua($matches[0]));
1723      }
1724    }
1725  
1726    /**
1727     * Initializes and executes a cURL request.
1728     *
1729     * @param $curl_options
1730     *   An associative array of cURL options to set, where the keys are constants
1731     *   defined by the cURL library. For a list of valid options, see
1732     *   http://www.php.net/manual/function.curl-setopt.php
1733     * @param $redirect
1734     *   FALSE if this is an initial request, TRUE if this request is the result
1735     *   of a redirect.
1736     *
1737     * @return
1738     *   The content returned from the call to curl_exec().
1739     *
1740     * @see curlInitialize()
1741     */
1742    protected function curlExec($curl_options, $redirect = FALSE) {
1743      $this->curlInitialize();
1744  
1745      // cURL incorrectly handles URLs with a fragment by including the
1746      // fragment in the request to the server, causing some web servers
1747      // to reject the request citing "400 - Bad Request". To prevent
1748      // this, we strip the fragment from the request.
1749      // TODO: Remove this for Drupal 8, since fixed in curl 7.20.0.
1750      if (!empty($curl_options[CURLOPT_URL]) && strpos($curl_options[CURLOPT_URL], '#')) {
1751        $original_url = $curl_options[CURLOPT_URL];
1752        $curl_options[CURLOPT_URL] = strtok($curl_options[CURLOPT_URL], '#');
1753      }
1754  
1755      $url = empty($curl_options[CURLOPT_URL]) ? curl_getinfo($this->curlHandle, CURLINFO_EFFECTIVE_URL) : $curl_options[CURLOPT_URL];
1756  
1757      if (!empty($curl_options[CURLOPT_POST])) {
1758        // This is a fix for the Curl library to prevent Expect: 100-continue
1759        // headers in POST requests, that may cause unexpected HTTP response
1760        // codes from some webservers (like lighttpd that returns a 417 error
1761        // code). It is done by setting an empty "Expect" header field that is
1762        // not overwritten by Curl.
1763        $curl_options[CURLOPT_HTTPHEADER][] = 'Expect:';
1764      }
1765      curl_setopt_array($this->curlHandle, $this->additionalCurlOptions + $curl_options);
1766  
1767      if (!$redirect) {
1768        // Reset headers, the session ID and the redirect counter.
1769        $this->session_id = NULL;
1770        $this->headers = array();
1771        $this->redirect_count = 0;
1772      }
1773  
1774      $content = curl_exec($this->curlHandle);
1775      $status = curl_getinfo($this->curlHandle, CURLINFO_HTTP_CODE);
1776  
1777      // cURL incorrectly handles URLs with fragments, so instead of
1778      // letting cURL handle redirects we take of them ourselves to
1779      // to prevent fragments being sent to the web server as part
1780      // of the request.
1781      // TODO: Remove this for Drupal 8, since fixed in curl 7.20.0.
1782      if (in_array($status, array(300, 301, 302, 303, 305, 307)) && $this->redirect_count < variable_get('simpletest_maximum_redirects', 5)) {
1783        if ($this->drupalGetHeader('location')) {
1784          $this->redirect_count++;
1785          $curl_options = array();
1786          $curl_options[CURLOPT_URL] = $this->drupalGetHeader('location');
1787          $curl_options[CURLOPT_HTTPGET] = TRUE;
1788          return $this->curlExec($curl_options, TRUE);
1789        }
1790      }
1791  
1792      $this->drupalSetContent($content, isset($original_url) ? $original_url : curl_getinfo($this->curlHandle, CURLINFO_EFFECTIVE_URL));
1793      $message_vars = array(
1794        '!method' => !empty($curl_options[CURLOPT_NOBODY]) ? 'HEAD' : (empty($curl_options[CURLOPT_POSTFIELDS]) ? 'GET' : 'POST'),
1795        '@url' => isset($original_url) ? $original_url : $url,
1796        '@status' => $status,
1797        '!length' => format_size(strlen($this->drupalGetContent()))
1798      );
1799      $message = t('!method @url returned @status (!length).', $message_vars);
1800      $this->assertTrue($this->drupalGetContent() !== FALSE, $message, t('Browser'));
1801      return $this->drupalGetContent();
1802    }
1803  
1804    /**
1805     * Reads headers and registers errors received from the tested site.
1806     *
1807     * @see _drupal_log_error().
1808     *
1809     * @param $curlHandler
1810     *   The cURL handler.
1811     * @param $header
1812     *   An header.
1813     */
1814    protected function curlHeaderCallback($curlHandler, $header) {
1815      // Header fields can be extended over multiple lines by preceding each
1816      // extra line with at least one SP or HT. They should be joined on receive.
1817      // Details are in RFC2616 section 4.
1818      if ($header[0] == ' ' || $header[0] == "\t") {
1819        // Normalize whitespace between chucks.
1820        $this->headers[] = array_pop($this->headers) . ' ' . trim($header);
1821      }
1822      else {
1823        $this->headers[] = $header;
1824      }
1825  
1826      // Errors are being sent via X-Drupal-Assertion-* headers,
1827      // generated by _drupal_log_error() in the exact form required
1828      // by DrupalWebTestCase::error().
1829      if (preg_match('/^X-Drupal-Assertion-[0-9]+: (.*)$/', $header, $matches)) {
1830        // Call DrupalWebTestCase::error() with the parameters from the header.
1831        call_user_func_array(array(&$this, 'error'), unserialize(urldecode($matches[1])));
1832      }
1833  
1834      // Save cookies.
1835      if (preg_match('/^Set-Cookie: ([^=]+)=(.+)/', $header, $matches)) {
1836        $name = $matches[1];
1837        $parts = array_map('trim', explode(';', $matches[2]));
1838        $value = array_shift($parts);
1839        $this->cookies[$name] = array('value' => $value, 'secure' => in_array('secure', $parts));
1840        if ($name == $this->session_name) {
1841          if ($value != 'deleted') {
1842            $this->session_id = $value;
1843          }
1844          else {
1845            $this->session_id = NULL;
1846          }
1847        }
1848      }
1849  
1850      // This is required by cURL.
1851      return strlen($header);
1852    }
1853  
1854    /**
1855     * Close the cURL handler and unset the handler.
1856     */
1857    protected function curlClose() {
1858      if (isset($this->curlHandle)) {
1859        curl_close($this->curlHandle);
1860        unset($this->curlHandle);
1861      }
1862    }
1863  
1864    /**
1865     * Parse content returned from curlExec using DOM and SimpleXML.
1866     *
1867     * @return
1868     *   A SimpleXMLElement or FALSE on failure.
1869     */
1870    protected function parse() {
1871      if (!$this->elements) {
1872        // DOM can load HTML soup. But, HTML soup can throw warnings, suppress
1873        // them.
1874        $htmlDom = new DOMDocument();
1875        @$htmlDom->loadHTML($this->drupalGetContent());
1876        if ($htmlDom) {
1877          $this->pass(t('Valid HTML found on "@path"', array('@path' => $this->getUrl())), t('Browser'));
1878          // It's much easier to work with simplexml than DOM, luckily enough
1879          // we can just simply import our DOM tree.
1880          $this->elements = simplexml_import_dom($htmlDom);
1881        }
1882      }
1883      if (!$this->elements) {
1884        $this->fail(t('Parsed page successfully.'), t('Browser'));
1885      }
1886  
1887      return $this->elements;
1888    }
1889  
1890    /**
1891     * Retrieves a Drupal path or an absolute path.
1892     *
1893     * @param $path
1894     *   Drupal path or URL to load into internal browser
1895     * @param $options
1896     *   Options to be forwarded to url().
1897     * @param $headers
1898     *   An array containing additional HTTP request headers, each formatted as
1899     *   "name: value".
1900     * @return
1901     *   The retrieved HTML string, also available as $this->drupalGetContent()
1902     */
1903    protected function drupalGet($path, array $options = array(), array $headers = array()) {
1904      $options['absolute'] = TRUE;
1905  
1906      // We re-using a CURL connection here. If that connection still has certain
1907      // options set, it might change the GET into a POST. Make sure we clear out
1908      // previous options.
1909      $out = $this->curlExec(array(CURLOPT_HTTPGET => TRUE, CURLOPT_URL => url($path, $options), CURLOPT_NOBODY => FALSE, CURLOPT_HTTPHEADER => $headers));
1910      $this->refreshVariables(); // Ensure that any changes to variables in the other thread are picked up.
1911  
1912      // Replace original page output with new output from redirected page(s).
1913      if ($new = $this->checkForMetaRefresh()) {
1914        $out = $new;
1915      }
1916      $this->verbose('GET request to: ' . $path .
1917                     '<hr />Ending URL: ' . $this->getUrl() .
1918                     '<hr />' . $out);
1919      return $out;
1920    }
1921  
1922    /**
1923     * Retrieve a Drupal path or an absolute path and JSON decode the result.
1924     */
1925    protected function drupalGetAJAX($path, array $options = array(), array $headers = array()) {
1926      return drupal_json_decode($this->drupalGet($path, $options, $headers));
1927    }
1928  
1929    /**
1930     * Execute a POST request on a Drupal page.
1931     * It will be done as usual POST request with SimpleBrowser.
1932     *
1933     * @param $path
1934     *   Location of the post form. Either a Drupal path or an absolute path or
1935     *   NULL to post to the current page. For multi-stage forms you can set the
1936     *   path to NULL and have it post to the last received page. Example:
1937     *
1938     *   @code
1939     *   // First step in form.
1940     *   $edit = array(...);
1941     *   $this->drupalPost('some_url', $edit, t('Save'));
1942     *
1943     *   // Second step in form.
1944     *   $edit = array(...);
1945     *   $this->drupalPost(NULL, $edit, t('Save'));
1946     *   @endcode
1947     * @param  $edit
1948     *   Field data in an associative array. Changes the current input fields
1949     *   (where possible) to the values indicated. A checkbox can be set to
1950     *   TRUE to be checked and FALSE to be unchecked. Note that when a form
1951     *   contains file upload fields, other fields cannot start with the '@'
1952     *   character.
1953     *
1954     *   Multiple select fields can be set using name[] and setting each of the
1955     *   possible values. Example:
1956     *   @code
1957     *   $edit = array();
1958     *   $edit['name[]'] = array('value1', 'value2');
1959     *   @endcode
1960     * @param $submit
1961     *   Value of the submit button whose click is to be emulated. For example,
1962     *   t('Save'). The processing of the request depends on this value. For
1963     *   example, a form may have one button with the value t('Save') and another
1964     *   button with the value t('Delete'), and execute different code depending
1965     *   on which one is clicked.
1966     *
1967     *   This function can also be called to emulate an Ajax submission. In this
1968     *   case, this value needs to be an array with the following keys:
1969     *   - path: A path to submit the form values to for Ajax-specific processing,
1970     *     which is likely different than the $path parameter used for retrieving
1971     *     the initial form. Defaults to 'system/ajax'.
1972     *   - triggering_element: If the value for the 'path' key is 'system/ajax' or
1973     *     another generic Ajax processing path, this needs to be set to the name
1974     *     of the element. If the name doesn't identify the element uniquely, then
1975     *     this should instead be an array with a single key/value pair,
1976     *     corresponding to the element name and value. The callback for the
1977     *     generic Ajax processing path uses this to find the #ajax information
1978     *     for the element, including which specific callback to use for
1979     *     processing the request.
1980     *
1981     *   This can also be set to NULL in order to emulate an Internet Explorer
1982     *   submission of a form with a single text field, and pressing ENTER in that
1983     *   textfield: under these conditions, no button information is added to the
1984     *   POST data.
1985     * @param $options
1986     *   Options to be forwarded to url().
1987     * @param $headers
1988     *   An array containing additional HTTP request headers, each formatted as
1989     *   "name: value".
1990     * @param $form_html_id
1991     *   (optional) HTML ID of the form to be submitted. On some pages
1992     *   there are many identical forms, so just using the value of the submit
1993     *   button is not enough. For example: 'trigger-node-presave-assign-form'.
1994     *   Note that this is not the Drupal $form_id, but rather the HTML ID of the
1995     *   form, which is typically the same thing but with hyphens replacing the
1996     *   underscores.
1997     * @param $extra_post
1998     *   (optional) A string of additional data to append to the POST submission.
1999     *   This can be used to add POST data for which there are no HTML fields, as
2000     *   is done by drupalPostAJAX(). This string is literally appended to the
2001     *   POST data, so it must already be urlencoded and contain a leading "&"
2002     *   (e.g., "&extra_var1=hello+world&extra_var2=you%26me").
2003     */
2004    protected function drupalPost($path, $edit, $submit, array $options = array(), array $headers = array(), $form_html_id = NULL, $extra_post = NULL) {
2005      $submit_matches = FALSE;
2006      $ajax = is_array($submit);
2007      if (isset($path)) {
2008        $this->drupalGet($path, $options);
2009      }
2010      if ($this->parse()) {
2011        $edit_save = $edit;
2012        // Let's iterate over all the forms.
2013        $xpath = "//form";
2014        if (!empty($form_html_id)) {
2015          $xpath .= "[@id='" . $form_html_id . "']";
2016        }
2017        $forms = $this->xpath($xpath);
2018        foreach ($forms as $form) {
2019          // We try to set the fields of this form as specified in $edit.
2020          $edit = $edit_save;
2021          $post = array();
2022          $upload = array();
2023          $submit_matches = $this->handleForm($post, $edit, $upload, $ajax ? NULL : $submit, $form);
2024          $action = isset($form['action']) ? $this->getAbsoluteUrl((string) $form['action']) : $this->getUrl();
2025          if ($ajax) {
2026            $action = $this->getAbsoluteUrl(!empty($submit['path']) ? $submit['path'] : 'system/ajax');
2027            // Ajax callbacks verify the triggering element if necessary, so while
2028            // we may eventually want extra code that verifies it in the
2029            // handleForm() function, it's not currently a requirement.
2030            $submit_matches = TRUE;
2031          }
2032  
2033          // We post only if we managed to handle every field in edit and the
2034          // submit button matches.
2035          if (!$edit && ($submit_matches || !isset($submit))) {
2036            $post_array = $post;
2037            if ($upload) {
2038              // TODO: cURL handles file uploads for us, but the implementation
2039              // is broken. This is a less than elegant workaround. Alternatives
2040              // are being explored at #253506.
2041              foreach ($upload as $key => $file) {
2042                $file = drupal_realpath($file);
2043                if ($file && is_file($file)) {
2044                  $post[$key] = '@' . $file;
2045                }
2046              }
2047            }
2048            else {
2049              foreach ($post as $key => $value) {
2050                // Encode according to application/x-www-form-urlencoded
2051                // Both names and values needs to be urlencoded, according to
2052                // http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.1
2053                $post[$key] = urlencode($key) . '=' . urlencode($value);
2054              }
2055              $post = implode('&', $post) . $extra_post;
2056            }
2057            $out = $this->curlExec(array(CURLOPT_URL => $action, CURLOPT_POST => TRUE, CURLOPT_POSTFIELDS => $post, CURLOPT_HTTPHEADER => $headers));
2058            // Ensure that any changes to variables in the other thread are picked up.
2059            $this->refreshVariables();
2060  
2061            // Replace original page output with new output from redirected page(s).
2062            if ($new = $this->checkForMetaRefresh()) {
2063              $out = $new;
2064            }
2065            $this->verbose('POST request to: ' . $path .
2066                           '<hr />Ending URL: ' . $this->getUrl() .
2067                           '<hr />Fields: ' . highlight_string('<?php ' . var_export($post_array, TRUE), TRUE) .
2068                           '<hr />' . $out);
2069            return $out;
2070          }
2071        }
2072        // We have not found a form which contained all fields of $edit.
2073        foreach ($edit as $name => $value) {
2074          $this->fail(t('Failed to set field @name to @value', array('@name' => $name, '@value' => $value)));
2075        }
2076        if (!$ajax && isset($submit)) {
2077          $this->assertTrue($submit_matches, t('Found the @submit button', array('@submit' => $submit)));
2078        }
2079        $this->fail(t('Found the requested form fields at @path', array('@path' => $path)));
2080      }
2081    }
2082  
2083    /**
2084     * Execute an Ajax submission.
2085     *
2086     * This executes a POST as ajax.js does. It uses the returned JSON data, an
2087     * array of commands, to update $this->content using equivalent DOM
2088     * manipulation as is used by ajax.js. It also returns the array of commands.
2089     *
2090     * @param $path
2091     *   Location of the form containing the Ajax enabled element to test. Can be
2092     *   either a Drupal path or an absolute path or NULL to use the current page.
2093     * @param $edit
2094     *   Field data in an associative array. Changes the current input fields
2095     *   (where possible) to the values indicated.
2096     * @param $triggering_element
2097     *   The name of the form element that is responsible for triggering the Ajax
2098     *   functionality to test. May be a string or, if the triggering element is
2099     *   a button, an associative array where the key is the name of the button
2100     *   and the value is the button label. i.e.) array('op' => t('Refresh')).
2101     * @param $ajax_path
2102     *   (optional) Override the path set by the Ajax settings of the triggering
2103     *   element. In the absence of both the triggering element's Ajax path and
2104     *   $ajax_path 'system/ajax' will be used.
2105     * @param $options
2106     *   (optional) Options to be forwarded to url().
2107     * @param $headers
2108     *   (optional) An array containing additional HTTP request headers, each
2109     *   formatted as "name: value". Forwarded to drupalPost().
2110     * @param $form_html_id
2111     *   (optional) HTML ID of the form to be submitted, use when there is more
2112     *   than one identical form on the same page and the value of the triggering
2113     *   element is not enough to identify the form. Note this is not the Drupal
2114     *   ID of the form but rather the HTML ID of the form.
2115     * @param $ajax_settings
2116     *   (optional) An array of Ajax settings which if specified will be used in
2117     *   place of the Ajax settings of the triggering element.
2118     *
2119     * @return
2120     *   An array of Ajax commands.
2121     *
2122     * @see drupalPost()
2123     * @see ajax.js
2124     */
2125    protected function drupalPostAJAX($path, $edit, $triggering_element, $ajax_path = NULL, array $options = array(), array $headers = array(), $form_html_id = NULL, $ajax_settings = NULL) {
2126      // Get the content of the initial page prior to calling drupalPost(), since
2127      // drupalPost() replaces $this->content.
2128      if (isset($path)) {
2129        $this->drupalGet($path, $options);
2130      }
2131      $content = $this->content;
2132      $drupal_settings = $this->drupalSettings;
2133  
2134      // Get the Ajax settings bound to the triggering element.
2135      if (!isset($ajax_settings)) {
2136        if (is_array($triggering_element)) {
2137          $xpath = '//*[@name="' . key($triggering_element) . '" and @value="' . current($triggering_element) . '"]';
2138        }
2139        else {
2140          $xpath = '//*[@name="' . $triggering_element . '"]';
2141        }
2142        if (isset($form_html_id)) {
2143          $xpath = '//form[@id="' . $form_html_id . '"]' . $xpath;
2144        }
2145        $element = $this->xpath($xpath);
2146        $element_id = (string) $element[0]['id'];
2147        $ajax_settings = $drupal_settings['ajax'][$element_id];
2148      }
2149  
2150      // Add extra information to the POST data as ajax.js does.
2151      $extra_post = '';
2152      if (isset($ajax_settings['submit'])) {
2153        foreach ($ajax_settings['submit'] as $key => $value) {
2154          $extra_post .= '&' . urlencode($key) . '=' . urlencode($value);
2155        }
2156      }
2157      foreach ($this->xpath('//*[@id]') as $element) {
2158        $id = (string) $element['id'];
2159        $extra_post .= '&' . urlencode('ajax_html_ids[]') . '=' . urlencode($id);
2160      }
2161      if (isset($drupal_settings['ajaxPageState'])) {
2162        $extra_post .= '&' . urlencode('ajax_page_state[theme]') . '=' . urlencode($drupal_settings['ajaxPageState']['theme']);
2163        $extra_post .= '&' . urlencode('ajax_page_state[theme_token]') . '=' . urlencode($drupal_settings['ajaxPageState']['theme_token']);
2164        foreach ($drupal_settings['ajaxPageState']['css'] as $key => $value) {
2165          $extra_post .= '&' . urlencode("ajax_page_state[css][$key]") . '=1';
2166        }
2167        foreach ($drupal_settings['ajaxPageState']['js'] as $key => $value) {
2168          $extra_post .= '&' . urlencode("ajax_page_state[js][$key]") . '=1';
2169        }
2170      }
2171  
2172      // Unless a particular path is specified, use the one specified by the
2173      // Ajax settings, or else 'system/ajax'.
2174      if (!isset($ajax_path)) {
2175        $ajax_path = isset($ajax_settings['url']) ? $ajax_settings['url'] : 'system/ajax';
2176      }
2177  
2178      // Submit the POST request.
2179      $return = drupal_json_decode($this->drupalPost(NULL, $edit, array('path' => $ajax_path, 'triggering_element' => $triggering_element), $options, $headers, $form_html_id, $extra_post));
2180  
2181      // Change the page content by applying the returned commands.
2182      if (!empty($ajax_settings) && !empty($return)) {
2183        // ajax.js applies some defaults to the settings object, so do the same
2184        // for what's used by this function.
2185        $ajax_settings += array(
2186          'method' => 'replaceWith',
2187        );
2188        // DOM can load HTML soup. But, HTML soup can throw warnings, suppress
2189        // them.
2190        $dom = new DOMDocument();
2191        @$dom->loadHTML($content);
2192        // XPath allows for finding wrapper nodes better than DOM does.
2193        $xpath = new DOMXPath($dom);
2194        foreach ($return as $command) {
2195          switch ($command['command']) {
2196            case 'settings':
2197              $drupal_settings = drupal_array_merge_deep($drupal_settings, $command['settings']);
2198              break;
2199  
2200            case 'insert':
2201              $wrapperNode = NULL;
2202              // When a command doesn't specify a selector, use the
2203              // #ajax['wrapper'] which is always an HTML ID.
2204              if (!isset($command['selector'])) {
2205                $wrapperNode = $xpath->query('//*[@id="' . $ajax_settings['wrapper'] . '"]')->item(0);
2206              }
2207              // @todo Ajax commands can target any jQuery selector, but these are
2208              //   hard to fully emulate with XPath. For now, just handle 'head'
2209              //   and 'body', since these are used by ajax_render().
2210              elseif (in_array($command['selector'], array('head', 'body'))) {
2211                $wrapperNode = $xpath->query('//' . $command['selector'])->item(0);
2212              }
2213              if ($wrapperNode) {
2214                // ajax.js adds an enclosing DIV to work around a Safari bug.
2215                $newDom = new DOMDocument();
2216                $newDom->loadHTML('<div>' . $command['data'] . '</div>');
2217                $newNode = $dom->importNode($newDom->documentElement->firstChild->firstChild, TRUE);
2218                $method = isset($command['method']) ? $command['method'] : $ajax_settings['method'];
2219                // The "method" is a jQuery DOM manipulation function. Emulate
2220                // each one using PHP's DOMNode API.
2221                switch ($method) {
2222                  case 'replaceWith':
2223                    $wrapperNode->parentNode->replaceChild($newNode, $wrapperNode);
2224                    break;
2225                  case 'append':
2226                    $wrapperNode->appendChild($newNode);
2227                    break;
2228                  case 'prepend':
2229                    // If no firstChild, insertBefore() falls back to
2230                    // appendChild().
2231                    $wrapperNode->insertBefore($newNode, $wrapperNode->firstChild);
2232                    break;
2233                  case 'before':
2234                    $wrapperNode->parentNode->insertBefore($newNode, $wrapperNode);
2235                    break;
2236                  case 'after':
2237                    // If no nextSibling, insertBefore() falls back to
2238                    // appendChild().
2239                    $wrapperNode->parentNode->insertBefore($newNode, $wrapperNode->nextSibling);
2240                    break;
2241                  case 'html':
2242                    foreach ($wrapperNode->childNodes as $childNode) {
2243                      $wrapperNode->removeChild($childNode);
2244                    }
2245                    $wrapperNode->appendChild($newNode);
2246                    break;
2247                }
2248              }
2249              break;
2250  
2251            // @todo Add suitable implementations for these commands in order to
2252            //   have full test coverage of what ajax.js can do.
2253            case 'remove':
2254              break;
2255            case 'changed':
2256              break;
2257            case 'css':
2258              break;
2259            case 'data':
2260              break;
2261            case 'restripe':
2262              break;
2263          }
2264        }
2265        $content = $dom->saveHTML();
2266      }
2267      $this->drupalSetContent($content);
2268      $this->drupalSetSettings($drupal_settings);
2269      return $return;
2270    }
2271  
2272    /**
2273     * Runs cron in the Drupal installed by Simpletest.
2274     */
2275    protected function cronRun() {
2276      $this->drupalGet($GLOBALS['base_url'] . '/cron.php', array('external' => TRUE, 'query' => array('cron_key' => variable_get('cron_key', 'drupal'))));
2277    }
2278  
2279    /**
2280     * Check for meta refresh tag and if found call drupalGet() recursively. This
2281     * function looks for the http-equiv attribute to be set to "Refresh"
2282     * and is case-sensitive.
2283     *
2284     * @return
2285     *   Either the new page content or FALSE.
2286     */
2287    protected function checkForMetaRefresh() {
2288      if (strpos($this->drupalGetContent(), '<meta ') && $this->parse()) {
2289        $refresh = $this->xpath('//meta[@http-equiv="Refresh"]');
2290        if (!empty($refresh)) {
2291          // Parse the content attribute of the meta tag for the format:
2292          // "[delay]: URL=[page_to_redirect_to]".
2293          if (preg_match('/\d+;\s*URL=(?P<url>.*)/i', $refresh[0]['content'], $match)) {
2294            return $this->drupalGet($this->getAbsoluteUrl(decode_entities($match['url'])));
2295          }
2296        }
2297      }
2298      return FALSE;
2299    }
2300  
2301    /**
2302     * Retrieves only the headers for a Drupal path or an absolute path.
2303     *
2304     * @param $path
2305     *   Drupal path or URL to load into internal browser
2306     * @param $options
2307     *   Options to be forwarded to url().
2308     * @param $headers
2309     *   An array containing additional HTTP request headers, each formatted as
2310     *   "name: value".
2311     * @return
2312     *   The retrieved headers, also available as $this->drupalGetContent()
2313     */
2314    protected function drupalHead($path, array $options = array(), array $headers = array()) {
2315      $options['absolute'] = TRUE;
2316      $out = $this->curlExec(array(CURLOPT_NOBODY => TRUE, CURLOPT_URL => url($path, $options), CURLOPT_HTTPHEADER => $headers));
2317      $this->refreshVariables(); // Ensure that any changes to variables in the other thread are picked up.
2318      return $out;
2319    }
2320  
2321    /**
2322     * Handle form input related to drupalPost(). Ensure that the specified fields
2323     * exist and attempt to create POST data in the correct manner for the particular
2324     * field type.
2325     *
2326     * @param $post
2327     *   Reference to array of post values.
2328     * @param $edit
2329     *   Reference to array of edit values to be checked against the form.
2330     * @param $submit
2331     *   Form submit button value.
2332     * @param $form
2333     *   Array of form elements.
2334     * @return
2335     *   Submit value matches a valid submit input in the form.
2336     */
2337    protected function handleForm(&$post, &$edit, &$upload, $submit, $form) {
2338      // Retrieve the form elements.
2339      $elements = $form->xpath('.//input[not(@disabled)]|.//textarea[not(@disabled)]|.//select[not(@disabled)]');
2340      $submit_matches = FALSE;
2341      foreach ($elements as $element) {
2342        // SimpleXML objects need string casting all the time.
2343        $name = (string) $element['name'];
2344        // This can either be the type of <input> or the name of the tag itself
2345        // for <select> or <textarea>.
2346        $type = isset($element['type']) ? (string) $element['type'] : $element->getName();
2347        $value = isset($element['value']) ? (string) $element['value'] : '';
2348        $done = FALSE;
2349        if (isset($edit[$name])) {
2350          switch ($type) {
2351            case 'text':
2352            case 'tel':
2353            case 'textarea':
2354            case 'url':
2355            case 'number':
2356            case 'range':
2357            case 'color':
2358            case 'hidden':
2359            case 'password':
2360            case 'email':
2361            case 'search':
2362              $post[$name] = $edit[$name];
2363              unset($edit[$name]);
2364              break;
2365            case 'radio':
2366              if ($edit[$name] == $value) {
2367                $post[$name] = $edit[$name];
2368                unset($edit[$name]);
2369              }
2370              break;
2371            case 'checkbox':
2372              // To prevent checkbox from being checked.pass in a FALSE,
2373              // otherwise the checkbox will be set to its value regardless
2374              // of $edit.
2375              if ($edit[$name] === FALSE) {
2376                unset($edit[$name]);
2377                continue 2;
2378              }
2379              else {
2380                unset($edit[$name]);
2381                $post[$name] = $value;
2382              }
2383              break;
2384            case 'select':
2385              $new_value = $edit[$name];
2386              $options = $this->getAllOptions($element);
2387              if (is_array($new_value)) {
2388                // Multiple select box.
2389                if (!empty($new_value)) {
2390                  $index = 0;
2391                  $key = preg_replace('/\[\]$/', '', $name);
2392                  foreach ($options as $option) {
2393                    $option_value = (string) $option['value'];
2394                    if (in_array($option_value, $new_value)) {
2395                      $post[$key . '[' . $index++ . ']'] = $option_value;
2396                      $done = TRUE;
2397                      unset($edit[$name]);
2398                    }
2399                  }
2400                }
2401                else {
2402                  // No options selected: do not include any POST data for the
2403                  // element.
2404                  $done = TRUE;
2405                  unset($edit[$name]);
2406                }
2407              }
2408              else {
2409                // Single select box.
2410                foreach ($options as $option) {
2411                  if ($new_value == $option['value']) {
2412                    $post[$name] = $new_value;
2413                    unset($edit[$name]);
2414                    $done = TRUE;
2415                    break;
2416                  }
2417                }
2418              }
2419              break;
2420            case 'file':
2421              $upload[$name] = $edit[$name];
2422              unset($edit[$name]);
2423              break;
2424          }
2425        }
2426        if (!isset($post[$name]) && !$done) {
2427          switch ($type) {
2428            case 'textarea':
2429              $post[$name] = (string) $element;
2430              break;
2431            case 'select':
2432              $single = empty($element['multiple']);
2433              $first = TRUE;
2434              $index = 0;
2435              $key = preg_replace('/\[\]$/', '', $name);
2436              $options = $this->getAllOptions($element);
2437              foreach ($options as $option) {
2438                // For single select, we load the first option, if there is a
2439                // selected option that will overwrite it later.
2440                if ($option['selected'] || ($first && $single)) {
2441                  $first = FALSE;
2442                  if ($single) {
2443                    $post[$name] = (string) $option['value'];
2444                  }
2445                  else {
2446                    $post[$key . '[' . $index++ . ']'] = (string) $option['value'];
2447                  }
2448                }
2449              }
2450              break;
2451            case 'file':
2452              break;
2453            case 'submit':
2454            case 'image':
2455              if (isset($submit) && $submit == $value) {
2456                $post[$name] = $value;
2457                $submit_matches = TRUE;
2458              }
2459              break;
2460            case 'radio':
2461            case 'checkbox':
2462              if (!isset($element['checked'])) {
2463                break;
2464              }
2465              // Deliberate no break.
2466            default:
2467              $post[$name] = $value;
2468          }
2469        }
2470      }
2471      return $submit_matches;
2472    }
2473  
2474    /**
2475     * Builds an XPath query.
2476     *
2477     * Builds an XPath query by replacing placeholders in the query by the value
2478     * of the arguments.
2479     *
2480     * XPath 1.0 (the version supported by libxml2, the underlying XML library
2481     * used by PHP) doesn't support any form of quotation. This function
2482     * simplifies the building of XPath expression.
2483     *
2484     * @param $xpath
2485     *   An XPath query, possibly with placeholders in the form ':name'.
2486     * @param $args
2487     *   An array of arguments with keys in the form ':name' matching the
2488     *   placeholders in the query. The values may be either strings or numeric
2489     *   values.
2490     * @return
2491     *   An XPath query with arguments replaced.
2492     */
2493    protected function buildXPathQuery($xpath, array $args = array()) {
2494      // Replace placeholders.
2495      foreach ($args as $placeholder => $value) {
2496        // XPath 1.0 doesn't support a way to escape single or double quotes in a
2497        // string literal. We split double quotes out of the string, and encode
2498        // them separately.
2499        if (is_string($value)) {
2500          // Explode the text at the quote characters.
2501          $parts = explode('"', $value);
2502  
2503          // Quote the parts.
2504          foreach ($parts as &$part) {
2505            $part = '"' . $part . '"';
2506          }
2507  
2508          // Return the string.
2509          $value = count($parts) > 1 ? 'concat(' . implode(', \'"\', ', $parts) . ')' : $parts[0];
2510        }
2511        $xpath = preg_replace('/' . preg_quote($placeholder) . '\b/', $value, $xpath);
2512      }
2513      return $xpath;
2514    }
2515  
2516    /**
2517     * Perform an xpath search on the contents of the internal browser. The search
2518     * is relative to the root element (HTML tag normally) of the page.
2519     *
2520     * @param $xpath
2521     *   The xpath string to use in the search.
2522     * @return
2523     *   The return value of the xpath search. For details on the xpath string
2524     *   format and return values see the SimpleXML documentation,
2525     *   http://us.php.net/manual/function.simplexml-element-xpath.php.
2526     */
2527    protected function xpath($xpath, array $arguments = array()) {
2528      if ($this->parse()) {
2529        $xpath = $this->buildXPathQuery($xpath, $arguments);
2530        $result = $this->elements->xpath($xpath);
2531        // Some combinations of PHP / libxml versions return an empty array
2532        // instead of the documented FALSE. Forcefully convert any falsish values
2533        // to an empty array to allow foreach(...) constructions.
2534        return $result ? $result : array();
2535      }
2536      else {
2537        return FALSE;
2538      }
2539    }
2540  
2541    /**
2542     * Get all option elements, including nested options, in a select.
2543     *
2544     * @param $element
2545     *   The element for which to get the options.
2546     * @return
2547     *   Option elements in select.
2548     */
2549    protected function getAllOptions(SimpleXMLElement $element) {
2550      $options = array();
2551      // Add all options items.
2552      foreach ($element->option as $option) {
2553        $options[] = $option;
2554      }
2555  
2556      // Search option group children.
2557      if (isset($element->optgroup)) {
2558        foreach ($element->optgroup as $group) {
2559          $options = array_merge($options, $this->getAllOptions($group));
2560        }
2561      }
2562      return $options;
2563    }
2564  
2565    /**
2566     * Pass if a link with the specified label is found, and optional with the
2567     * specified index.
2568     *
2569     * @param $label
2570     *   Text between the anchor tags.
2571     * @param $index
2572     *   Link position counting from zero.
2573     * @param $message
2574     *   Message to display.
2575     * @param $group
2576     *   The group this message belongs to, defaults to 'Other'.
2577     * @return
2578     *   TRUE if the assertion succeeded, FALSE otherwise.
2579     */
2580    protected function assertLink($label, $index = 0, $message = '', $group = 'Other') {
2581      $links = $this->xpath('//a[normalize-space(text())=:label]', array(':label' => $label));
2582      $message = ($message ?  $message : t('Link with label %label found.', array('%label' => $label)));
2583      return $this->assert(isset($links[$index]), $message, $group);
2584    }
2585  
2586    /**
2587     * Pass if a link with the specified label is not found.
2588     *
2589     * @param $label
2590     *   Text between the anchor tags.
2591     * @param $index
2592     *   Link position counting from zero.
2593     * @param $message
2594     *   Message to display.
2595     * @param $group
2596     *   The group this message belongs to, defaults to 'Other'.
2597     * @return
2598     *   TRUE if the assertion succeeded, FALSE otherwise.
2599     */
2600    protected function assertNoLink($label, $message = '', $group = 'Other') {
2601      $links = $this->xpath('//a[normalize-space(text())=:label]', array(':label' => $label));
2602      $message = ($message ?  $message : t('Link with label %label not found.', array('%label' => $label)));
2603      return $this->assert(empty($links), $message, $group);
2604    }
2605  
2606    /**
2607     * Pass if a link containing a given href (part) is found.
2608     *
2609     * @param $href
2610     *   The full or partial value of the 'href' attribute of the anchor tag.
2611     * @param $index
2612     *   Link position counting from zero.
2613     * @param $message
2614     *   Message to display.
2615     * @param $group
2616     *   The group this message belongs to, defaults to 'Other'.
2617     *
2618     * @return
2619     *   TRUE if the assertion succeeded, FALSE otherwise.
2620     */
2621    protected function assertLinkByHref($href, $index = 0, $message = '', $group = 'Other') {
2622      $links = $this->xpath('//a[contains(@href, :href)]', array(':href' => $href));
2623      $message = ($message ?  $message : t('Link containing href %href found.', array('%href' => $href)));
2624      return $this->assert(isset($links[$index]), $message, $group);
2625    }
2626  
2627    /**
2628     * Pass if a link containing a given href (part) is not found.
2629     *
2630     * @param $href
2631     *   The full or partial value of the 'href' attribute of the anchor tag.
2632     * @param $message
2633     *   Message to display.
2634     * @param $group
2635     *   The group this message belongs to, defaults to 'Other'.
2636     *
2637     * @return
2638     *   TRUE if the assertion succeeded, FALSE otherwise.
2639     */
2640    protected function assertNoLinkByHref($href, $message = '', $group = 'Other') {
2641      $links = $this->xpath('//a[contains(@href, :href)]', array(':href' => $href));
2642      $message = ($message ?  $message : t('No link containing href %href found.', array('%href' => $href)));
2643      return $this->assert(empty($links), $message, $group);
2644    }
2645  
2646    /**
2647     * Follows a link by name.
2648     *
2649     * Will click the first link found with this link text by default, or a
2650     * later one if an index is given. Match is case insensitive with
2651     * normalized space. The label is translated label. There is an assert
2652     * for successful click.
2653     *
2654     * @param $label
2655     *   Text between the anchor tags.
2656     * @param $index
2657     *   Link position counting from zero.
2658     * @return
2659     *   Page on success, or FALSE on failure.
2660     */
2661    protected function clickLink($label, $index = 0) {
2662      $url_before = $this->getUrl();
2663      $urls = $this->xpath('//a[normalize-space(text())=:label]', array(':label' => $label));
2664  
2665      if (isset($urls[$index])) {
2666        $url_target = $this->getAbsoluteUrl($urls[$index]['href']);
2667      }
2668  
2669      $this->assertTrue(isset($urls[$index]), t('Clicked link %label (@url_target) from @url_before', array('%label' => $label, '@url_target' => $url_target, '@url_before' => $url_before)), t('Browser'));
2670  
2671      if (isset($url_target)) {
2672        return $this->drupalGet($url_target);
2673      }
2674      return FALSE;
2675    }
2676  
2677    /**
2678     * Takes a path and returns an absolute path.
2679     *
2680     * @param $path
2681     *   A path from the internal browser content.
2682     * @return
2683     *   The $path with $base_url prepended, if necessary.
2684     */
2685    protected function getAbsoluteUrl($path) {
2686      global $base_url, $base_path;
2687  
2688      $parts = parse_url($path);
2689      if (empty($parts['host'])) {
2690        // Ensure that we have a string (and no xpath object).
2691        $path = (string) $path;
2692        // Strip $base_path, if existent.
2693        $length = strlen($base_path);
2694        if (substr($path, 0, $length) === $base_path) {
2695          $path = substr($path, $length);
2696        }
2697        // Ensure that we have an absolute path.
2698        if ($path[0] !== '/') {
2699          $path = '/' . $path;
2700        }
2701        // Finally, prepend the $base_url.
2702        $path = $base_url . $path;
2703      }
2704      return $path;
2705    }
2706  
2707    /**
2708     * Get the current URL from the cURL handler.
2709     *
2710     * @return
2711     *   The current URL.
2712     */
2713    protected function getUrl() {
2714      return $this->url;
2715    }
2716  
2717    /**
2718     * Gets the HTTP response headers of the requested page. Normally we are only
2719     * interested in the headers returned by the last request. However, if a page
2720     * is redirected or HTTP authentication is in use, multiple requests will be
2721     * required to retrieve the page. Headers from all requests may be requested
2722     * by passing TRUE to this function.
2723     *
2724     * @param $all_requests
2725     *   Boolean value specifying whether to return headers from all requests
2726     *   instead of just the last request. Defaults to FALSE.
2727     * @return
2728     *   A name/value array if headers from only the last request are requested.
2729     *   If headers from all requests are requested, an array of name/value
2730     *   arrays, one for each request.
2731     *
2732     *   The pseudonym ":status" is used for the HTTP status line.
2733     *
2734     *   Values for duplicate headers are stored as a single comma-separated list.
2735     */
2736    protected function drupalGetHeaders($all_requests = FALSE) {
2737      $request = 0;
2738      $headers = array($request => array());
2739      foreach ($this->headers as $header) {
2740        $header = trim($header);
2741        if ($header === '') {
2742          $request++;
2743        }
2744        else {
2745          if (strpos($header, 'HTTP/') === 0) {
2746            $name = ':status';
2747            $value = $header;
2748          }
2749          else {
2750            list($name, $value) = explode(':', $header, 2);
2751            $name = strtolower($name);
2752          }
2753          if (isset($headers[$request][$name])) {
2754            $headers[$request][$name] .= ',' . trim($value);
2755          }
2756          else {
2757            $headers[$request][$name] = trim($value);
2758          }
2759        }
2760      }
2761      if (!$all_requests) {
2762        $headers = array_pop($headers);
2763      }
2764      return $headers;
2765    }
2766  
2767    /**
2768     * Gets the value of an HTTP response header. If multiple requests were
2769     * required to retrieve the page, only the headers from the last request will
2770     * be checked by default. However, if TRUE is passed as the second argument,
2771     * all requests will be processed from last to first until the header is
2772     * found.
2773     *
2774     * @param $name
2775     *   The name of the header to retrieve. Names are case-insensitive (see RFC
2776     *   2616 section 4.2).
2777     * @param $all_requests
2778     *   Boolean value specifying whether to check all requests if the header is
2779     *   not found in the last request. Defaults to FALSE.
2780     * @return
2781     *   The HTTP header value or FALSE if not found.
2782     */
2783    protected function drupalGetHeader($name, $all_requests = FALSE) {
2784      $name = strtolower($name);
2785      $header = FALSE;
2786      if ($all_requests) {
2787        foreach (array_reverse($this->drupalGetHeaders(TRUE)) as $headers) {
2788          if (isset($headers[$name])) {
2789            $header = $headers[$name];
2790            break;
2791          }
2792        }
2793      }
2794      else {
2795        $headers = $this->drupalGetHeaders();
2796        if (isset($headers[$name])) {
2797          $header = $headers[$name];
2798        }
2799      }
2800      return $header;
2801    }
2802  
2803    /**
2804     * Gets the current raw HTML of requested page.
2805     */
2806    protected function drupalGetContent() {
2807      return $this->content;
2808    }
2809  
2810    /**
2811     * Gets the value of the Drupal.settings JavaScript variable for the currently loaded page.
2812     */
2813    protected function drupalGetSettings() {
2814      return $this->drupalSettings;
2815    }
2816  
2817    /**
2818     * Gets an array containing all e-mails sent during this test case.
2819     *
2820     * @param $filter
2821     *   An array containing key/value pairs used to filter the e-mails that are returned.
2822     * @return
2823     *   An array containing e-mail messages captured during the current test.
2824     */
2825    protected function drupalGetMails($filter = array()) {
2826      $captured_emails = variable_get('drupal_test_email_collector', array());
2827      $filtered_emails = array();
2828  
2829      foreach ($captured_emails as $message) {
2830        foreach ($filter as $key => $value) {
2831          if (!isset($message[$key]) || $message[$key] != $value) {
2832            continue 2;
2833          }
2834        }
2835        $filtered_emails[] = $message;
2836      }
2837  
2838      return $filtered_emails;
2839    }
2840  
2841    /**
2842     * Sets the raw HTML content. This can be useful when a page has been fetched
2843     * outside of the internal browser and assertions need to be made on the
2844     * returned page.
2845     *
2846     * A good example would be when testing drupal_http_request(). After fetching
2847     * the page the content can be set and page elements can be checked to ensure
2848     * that the function worked properly.
2849     */
2850    protected function drupalSetContent($content, $url = 'internal:') {
2851      $this->content = $content;
2852      $this->url = $url;
2853      $this->plainTextContent = FALSE;
2854      $this->elements = FALSE;
2855      $this->drupalSettings = array();
2856      if (preg_match('/jQuery\.extend\(Drupal\.settings, (.*?)\);/', $content, $matches)) {
2857        $this->drupalSettings = drupal_json_decode($matches[1]);
2858      }
2859    }
2860  
2861    /**
2862     * Sets the value of the Drupal.settings JavaScript variable for the currently loaded page.
2863     */
2864    protected function drupalSetSettings($settings) {
2865      $this->drupalSettings = $settings;
2866    }
2867  
2868    /**
2869     * Pass if the internal browser's URL matches the given path.
2870     *
2871     * @param $path
2872     *   The expected system path.
2873     * @param $options
2874     *   (optional) Any additional options to pass for $path to url().
2875     * @param $message
2876     *   Message to display.
2877     * @param $group
2878     *   The group this message belongs to, defaults to 'Other'.
2879     *
2880     * @return
2881     *   TRUE on pass, FALSE on fail.
2882     */
2883    protected function assertUrl($path, array $options = array(), $message = '', $group = 'Other') {
2884      if (!$message) {
2885        $message = t('Current URL is @url.', array(
2886          '@url' => var_export(url($path, $options), TRUE),
2887        ));
2888      }
2889      $options['absolute'] = TRUE;
2890      return $this->assertEqual($this->getUrl(), url($path, $options), $message, $group);
2891    }
2892  
2893    /**
2894     * Pass if the raw text IS found on the loaded page, fail otherwise. Raw text
2895     * refers to the raw HTML that the page generated.
2896     *
2897     * @param $raw
2898     *   Raw (HTML) string to look for.
2899     * @param $message
2900     *   Message to display.
2901     * @param $group
2902     *   The group this message belongs to, defaults to 'Other'.
2903     * @return
2904     *   TRUE on pass, FALSE on fail.
2905     */
2906    protected function assertRaw($raw, $message = '', $group = 'Other') {
2907      if (!$message) {
2908        $message = t('Raw "@raw" found', array('@raw' => $raw));
2909      }
2910      return $this->assert(strpos($this->drupalGetContent(), $raw) !== FALSE, $message, $group);
2911    }
2912  
2913    /**
2914     * Pass if the raw text is NOT found on the loaded page, fail otherwise. Raw text
2915     * refers to the raw HTML that the page generated.
2916     *
2917     * @param $raw
2918     *   Raw (HTML) string to look for.
2919     * @param $message
2920     *   Message to display.
2921     * @param $group
2922     *   The group this message belongs to, defaults to 'Other'.
2923     * @return
2924     *   TRUE on pass, FALSE on fail.
2925     */
2926    protected function assertNoRaw($raw, $message = '', $group = 'Other') {
2927      if (!$message) {
2928        $message = t('Raw "@raw" not found', array('@raw' => $raw));
2929      }
2930      return $this->assert(strpos($this->drupalGetContent(), $raw) === FALSE, $message, $group);
2931    }
2932  
2933    /**
2934     * Pass if the text IS found on the text version of the page. The text version
2935     * is the equivalent of what a user would see when viewing through a web browser.
2936     * In other words the HTML has been filtered out of the contents.
2937     *
2938     * @param $text
2939     *   Plain text to look for.
2940     * @param $message
2941     *   Message to display.
2942     * @param $group
2943     *   The group this message belongs to, defaults to 'Other'.
2944     * @return
2945     *   TRUE on pass, FALSE on fail.
2946     */
2947    protected function assertText($text, $message = '', $group = 'Other') {
2948      return $this->assertTextHelper($text, $message, $group, FALSE);
2949    }
2950  
2951    /**
2952     * Pass if the text is NOT found on the text version of the page. The text version
2953     * is the equivalent of what a user would see when viewing through a web browser.
2954     * In other words the HTML has been filtered out of the contents.
2955     *
2956     * @param $text
2957     *   Plain text to look for.
2958     * @param $message
2959     *   Message to display.
2960     * @param $group
2961     *   The group this message belongs to, defaults to 'Other'.
2962     * @return
2963     *   TRUE on pass, FALSE on fail.
2964     */
2965    protected function assertNoText($text, $message = '', $group = 'Other') {
2966      return $this->assertTextHelper($text, $message, $group, TRUE);
2967    }
2968  
2969    /**
2970     * Helper for assertText and assertNoText.
2971     *
2972     * It is not recommended to call this function directly.
2973     *
2974     * @param $text
2975     *   Plain text to look for.
2976     * @param $message
2977     *   Message to display.
2978     * @param $group
2979     *   The group this message belongs to.
2980     * @param $not_exists
2981     *   TRUE if this text should not exist, FALSE if it should.
2982     * @return
2983     *   TRUE on pass, FALSE on fail.
2984     */
2985    protected function assertTextHelper($text, $message = '', $group, $not_exists) {
2986      if ($this->plainTextContent === FALSE) {
2987        $this->plainTextContent = filter_xss($this->drupalGetContent(), array());
2988      }
2989      if (!$message) {
2990        $message = !$not_exists ? t('"@text" found', array('@text' => $text)) : t('"@text" not found', array('@text' => $text));
2991      }
2992      return $this->assert($not_exists == (strpos($this->plainTextContent, $text) === FALSE), $message, $group);
2993    }
2994  
2995    /**
2996     * Pass if the text is found ONLY ONCE on the text version of the page.
2997     *
2998     * The text version is the equivalent of what a user would see when viewing
2999     * through a web browser. In other words the HTML has been filtered out of
3000     * the contents.
3001     *
3002     * @param $text
3003     *   Plain text to look for.
3004     * @param $message
3005     *   Message to display.
3006     * @param $group
3007     *   The group this message belongs to, defaults to 'Other'.
3008     * @return
3009     *   TRUE on pass, FALSE on fail.
3010     */
3011    protected function assertUniqueText($text, $message = '', $group = 'Other') {
3012      return $this->assertUniqueTextHelper($text, $message, $group, TRUE);
3013    }
3014  
3015    /**
3016     * Pass if the text is found MORE THAN ONCE on the text version of the page.
3017     *
3018     * The text version is the equivalent of what a user would see when viewing
3019     * through a web browser. In other words the HTML has been filtered out of
3020     * the contents.
3021     *
3022     * @param $text
3023     *   Plain text to look for.
3024     * @param $message
3025     *   Message to display.
3026     * @param $group
3027     *   The group this message belongs to, defaults to 'Other'.
3028     * @return
3029     *   TRUE on pass, FALSE on fail.
3030     */
3031    protected function assertNoUniqueText($text, $message = '', $group = 'Other') {
3032      return $this->assertUniqueTextHelper($text, $message, $group, FALSE);
3033    }
3034  
3035    /**
3036     * Helper for assertUniqueText and assertNoUniqueText.
3037     *
3038     * It is not recommended to call this function directly.
3039     *
3040     * @param $text
3041     *   Plain text to look for.
3042     * @param $message
3043     *   Message to display.
3044     * @param $group
3045     *   The group this message belongs to.
3046     * @param $be_unique
3047     *   TRUE if this text should be found only once, FALSE if it should be found more than once.
3048     * @return
3049     *   TRUE on pass, FALSE on fail.
3050     */
3051    protected function assertUniqueTextHelper($text, $message = '', $group, $be_unique) {
3052      if ($this->plainTextContent === FALSE) {
3053        $this->plainTextContent = filter_xss($this->drupalGetContent(), array());
3054      }
3055      if (!$message) {
3056        $message = '"' . $text . '"' . ($be_unique ? ' found only once' : ' found more than once');
3057      }
3058      $first_occurance = strpos($this->plainTextContent, $text);
3059      if ($first_occurance === FALSE) {
3060        return $this->assert(FALSE, $message, $group);
3061      }
3062      $offset = $first_occurance + strlen($text);
3063      $second_occurance = strpos($this->plainTextContent, $text, $offset);
3064      return $this->assert($be_unique == ($second_occurance === FALSE), $message, $group);
3065    }
3066  
3067    /**
3068     * Will trigger a pass if the Perl regex pattern is found in the raw content.
3069     *
3070     * @param $pattern
3071     *   Perl regex to look for including the regex delimiters.
3072     * @param $message
3073     *   Message to display.
3074     * @param $group
3075     *   The group this message belongs to.
3076     * @return
3077     *   TRUE on pass, FALSE on fail.
3078     */
3079    protected function assertPattern($pattern, $message = '', $group = 'Other') {
3080      if (!$message) {
3081        $message = t('Pattern "@pattern" found', array('@pattern' => $pattern));
3082      }
3083      return $this->assert((bool) preg_match($pattern, $this->drupalGetContent()), $message, $group);
3084    }
3085  
3086    /**
3087     * Will trigger a pass if the perl regex pattern is not present in raw content.
3088     *
3089     * @param $pattern
3090     *   Perl regex to look for including the regex delimiters.
3091     * @param $message
3092     *   Message to display.
3093     * @param $group
3094     *   The group this message belongs to.
3095     * @return
3096     *   TRUE on pass, FALSE on fail.
3097     */
3098    protected function assertNoPattern($pattern, $message = '', $group = 'Other') {
3099      if (!$message) {
3100        $message = t('Pattern "@pattern" not found', array('@pattern' => $pattern));
3101      }
3102      return $this->assert(!preg_match($pattern, $this->drupalGetContent()), $message, $group);
3103    }
3104  
3105    /**
3106     * Pass if the page title is the given string.
3107     *
3108     * @param $title
3109     *   The string the title should be.
3110     * @param $message
3111     *   Message to display.
3112     * @param $group
3113     *   The group this message belongs to.
3114     * @return
3115     *   TRUE on pass, FALSE on fail.
3116     */
3117    protected function assertTitle($title, $message = '', $group = 'Other') {
3118      $actual = (string) current($this->xpath('//title'));
3119      if (!$message) {
3120        $message = t('Page title @actual is equal to @expected.', array(
3121          '@actual' => var_export($actual, TRUE),
3122          '@expected' => var_export($title, TRUE),
3123        ));
3124      }
3125      return $this->assertEqual($actual, $title, $message, $group);
3126    }
3127  
3128    /**
3129     * Pass if the page title is not the given string.
3130     *
3131     * @param $title
3132     *   The string the title should not be.
3133     * @param $message
3134     *   Message to display.
3135     * @param $group
3136     *   The group this message belongs to.
3137     * @return
3138     *   TRUE on pass, FALSE on fail.
3139     */
3140    protected function assertNoTitle($title, $message = '', $group = 'Other') {
3141      $actual = (string) current($this->xpath('//title'));
3142      if (!$message) {
3143        $message = t('Page title @actual is not equal to @unexpected.', array(
3144          '@actual' => var_export($actual, TRUE),
3145          '@unexpected' => var_export($title, TRUE),
3146        ));
3147      }
3148      return $this->assertNotEqual($actual, $title, $message, $group);
3149    }
3150  
3151    /**
3152     * Asserts that a field exists in the current page by the given XPath.
3153     *
3154     * @param $xpath
3155     *   XPath used to find the field.
3156     * @param $value
3157     *   (optional) Value of the field to assert.
3158     * @param $message
3159     *   (optional) Message to display.
3160     * @param $group
3161     *   (optional) The group this message belongs to.
3162     *
3163     * @return
3164     *   TRUE on pass, FALSE on fail.
3165     */
3166    protected function assertFieldByXPath($xpath, $value = NULL, $message = '', $group = 'Other') {
3167      $fields = $this->xpath($xpath);
3168  
3169      // If value specified then check array for match.
3170      $found = TRUE;
3171      if (isset($value)) {
3172        $found = FALSE;
3173        if ($fields) {
3174          foreach ($fields as $field) {
3175            if (isset($field['value']) && $field['value'] == $value) {
3176              // Input element with correct value.
3177              $found = TRUE;
3178            }
3179            elseif (isset($field->option)) {
3180              // Select element found.
3181              if ($this->getSelectedItem($field) == $value) {
3182                $found = TRUE;
3183              }
3184              else {
3185                // No item selected so use first item.
3186                $items = $this->getAllOptions($field);
3187                if (!empty($items) && $items[0]['value'] == $value) {
3188                  $found = TRUE;
3189                }
3190              }
3191            }
3192            elseif ((string) $field == $value) {
3193              // Text area with correct text.
3194              $found = TRUE;
3195            }
3196          }
3197        }
3198      }
3199      return $this->assertTrue($fields && $found, $message, $group);
3200    }
3201  
3202    /**
3203     * Get the selected value from a select field.
3204     *
3205     * @param $element
3206     *   SimpleXMLElement select element.
3207     * @return
3208     *   The selected value or FALSE.
3209     */
3210    protected function getSelectedItem(SimpleXMLElement $element) {
3211      foreach ($element->children() as $item) {
3212        if (isset($item['selected'])) {
3213          return $item['value'];
3214        }
3215        elseif ($item->getName() == 'optgroup') {
3216          if ($value = $this->getSelectedItem($item)) {
3217            return $value;
3218          }
3219        }
3220      }
3221      return FALSE;
3222    }
3223  
3224    /**
3225     * Asserts that a field does not exist in the current page by the given XPath.
3226     *
3227     * @param $xpath
3228     *   XPath used to find the field.
3229     * @param $value
3230     *   (optional) Value of the field to assert.
3231     * @param $message
3232     *   (optional) Message to display.
3233     * @param $group
3234     *   (optional) The group this message belongs to.
3235     *
3236     * @return
3237     *   TRUE on pass, FALSE on fail.
3238     */
3239    protected function assertNoFieldByXPath($xpath, $value = NULL, $message = '', $group = 'Other') {
3240      $fields = $this->xpath($xpath);
3241  
3242      // If value specified then check array for match.
3243      $found = TRUE;
3244      if (isset($value)) {
3245        $found = FALSE;
3246        if ($fields) {
3247          foreach ($fields as $field) {
3248            if ($field['value'] == $value) {
3249              $found = TRUE;
3250            }
3251          }
3252        }
3253      }
3254      return $this->assertFalse($fields && $found, $message, $group);
3255    }
3256  
3257    /**
3258     * Asserts that a field exists in the current page with the given name and value.
3259     *
3260     * @param $name
3261     *   Name of field to assert.
3262     * @param $value
3263     *   Value of the field to assert.
3264     * @param $message
3265     *   Message to display.
3266     * @param $group
3267     *   The group this message belongs to.
3268     * @return
3269     *   TRUE on pass, FALSE on fail.
3270     */
3271    protected function assertFieldByName($name, $value = NULL, $message = NULL) {
3272      if (!isset($message)) {
3273        if (!isset($value)) {
3274          $message = t('Found field with name @name', array(
3275            '@name' => var_export($name, TRUE),
3276          ));
3277        }
3278        else {
3279          $message = t('Found field with name @name and value @value', array(
3280            '@name' => var_export($name, TRUE),
3281            '@value' => var_export($value, TRUE),
3282          ));
3283        }
3284      }
3285      return $this->assertFieldByXPath($this->constructFieldXpath('name', $name), $value, $message, t('Browser'));
3286    }
3287  
3288    /**
3289     * Asserts that a field does not exist with the given name and value.
3290     *
3291     * @param $name
3292     *   Name of field to assert.
3293     * @param $value
3294     *   Value of the field to assert.
3295     * @param $message
3296     *   Message to display.
3297     * @param $group
3298     *   The group this message belongs to.
3299     * @return
3300     *   TRUE on pass, FALSE on fail.
3301     */
3302    protected function assertNoFieldByName($name, $value = '', $message = '') {
3303      return $this->assertNoFieldByXPath($this->constructFieldXpath('name', $name), $value, $message ? $message : t('Did not find field by name @name', array('@name' => $name)), t('Browser'));
3304    }
3305  
3306    /**
3307     * Asserts that a field exists in the current page with the given id and value.
3308     *
3309     * @param $id
3310     *   Id of field to assert.
3311     * @param $value
3312     *   Value of the field to assert.
3313     * @param $message
3314     *   Message to display.
3315     * @param $group
3316     *   The group this message belongs to.
3317     * @return
3318     *   TRUE on pass, FALSE on fail.
3319     */
3320    protected function assertFieldById($id, $value = '', $message = '') {
3321      return $this->assertFieldByXPath($this->constructFieldXpath('id', $id), $value, $message ? $message : t('Found field by id @id', array('@id' => $id)), t('Browser'));
3322    }
3323  
3324    /**
3325     * Asserts that a field does not exist with the given id and value.
3326     *
3327     * @param $id
3328     *   Id of field to assert.
3329     * @param $value
3330     *   Value of the field to assert.
3331     * @param $message
3332     *   Message to display.
3333     * @param $group
3334     *   The group this message belongs to.
3335     * @return
3336     *   TRUE on pass, FALSE on fail.
3337     */
3338    protected function assertNoFieldById($id, $value = '', $message = '') {
3339      return $this->assertNoFieldByXPath($this->constructFieldXpath('id', $id), $value, $message ? $message : t('Did not find field by id @id', array('@id' => $id)), t('Browser'));
3340    }
3341  
3342    /**
3343     * Asserts that a checkbox field in the current page is checked.
3344     *
3345     * @param $id
3346     *   Id of field to assert.
3347     * @param $message
3348     *   Message to display.
3349     * @return
3350     *   TRUE on pass, FALSE on fail.
3351     */
3352    protected function assertFieldChecked($id, $message = '') {
3353      $elements = $this->xpath('//input[@id=:id]', array(':id' => $id));
3354      return $this->assertTrue(isset($elements[0]) && !empty($elements[0]['checked']), $message ? $message : t('Checkbox field @id is checked.', array('@id' => $id)), t('Browser'));
3355    }
3356  
3357    /**
3358     * Asserts that a checkbox field in the current page is not checked.
3359     *
3360     * @param $id
3361     *   Id of field to assert.
3362     * @param $message
3363     *   Message to display.
3364     * @return
3365     *   TRUE on pass, FALSE on fail.
3366     */
3367    protected function assertNoFieldChecked($id, $message = '') {
3368      $elements = $this->xpath('//input[@id=:id]', array(':id' => $id));
3369      return $this->assertTrue(isset($elements[0]) && empty($elements[0]['checked']), $message ? $message : t('Checkbox field @id is not checked.', array('@id' => $id)), t('Browser'));
3370    }
3371  
3372    /**
3373     * Asserts that a select option in the current page is checked.
3374     *
3375     * @param $id
3376     *   Id of select field to assert.
3377     * @param $option
3378     *   Option to assert.
3379     * @param $message
3380     *   Message to display.
3381     * @return
3382     *   TRUE on pass, FALSE on fail.
3383     *
3384     * @todo $id is unusable. Replace with $name.
3385     */
3386    protected function assertOptionSelected($id, $option, $message = '') {
3387      $elements = $this->xpath('//select[@id=:id]//option[@value=:option]', array(':id' => $id, ':option' => $option));
3388      return $this->assertTrue(isset($elements[0]) && !empty($elements[0]['selected']), $message ? $message : t('Option @option for field @id is selected.', array('@option' => $option, '@id' => $id)), t('Browser'));
3389    }
3390  
3391    /**
3392     * Asserts that a select option in the current page is not checked.
3393     *
3394     * @param $id
3395     *   Id of select field to assert.
3396     * @param $option
3397     *   Option to assert.
3398     * @param $message
3399     *   Message to display.
3400     * @return
3401     *   TRUE on pass, FALSE on fail.
3402     */
3403    protected function assertNoOptionSelected($id, $option, $message = '') {
3404      $elements = $this->xpath('//select[@id=:id]//option[@value=:option]', array(':id' => $id, ':option' => $option));
3405      return $this->assertTrue(isset($elements[0]) && empty($elements[0]['selected']), $message ? $message : t('Option @option for field @id is not selected.', array('@option' => $option, '@id' => $id)), t('Browser'));
3406    }
3407  
3408    /**
3409     * Asserts that a field exists with the given name or id.
3410     *
3411     * @param $field
3412     *   Name or id of field to assert.
3413     * @param $message
3414     *   Message to display.
3415     * @param $group
3416     *   The group this message belongs to.
3417     * @return
3418     *   TRUE on pass, FALSE on fail.
3419     */
3420    protected function assertField($field, $message = '', $group = 'Other') {
3421      return $this->assertFieldByXPath($this->constructFieldXpath('name', $field) . '|' . $this->constructFieldXpath('id', $field), NULL, $message, $group);
3422    }
3423  
3424    /**
3425     * Asserts that a field does not exist with the given name or id.
3426     *
3427     * @param $field
3428     *   Name or id of field to assert.
3429     * @param $message
3430     *   Message to display.
3431     * @param $group
3432     *   The group this message belongs to.
3433     * @return
3434     *   TRUE on pass, FALSE on fail.
3435     */
3436    protected function assertNoField($field, $message = '', $group = 'Other') {
3437      return $this->assertNoFieldByXPath($this->constructFieldXpath('name', $field) . '|' . $this->constructFieldXpath('id', $field), NULL, $message, $group);
3438    }
3439  
3440    /**
3441     * Asserts that each HTML ID is used for just a single element.
3442     *
3443     * @param $message
3444     *   Message to display.
3445     * @param $group
3446     *   The group this message belongs to.
3447     * @param $ids_to_skip
3448     *   An optional array of ids to skip when checking for duplicates. It is
3449     *   always a bug to have duplicate HTML IDs, so this parameter is to enable
3450     *   incremental fixing of core code. Whenever a test passes this parameter,
3451     *   it should add a "todo" comment above the call to this function explaining
3452     *   the legacy bug that the test wishes to ignore and including a link to an
3453     *   issue that is working to fix that legacy bug.
3454     * @return
3455     *   TRUE on pass, FALSE on fail.
3456     */
3457    protected function assertNoDuplicateIds($message = '', $group = 'Other', $ids_to_skip = array()) {
3458      $status = TRUE;
3459      foreach ($this->xpath('//*[@id]') as $element) {
3460        $id = (string) $element['id'];
3461        if (isset($seen_ids[$id]) && !in_array($id, $ids_to_skip)) {
3462          $this->fail(t('The HTML ID %id is unique.', array('%id' => $id)), $group);
3463          $status = FALSE;
3464        }
3465        $seen_ids[$id] = TRUE;
3466      }
3467      return $this->assert($status, $message, $group);
3468    }
3469  
3470    /**
3471     * Helper function: construct an XPath for the given set of attributes and value.
3472     *
3473     * @param $attribute
3474     *   Field attributes.
3475     * @param $value
3476     *   Value of field.
3477     * @return
3478     *   XPath for specified values.
3479     */
3480    protected function constructFieldXpath($attribute, $value) {
3481      $xpath = '//textarea[@' . $attribute . '=:value]|//input[@' . $attribute . '=:value]|//select[@' . $attribute . '=:value]';
3482      return $this->buildXPathQuery($xpath, array(':value' => $value));
3483    }
3484  
3485    /**
3486     * Asserts the page responds with the specified response code.
3487     *
3488     * @param $code
3489     *   Response code. For example 200 is a successful page request. For a list
3490     *   of all codes see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html.
3491     * @param $message
3492     *   Message to display.
3493     * @return
3494     *   Assertion result.
3495     */
3496    protected function assertResponse($code, $message = '') {
3497      $curl_code = curl_getinfo($this->curlHandle, CURLINFO_HTTP_CODE);
3498      $match = is_array($code) ? in_array($curl_code, $code) : $curl_code == $code;
3499      return $this->assertTrue($match, $message ? $message : t('HTTP response expected !code, actual !curl_code', array('!code' => $code, '!curl_code' => $curl_code)), t('Browser'));
3500    }
3501  
3502    /**
3503     * Asserts the page did not return the specified response code.
3504     *
3505     * @param $code
3506     *   Response code. For example 200 is a successful page request. For a list
3507     *   of all codes see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html.
3508     * @param $message
3509     *   Message to display.
3510     *
3511     * @return
3512     *   Assertion result.
3513     */
3514    protected function assertNoResponse($code, $message = '') {
3515      $curl_code = curl_getinfo($this->curlHandle, CURLINFO_HTTP_CODE);
3516      $match = is_array($code) ? in_array($curl_code, $code) : $curl_code == $code;
3517      return $this->assertFalse($match, $message ? $message : t('HTTP response not expected !code, actual !curl_code', array('!code' => $code, '!curl_code' => $curl_code)), t('Browser'));
3518    }
3519  
3520    /**
3521     * Asserts that the most recently sent e-mail message has the given value.
3522     *
3523     * The field in $name must have the content described in $value.
3524     *
3525     * @param $name
3526     *   Name of field or message property to assert. Examples: subject, body, id, ...
3527     * @param $value
3528     *   Value of the field to assert.
3529     * @param $message
3530     *   Message to display.
3531     *
3532     * @return
3533     *   TRUE on pass, FALSE on fail.
3534     */
3535    protected function assertMail($name, $value = '', $message = '') {
3536      $captured_emails = variable_get('drupal_test_email_collector', array());
3537      $email = end($captured_emails);
3538      return $this->assertTrue($email && isset($email[$name]) && $email[$name] == $value, $message, t('E-mail'));
3539    }
3540  
3541    /**
3542     * Asserts that the most recently sent e-mail message has the string in it.
3543     *
3544     * @param $field_name
3545     *   Name of field or message property to assert: subject, body, id, ...
3546     * @param $string
3547     *   String to search for.
3548     * @param $email_depth
3549     *   Number of emails to search for string, starting with most recent.
3550     *
3551     * @return
3552     *   TRUE on pass, FALSE on fail.
3553     */
3554    protected function assertMailString($field_name, $string, $email_depth) {
3555      $mails = $this->drupalGetMails();
3556      $string_found = FALSE;
3557      for ($i = sizeof($mails) -1; $i >= sizeof($mails) - $email_depth && $i >= 0; $i--) {
3558        $mail = $mails[$i];
3559        // Normalize whitespace, as we don't know what the mail system might have
3560        // done. Any run of whitespace becomes a single space.
3561        $normalized_mail = preg_replace('/\s+/', ' ', $mail[$field_name]);
3562        $normalized_string = preg_replace('/\s+/', ' ', $string);
3563        $string_found = (FALSE !== strpos($normalized_mail, $normalized_string));
3564        if ($string_found) {
3565          break;
3566        }
3567      }
3568      return $this->assertTrue($string_found, t('Expected text found in @field of email message: "@expected".', array('@field' => $field_name, '@expected' => $string)));
3569    }
3570  
3571    /**
3572     * Asserts that the most recently sent e-mail message has the pattern in it.
3573     *
3574     * @param $field_name
3575     *   Name of field or message property to assert: subject, body, id, ...
3576     * @param $regex
3577     *   Pattern to search for.
3578     *
3579     * @return
3580     *   TRUE on pass, FALSE on fail.
3581     */
3582    protected function assertMailPattern($field_name, $regex, $message) {
3583      $mails = $this->drupalGetMails();
3584      $mail = end($mails);
3585      $regex_found = preg_match("/$regex/", $mail[$field_name]);
3586      return $this->assertTrue($regex_found, t('Expected text found in @field of email message: "@expected".', array('@field' => $field_name, '@expected' => $regex)));
3587    }
3588  
3589    /**
3590     * Outputs to verbose the most recent $count emails sent.
3591     *
3592     * @param $count
3593     *   Optional number of emails to output.
3594     */
3595    protected function verboseEmail($count = 1) {
3596      $mails = $this->drupalGetMails();
3597      for ($i = sizeof($mails) -1; $i >= sizeof($mails) - $count && $i >= 0; $i--) {
3598        $mail = $mails[$i];
3599        $this->verbose(t('Email:') . '<pre>' . print_r($mail, TRUE) . '</pre>');
3600      }
3601    }
3602  }
3603  
3604  /**
3605   * Logs verbose message in a text file.
3606   *
3607   * If verbose mode is enabled then page requests will be dumped to a file and
3608   * presented on the test result screen. The messages will be placed in a file
3609   * located in the simpletest directory in the original file system.
3610   *
3611   * @param $message
3612   *   The verbose message to be stored.
3613   * @param $original_file_directory
3614   *   The original file directory, before it was changed for testing purposes.
3615   * @param $test_class
3616   *   The active test case class.
3617   *
3618   * @return
3619   *   The ID of the message to be placed in related assertion messages.
3620   *
3621   * @see DrupalTestCase->originalFileDirectory
3622   * @see DrupalWebTestCase->verbose()
3623   */
3624  function simpletest_verbose($message, $original_file_directory = NULL, $test_class = NULL) {
3625    static $file_directory = NULL, $class = NULL, $id = 1, $verbose = NULL;
3626  
3627    // Will pass first time during setup phase, and when verbose is TRUE.
3628    if (!isset($original_file_directory) && !$verbose) {
3629      return FALSE;
3630    }
3631  
3632    if ($message && $file_directory) {
3633      $message = '<hr />ID #' . $id . ' (<a href="' . $class . '-' . ($id - 1) . '.html">Previous</a> | <a href="' . $class . '-' . ($id + 1) . '.html">Next</a>)<hr />' . $message;
3634      file_put_contents($file_directory . "/simpletest/verbose/$class-$id.html", $message, FILE_APPEND);
3635      return $id++;
3636    }
3637  
3638    if ($original_file_directory) {
3639      $file_directory = $original_file_directory;
3640      $class = $test_class;
3641      $verbose = variable_get('simpletest_verbose', TRUE);
3642      $directory = $file_directory . '/simpletest/verbose';
3643      $writable = file_prepare_directory($directory, FILE_CREATE_DIRECTORY);
3644      if ($writable && !file_exists($directory . '/.htaccess')) {
3645        file_put_contents($directory . '/.htaccess', "<IfModule mod_expires.c>\nExpiresActive Off\n</IfModule>\n");
3646      }
3647      return $writable;
3648    }
3649    return FALSE;
3650  }

title

Description

title

Description

title

Description

title

title

Body