Projet

Général

Profil

Paste
Télécharger (133 ko) Statistiques
| Branche: | Révision:

root / drupal7 / modules / simpletest / drupal_web_test_case.php @ 01dfd3b5

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
   * URL to the verbose output file directory.
44
   *
45
   * @var string
46
   */
47
  protected $verboseDirectoryUrl;
48

    
49
  /**
50
   * Time limit for the test.
51
   */
52
  protected $timeLimit = 500;
53

    
54
  /**
55
   * Current results of this test case.
56
   *
57
   * @var Array
58
   */
59
  public $results = array(
60
    '#pass' => 0,
61
    '#fail' => 0,
62
    '#exception' => 0,
63
    '#debug' => 0,
64
  );
65

    
66
  /**
67
   * Assertions thrown in that test case.
68
   *
69
   * @var Array
70
   */
71
  protected $assertions = array();
72

    
73
  /**
74
   * This class is skipped when looking for the source of an assertion.
75
   *
76
   * When displaying which function an assert comes from, it's not too useful
77
   * to see "drupalWebTestCase->drupalLogin()', we would like to see the test
78
   * that called it. So we need to skip the classes defining these helper
79
   * methods.
80
   */
81
  protected $skipClasses = array(__CLASS__ => TRUE);
82

    
83
  /**
84
   * Flag to indicate whether the test has been set up.
85
   *
86
   * The setUp() method isolates the test from the parent Drupal site by
87
   * creating a random prefix for the database and setting up a clean file
88
   * storage directory. The tearDown() method then cleans up this test
89
   * environment. We must ensure that setUp() has been run. Otherwise,
90
   * tearDown() will act on the parent Drupal site rather than the test
91
   * environment, destroying live data.
92
   */
93
  protected $setup = FALSE;
94

    
95
  protected $setupDatabasePrefix = FALSE;
96

    
97
  protected $setupEnvironment = FALSE;
98

    
99
  /**
100
   * Constructor for DrupalTestCase.
101
   *
102
   * @param $test_id
103
   *   Tests with the same id are reported together.
104
   */
105
  public function __construct($test_id = NULL) {
106
    $this->testId = $test_id;
107
  }
108

    
109
  /**
110
   * Internal helper: stores the assert.
111
   *
112
   * @param $status
113
   *   Can be 'pass', 'fail', 'exception'.
114
   *   TRUE is a synonym for 'pass', FALSE for 'fail'.
115
   * @param $message
116
   *   The message string.
117
   * @param $group
118
   *   Which group this assert belongs to.
119
   * @param $caller
120
   *   By default, the assert comes from a function whose name starts with
121
   *   'test'. Instead, you can specify where this assert originates from
122
   *   by passing in an associative array as $caller. Key 'file' is
123
   *   the name of the source file, 'line' is the line number and 'function'
124
   *   is the caller function itself.
125
   */
126
  protected function assert($status, $message = '', $group = 'Other', array $caller = NULL) {
127
    // Convert boolean status to string status.
128
    if (is_bool($status)) {
129
      $status = $status ? 'pass' : 'fail';
130
    }
131

    
132
    // Increment summary result counter.
133
    $this->results['#' . $status]++;
134

    
135
    // Get the function information about the call to the assertion method.
136
    if (!$caller) {
137
      $caller = $this->getAssertionCall();
138
    }
139

    
140
    // Creation assertion array that can be displayed while tests are running.
141
    $this->assertions[] = $assertion = array(
142
      'test_id' => $this->testId,
143
      'test_class' => get_class($this),
144
      'status' => $status,
145
      'message' => $message,
146
      'message_group' => $group,
147
      'function' => $caller['function'],
148
      'line' => $caller['line'],
149
      'file' => $caller['file'],
150
    );
151

    
152
    // Store assertion for display after the test has completed.
153
    self::getDatabaseConnection()
154
      ->insert('simpletest')
155
      ->fields($assertion)
156
      ->execute();
157

    
158
    // We do not use a ternary operator here to allow a breakpoint on
159
    // test failure.
160
    if ($status == 'pass') {
161
      return TRUE;
162
    }
163
    else {
164
      return FALSE;
165
    }
166
  }
167

    
168
  /**
169
   * Returns the database connection to the site running Simpletest.
170
   *
171
   * @return DatabaseConnection
172
   *   The database connection to use for inserting assertions.
173
   */
174
  public static function getDatabaseConnection() {
175
    try {
176
      $connection = Database::getConnection('default', 'simpletest_original_default');
177
    }
178
    catch (DatabaseConnectionNotDefinedException $e) {
179
      // If the test was not set up, the simpletest_original_default
180
      // connection does not exist.
181
      $connection = Database::getConnection('default', 'default');
182
    }
183

    
184
    return $connection;
185
  }
186

    
187
  /**
188
   * Store an assertion from outside the testing context.
189
   *
190
   * This is useful for inserting assertions that can only be recorded after
191
   * the test case has been destroyed, such as PHP fatal errors. The caller
192
   * information is not automatically gathered since the caller is most likely
193
   * inserting the assertion on behalf of other code. In all other respects
194
   * the method behaves just like DrupalTestCase::assert() in terms of storing
195
   * the assertion.
196
   *
197
   * @return
198
   *   Message ID of the stored assertion.
199
   *
200
   * @see DrupalTestCase::assert()
201
   * @see DrupalTestCase::deleteAssert()
202
   */
203
  public static function insertAssert($test_id, $test_class, $status, $message = '', $group = 'Other', array $caller = array()) {
204
    // Convert boolean status to string status.
205
    if (is_bool($status)) {
206
      $status = $status ? 'pass' : 'fail';
207
    }
208

    
209
    $caller += array(
210
      'function' => t('Unknown'),
211
      'line' => 0,
212
      'file' => t('Unknown'),
213
    );
214

    
215
    $assertion = array(
216
      'test_id' => $test_id,
217
      'test_class' => $test_class,
218
      'status' => $status,
219
      'message' => $message,
220
      'message_group' => $group,
221
      'function' => $caller['function'],
222
      'line' => $caller['line'],
223
      'file' => $caller['file'],
224
    );
225

    
226
    return self::getDatabaseConnection()
227
      ->insert('simpletest')
228
      ->fields($assertion)
229
      ->execute();
230
  }
231

    
232
  /**
233
   * Delete an assertion record by message ID.
234
   *
235
   * @param $message_id
236
   *   Message ID of the assertion to delete.
237
   * @return
238
   *   TRUE if the assertion was deleted, FALSE otherwise.
239
   *
240
   * @see DrupalTestCase::insertAssert()
241
   */
242
  public static function deleteAssert($message_id) {
243
    return (bool) self::getDatabaseConnection()
244
      ->delete('simpletest')
245
      ->condition('message_id', $message_id)
246
      ->execute();
247
  }
248

    
249
  /**
250
   * Cycles through backtrace until the first non-assertion method is found.
251
   *
252
   * @return
253
   *   Array representing the true caller.
254
   */
255
  protected function getAssertionCall() {
256
    $backtrace = debug_backtrace();
257

    
258
    // The first element is the call. The second element is the caller.
259
    // We skip calls that occurred in one of the methods of our base classes
260
    // or in an assertion function.
261
   while (($caller = $backtrace[1]) &&
262
         ((isset($caller['class']) && isset($this->skipClasses[$caller['class']])) ||
263
           substr($caller['function'], 0, 6) == 'assert')) {
264
      // We remove that call.
265
      array_shift($backtrace);
266
    }
267

    
268
    return _drupal_get_last_caller($backtrace);
269
  }
270

    
271
  /**
272
   * Check to see if a value is not false (not an empty string, 0, NULL, or FALSE).
273
   *
274
   * @param $value
275
   *   The value on which the assertion is to be done.
276
   * @param $message
277
   *   The message to display along with the assertion.
278
   * @param $group
279
   *   The type of assertion - examples are "Browser", "PHP".
280
   * @return
281
   *   TRUE if the assertion succeeded, FALSE otherwise.
282
   */
283
  protected function assertTrue($value, $message = '', $group = 'Other') {
284
    return $this->assert((bool) $value, $message ? $message : t('Value @value is TRUE.', array('@value' => var_export($value, TRUE))), $group);
285
  }
286

    
287
  /**
288
   * Check to see if a value is false (an empty string, 0, NULL, or FALSE).
289
   *
290
   * @param $value
291
   *   The value on which the assertion is to be done.
292
   * @param $message
293
   *   The message to display along with the assertion.
294
   * @param $group
295
   *   The type of assertion - examples are "Browser", "PHP".
296
   * @return
297
   *   TRUE if the assertion succeeded, FALSE otherwise.
298
   */
299
  protected function assertFalse($value, $message = '', $group = 'Other') {
300
    return $this->assert(!$value, $message ? $message : t('Value @value is FALSE.', array('@value' => var_export($value, TRUE))), $group);
301
  }
302

    
303
  /**
304
   * Check to see if a value is NULL.
305
   *
306
   * @param $value
307
   *   The value on which the assertion is to be done.
308
   * @param $message
309
   *   The message to display along with the assertion.
310
   * @param $group
311
   *   The type of assertion - examples are "Browser", "PHP".
312
   * @return
313
   *   TRUE if the assertion succeeded, FALSE otherwise.
314
   */
315
  protected function assertNull($value, $message = '', $group = 'Other') {
316
    return $this->assert(!isset($value), $message ? $message : t('Value @value is NULL.', array('@value' => var_export($value, TRUE))), $group);
317
  }
318

    
319
  /**
320
   * Check to see if a value is not NULL.
321
   *
322
   * @param $value
323
   *   The value on which the assertion is to be done.
324
   * @param $message
325
   *   The message to display along with the assertion.
326
   * @param $group
327
   *   The type of assertion - examples are "Browser", "PHP".
328
   * @return
329
   *   TRUE if the assertion succeeded, FALSE otherwise.
330
   */
331
  protected function assertNotNull($value, $message = '', $group = 'Other') {
332
    return $this->assert(isset($value), $message ? $message : t('Value @value is not NULL.', array('@value' => var_export($value, TRUE))), $group);
333
  }
334

    
335
  /**
336
   * Check to see if two values are equal.
337
   *
338
   * @param $first
339
   *   The first value to check.
340
   * @param $second
341
   *   The second value to check.
342
   * @param $message
343
   *   The message to display along with the assertion.
344
   * @param $group
345
   *   The type of assertion - examples are "Browser", "PHP".
346
   * @return
347
   *   TRUE if the assertion succeeded, FALSE otherwise.
348
   */
349
  protected function assertEqual($first, $second, $message = '', $group = 'Other') {
350
    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);
351
  }
352

    
353
  /**
354
   * Check to see if two values are not equal.
355
   *
356
   * @param $first
357
   *   The first value to check.
358
   * @param $second
359
   *   The second value to check.
360
   * @param $message
361
   *   The message to display along with the assertion.
362
   * @param $group
363
   *   The type of assertion - examples are "Browser", "PHP".
364
   * @return
365
   *   TRUE if the assertion succeeded, FALSE otherwise.
366
   */
367
  protected function assertNotEqual($first, $second, $message = '', $group = 'Other') {
368
    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);
369
  }
370

    
371
  /**
372
   * Check to see if two values are identical.
373
   *
374
   * @param $first
375
   *   The first value to check.
376
   * @param $second
377
   *   The second value to check.
378
   * @param $message
379
   *   The message to display along with the assertion.
380
   * @param $group
381
   *   The type of assertion - examples are "Browser", "PHP".
382
   * @return
383
   *   TRUE if the assertion succeeded, FALSE otherwise.
384
   */
385
  protected function assertIdentical($first, $second, $message = '', $group = 'Other') {
386
    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);
387
  }
388

    
389
  /**
390
   * Check to see if two values are not identical.
391
   *
392
   * @param $first
393
   *   The first value to check.
394
   * @param $second
395
   *   The second value to check.
396
   * @param $message
397
   *   The message to display along with the assertion.
398
   * @param $group
399
   *   The type of assertion - examples are "Browser", "PHP".
400
   * @return
401
   *   TRUE if the assertion succeeded, FALSE otherwise.
402
   */
403
  protected function assertNotIdentical($first, $second, $message = '', $group = 'Other') {
404
    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);
405
  }
406

    
407
  /**
408
   * Fire an assertion that is always positive.
409
   *
410
   * @param $message
411
   *   The message to display along with the assertion.
412
   * @param $group
413
   *   The type of assertion - examples are "Browser", "PHP".
414
   * @return
415
   *   TRUE.
416
   */
417
  protected function pass($message = NULL, $group = 'Other') {
418
    return $this->assert(TRUE, $message, $group);
419
  }
420

    
421
  /**
422
   * Fire an assertion that is always negative.
423
   *
424
   * @param $message
425
   *   The message to display along with the assertion.
426
   * @param $group
427
   *   The type of assertion - examples are "Browser", "PHP".
428
   * @return
429
   *   FALSE.
430
   */
431
  protected function fail($message = NULL, $group = 'Other') {
432
    return $this->assert(FALSE, $message, $group);
433
  }
434

    
435
  /**
436
   * Fire an error assertion.
437
   *
438
   * @param $message
439
   *   The message to display along with the assertion.
440
   * @param $group
441
   *   The type of assertion - examples are "Browser", "PHP".
442
   * @param $caller
443
   *   The caller of the error.
444
   * @return
445
   *   FALSE.
446
   */
447
  protected function error($message = '', $group = 'Other', array $caller = NULL) {
448
    if ($group == 'User notice') {
449
      // Since 'User notice' is set by trigger_error() which is used for debug
450
      // set the message to a status of 'debug'.
451
      return $this->assert('debug', $message, 'Debug', $caller);
452
    }
453

    
454
    return $this->assert('exception', $message, $group, $caller);
455
  }
456

    
457
  /**
458
   * Logs a verbose message in a text file.
459
   *
460
   * The link to the verbose message will be placed in the test results as a
461
   * passing assertion with the text '[verbose message]'.
462
   *
463
   * @param $message
464
   *   The verbose message to be stored.
465
   *
466
   * @see simpletest_verbose()
467
   */
468
  protected function verbose($message) {
469
    if ($id = simpletest_verbose($message)) {
470
      $class_safe = str_replace('\\', '_', get_class($this));
471
      $url = $this->verboseDirectoryUrl . '/' . $class_safe . '-' . $id . '.html';
472
      // Not using l() to avoid invoking the theme system, so that unit tests
473
      // can use verbose() as well.
474
      $link = '<a href="' . $url . '" target="_blank">' . t('Verbose message') . '</a>';
475
      $this->error($link, 'User notice');
476
    }
477
  }
478

    
479
  /**
480
   * Run all tests in this class.
481
   *
482
   * Regardless of whether $methods are passed or not, only method names
483
   * starting with "test" are executed.
484
   *
485
   * @param $methods
486
   *   (optional) A list of method names in the test case class to run; e.g.,
487
   *   array('testFoo', 'testBar'). By default, all methods of the class are
488
   *   taken into account, but it can be useful to only run a few selected test
489
   *   methods during debugging.
490
   */
491
  public function run(array $methods = array()) {
492
    // Initialize verbose debugging.
493
    $class = get_class($this);
494
    simpletest_verbose(NULL, variable_get('file_public_path', conf_path() . '/files'), str_replace('\\', '_', $class));
495

    
496
    // HTTP auth settings (<username>:<password>) for the simpletest browser
497
    // when sending requests to the test site.
498
    $this->httpauth_method = variable_get('simpletest_httpauth_method', CURLAUTH_BASIC);
499
    $username = variable_get('simpletest_httpauth_username', NULL);
500
    $password = variable_get('simpletest_httpauth_password', NULL);
501
    if ($username && $password) {
502
      $this->httpauth_credentials = $username . ':' . $password;
503
    }
504

    
505
    set_error_handler(array($this, 'errorHandler'));
506
    // Iterate through all the methods in this class, unless a specific list of
507
    // methods to run was passed.
508
    $class_methods = get_class_methods($class);
509
    if ($methods) {
510
      $class_methods = array_intersect($class_methods, $methods);
511
    }
512
    foreach ($class_methods as $method) {
513
      // If the current method starts with "test", run it - it's a test.
514
      if (strtolower(substr($method, 0, 4)) == 'test') {
515
        // Insert a fail record. This will be deleted on completion to ensure
516
        // that testing completed.
517
        $method_info = new ReflectionMethod($class, $method);
518
        $caller = array(
519
          'file' => $method_info->getFileName(),
520
          'line' => $method_info->getStartLine(),
521
          'function' => $class . '->' . $method . '()',
522
        );
523
        $completion_check_id = DrupalTestCase::insertAssert($this->testId, $class, FALSE, t('The test did not complete due to a fatal error.'), 'Completion check', $caller);
524
        $this->setUp();
525
        if ($this->setup) {
526
          try {
527
            $this->$method();
528
            // Finish up.
529
          }
530
          catch (Exception $e) {
531
            $this->exceptionHandler($e);
532
          }
533
          $this->tearDown();
534
        }
535
        else {
536
          $this->fail(t("The test cannot be executed because it has not been set up properly."));
537
        }
538
        // Remove the completion check record.
539
        DrupalTestCase::deleteAssert($completion_check_id);
540
      }
541
    }
542
    // Clear out the error messages and restore error handler.
543
    drupal_get_messages();
544
    restore_error_handler();
545
  }
546

    
547
  /**
548
   * Handle errors during test runs.
549
   *
550
   * Because this is registered in set_error_handler(), it has to be public.
551
   * @see set_error_handler
552
   */
553
  public function errorHandler($severity, $message, $file = NULL, $line = NULL) {
554
    if ($severity & error_reporting()) {
555
      $error_map = array(
556
        E_STRICT => 'Run-time notice',
557
        E_WARNING => 'Warning',
558
        E_NOTICE => 'Notice',
559
        E_CORE_ERROR => 'Core error',
560
        E_CORE_WARNING => 'Core warning',
561
        E_USER_ERROR => 'User error',
562
        E_USER_WARNING => 'User warning',
563
        E_USER_NOTICE => 'User notice',
564
        E_RECOVERABLE_ERROR => 'Recoverable error',
565
      );
566

    
567
      // PHP 5.3 adds new error logging constants. Add these conditionally for
568
      // backwards compatibility with PHP 5.2.
569
      if (defined('E_DEPRECATED')) {
570
        $error_map += array(
571
          E_DEPRECATED => 'Deprecated',
572
          E_USER_DEPRECATED => 'User deprecated',
573
        );
574
      }
575

    
576
      $backtrace = debug_backtrace();
577
      $this->error($message, $error_map[$severity], _drupal_get_last_caller($backtrace));
578
    }
579
    return TRUE;
580
  }
581

    
582
  /**
583
   * Handle exceptions.
584
   *
585
   * @see set_exception_handler
586
   */
587
  protected function exceptionHandler($exception) {
588
    $backtrace = $exception->getTrace();
589
    // Push on top of the backtrace the call that generated the exception.
590
    array_unshift($backtrace, array(
591
      'line' => $exception->getLine(),
592
      'file' => $exception->getFile(),
593
    ));
594
    require_once DRUPAL_ROOT . '/includes/errors.inc';
595
    // The exception message is run through check_plain() by _drupal_decode_exception().
596
    $this->error(t('%type: !message in %function (line %line of %file).', _drupal_decode_exception($exception)), 'Uncaught exception', _drupal_get_last_caller($backtrace));
597
  }
598

    
599
  /**
600
   * Generates a random string of ASCII characters of codes 32 to 126.
601
   *
602
   * The generated string includes alpha-numeric characters and common
603
   * miscellaneous characters. Use this method when testing general input
604
   * where the content is not restricted.
605
   *
606
   * Do not use this method when special characters are not possible (e.g., in
607
   * machine or file names that have already been validated); instead,
608
   * use DrupalWebTestCase::randomName().
609
   *
610
   * @param $length
611
   *   Length of random string to generate.
612
   *
613
   * @return
614
   *   Randomly generated string.
615
   *
616
   * @see DrupalWebTestCase::randomName()
617
   */
618
  public static function randomString($length = 8) {
619
    $str = '';
620
    for ($i = 0; $i < $length; $i++) {
621
      $str .= chr(mt_rand(32, 126));
622
    }
623
    return $str;
624
  }
625

    
626
  /**
627
   * Generates a random string containing letters and numbers.
628
   *
629
   * The string will always start with a letter. The letters may be upper or
630
   * lower case. This method is better for restricted inputs that do not
631
   * accept certain characters. For example, when testing input fields that
632
   * require machine readable values (i.e. without spaces and non-standard
633
   * characters) this method is best.
634
   *
635
   * Do not use this method when testing unvalidated user input. Instead, use
636
   * DrupalWebTestCase::randomString().
637
   *
638
   * @param $length
639
   *   Length of random string to generate.
640
   *
641
   * @return
642
   *   Randomly generated string.
643
   *
644
   * @see DrupalWebTestCase::randomString()
645
   */
646
  public static function randomName($length = 8) {
647
    $values = array_merge(range(65, 90), range(97, 122), range(48, 57));
648
    $max = count($values) - 1;
649
    $str = chr(mt_rand(97, 122));
650
    for ($i = 1; $i < $length; $i++) {
651
      $str .= chr($values[mt_rand(0, $max)]);
652
    }
653
    return $str;
654
  }
655

    
656
  /**
657
   * Converts a list of possible parameters into a stack of permutations.
658
   *
659
   * Takes a list of parameters containing possible values, and converts all of
660
   * them into a list of items containing every possible permutation.
661
   *
662
   * Example:
663
   * @code
664
   * $parameters = array(
665
   *   'one' => array(0, 1),
666
   *   'two' => array(2, 3),
667
   * );
668
   * $permutations = DrupalTestCase::generatePermutations($parameters)
669
   * // Result:
670
   * $permutations == array(
671
   *   array('one' => 0, 'two' => 2),
672
   *   array('one' => 1, 'two' => 2),
673
   *   array('one' => 0, 'two' => 3),
674
   *   array('one' => 1, 'two' => 3),
675
   * )
676
   * @endcode
677
   *
678
   * @param $parameters
679
   *   An associative array of parameters, keyed by parameter name, and whose
680
   *   values are arrays of parameter values.
681
   *
682
   * @return
683
   *   A list of permutations, which is an array of arrays. Each inner array
684
   *   contains the full list of parameters that have been passed, but with a
685
   *   single value only.
686
   */
687
  public static function generatePermutations($parameters) {
688
    $all_permutations = array(array());
689
    foreach ($parameters as $parameter => $values) {
690
      $new_permutations = array();
691
      // Iterate over all values of the parameter.
692
      foreach ($values as $value) {
693
        // Iterate over all existing permutations.
694
        foreach ($all_permutations as $permutation) {
695
          // Add the new parameter value to existing permutations.
696
          $new_permutations[] = $permutation + array($parameter => $value);
697
        }
698
      }
699
      // Replace the old permutations with the new permutations.
700
      $all_permutations = $new_permutations;
701
    }
702
    return $all_permutations;
703
  }
704
}
705

    
706
/**
707
 * Test case for Drupal unit tests.
708
 *
709
 * These tests can not access the database nor files. Calling any Drupal
710
 * function that needs the database will throw exceptions. These include
711
 * watchdog(), module_implements(), module_invoke_all() etc.
712
 */
713
class DrupalUnitTestCase extends DrupalTestCase {
714

    
715
  /**
716
   * Constructor for DrupalUnitTestCase.
717
   */
718
  function __construct($test_id = NULL) {
719
    parent::__construct($test_id);
720
    $this->skipClasses[__CLASS__] = TRUE;
721
  }
722

    
723
  /**
724
   * Sets up unit test environment.
725
   *
726
   * Unlike DrupalWebTestCase::setUp(), DrupalUnitTestCase::setUp() does not
727
   * install modules because tests are performed without accessing the database.
728
   * Any required files must be explicitly included by the child class setUp()
729
   * method.
730
   */
731
  protected function setUp() {
732
    global $conf, $language;
733

    
734
    // Store necessary current values before switching to the test environment.
735
    $this->originalFileDirectory = variable_get('file_public_path', conf_path() . '/files');
736
    $this->verboseDirectoryUrl = file_create_url($this->originalFileDirectory . '/simpletest/verbose');
737

    
738
    // Set up English language.
739
    $this->originalLanguage = $language;
740
    $this->originalLanguageDefault = variable_get('language_default');
741
    unset($conf['language_default']);
742
    $language = language_default();
743

    
744
    // Reset all statics so that test is performed with a clean environment.
745
    drupal_static_reset();
746

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

    
750
    // Create test directory.
751
    $public_files_directory = $this->originalFileDirectory . '/simpletest/' . substr($this->databasePrefix, 10);
752
    file_prepare_directory($public_files_directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
753
    $conf['file_public_path'] = $public_files_directory;
754

    
755
    // Clone the current connection and replace the current prefix.
756
    $connection_info = Database::getConnectionInfo('default');
757
    Database::renameConnection('default', 'simpletest_original_default');
758
    foreach ($connection_info as $target => $value) {
759
      $connection_info[$target]['prefix'] = array(
760
        'default' => $value['prefix']['default'] . $this->databasePrefix,
761
      );
762
    }
763
    Database::addConnectionInfo('default', 'default', $connection_info['default']);
764

    
765
    // Set user agent to be consistent with web test case.
766
    $_SERVER['HTTP_USER_AGENT'] = $this->databasePrefix;
767

    
768
    // If locale is enabled then t() will try to access the database and
769
    // subsequently will fail as the database is not accessible.
770
    $module_list = module_list();
771
    if (isset($module_list['locale'])) {
772
      // Transform the list into the format expected as input to module_list().
773
      foreach ($module_list as &$module) {
774
        $module = array('filename' => drupal_get_filename('module', $module));
775
      }
776
      $this->originalModuleList = $module_list;
777
      unset($module_list['locale']);
778
      module_list(TRUE, FALSE, FALSE, $module_list);
779
    }
780
    $this->setup = TRUE;
781
  }
782

    
783
  protected function tearDown() {
784
    global $conf, $language;
785

    
786
    // Get back to the original connection.
787
    Database::removeConnection('default');
788
    Database::renameConnection('simpletest_original_default', 'default');
789

    
790
    $conf['file_public_path'] = $this->originalFileDirectory;
791
    // Restore modules if necessary.
792
    if (isset($this->originalModuleList)) {
793
      module_list(TRUE, FALSE, FALSE, $this->originalModuleList);
794
    }
795

    
796
    // Reset language.
797
    $language = $this->originalLanguage;
798
    if ($this->originalLanguageDefault) {
799
      $GLOBALS['conf']['language_default'] = $this->originalLanguageDefault;
800
    }
801
  }
802
}
803

    
804
/**
805
 * Test case for typical Drupal tests.
806
 */
807
class DrupalWebTestCase extends DrupalTestCase {
808
  /**
809
   * The profile to install as a basis for testing.
810
   *
811
   * @var string
812
   */
813
  protected $profile = 'standard';
814

    
815
  /**
816
   * The URL currently loaded in the internal browser.
817
   *
818
   * @var string
819
   */
820
  protected $url;
821

    
822
  /**
823
   * The handle of the current cURL connection.
824
   *
825
   * @var resource
826
   */
827
  protected $curlHandle;
828

    
829
  /**
830
   * The headers of the page currently loaded in the internal browser.
831
   *
832
   * @var Array
833
   */
834
  protected $headers;
835

    
836
  /**
837
   * The content of the page currently loaded in the internal browser.
838
   *
839
   * @var string
840
   */
841
  protected $content;
842

    
843
  /**
844
   * The content of the page currently loaded in the internal browser (plain text version).
845
   *
846
   * @var string
847
   */
848
  protected $plainTextContent;
849

    
850
  /**
851
   * The value of the Drupal.settings JavaScript variable for the page currently loaded in the internal browser.
852
   *
853
   * @var Array
854
   */
855
  protected $drupalSettings;
856

    
857
  /**
858
   * The parsed version of the page.
859
   *
860
   * @var SimpleXMLElement
861
   */
862
  protected $elements = NULL;
863

    
864
  /**
865
   * The current user logged in using the internal browser.
866
   *
867
   * @var bool
868
   */
869
  protected $loggedInUser = FALSE;
870

    
871
  /**
872
   * The current cookie file used by cURL.
873
   *
874
   * We do not reuse the cookies in further runs, so we do not need a file
875
   * but we still need cookie handling, so we set the jar to NULL.
876
   */
877
  protected $cookieFile = NULL;
878

    
879
  /**
880
   * The cookies of the page currently loaded in the internal browser.
881
   *
882
   * @var array
883
   */
884
  protected $cookies = array();
885

    
886
  /**
887
   * Additional cURL options.
888
   *
889
   * DrupalWebTestCase itself never sets this but always obeys what is set.
890
   */
891
  protected $additionalCurlOptions = array();
892

    
893
  /**
894
   * The original user, before it was changed to a clean uid = 1 for testing purposes.
895
   *
896
   * @var object
897
   */
898
  protected $originalUser = NULL;
899

    
900
  /**
901
   * The original shutdown handlers array, before it was cleaned for testing purposes.
902
   *
903
   * @var array
904
   */
905
  protected $originalShutdownCallbacks = array();
906

    
907
  /**
908
   * HTTP authentication method
909
   */
910
  protected $httpauth_method = CURLAUTH_BASIC;
911

    
912
  /**
913
   * HTTP authentication credentials (<username>:<password>).
914
   */
915
  protected $httpauth_credentials = NULL;
916

    
917
  /**
918
   * The current session name, if available.
919
   */
920
  protected $session_name = NULL;
921

    
922
  /**
923
   * The current session ID, if available.
924
   */
925
  protected $session_id = NULL;
926

    
927
  /**
928
   * Whether the files were copied to the test files directory.
929
   */
930
  protected $generatedTestFiles = FALSE;
931

    
932
  /**
933
   * The number of redirects followed during the handling of a request.
934
   */
935
  protected $redirect_count;
936

    
937
  /**
938
   * Constructor for DrupalWebTestCase.
939
   */
940
  function __construct($test_id = NULL) {
941
    parent::__construct($test_id);
942
    $this->skipClasses[__CLASS__] = TRUE;
943
  }
944

    
945
  /**
946
   * Get a node from the database based on its title.
947
   *
948
   * @param $title
949
   *   A node title, usually generated by $this->randomName().
950
   * @param $reset
951
   *   (optional) Whether to reset the internal node_load() cache.
952
   *
953
   * @return
954
   *   A node object matching $title.
955
   */
956
  function drupalGetNodeByTitle($title, $reset = FALSE) {
957
    $nodes = node_load_multiple(array(), array('title' => $title), $reset);
958
    // Load the first node returned from the database.
959
    $returned_node = reset($nodes);
960
    return $returned_node;
961
  }
962

    
963
  /**
964
   * Creates a node based on default settings.
965
   *
966
   * @param $settings
967
   *   An associative array of settings to change from the defaults, keys are
968
   *   node properties, for example 'title' => 'Hello, world!'.
969
   * @return
970
   *   Created node object.
971
   */
972
  protected function drupalCreateNode($settings = array()) {
973
    // Populate defaults array.
974
    $settings += array(
975
      'title'     => $this->randomName(8),
976
      'comment'   => 2,
977
      'changed'   => REQUEST_TIME,
978
      'moderate'  => 0,
979
      'promote'   => 0,
980
      'revision'  => 1,
981
      'log'       => '',
982
      'status'    => 1,
983
      'sticky'    => 0,
984
      'type'      => 'page',
985
      'revisions' => NULL,
986
      'language'  => LANGUAGE_NONE,
987
    );
988

    
989
    // Add the body after the language is defined so that it may be set
990
    // properly.
991
    $settings += array(
992
      'body' => array($settings['language'] => array(array())),
993
    );
994

    
995
    // Use the original node's created time for existing nodes.
996
    if (isset($settings['created']) && !isset($settings['date'])) {
997
      $settings['date'] = format_date($settings['created'], 'custom', 'Y-m-d H:i:s O');
998
    }
999

    
1000
    // If the node's user uid is not specified manually, use the currently
1001
    // logged in user if available, or else the user running the test.
1002
    if (!isset($settings['uid'])) {
1003
      if ($this->loggedInUser) {
1004
        $settings['uid'] = $this->loggedInUser->uid;
1005
      }
1006
      else {
1007
        global $user;
1008
        $settings['uid'] = $user->uid;
1009
      }
1010
    }
1011

    
1012
    // Merge body field value and format separately.
1013
    $body = array(
1014
      'value' => $this->randomName(32),
1015
      'format' => filter_default_format(),
1016
    );
1017
    $settings['body'][$settings['language']][0] += $body;
1018

    
1019
    $node = (object) $settings;
1020
    node_save($node);
1021

    
1022
    // Small hack to link revisions to our test user.
1023
    db_update('node_revision')
1024
      ->fields(array('uid' => $node->uid))
1025
      ->condition('vid', $node->vid)
1026
      ->execute();
1027
    return $node;
1028
  }
1029

    
1030
  /**
1031
   * Creates a custom content type based on default settings.
1032
   *
1033
   * @param $settings
1034
   *   An array of settings to change from the defaults.
1035
   *   Example: 'type' => 'foo'.
1036
   * @return
1037
   *   Created content type.
1038
   */
1039
  protected function drupalCreateContentType($settings = array()) {
1040
    // Find a non-existent random type name.
1041
    do {
1042
      $name = strtolower($this->randomName(8));
1043
    } while (node_type_get_type($name));
1044

    
1045
    // Populate defaults array.
1046
    $defaults = array(
1047
      'type' => $name,
1048
      'name' => $name,
1049
      'base' => 'node_content',
1050
      'description' => '',
1051
      'help' => '',
1052
      'title_label' => 'Title',
1053
      'has_title' => 1,
1054
    );
1055
    // Imposed values for a custom type.
1056
    $forced = array(
1057
      'orig_type' => '',
1058
      'old_type' => '',
1059
      'module' => 'node',
1060
      'custom' => 1,
1061
      'modified' => 1,
1062
      'locked' => 0,
1063
    );
1064
    $type = $forced + $settings + $defaults;
1065
    $type = (object) $type;
1066

    
1067
    $saved_type = node_type_save($type);
1068
    node_types_rebuild();
1069
    menu_rebuild();
1070
    node_add_body_field($type);
1071

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

    
1074
    // Reset permissions so that permissions for this content type are available.
1075
    $this->checkPermissions(array(), TRUE);
1076

    
1077
    return $type;
1078
  }
1079

    
1080
  /**
1081
   * Get a list files that can be used in tests.
1082
   *
1083
   * @param $type
1084
   *   File type, possible values: 'binary', 'html', 'image', 'javascript', 'php', 'sql', 'text'.
1085
   * @param $size
1086
   *   File size in bytes to match. Please check the tests/files folder.
1087
   * @return
1088
   *   List of files that match filter.
1089
   */
1090
  protected function drupalGetTestFiles($type, $size = NULL) {
1091
    if (empty($this->generatedTestFiles)) {
1092
      // Generate binary test files.
1093
      $lines = array(64, 1024);
1094
      $count = 0;
1095
      foreach ($lines as $line) {
1096
        simpletest_generate_file('binary-' . $count++, 64, $line, 'binary');
1097
      }
1098

    
1099
      // Generate text test files.
1100
      $lines = array(16, 256, 1024, 2048, 20480);
1101
      $count = 0;
1102
      foreach ($lines as $line) {
1103
        simpletest_generate_file('text-' . $count++, 64, $line, 'text');
1104
      }
1105

    
1106
      // Copy other test files from simpletest.
1107
      $original = drupal_get_path('module', 'simpletest') . '/files';
1108
      $files = file_scan_directory($original, '/(html|image|javascript|php|sql)-.*/');
1109
      foreach ($files as $file) {
1110
        file_unmanaged_copy($file->uri, variable_get('file_public_path', conf_path() . '/files'));
1111
      }
1112

    
1113
      $this->generatedTestFiles = TRUE;
1114
    }
1115

    
1116
    $files = array();
1117
    // Make sure type is valid.
1118
    if (in_array($type, array('binary', 'html', 'image', 'javascript', 'php', 'sql', 'text'))) {
1119
      $files = file_scan_directory('public://', '/' . $type . '\-.*/');
1120

    
1121
      // If size is set then remove any files that are not of that size.
1122
      if ($size !== NULL) {
1123
        foreach ($files as $file) {
1124
          $stats = stat($file->uri);
1125
          if ($stats['size'] != $size) {
1126
            unset($files[$file->uri]);
1127
          }
1128
        }
1129
      }
1130
    }
1131
    usort($files, array($this, 'drupalCompareFiles'));
1132
    return $files;
1133
  }
1134

    
1135
  /**
1136
   * Compare two files based on size and file name.
1137
   */
1138
  protected function drupalCompareFiles($file1, $file2) {
1139
    $compare_size = filesize($file1->uri) - filesize($file2->uri);
1140
    if ($compare_size) {
1141
      // Sort by file size.
1142
      return $compare_size;
1143
    }
1144
    else {
1145
      // The files were the same size, so sort alphabetically.
1146
      return strnatcmp($file1->name, $file2->name);
1147
    }
1148
  }
1149

    
1150
  /**
1151
   * Create a user with a given set of permissions.
1152
   *
1153
   * @param array $permissions
1154
   *   Array of permission names to assign to user. Note that the user always
1155
   *   has the default permissions derived from the "authenticated users" role.
1156
   *
1157
   * @return object|false
1158
   *   A fully loaded user object with pass_raw property, or FALSE if account
1159
   *   creation fails.
1160
   */
1161
  protected function drupalCreateUser(array $permissions = array()) {
1162
    // Create a role with the given permission set, if any.
1163
    $rid = FALSE;
1164
    if ($permissions) {
1165
      $rid = $this->drupalCreateRole($permissions);
1166
      if (!$rid) {
1167
        return FALSE;
1168
      }
1169
    }
1170

    
1171
    // Create a user assigned to that role.
1172
    $edit = array();
1173
    $edit['name']   = $this->randomName();
1174
    $edit['mail']   = $edit['name'] . '@example.com';
1175
    $edit['pass']   = user_password();
1176
    $edit['status'] = 1;
1177
    if ($rid) {
1178
      $edit['roles'] = array($rid => $rid);
1179
    }
1180

    
1181
    $account = user_save(drupal_anonymous_user(), $edit);
1182

    
1183
    $this->assertTrue(!empty($account->uid), t('User created with name %name and pass %pass', array('%name' => $edit['name'], '%pass' => $edit['pass'])), t('User login'));
1184
    if (empty($account->uid)) {
1185
      return FALSE;
1186
    }
1187

    
1188
    // Add the raw password so that we can log in as this user.
1189
    $account->pass_raw = $edit['pass'];
1190
    return $account;
1191
  }
1192

    
1193
  /**
1194
   * Creates a role with specified permissions.
1195
   *
1196
   * @param $permissions
1197
   *   Array of permission names to assign to role.
1198
   * @param $name
1199
   *   (optional) String for the name of the role.  Defaults to a random string.
1200
   * @return
1201
   *   Role ID of newly created role, or FALSE if role creation failed.
1202
   */
1203
  protected function drupalCreateRole(array $permissions, $name = NULL) {
1204
    // Generate random name if it was not passed.
1205
    if (!$name) {
1206
      $name = $this->randomName();
1207
    }
1208

    
1209
    // Check the all the permissions strings are valid.
1210
    if (!$this->checkPermissions($permissions)) {
1211
      return FALSE;
1212
    }
1213

    
1214
    // Create new role.
1215
    $role = new stdClass();
1216
    $role->name = $name;
1217
    user_role_save($role);
1218
    user_role_grant_permissions($role->rid, $permissions);
1219

    
1220
    $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'));
1221
    if ($role && !empty($role->rid)) {
1222
      $count = db_query('SELECT COUNT(*) FROM {role_permission} WHERE rid = :rid', array(':rid' => $role->rid))->fetchField();
1223
      $this->assertTrue($count == count($permissions), t('Created permissions: @perms', array('@perms' => implode(', ', $permissions))), t('Role'));
1224
      return $role->rid;
1225
    }
1226
    else {
1227
      return FALSE;
1228
    }
1229
  }
1230

    
1231
  /**
1232
   * Check to make sure that the array of permissions are valid.
1233
   *
1234
   * @param $permissions
1235
   *   Permissions to check.
1236
   * @param $reset
1237
   *   Reset cached available permissions.
1238
   * @return
1239
   *   TRUE or FALSE depending on whether the permissions are valid.
1240
   */
1241
  protected function checkPermissions(array $permissions, $reset = FALSE) {
1242
    $available = &drupal_static(__FUNCTION__);
1243

    
1244
    if (!isset($available) || $reset) {
1245
      $available = array_keys(module_invoke_all('permission'));
1246
    }
1247

    
1248
    $valid = TRUE;
1249
    foreach ($permissions as $permission) {
1250
      if (!in_array($permission, $available)) {
1251
        $this->fail(t('Invalid permission %permission.', array('%permission' => $permission)), t('Role'));
1252
        $valid = FALSE;
1253
      }
1254
    }
1255
    return $valid;
1256
  }
1257

    
1258
  /**
1259
   * Log in a user with the internal browser.
1260
   *
1261
   * If a user is already logged in, then the current user is logged out before
1262
   * logging in the specified user.
1263
   *
1264
   * Please note that neither the global $user nor the passed-in user object is
1265
   * populated with data of the logged in user. If you need full access to the
1266
   * user object after logging in, it must be updated manually. If you also need
1267
   * access to the plain-text password of the user (set by drupalCreateUser()),
1268
   * e.g. to log in the same user again, then it must be re-assigned manually.
1269
   * For example:
1270
   * @code
1271
   *   // Create a user.
1272
   *   $account = $this->drupalCreateUser(array());
1273
   *   $this->drupalLogin($account);
1274
   *   // Load real user object.
1275
   *   $pass_raw = $account->pass_raw;
1276
   *   $account = user_load($account->uid);
1277
   *   $account->pass_raw = $pass_raw;
1278
   * @endcode
1279
   *
1280
   * @param $account
1281
   *   User object representing the user to log in.
1282
   *
1283
   * @see drupalCreateUser()
1284
   */
1285
  protected function drupalLogin(stdClass $account) {
1286
    if ($this->loggedInUser) {
1287
      $this->drupalLogout();
1288
    }
1289

    
1290
    $edit = array(
1291
      'name' => $account->name,
1292
      'pass' => $account->pass_raw
1293
    );
1294
    $this->drupalPost('user', $edit, t('Log in'));
1295

    
1296
    // If a "log out" link appears on the page, it is almost certainly because
1297
    // the login was successful.
1298
    $pass = $this->assertLink(t('Log out'), 0, t('User %name successfully logged in.', array('%name' => $account->name)), t('User login'));
1299

    
1300
    if ($pass) {
1301
      $this->loggedInUser = $account;
1302
    }
1303
  }
1304

    
1305
  /**
1306
   * Generate a token for the currently logged in user.
1307
   */
1308
  protected function drupalGetToken($value = '') {
1309
    $private_key = drupal_get_private_key();
1310
    return drupal_hmac_base64($value, $this->session_id . $private_key);
1311
  }
1312

    
1313
  /*
1314
   * Logs a user out of the internal browser, then check the login page to confirm logout.
1315
   */
1316
  protected function drupalLogout() {
1317
    // Make a request to the logout page, and redirect to the user page, the
1318
    // idea being if you were properly logged out you should be seeing a login
1319
    // screen.
1320
    $this->drupalGet('user/logout');
1321
    $this->drupalGet('user');
1322
    $pass = $this->assertField('name', t('Username field found.'), t('Logout'));
1323
    $pass = $pass && $this->assertField('pass', t('Password field found.'), t('Logout'));
1324

    
1325
    if ($pass) {
1326
      $this->loggedInUser = FALSE;
1327
    }
1328
  }
1329

    
1330
  /**
1331
   * Generates a database prefix for running tests.
1332
   *
1333
   * The generated database table prefix is used for the Drupal installation
1334
   * being performed for the test. It is also used as user agent HTTP header
1335
   * value by the cURL-based browser of DrupalWebTestCase, which is sent
1336
   * to the Drupal installation of the test. During early Drupal bootstrap, the
1337
   * user agent HTTP header is parsed, and if it matches, all database queries
1338
   * use the database table prefix that has been generated here.
1339
   *
1340
   * @see DrupalWebTestCase::curlInitialize()
1341
   * @see drupal_valid_test_ua()
1342
   * @see DrupalWebTestCase::setUp()
1343
   */
1344
  protected function prepareDatabasePrefix() {
1345
    $this->databasePrefix = 'simpletest' . mt_rand(1000, 1000000);
1346

    
1347
    // As soon as the database prefix is set, the test might start to execute.
1348
    // All assertions as well as the SimpleTest batch operations are associated
1349
    // with the testId, so the database prefix has to be associated with it.
1350
    db_update('simpletest_test_id')
1351
      ->fields(array('last_prefix' => $this->databasePrefix))
1352
      ->condition('test_id', $this->testId)
1353
      ->execute();
1354
  }
1355

    
1356
  /**
1357
   * Changes the database connection to the prefixed one.
1358
   *
1359
   * @see DrupalWebTestCase::setUp()
1360
   */
1361
  protected function changeDatabasePrefix() {
1362
    if (empty($this->databasePrefix)) {
1363
      $this->prepareDatabasePrefix();
1364
      // If $this->prepareDatabasePrefix() failed to work, return without
1365
      // setting $this->setupDatabasePrefix to TRUE, so setUp() methods will
1366
      // know to bail out.
1367
      if (empty($this->databasePrefix)) {
1368
        return;
1369
      }
1370
    }
1371

    
1372
    // Clone the current connection and replace the current prefix.
1373
    $connection_info = Database::getConnectionInfo('default');
1374
    Database::renameConnection('default', 'simpletest_original_default');
1375
    foreach ($connection_info as $target => $value) {
1376
      $connection_info[$target]['prefix'] = array(
1377
        'default' => $value['prefix']['default'] . $this->databasePrefix,
1378
      );
1379
    }
1380
    Database::addConnectionInfo('default', 'default', $connection_info['default']);
1381

    
1382
    // Indicate the database prefix was set up correctly.
1383
    $this->setupDatabasePrefix = TRUE;
1384
  }
1385

    
1386
  /**
1387
   * Prepares the current environment for running the test.
1388
   *
1389
   * Backups various current environment variables and resets them, so they do
1390
   * not interfere with the Drupal site installation in which tests are executed
1391
   * and can be restored in tearDown().
1392
   *
1393
   * Also sets up new resources for the testing environment, such as the public
1394
   * filesystem and configuration directories.
1395
   *
1396
   * @see DrupalWebTestCase::setUp()
1397
   * @see DrupalWebTestCase::tearDown()
1398
   */
1399
  protected function prepareEnvironment() {
1400
    global $user, $language, $language_url, $conf;
1401

    
1402
    // Store necessary current values before switching to prefixed database.
1403
    $this->originalLanguage = $language;
1404
    $this->originalLanguageUrl = $language_url;
1405
    $this->originalLanguageDefault = variable_get('language_default');
1406
    $this->originalFileDirectory = variable_get('file_public_path', conf_path() . '/files');
1407
    $this->verboseDirectoryUrl = file_create_url($this->originalFileDirectory . '/simpletest/verbose');
1408
    $this->originalProfile = drupal_get_profile();
1409
    $this->originalCleanUrl = variable_get('clean_url', 0);
1410
    $this->originalUser = $user;
1411

    
1412
    // Set to English to prevent exceptions from utf8_truncate() from t()
1413
    // during install if the current language is not 'en'.
1414
    // The following array/object conversion is copied from language_default().
1415
    $language_url = $language = (object) array('language' => 'en', 'name' => 'English', 'native' => 'English', 'direction' => 0, 'enabled' => 1, 'plurals' => 0, 'formula' => '', 'domain' => '', 'prefix' => '', 'weight' => 0, 'javascript' => '');
1416

    
1417
    // Save and clean the shutdown callbacks array because it is static cached
1418
    // and will be changed by the test run. Otherwise it will contain callbacks
1419
    // from both environments and the testing environment will try to call the
1420
    // handlers defined by the original one.
1421
    $callbacks = &drupal_register_shutdown_function();
1422
    $this->originalShutdownCallbacks = $callbacks;
1423
    $callbacks = array();
1424

    
1425
    // Create test directory ahead of installation so fatal errors and debug
1426
    // information can be logged during installation process.
1427
    // Use temporary files directory with the same prefix as the database.
1428
    $this->public_files_directory = $this->originalFileDirectory . '/simpletest/' . substr($this->databasePrefix, 10);
1429
    $this->private_files_directory = $this->public_files_directory . '/private';
1430
    $this->temp_files_directory = $this->private_files_directory . '/temp';
1431

    
1432
    // Create the directories
1433
    file_prepare_directory($this->public_files_directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
1434
    file_prepare_directory($this->private_files_directory, FILE_CREATE_DIRECTORY);
1435
    file_prepare_directory($this->temp_files_directory, FILE_CREATE_DIRECTORY);
1436
    $this->generatedTestFiles = FALSE;
1437

    
1438
    // Log fatal errors.
1439
    ini_set('log_errors', 1);
1440
    ini_set('error_log', $this->public_files_directory . '/error.log');
1441

    
1442
    // Set the test information for use in other parts of Drupal.
1443
    $test_info = &$GLOBALS['drupal_test_info'];
1444
    $test_info['test_run_id'] = $this->databasePrefix;
1445
    $test_info['in_child_site'] = FALSE;
1446

    
1447
    // Indicate the environment was set up correctly.
1448
    $this->setupEnvironment = TRUE;
1449
  }
1450

    
1451
  /**
1452
   * Sets up a Drupal site for running functional and integration tests.
1453
   *
1454
   * Generates a random database prefix and installs Drupal with the specified
1455
   * installation profile in DrupalWebTestCase::$profile into the
1456
   * prefixed database. Afterwards, installs any additional modules specified by
1457
   * the test.
1458
   *
1459
   * After installation all caches are flushed and several configuration values
1460
   * are reset to the values of the parent site executing the test, since the
1461
   * default values may be incompatible with the environment in which tests are
1462
   * being executed.
1463
   *
1464
   * @param ...
1465
   *   List of modules to enable for the duration of the test. This can be
1466
   *   either a single array or a variable number of string arguments.
1467
   *
1468
   * @see DrupalWebTestCase::prepareDatabasePrefix()
1469
   * @see DrupalWebTestCase::changeDatabasePrefix()
1470
   * @see DrupalWebTestCase::prepareEnvironment()
1471
   */
1472
  protected function setUp() {
1473
    global $user, $language, $language_url, $conf;
1474

    
1475
    // Create the database prefix for this test.
1476
    $this->prepareDatabasePrefix();
1477

    
1478
    // Prepare the environment for running tests.
1479
    $this->prepareEnvironment();
1480
    if (!$this->setupEnvironment) {
1481
      return FALSE;
1482
    }
1483

    
1484
    // Reset all statics and variables to perform tests in a clean environment.
1485
    $conf = array();
1486
    drupal_static_reset();
1487

    
1488
    // Change the database prefix.
1489
    // All static variables need to be reset before the database prefix is
1490
    // changed, since DrupalCacheArray implementations attempt to
1491
    // write back to persistent caches when they are destructed.
1492
    $this->changeDatabasePrefix();
1493
    if (!$this->setupDatabasePrefix) {
1494
      return FALSE;
1495
    }
1496

    
1497
    // Preset the 'install_profile' system variable, so the first call into
1498
    // system_rebuild_module_data() (in drupal_install_system()) will register
1499
    // the test's profile as a module. Without this, the installation profile of
1500
    // the parent site (executing the test) is registered, and the test
1501
    // profile's hook_install() and other hook implementations are never invoked.
1502
    $conf['install_profile'] = $this->profile;
1503

    
1504
    // Perform the actual Drupal installation.
1505
    include_once DRUPAL_ROOT . '/includes/install.inc';
1506
    drupal_install_system();
1507

    
1508
    $this->preloadRegistry();
1509

    
1510
    // Set path variables.
1511
    variable_set('file_public_path', $this->public_files_directory);
1512
    variable_set('file_private_path', $this->private_files_directory);
1513
    variable_set('file_temporary_path', $this->temp_files_directory);
1514

    
1515
    // Set the 'simpletest_parent_profile' variable to add the parent profile's
1516
    // search path to the child site's search paths.
1517
    // @see drupal_system_listing()
1518
    // @todo This may need to be primed like 'install_profile' above.
1519
    variable_set('simpletest_parent_profile', $this->originalProfile);
1520

    
1521
    // Include the testing profile.
1522
    variable_set('install_profile', $this->profile);
1523
    $profile_details = install_profile_info($this->profile, 'en');
1524

    
1525
    // Install the modules specified by the testing profile.
1526
    module_enable($profile_details['dependencies'], FALSE);
1527

    
1528
    // Install modules needed for this test. This could have been passed in as
1529
    // either a single array argument or a variable number of string arguments.
1530
    // @todo Remove this compatibility layer in Drupal 8, and only accept
1531
    // $modules as a single array argument.
1532
    $modules = func_get_args();
1533
    if (isset($modules[0]) && is_array($modules[0])) {
1534
      $modules = $modules[0];
1535
    }
1536
    if ($modules) {
1537
      $success = module_enable($modules, TRUE);
1538
      $this->assertTrue($success, t('Enabled modules: %modules', array('%modules' => implode(', ', $modules))));
1539
    }
1540

    
1541
    // Run the profile tasks.
1542
    $install_profile_module_exists = db_query("SELECT 1 FROM {system} WHERE type = 'module' AND name = :name", array(
1543
      ':name' => $this->profile,
1544
    ))->fetchField();
1545
    if ($install_profile_module_exists) {
1546
      module_enable(array($this->profile), FALSE);
1547
    }
1548

    
1549
    // Reset/rebuild all data structures after enabling the modules.
1550
    $this->resetAll();
1551

    
1552
    // Run cron once in that environment, as install.php does at the end of
1553
    // the installation process.
1554
    drupal_cron_run();
1555

    
1556
    // Ensure that the session is not written to the new environment and replace
1557
    // the global $user session with uid 1 from the new test site.
1558
    drupal_save_session(FALSE);
1559
    // Login as uid 1.
1560
    $user = user_load(1);
1561

    
1562
    // Restore necessary variables.
1563
    variable_set('install_task', 'done');
1564
    variable_set('clean_url', $this->originalCleanUrl);
1565
    variable_set('site_mail', 'simpletest@example.com');
1566
    variable_set('date_default_timezone', date_default_timezone_get());
1567

    
1568
    // Set up English language.
1569
    unset($conf['language_default']);
1570
    $language_url = $language = language_default();
1571

    
1572
    // Use the test mail class instead of the default mail handler class.
1573
    variable_set('mail_system', array('default-system' => 'TestingMailSystem'));
1574

    
1575
    drupal_set_time_limit($this->timeLimit);
1576
    $this->setup = TRUE;
1577
  }
1578

    
1579
  /**
1580
   * Preload the registry from the testing site.
1581
   *
1582
   * This method is called by DrupalWebTestCase::setUp(), and preloads the
1583
   * registry from the testing site to cut down on the time it takes to
1584
   * set up a clean environment for the current test run.
1585
   */
1586
  protected function preloadRegistry() {
1587
    // Use two separate queries, each with their own connections: copy the
1588
    // {registry} and {registry_file} tables over from the parent installation
1589
    // to the child installation.
1590
    $original_connection = Database::getConnection('default', 'simpletest_original_default');
1591
    $test_connection = Database::getConnection();
1592

    
1593
    foreach (array('registry', 'registry_file') as $table) {
1594
      // Find the records from the parent database.
1595
      $source_query = $original_connection
1596
        ->select($table, array(), array('fetch' => PDO::FETCH_ASSOC))
1597
        ->fields($table);
1598

    
1599
      $dest_query = $test_connection->insert($table);
1600

    
1601
      $first = TRUE;
1602
      foreach ($source_query->execute() as $row) {
1603
        if ($first) {
1604
          $dest_query->fields(array_keys($row));
1605
          $first = FALSE;
1606
        }
1607
        // Insert the records into the child database.
1608
        $dest_query->values($row);
1609
      }
1610

    
1611
      $dest_query->execute();
1612
    }
1613
  }
1614

    
1615
  /**
1616
   * Reset all data structures after having enabled new modules.
1617
   *
1618
   * This method is called by DrupalWebTestCase::setUp() after enabling
1619
   * the requested modules. It must be called again when additional modules
1620
   * are enabled later.
1621
   */
1622
  protected function resetAll() {
1623
    // Reset all static variables.
1624
    drupal_static_reset();
1625
    // Reset the list of enabled modules.
1626
    module_list(TRUE);
1627

    
1628
    // Reset cached schema for new database prefix. This must be done before
1629
    // drupal_flush_all_caches() so rebuilds can make use of the schema of
1630
    // modules enabled on the cURL side.
1631
    drupal_get_schema(NULL, TRUE);
1632

    
1633
    // Perform rebuilds and flush remaining caches.
1634
    drupal_flush_all_caches();
1635

    
1636
    // Reload global $conf array and permissions.
1637
    $this->refreshVariables();
1638
    $this->checkPermissions(array(), TRUE);
1639
  }
1640

    
1641
  /**
1642
   * Refresh the in-memory set of variables. Useful after a page request is made
1643
   * that changes a variable in a different thread.
1644
   *
1645
   * In other words calling a settings page with $this->drupalPost() with a changed
1646
   * value would update a variable to reflect that change, but in the thread that
1647
   * made the call (thread running the test) the changed variable would not be
1648
   * picked up.
1649
   *
1650
   * This method clears the variables cache and loads a fresh copy from the database
1651
   * to ensure that the most up-to-date set of variables is loaded.
1652
   */
1653
  protected function refreshVariables() {
1654
    global $conf;
1655
    cache_clear_all('variables', 'cache_bootstrap');
1656
    $conf = variable_initialize();
1657
  }
1658

    
1659
  /**
1660
   * Delete created files and temporary files directory, delete the tables created by setUp(),
1661
   * and reset the database prefix.
1662
   */
1663
  protected function tearDown() {
1664
    global $user, $language, $language_url;
1665

    
1666
    // In case a fatal error occurred that was not in the test process read the
1667
    // log to pick up any fatal errors.
1668
    simpletest_log_read($this->testId, $this->databasePrefix, get_class($this), TRUE);
1669

    
1670
    $emailCount = count(variable_get('drupal_test_email_collector', array()));
1671
    if ($emailCount) {
1672
      $message = format_plural($emailCount, '1 e-mail was sent during this test.', '@count e-mails were sent during this test.');
1673
      $this->pass($message, t('E-mail'));
1674
    }
1675

    
1676
    // Delete temporary files directory.
1677
    file_unmanaged_delete_recursive($this->originalFileDirectory . '/simpletest/' . substr($this->databasePrefix, 10));
1678

    
1679
    // Remove all prefixed tables.
1680
    $tables = db_find_tables_d8('%');
1681
    if (empty($tables)) {
1682
      $this->fail('Failed to find test tables to drop.');
1683
    }
1684
    foreach ($tables as $table) {
1685
      if (db_drop_table($table)) {
1686
        unset($tables[$table]);
1687
      }
1688
    }
1689
    if (!empty($tables)) {
1690
      $this->fail('Failed to drop all prefixed tables.');
1691
    }
1692

    
1693
    // Get back to the original connection.
1694
    Database::removeConnection('default');
1695
    Database::renameConnection('simpletest_original_default', 'default');
1696

    
1697
    // Restore original shutdown callbacks array to prevent original
1698
    // environment of calling handlers from test run.
1699
    $callbacks = &drupal_register_shutdown_function();
1700
    $callbacks = $this->originalShutdownCallbacks;
1701

    
1702
    // Return the user to the original one.
1703
    $user = $this->originalUser;
1704
    drupal_save_session(TRUE);
1705

    
1706
    // Ensure that internal logged in variable and cURL options are reset.
1707
    $this->loggedInUser = FALSE;
1708
    $this->additionalCurlOptions = array();
1709

    
1710
    // Reload module list and implementations to ensure that test module hooks
1711
    // aren't called after tests.
1712
    module_list(TRUE);
1713
    module_implements('', FALSE, TRUE);
1714

    
1715
    // Reset the Field API.
1716
    field_cache_clear();
1717

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

    
1721
    // Reset public files directory.
1722
    $GLOBALS['conf']['file_public_path'] = $this->originalFileDirectory;
1723

    
1724
    // Reset language.
1725
    $language = $this->originalLanguage;
1726
    $language_url = $this->originalLanguageUrl;
1727
    if ($this->originalLanguageDefault) {
1728
      $GLOBALS['conf']['language_default'] = $this->originalLanguageDefault;
1729
    }
1730

    
1731
    // Close the CURL handler and reset the cookies array so test classes
1732
    // containing multiple tests are not polluted.
1733
    $this->curlClose();
1734
    $this->cookies = array();
1735
  }
1736

    
1737
  /**
1738
   * Initializes the cURL connection.
1739
   *
1740
   * If the simpletest_httpauth_credentials variable is set, this function will
1741
   * add HTTP authentication headers. This is necessary for testing sites that
1742
   * are protected by login credentials from public access.
1743
   * See the description of $curl_options for other options.
1744
   */
1745
  protected function curlInitialize() {
1746
    global $base_url;
1747

    
1748
    if (!isset($this->curlHandle)) {
1749
      $this->curlHandle = curl_init();
1750

    
1751
      // Some versions/configurations of cURL break on a NULL cookie jar, so
1752
      // supply a real file.
1753
      if (empty($this->cookieFile)) {
1754
        $this->cookieFile = $this->public_files_directory . '/cookie.jar';
1755
      }
1756

    
1757
      $curl_options = array(
1758
        CURLOPT_COOKIEJAR => $this->cookieFile,
1759
        CURLOPT_URL => $base_url,
1760
        CURLOPT_FOLLOWLOCATION => FALSE,
1761
        CURLOPT_RETURNTRANSFER => TRUE,
1762
        CURLOPT_SSL_VERIFYPEER => FALSE, // Required to make the tests run on HTTPS.
1763
        CURLOPT_SSL_VERIFYHOST => FALSE, // Required to make the tests run on HTTPS.
1764
        CURLOPT_HEADERFUNCTION => array(&$this, 'curlHeaderCallback'),
1765
        CURLOPT_USERAGENT => $this->databasePrefix,
1766
      );
1767
      if (isset($this->httpauth_credentials)) {
1768
        $curl_options[CURLOPT_HTTPAUTH] = $this->httpauth_method;
1769
        $curl_options[CURLOPT_USERPWD] = $this->httpauth_credentials;
1770
      }
1771
      // curl_setopt_array() returns FALSE if any of the specified options
1772
      // cannot be set, and stops processing any further options.
1773
      $result = curl_setopt_array($this->curlHandle, $this->additionalCurlOptions + $curl_options);
1774
      if (!$result) {
1775
        throw new Exception('One or more cURL options could not be set.');
1776
      }
1777

    
1778
      // By default, the child session name should be the same as the parent.
1779
      $this->session_name = session_name();
1780
    }
1781
    // We set the user agent header on each request so as to use the current
1782
    // time and a new uniqid.
1783
    if (preg_match('/simpletest\d+/', $this->databasePrefix, $matches)) {
1784
      curl_setopt($this->curlHandle, CURLOPT_USERAGENT, drupal_generate_test_ua($matches[0]));
1785
    }
1786
  }
1787

    
1788
  /**
1789
   * Initializes and executes a cURL request.
1790
   *
1791
   * @param $curl_options
1792
   *   An associative array of cURL options to set, where the keys are constants
1793
   *   defined by the cURL library. For a list of valid options, see
1794
   *   http://www.php.net/manual/function.curl-setopt.php
1795
   * @param $redirect
1796
   *   FALSE if this is an initial request, TRUE if this request is the result
1797
   *   of a redirect.
1798
   *
1799
   * @return
1800
   *   The content returned from the call to curl_exec().
1801
   *
1802
   * @see curlInitialize()
1803
   */
1804
  protected function curlExec($curl_options, $redirect = FALSE) {
1805
    $this->curlInitialize();
1806

    
1807
    if (!empty($curl_options[CURLOPT_URL])) {
1808
      // Forward XDebug activation if present.
1809
      if (isset($_COOKIE['XDEBUG_SESSION'])) {
1810
        $options = drupal_parse_url($curl_options[CURLOPT_URL]);
1811
        $options += array('query' => array());
1812
        $options['query'] += array('XDEBUG_SESSION_START' => $_COOKIE['XDEBUG_SESSION']);
1813
        $curl_options[CURLOPT_URL] = url($options['path'], $options);
1814
      }
1815

    
1816
      // cURL incorrectly handles URLs with a fragment by including the
1817
      // fragment in the request to the server, causing some web servers
1818
      // to reject the request citing "400 - Bad Request". To prevent
1819
      // this, we strip the fragment from the request.
1820
      // TODO: Remove this for Drupal 8, since fixed in curl 7.20.0.
1821
      if (strpos($curl_options[CURLOPT_URL], '#')) {
1822
        $original_url = $curl_options[CURLOPT_URL];
1823
        $curl_options[CURLOPT_URL] = strtok($curl_options[CURLOPT_URL], '#');
1824
      }
1825
    }
1826

    
1827
    $url = empty($curl_options[CURLOPT_URL]) ? curl_getinfo($this->curlHandle, CURLINFO_EFFECTIVE_URL) : $curl_options[CURLOPT_URL];
1828

    
1829
    if (!empty($curl_options[CURLOPT_POST])) {
1830
      // This is a fix for the Curl library to prevent Expect: 100-continue
1831
      // headers in POST requests, that may cause unexpected HTTP response
1832
      // codes from some webservers (like lighttpd that returns a 417 error
1833
      // code). It is done by setting an empty "Expect" header field that is
1834
      // not overwritten by Curl.
1835
      $curl_options[CURLOPT_HTTPHEADER][] = 'Expect:';
1836
    }
1837
    curl_setopt_array($this->curlHandle, $this->additionalCurlOptions + $curl_options);
1838

    
1839
    if (!$redirect) {
1840
      // Reset headers, the session ID and the redirect counter.
1841
      $this->session_id = NULL;
1842
      $this->headers = array();
1843
      $this->redirect_count = 0;
1844
    }
1845

    
1846
    $content = curl_exec($this->curlHandle);
1847
    $status = curl_getinfo($this->curlHandle, CURLINFO_HTTP_CODE);
1848

    
1849
    // cURL incorrectly handles URLs with fragments, so instead of
1850
    // letting cURL handle redirects we take of them ourselves to
1851
    // to prevent fragments being sent to the web server as part
1852
    // of the request.
1853
    // TODO: Remove this for Drupal 8, since fixed in curl 7.20.0.
1854
    if (in_array($status, array(300, 301, 302, 303, 305, 307)) && $this->redirect_count < variable_get('simpletest_maximum_redirects', 5)) {
1855
      if ($this->drupalGetHeader('location')) {
1856
        $this->redirect_count++;
1857
        $curl_options = array();
1858
        $curl_options[CURLOPT_URL] = $this->drupalGetHeader('location');
1859
        $curl_options[CURLOPT_HTTPGET] = TRUE;
1860
        return $this->curlExec($curl_options, TRUE);
1861
      }
1862
    }
1863

    
1864
    $this->drupalSetContent($content, isset($original_url) ? $original_url : curl_getinfo($this->curlHandle, CURLINFO_EFFECTIVE_URL));
1865
    $message_vars = array(
1866
      '!method' => !empty($curl_options[CURLOPT_NOBODY]) ? 'HEAD' : (empty($curl_options[CURLOPT_POSTFIELDS]) ? 'GET' : 'POST'),
1867
      '@url' => isset($original_url) ? $original_url : $url,
1868
      '@status' => $status,
1869
      '!length' => format_size(strlen($this->drupalGetContent()))
1870
    );
1871
    $message = t('!method @url returned @status (!length).', $message_vars);
1872
    $this->assertTrue($this->drupalGetContent() !== FALSE, $message, t('Browser'));
1873
    return $this->drupalGetContent();
1874
  }
1875

    
1876
  /**
1877
   * Reads headers and registers errors received from the tested site.
1878
   *
1879
   * @see _drupal_log_error().
1880
   *
1881
   * @param $curlHandler
1882
   *   The cURL handler.
1883
   * @param $header
1884
   *   An header.
1885
   */
1886
  protected function curlHeaderCallback($curlHandler, $header) {
1887
    // Header fields can be extended over multiple lines by preceding each
1888
    // extra line with at least one SP or HT. They should be joined on receive.
1889
    // Details are in RFC2616 section 4.
1890
    if ($header[0] == ' ' || $header[0] == "\t") {
1891
      // Normalize whitespace between chucks.
1892
      $this->headers[] = array_pop($this->headers) . ' ' . trim($header);
1893
    }
1894
    else {
1895
      $this->headers[] = $header;
1896
    }
1897

    
1898
    // Errors are being sent via X-Drupal-Assertion-* headers,
1899
    // generated by _drupal_log_error() in the exact form required
1900
    // by DrupalWebTestCase::error().
1901
    if (preg_match('/^X-Drupal-Assertion-[0-9]+: (.*)$/', $header, $matches)) {
1902
      // Call DrupalWebTestCase::error() with the parameters from the header.
1903
      call_user_func_array(array(&$this, 'error'), unserialize(urldecode($matches[1])));
1904
    }
1905

    
1906
    // Save cookies.
1907
    if (preg_match('/^Set-Cookie: ([^=]+)=(.+)/', $header, $matches)) {
1908
      $name = $matches[1];
1909
      $parts = array_map('trim', explode(';', $matches[2]));
1910
      $value = array_shift($parts);
1911
      $this->cookies[$name] = array('value' => $value, 'secure' => in_array('secure', $parts));
1912
      if ($name == $this->session_name) {
1913
        if ($value != 'deleted') {
1914
          $this->session_id = $value;
1915
        }
1916
        else {
1917
          $this->session_id = NULL;
1918
        }
1919
      }
1920
    }
1921

    
1922
    // This is required by cURL.
1923
    return strlen($header);
1924
  }
1925

    
1926
  /**
1927
   * Close the cURL handler and unset the handler.
1928
   */
1929
  protected function curlClose() {
1930
    if (isset($this->curlHandle)) {
1931
      curl_close($this->curlHandle);
1932
      unset($this->curlHandle);
1933
    }
1934
  }
1935

    
1936
  /**
1937
   * Parse content returned from curlExec using DOM and SimpleXML.
1938
   *
1939
   * @return
1940
   *   A SimpleXMLElement or FALSE on failure.
1941
   */
1942
  protected function parse() {
1943
    if (!$this->elements) {
1944
      // DOM can load HTML soup. But, HTML soup can throw warnings, suppress
1945
      // them.
1946
      $htmlDom = new DOMDocument();
1947
      @$htmlDom->loadHTML($this->drupalGetContent());
1948
      if ($htmlDom) {
1949
        $this->pass(t('Valid HTML found on "@path"', array('@path' => $this->getUrl())), t('Browser'));
1950
        // It's much easier to work with simplexml than DOM, luckily enough
1951
        // we can just simply import our DOM tree.
1952
        $this->elements = simplexml_import_dom($htmlDom);
1953
      }
1954
    }
1955
    if (!$this->elements) {
1956
      $this->fail(t('Parsed page successfully.'), t('Browser'));
1957
    }
1958

    
1959
    return $this->elements;
1960
  }
1961

    
1962
  /**
1963
   * Retrieves a Drupal path or an absolute path.
1964
   *
1965
   * @param $path
1966
   *   Drupal path or URL to load into internal browser
1967
   * @param $options
1968
   *   Options to be forwarded to url().
1969
   * @param $headers
1970
   *   An array containing additional HTTP request headers, each formatted as
1971
   *   "name: value".
1972
   * @return
1973
   *   The retrieved HTML string, also available as $this->drupalGetContent()
1974
   */
1975
  protected function drupalGet($path, array $options = array(), array $headers = array()) {
1976
    $options['absolute'] = TRUE;
1977

    
1978
    // We re-using a CURL connection here. If that connection still has certain
1979
    // options set, it might change the GET into a POST. Make sure we clear out
1980
    // previous options.
1981
    $out = $this->curlExec(array(CURLOPT_HTTPGET => TRUE, CURLOPT_URL => url($path, $options), CURLOPT_NOBODY => FALSE, CURLOPT_HTTPHEADER => $headers));
1982
    $this->refreshVariables(); // Ensure that any changes to variables in the other thread are picked up.
1983

    
1984
    // Replace original page output with new output from redirected page(s).
1985
    if ($new = $this->checkForMetaRefresh()) {
1986
      $out = $new;
1987
    }
1988
    $this->verbose('GET request to: ' . $path .
1989
                   '<hr />Ending URL: ' . $this->getUrl() .
1990
                   '<hr />' . $out);
1991
    return $out;
1992
  }
1993

    
1994
  /**
1995
   * Retrieve a Drupal path or an absolute path and JSON decode the result.
1996
   */
1997
  protected function drupalGetAJAX($path, array $options = array(), array $headers = array()) {
1998
    return drupal_json_decode($this->drupalGet($path, $options, $headers));
1999
  }
2000

    
2001
  /**
2002
   * Execute a POST request on a Drupal page.
2003
   * It will be done as usual POST request with SimpleBrowser.
2004
   *
2005
   * @param $path
2006
   *   Location of the post form. Either a Drupal path or an absolute path or
2007
   *   NULL to post to the current page. For multi-stage forms you can set the
2008
   *   path to NULL and have it post to the last received page. Example:
2009
   *
2010
   *   @code
2011
   *   // First step in form.
2012
   *   $edit = array(...);
2013
   *   $this->drupalPost('some_url', $edit, t('Save'));
2014
   *
2015
   *   // Second step in form.
2016
   *   $edit = array(...);
2017
   *   $this->drupalPost(NULL, $edit, t('Save'));
2018
   *   @endcode
2019
   * @param  $edit
2020
   *   Field data in an associative array. Changes the current input fields
2021
   *   (where possible) to the values indicated. A checkbox can be set to
2022
   *   TRUE to be checked and FALSE to be unchecked. Note that when a form
2023
   *   contains file upload fields, other fields cannot start with the '@'
2024
   *   character.
2025
   *
2026
   *   Multiple select fields can be set using name[] and setting each of the
2027
   *   possible values. Example:
2028
   *   @code
2029
   *   $edit = array();
2030
   *   $edit['name[]'] = array('value1', 'value2');
2031
   *   @endcode
2032
   * @param $submit
2033
   *   Value of the submit button whose click is to be emulated. For example,
2034
   *   t('Save'). The processing of the request depends on this value. For
2035
   *   example, a form may have one button with the value t('Save') and another
2036
   *   button with the value t('Delete'), and execute different code depending
2037
   *   on which one is clicked.
2038
   *
2039
   *   This function can also be called to emulate an Ajax submission. In this
2040
   *   case, this value needs to be an array with the following keys:
2041
   *   - path: A path to submit the form values to for Ajax-specific processing,
2042
   *     which is likely different than the $path parameter used for retrieving
2043
   *     the initial form. Defaults to 'system/ajax'.
2044
   *   - triggering_element: If the value for the 'path' key is 'system/ajax' or
2045
   *     another generic Ajax processing path, this needs to be set to the name
2046
   *     of the element. If the name doesn't identify the element uniquely, then
2047
   *     this should instead be an array with a single key/value pair,
2048
   *     corresponding to the element name and value. The callback for the
2049
   *     generic Ajax processing path uses this to find the #ajax information
2050
   *     for the element, including which specific callback to use for
2051
   *     processing the request.
2052
   *
2053
   *   This can also be set to NULL in order to emulate an Internet Explorer
2054
   *   submission of a form with a single text field, and pressing ENTER in that
2055
   *   textfield: under these conditions, no button information is added to the
2056
   *   POST data.
2057
   * @param $options
2058
   *   Options to be forwarded to url().
2059
   * @param $headers
2060
   *   An array containing additional HTTP request headers, each formatted as
2061
   *   "name: value".
2062
   * @param $form_html_id
2063
   *   (optional) HTML ID of the form to be submitted. On some pages
2064
   *   there are many identical forms, so just using the value of the submit
2065
   *   button is not enough. For example: 'trigger-node-presave-assign-form'.
2066
   *   Note that this is not the Drupal $form_id, but rather the HTML ID of the
2067
   *   form, which is typically the same thing but with hyphens replacing the
2068
   *   underscores.
2069
   * @param $extra_post
2070
   *   (optional) A string of additional data to append to the POST submission.
2071
   *   This can be used to add POST data for which there are no HTML fields, as
2072
   *   is done by drupalPostAJAX(). This string is literally appended to the
2073
   *   POST data, so it must already be urlencoded and contain a leading "&"
2074
   *   (e.g., "&extra_var1=hello+world&extra_var2=you%26me").
2075
   */
2076
  protected function drupalPost($path, $edit, $submit, array $options = array(), array $headers = array(), $form_html_id = NULL, $extra_post = NULL) {
2077
    $submit_matches = FALSE;
2078
    $ajax = is_array($submit);
2079
    if (isset($path)) {
2080
      $this->drupalGet($path, $options);
2081
    }
2082
    if ($this->parse()) {
2083
      $edit_save = $edit;
2084
      // Let's iterate over all the forms.
2085
      $xpath = "//form";
2086
      if (!empty($form_html_id)) {
2087
        $xpath .= "[@id='" . $form_html_id . "']";
2088
      }
2089
      $forms = $this->xpath($xpath);
2090
      foreach ($forms as $form) {
2091
        // We try to set the fields of this form as specified in $edit.
2092
        $edit = $edit_save;
2093
        $post = array();
2094
        $upload = array();
2095
        $submit_matches = $this->handleForm($post, $edit, $upload, $ajax ? NULL : $submit, $form);
2096
        $action = isset($form['action']) ? $this->getAbsoluteUrl((string) $form['action']) : $this->getUrl();
2097
        if ($ajax) {
2098
          $action = $this->getAbsoluteUrl(!empty($submit['path']) ? $submit['path'] : 'system/ajax');
2099
          // Ajax callbacks verify the triggering element if necessary, so while
2100
          // we may eventually want extra code that verifies it in the
2101
          // handleForm() function, it's not currently a requirement.
2102
          $submit_matches = TRUE;
2103
        }
2104

    
2105
        // We post only if we managed to handle every field in edit and the
2106
        // submit button matches.
2107
        if (!$edit && ($submit_matches || !isset($submit))) {
2108
          $post_array = $post;
2109
          if ($upload) {
2110
            // TODO: cURL handles file uploads for us, but the implementation
2111
            // is broken. This is a less than elegant workaround. Alternatives
2112
            // are being explored at #253506.
2113
            foreach ($upload as $key => $file) {
2114
              $file = drupal_realpath($file);
2115
              if ($file && is_file($file)) {
2116
                // Use the new CurlFile class for file uploads when using PHP
2117
                // 5.5 or higher.
2118
                if (class_exists('CurlFile')) {
2119
                  $post[$key] = curl_file_create($file);
2120
                }
2121
                else {
2122
                  $post[$key] = '@' . $file;
2123
                }
2124
              }
2125
            }
2126
          }
2127
          else {
2128
            foreach ($post as $key => $value) {
2129
              // Encode according to application/x-www-form-urlencoded
2130
              // Both names and values needs to be urlencoded, according to
2131
              // http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.1
2132
              $post[$key] = urlencode($key) . '=' . urlencode($value);
2133
            }
2134
            $post = implode('&', $post) . $extra_post;
2135
          }
2136
          $out = $this->curlExec(array(CURLOPT_URL => $action, CURLOPT_POST => TRUE, CURLOPT_POSTFIELDS => $post, CURLOPT_HTTPHEADER => $headers));
2137
          // Ensure that any changes to variables in the other thread are picked up.
2138
          $this->refreshVariables();
2139

    
2140
          // Replace original page output with new output from redirected page(s).
2141
          if ($new = $this->checkForMetaRefresh()) {
2142
            $out = $new;
2143
          }
2144
          $this->verbose('POST request to: ' . $path .
2145
                         '<hr />Ending URL: ' . $this->getUrl() .
2146
                         '<hr />Fields: ' . highlight_string('<?php ' . var_export($post_array, TRUE), TRUE) .
2147
                         '<hr />' . $out);
2148
          return $out;
2149
        }
2150
      }
2151
      // We have not found a form which contained all fields of $edit.
2152
      foreach ($edit as $name => $value) {
2153
        $this->fail(t('Failed to set field @name to @value', array('@name' => $name, '@value' => $value)));
2154
      }
2155
      if (!$ajax && isset($submit)) {
2156
        $this->assertTrue($submit_matches, t('Found the @submit button', array('@submit' => $submit)));
2157
      }
2158
      $this->fail(t('Found the requested form fields at @path', array('@path' => $path)));
2159
    }
2160
  }
2161

    
2162
  /**
2163
   * Execute an Ajax submission.
2164
   *
2165
   * This executes a POST as ajax.js does. It uses the returned JSON data, an
2166
   * array of commands, to update $this->content using equivalent DOM
2167
   * manipulation as is used by ajax.js. It also returns the array of commands.
2168
   *
2169
   * @param $path
2170
   *   Location of the form containing the Ajax enabled element to test. Can be
2171
   *   either a Drupal path or an absolute path or NULL to use the current page.
2172
   * @param $edit
2173
   *   Field data in an associative array. Changes the current input fields
2174
   *   (where possible) to the values indicated.
2175
   * @param $triggering_element
2176
   *   The name of the form element that is responsible for triggering the Ajax
2177
   *   functionality to test. May be a string or, if the triggering element is
2178
   *   a button, an associative array where the key is the name of the button
2179
   *   and the value is the button label. i.e.) array('op' => t('Refresh')).
2180
   * @param $ajax_path
2181
   *   (optional) Override the path set by the Ajax settings of the triggering
2182
   *   element. In the absence of both the triggering element's Ajax path and
2183
   *   $ajax_path 'system/ajax' will be used.
2184
   * @param $options
2185
   *   (optional) Options to be forwarded to url().
2186
   * @param $headers
2187
   *   (optional) An array containing additional HTTP request headers, each
2188
   *   formatted as "name: value". Forwarded to drupalPost().
2189
   * @param $form_html_id
2190
   *   (optional) HTML ID of the form to be submitted, use when there is more
2191
   *   than one identical form on the same page and the value of the triggering
2192
   *   element is not enough to identify the form. Note this is not the Drupal
2193
   *   ID of the form but rather the HTML ID of the form.
2194
   * @param $ajax_settings
2195
   *   (optional) An array of Ajax settings which if specified will be used in
2196
   *   place of the Ajax settings of the triggering element.
2197
   *
2198
   * @return
2199
   *   An array of Ajax commands.
2200
   *
2201
   * @see drupalPost()
2202
   * @see ajax.js
2203
   */
2204
  protected function drupalPostAJAX($path, $edit, $triggering_element, $ajax_path = NULL, array $options = array(), array $headers = array(), $form_html_id = NULL, $ajax_settings = NULL) {
2205
    // Get the content of the initial page prior to calling drupalPost(), since
2206
    // drupalPost() replaces $this->content.
2207
    if (isset($path)) {
2208
      $this->drupalGet($path, $options);
2209
    }
2210
    $content = $this->content;
2211
    $drupal_settings = $this->drupalSettings;
2212

    
2213
    // Get the Ajax settings bound to the triggering element.
2214
    if (!isset($ajax_settings)) {
2215
      if (is_array($triggering_element)) {
2216
        $xpath = '//*[@name="' . key($triggering_element) . '" and @value="' . current($triggering_element) . '"]';
2217
      }
2218
      else {
2219
        $xpath = '//*[@name="' . $triggering_element . '"]';
2220
      }
2221
      if (isset($form_html_id)) {
2222
        $xpath = '//form[@id="' . $form_html_id . '"]' . $xpath;
2223
      }
2224
      $element = $this->xpath($xpath);
2225
      $element_id = (string) $element[0]['id'];
2226
      $ajax_settings = $drupal_settings['ajax'][$element_id];
2227
    }
2228

    
2229
    // Add extra information to the POST data as ajax.js does.
2230
    $extra_post = '';
2231
    if (isset($ajax_settings['submit'])) {
2232
      foreach ($ajax_settings['submit'] as $key => $value) {
2233
        $extra_post .= '&' . urlencode($key) . '=' . urlencode($value);
2234
      }
2235
    }
2236
    foreach ($this->xpath('//*[@id]') as $element) {
2237
      $id = (string) $element['id'];
2238
      $extra_post .= '&' . urlencode('ajax_html_ids[]') . '=' . urlencode($id);
2239
    }
2240
    if (isset($drupal_settings['ajaxPageState'])) {
2241
      $extra_post .= '&' . urlencode('ajax_page_state[theme]') . '=' . urlencode($drupal_settings['ajaxPageState']['theme']);
2242
      $extra_post .= '&' . urlencode('ajax_page_state[theme_token]') . '=' . urlencode($drupal_settings['ajaxPageState']['theme_token']);
2243
      foreach ($drupal_settings['ajaxPageState']['css'] as $key => $value) {
2244
        $extra_post .= '&' . urlencode("ajax_page_state[css][$key]") . '=1';
2245
      }
2246
      foreach ($drupal_settings['ajaxPageState']['js'] as $key => $value) {
2247
        $extra_post .= '&' . urlencode("ajax_page_state[js][$key]") . '=1';
2248
      }
2249
    }
2250

    
2251
    // Unless a particular path is specified, use the one specified by the
2252
    // Ajax settings, or else 'system/ajax'.
2253
    if (!isset($ajax_path)) {
2254
      $ajax_path = isset($ajax_settings['url']) ? $ajax_settings['url'] : 'system/ajax';
2255
    }
2256

    
2257
    // Submit the POST request.
2258
    $return = drupal_json_decode($this->drupalPost(NULL, $edit, array('path' => $ajax_path, 'triggering_element' => $triggering_element), $options, $headers, $form_html_id, $extra_post));
2259
    $this->assertIdentical($this->drupalGetHeader('X-Drupal-Ajax-Token'), '1', 'Ajax response header found.');
2260

    
2261
    // Change the page content by applying the returned commands.
2262
    if (!empty($ajax_settings) && !empty($return)) {
2263
      // ajax.js applies some defaults to the settings object, so do the same
2264
      // for what's used by this function.
2265
      $ajax_settings += array(
2266
        'method' => 'replaceWith',
2267
      );
2268
      // DOM can load HTML soup. But, HTML soup can throw warnings, suppress
2269
      // them.
2270
      $dom = new DOMDocument();
2271
      @$dom->loadHTML($content);
2272
      // XPath allows for finding wrapper nodes better than DOM does.
2273
      $xpath = new DOMXPath($dom);
2274
      foreach ($return as $command) {
2275
        switch ($command['command']) {
2276
          case 'settings':
2277
            $drupal_settings = drupal_array_merge_deep($drupal_settings, $command['settings']);
2278
            break;
2279

    
2280
          case 'insert':
2281
            $wrapperNode = NULL;
2282
            // When a command doesn't specify a selector, use the
2283
            // #ajax['wrapper'] which is always an HTML ID.
2284
            if (!isset($command['selector'])) {
2285
              $wrapperNode = $xpath->query('//*[@id="' . $ajax_settings['wrapper'] . '"]')->item(0);
2286
            }
2287
            // @todo Ajax commands can target any jQuery selector, but these are
2288
            //   hard to fully emulate with XPath. For now, just handle 'head'
2289
            //   and 'body', since these are used by ajax_render().
2290
            elseif (in_array($command['selector'], array('head', 'body'))) {
2291
              $wrapperNode = $xpath->query('//' . $command['selector'])->item(0);
2292
            }
2293
            if ($wrapperNode) {
2294
              // ajax.js adds an enclosing DIV to work around a Safari bug.
2295
              $newDom = new DOMDocument();
2296
              // DOM can load HTML soup. But, HTML soup can throw warnings,
2297
              // suppress them.
2298
              $newDom->loadHTML('<div>' . $command['data'] . '</div>');
2299
              // Suppress warnings thrown when duplicate HTML IDs are
2300
              // encountered. This probably means we are replacing an element
2301
              // with the same ID.
2302
              $newNode = @$dom->importNode($newDom->documentElement->firstChild->firstChild, TRUE);
2303
              $method = isset($command['method']) ? $command['method'] : $ajax_settings['method'];
2304
              // The "method" is a jQuery DOM manipulation function. Emulate
2305
              // each one using PHP's DOMNode API.
2306
              switch ($method) {
2307
                case 'replaceWith':
2308
                  $wrapperNode->parentNode->replaceChild($newNode, $wrapperNode);
2309
                  break;
2310
                case 'append':
2311
                  $wrapperNode->appendChild($newNode);
2312
                  break;
2313
                case 'prepend':
2314
                  // If no firstChild, insertBefore() falls back to
2315
                  // appendChild().
2316
                  $wrapperNode->insertBefore($newNode, $wrapperNode->firstChild);
2317
                  break;
2318
                case 'before':
2319
                  $wrapperNode->parentNode->insertBefore($newNode, $wrapperNode);
2320
                  break;
2321
                case 'after':
2322
                  // If no nextSibling, insertBefore() falls back to
2323
                  // appendChild().
2324
                  $wrapperNode->parentNode->insertBefore($newNode, $wrapperNode->nextSibling);
2325
                  break;
2326
                case 'html':
2327
                  foreach ($wrapperNode->childNodes as $childNode) {
2328
                    $wrapperNode->removeChild($childNode);
2329
                  }
2330
                  $wrapperNode->appendChild($newNode);
2331
                  break;
2332
              }
2333
            }
2334
            break;
2335

    
2336
          case 'updateBuildId':
2337
            $buildId = $xpath->query('//input[@name="form_build_id" and @value="' . $command['old'] . '"]')->item(0);
2338
            if ($buildId) {
2339
              $buildId->setAttribute('value', $command['new']);
2340
            }
2341
            break;
2342

    
2343
          // @todo Add suitable implementations for these commands in order to
2344
          //   have full test coverage of what ajax.js can do.
2345
          case 'remove':
2346
            break;
2347
          case 'changed':
2348
            break;
2349
          case 'css':
2350
            break;
2351
          case 'data':
2352
            break;
2353
          case 'restripe':
2354
            break;
2355
          case 'add_css':
2356
            break;
2357
        }
2358
      }
2359
      $content = $dom->saveHTML();
2360
    }
2361
    $this->drupalSetContent($content);
2362
    $this->drupalSetSettings($drupal_settings);
2363

    
2364
    $verbose = 'AJAX POST request to: ' . $path;
2365
    $verbose .= '<br />AJAX callback path: ' . $ajax_path;
2366
    $verbose .= '<hr />Ending URL: ' . $this->getUrl();
2367
    $verbose .= '<hr />' . $this->content;
2368

    
2369
    $this->verbose($verbose);
2370

    
2371
    return $return;
2372
  }
2373

    
2374
  /**
2375
   * Runs cron in the Drupal installed by Simpletest.
2376
   */
2377
  protected function cronRun() {
2378
    $this->drupalGet($GLOBALS['base_url'] . '/cron.php', array('external' => TRUE, 'query' => array('cron_key' => variable_get('cron_key', 'drupal'))));
2379
  }
2380

    
2381
  /**
2382
   * Check for meta refresh tag and if found call drupalGet() recursively. This
2383
   * function looks for the http-equiv attribute to be set to "Refresh"
2384
   * and is case-sensitive.
2385
   *
2386
   * @return
2387
   *   Either the new page content or FALSE.
2388
   */
2389
  protected function checkForMetaRefresh() {
2390
    if (strpos($this->drupalGetContent(), '<meta ') && $this->parse()) {
2391
      $refresh = $this->xpath('//meta[@http-equiv="Refresh"]');
2392
      if (!empty($refresh)) {
2393
        // Parse the content attribute of the meta tag for the format:
2394
        // "[delay]: URL=[page_to_redirect_to]".
2395
        if (preg_match('/\d+;\s*URL=(?P<url>.*)/i', $refresh[0]['content'], $match)) {
2396
          return $this->drupalGet($this->getAbsoluteUrl(decode_entities($match['url'])));
2397
        }
2398
      }
2399
    }
2400
    return FALSE;
2401
  }
2402

    
2403
  /**
2404
   * Retrieves only the headers for a Drupal path or an absolute path.
2405
   *
2406
   * @param $path
2407
   *   Drupal path or URL to load into internal browser
2408
   * @param $options
2409
   *   Options to be forwarded to url().
2410
   * @param $headers
2411
   *   An array containing additional HTTP request headers, each formatted as
2412
   *   "name: value".
2413
   * @return
2414
   *   The retrieved headers, also available as $this->drupalGetContent()
2415
   */
2416
  protected function drupalHead($path, array $options = array(), array $headers = array()) {
2417
    $options['absolute'] = TRUE;
2418
    $out = $this->curlExec(array(CURLOPT_NOBODY => TRUE, CURLOPT_URL => url($path, $options), CURLOPT_HTTPHEADER => $headers));
2419
    $this->refreshVariables(); // Ensure that any changes to variables in the other thread are picked up.
2420
    return $out;
2421
  }
2422

    
2423
  /**
2424
   * Handle form input related to drupalPost(). Ensure that the specified fields
2425
   * exist and attempt to create POST data in the correct manner for the particular
2426
   * field type.
2427
   *
2428
   * @param $post
2429
   *   Reference to array of post values.
2430
   * @param $edit
2431
   *   Reference to array of edit values to be checked against the form.
2432
   * @param $submit
2433
   *   Form submit button value.
2434
   * @param $form
2435
   *   Array of form elements.
2436
   * @return
2437
   *   Submit value matches a valid submit input in the form.
2438
   */
2439
  protected function handleForm(&$post, &$edit, &$upload, $submit, $form) {
2440
    // Retrieve the form elements.
2441
    $elements = $form->xpath('.//input[not(@disabled)]|.//textarea[not(@disabled)]|.//select[not(@disabled)]');
2442
    $submit_matches = FALSE;
2443
    foreach ($elements as $element) {
2444
      // SimpleXML objects need string casting all the time.
2445
      $name = (string) $element['name'];
2446
      // This can either be the type of <input> or the name of the tag itself
2447
      // for <select> or <textarea>.
2448
      $type = isset($element['type']) ? (string) $element['type'] : $element->getName();
2449
      $value = isset($element['value']) ? (string) $element['value'] : '';
2450
      $done = FALSE;
2451
      if (isset($edit[$name])) {
2452
        switch ($type) {
2453
          case 'text':
2454
          case 'tel':
2455
          case 'textarea':
2456
          case 'url':
2457
          case 'number':
2458
          case 'range':
2459
          case 'color':
2460
          case 'hidden':
2461
          case 'password':
2462
          case 'email':
2463
          case 'search':
2464
            $post[$name] = $edit[$name];
2465
            unset($edit[$name]);
2466
            break;
2467
          case 'radio':
2468
            if ($edit[$name] == $value) {
2469
              $post[$name] = $edit[$name];
2470
              unset($edit[$name]);
2471
            }
2472
            break;
2473
          case 'checkbox':
2474
            // To prevent checkbox from being checked.pass in a FALSE,
2475
            // otherwise the checkbox will be set to its value regardless
2476
            // of $edit.
2477
            if ($edit[$name] === FALSE) {
2478
              unset($edit[$name]);
2479
              continue 2;
2480
            }
2481
            else {
2482
              unset($edit[$name]);
2483
              $post[$name] = $value;
2484
            }
2485
            break;
2486
          case 'select':
2487
            $new_value = $edit[$name];
2488
            $options = $this->getAllOptions($element);
2489
            if (is_array($new_value)) {
2490
              // Multiple select box.
2491
              if (!empty($new_value)) {
2492
                $index = 0;
2493
                $key = preg_replace('/\[\]$/', '', $name);
2494
                foreach ($options as $option) {
2495
                  $option_value = (string) $option['value'];
2496
                  if (in_array($option_value, $new_value)) {
2497
                    $post[$key . '[' . $index++ . ']'] = $option_value;
2498
                    $done = TRUE;
2499
                    unset($edit[$name]);
2500
                  }
2501
                }
2502
              }
2503
              else {
2504
                // No options selected: do not include any POST data for the
2505
                // element.
2506
                $done = TRUE;
2507
                unset($edit[$name]);
2508
              }
2509
            }
2510
            else {
2511
              // Single select box.
2512
              foreach ($options as $option) {
2513
                if ($new_value == $option['value']) {
2514
                  $post[$name] = $new_value;
2515
                  unset($edit[$name]);
2516
                  $done = TRUE;
2517
                  break;
2518
                }
2519
              }
2520
            }
2521
            break;
2522
          case 'file':
2523
            $upload[$name] = $edit[$name];
2524
            unset($edit[$name]);
2525
            break;
2526
        }
2527
      }
2528
      if (!isset($post[$name]) && !$done) {
2529
        switch ($type) {
2530
          case 'textarea':
2531
            $post[$name] = (string) $element;
2532
            break;
2533
          case 'select':
2534
            $single = empty($element['multiple']);
2535
            $first = TRUE;
2536
            $index = 0;
2537
            $key = preg_replace('/\[\]$/', '', $name);
2538
            $options = $this->getAllOptions($element);
2539
            foreach ($options as $option) {
2540
              // For single select, we load the first option, if there is a
2541
              // selected option that will overwrite it later.
2542
              if ($option['selected'] || ($first && $single)) {
2543
                $first = FALSE;
2544
                if ($single) {
2545
                  $post[$name] = (string) $option['value'];
2546
                }
2547
                else {
2548
                  $post[$key . '[' . $index++ . ']'] = (string) $option['value'];
2549
                }
2550
              }
2551
            }
2552
            break;
2553
          case 'file':
2554
            break;
2555
          case 'submit':
2556
          case 'image':
2557
            if (isset($submit) && $submit == $value) {
2558
              $post[$name] = $value;
2559
              $submit_matches = TRUE;
2560
            }
2561
            break;
2562
          case 'radio':
2563
          case 'checkbox':
2564
            if (!isset($element['checked'])) {
2565
              break;
2566
            }
2567
            // Deliberate no break.
2568
          default:
2569
            $post[$name] = $value;
2570
        }
2571
      }
2572
    }
2573
    return $submit_matches;
2574
  }
2575

    
2576
  /**
2577
   * Builds an XPath query.
2578
   *
2579
   * Builds an XPath query by replacing placeholders in the query by the value
2580
   * of the arguments.
2581
   *
2582
   * XPath 1.0 (the version supported by libxml2, the underlying XML library
2583
   * used by PHP) doesn't support any form of quotation. This function
2584
   * simplifies the building of XPath expression.
2585
   *
2586
   * @param $xpath
2587
   *   An XPath query, possibly with placeholders in the form ':name'.
2588
   * @param $args
2589
   *   An array of arguments with keys in the form ':name' matching the
2590
   *   placeholders in the query. The values may be either strings or numeric
2591
   *   values.
2592
   * @return
2593
   *   An XPath query with arguments replaced.
2594
   */
2595
  protected function buildXPathQuery($xpath, array $args = array()) {
2596
    // Replace placeholders.
2597
    foreach ($args as $placeholder => $value) {
2598
      // XPath 1.0 doesn't support a way to escape single or double quotes in a
2599
      // string literal. We split double quotes out of the string, and encode
2600
      // them separately.
2601
      if (is_string($value)) {
2602
        // Explode the text at the quote characters.
2603
        $parts = explode('"', $value);
2604

    
2605
        // Quote the parts.
2606
        foreach ($parts as &$part) {
2607
          $part = '"' . $part . '"';
2608
        }
2609

    
2610
        // Return the string.
2611
        $value = count($parts) > 1 ? 'concat(' . implode(', \'"\', ', $parts) . ')' : $parts[0];
2612
      }
2613
      $xpath = preg_replace('/' . preg_quote($placeholder) . '\b/', $value, $xpath);
2614
    }
2615
    return $xpath;
2616
  }
2617

    
2618
  /**
2619
   * Perform an xpath search on the contents of the internal browser. The search
2620
   * is relative to the root element (HTML tag normally) of the page.
2621
   *
2622
   * @param $xpath
2623
   *   The xpath string to use in the search.
2624
   * @param array $arguments
2625
   *   An array of arguments with keys in the form ':name' matching the
2626
   *   placeholders in the query. The values may be either strings or numeric
2627
   *   values.
2628
   *
2629
   * @return
2630
   *   The return value of the xpath search. For details on the xpath string
2631
   *   format and return values see the SimpleXML documentation,
2632
   *   http://us.php.net/manual/function.simplexml-element-xpath.php.
2633
   */
2634
  protected function xpath($xpath, array $arguments = array()) {
2635
    if ($this->parse()) {
2636
      $xpath = $this->buildXPathQuery($xpath, $arguments);
2637
      $result = $this->elements->xpath($xpath);
2638
      // Some combinations of PHP / libxml versions return an empty array
2639
      // instead of the documented FALSE. Forcefully convert any falsish values
2640
      // to an empty array to allow foreach(...) constructions.
2641
      return $result ? $result : array();
2642
    }
2643
    else {
2644
      return FALSE;
2645
    }
2646
  }
2647

    
2648
  /**
2649
   * Get all option elements, including nested options, in a select.
2650
   *
2651
   * @param $element
2652
   *   The element for which to get the options.
2653
   * @return
2654
   *   Option elements in select.
2655
   */
2656
  protected function getAllOptions(SimpleXMLElement $element) {
2657
    $options = array();
2658
    // Add all options items.
2659
    foreach ($element->option as $option) {
2660
      $options[] = $option;
2661
    }
2662

    
2663
    // Search option group children.
2664
    if (isset($element->optgroup)) {
2665
      foreach ($element->optgroup as $group) {
2666
        $options = array_merge($options, $this->getAllOptions($group));
2667
      }
2668
    }
2669
    return $options;
2670
  }
2671

    
2672
  /**
2673
   * Pass if a link with the specified label is found, and optional with the
2674
   * specified index.
2675
   *
2676
   * @param $label
2677
   *   Text between the anchor tags.
2678
   * @param $index
2679
   *   Link position counting from zero.
2680
   * @param $message
2681
   *   Message to display.
2682
   * @param $group
2683
   *   The group this message belongs to, defaults to 'Other'.
2684
   * @return
2685
   *   TRUE if the assertion succeeded, FALSE otherwise.
2686
   */
2687
  protected function assertLink($label, $index = 0, $message = '', $group = 'Other') {
2688
    $links = $this->xpath('//a[normalize-space(text())=:label]', array(':label' => $label));
2689
    $message = ($message ?  $message : t('Link with label %label found.', array('%label' => $label)));
2690
    return $this->assert(isset($links[$index]), $message, $group);
2691
  }
2692

    
2693
  /**
2694
   * Pass if a link with the specified label is not found.
2695
   *
2696
   * @param $label
2697
   *   Text between the anchor tags.
2698
   * @param $message
2699
   *   Message to display.
2700
   * @param $group
2701
   *   The group this message belongs to, defaults to 'Other'.
2702
   * @return
2703
   *   TRUE if the assertion succeeded, FALSE otherwise.
2704
   */
2705
  protected function assertNoLink($label, $message = '', $group = 'Other') {
2706
    $links = $this->xpath('//a[normalize-space(text())=:label]', array(':label' => $label));
2707
    $message = ($message ?  $message : t('Link with label %label not found.', array('%label' => $label)));
2708
    return $this->assert(empty($links), $message, $group);
2709
  }
2710

    
2711
  /**
2712
   * Pass if a link containing a given href (part) is found.
2713
   *
2714
   * @param $href
2715
   *   The full or partial value of the 'href' attribute of the anchor tag.
2716
   * @param $index
2717
   *   Link position counting from zero.
2718
   * @param $message
2719
   *   Message to display.
2720
   * @param $group
2721
   *   The group this message belongs to, defaults to 'Other'.
2722
   *
2723
   * @return
2724
   *   TRUE if the assertion succeeded, FALSE otherwise.
2725
   */
2726
  protected function assertLinkByHref($href, $index = 0, $message = '', $group = 'Other') {
2727
    $links = $this->xpath('//a[contains(@href, :href)]', array(':href' => $href));
2728
    $message = ($message ?  $message : t('Link containing href %href found.', array('%href' => $href)));
2729
    return $this->assert(isset($links[$index]), $message, $group);
2730
  }
2731

    
2732
  /**
2733
   * Pass if a link containing a given href (part) is not found.
2734
   *
2735
   * @param $href
2736
   *   The full or partial value of the 'href' attribute of the anchor tag.
2737
   * @param $message
2738
   *   Message to display.
2739
   * @param $group
2740
   *   The group this message belongs to, defaults to 'Other'.
2741
   *
2742
   * @return
2743
   *   TRUE if the assertion succeeded, FALSE otherwise.
2744
   */
2745
  protected function assertNoLinkByHref($href, $message = '', $group = 'Other') {
2746
    $links = $this->xpath('//a[contains(@href, :href)]', array(':href' => $href));
2747
    $message = ($message ?  $message : t('No link containing href %href found.', array('%href' => $href)));
2748
    return $this->assert(empty($links), $message, $group);
2749
  }
2750

    
2751
  /**
2752
   * Follows a link by name.
2753
   *
2754
   * Will click the first link found with this link text by default, or a later
2755
   * one if an index is given. Match is case sensitive with normalized space.
2756
   * The label is translated label.
2757
   *
2758
   * If the link is discovered and clicked, the test passes. Fail otherwise.
2759
   *
2760
   * @param $label
2761
   *   Text between the anchor tags.
2762
   * @param $index
2763
   *   Link position counting from zero.
2764
   * @return
2765
   *   Page contents on success, or FALSE on failure.
2766
   */
2767
  protected function clickLink($label, $index = 0) {
2768
    $url_before = $this->getUrl();
2769
    $urls = $this->xpath('//a[normalize-space(text())=:label]', array(':label' => $label));
2770
    if (isset($urls[$index])) {
2771
      $url_target = $this->getAbsoluteUrl($urls[$index]['href']);
2772
      $this->pass(t('Clicked link %label (@url_target) from @url_before', array('%label' => $label, '@url_target' => $url_target, '@url_before' => $url_before)), 'Browser');
2773
      return $this->drupalGet($url_target);
2774
    }
2775
    $this->fail(t('Link %label does not exist on @url_before', array('%label' => $label, '@url_before' => $url_before)), 'Browser');
2776
    return FALSE;
2777
  }
2778

    
2779
  /**
2780
   * Takes a path and returns an absolute path.
2781
   *
2782
   * @param $path
2783
   *   A path from the internal browser content.
2784
   * @return
2785
   *   The $path with $base_url prepended, if necessary.
2786
   */
2787
  protected function getAbsoluteUrl($path) {
2788
    global $base_url, $base_path;
2789

    
2790
    $parts = parse_url($path);
2791
    if (empty($parts['host'])) {
2792
      // Ensure that we have a string (and no xpath object).
2793
      $path = (string) $path;
2794
      // Strip $base_path, if existent.
2795
      $length = strlen($base_path);
2796
      if (substr($path, 0, $length) === $base_path) {
2797
        $path = substr($path, $length);
2798
      }
2799
      // Ensure that we have an absolute path.
2800
      if (empty($path) || $path[0] !== '/') {
2801
        $path = '/' . $path;
2802
      }
2803
      // Finally, prepend the $base_url.
2804
      $path = $base_url . $path;
2805
    }
2806
    return $path;
2807
  }
2808

    
2809
  /**
2810
   * Get the current URL from the cURL handler.
2811
   *
2812
   * @return
2813
   *   The current URL.
2814
   */
2815
  protected function getUrl() {
2816
    return $this->url;
2817
  }
2818

    
2819
  /**
2820
   * Gets the HTTP response headers of the requested page. Normally we are only
2821
   * interested in the headers returned by the last request. However, if a page
2822
   * is redirected or HTTP authentication is in use, multiple requests will be
2823
   * required to retrieve the page. Headers from all requests may be requested
2824
   * by passing TRUE to this function.
2825
   *
2826
   * @param $all_requests
2827
   *   Boolean value specifying whether to return headers from all requests
2828
   *   instead of just the last request. Defaults to FALSE.
2829
   * @return
2830
   *   A name/value array if headers from only the last request are requested.
2831
   *   If headers from all requests are requested, an array of name/value
2832
   *   arrays, one for each request.
2833
   *
2834
   *   The pseudonym ":status" is used for the HTTP status line.
2835
   *
2836
   *   Values for duplicate headers are stored as a single comma-separated list.
2837
   */
2838
  protected function drupalGetHeaders($all_requests = FALSE) {
2839
    $request = 0;
2840
    $headers = array($request => array());
2841
    foreach ($this->headers as $header) {
2842
      $header = trim($header);
2843
      if ($header === '') {
2844
        $request++;
2845
      }
2846
      else {
2847
        if (strpos($header, 'HTTP/') === 0) {
2848
          $name = ':status';
2849
          $value = $header;
2850
        }
2851
        else {
2852
          list($name, $value) = explode(':', $header, 2);
2853
          $name = strtolower($name);
2854
        }
2855
        if (isset($headers[$request][$name])) {
2856
          $headers[$request][$name] .= ',' . trim($value);
2857
        }
2858
        else {
2859
          $headers[$request][$name] = trim($value);
2860
        }
2861
      }
2862
    }
2863
    if (!$all_requests) {
2864
      $headers = array_pop($headers);
2865
    }
2866
    return $headers;
2867
  }
2868

    
2869
  /**
2870
   * Gets the value of an HTTP response header. If multiple requests were
2871
   * required to retrieve the page, only the headers from the last request will
2872
   * be checked by default. However, if TRUE is passed as the second argument,
2873
   * all requests will be processed from last to first until the header is
2874
   * found.
2875
   *
2876
   * @param $name
2877
   *   The name of the header to retrieve. Names are case-insensitive (see RFC
2878
   *   2616 section 4.2).
2879
   * @param $all_requests
2880
   *   Boolean value specifying whether to check all requests if the header is
2881
   *   not found in the last request. Defaults to FALSE.
2882
   * @return
2883
   *   The HTTP header value or FALSE if not found.
2884
   */
2885
  protected function drupalGetHeader($name, $all_requests = FALSE) {
2886
    $name = strtolower($name);
2887
    $header = FALSE;
2888
    if ($all_requests) {
2889
      foreach (array_reverse($this->drupalGetHeaders(TRUE)) as $headers) {
2890
        if (isset($headers[$name])) {
2891
          $header = $headers[$name];
2892
          break;
2893
        }
2894
      }
2895
    }
2896
    else {
2897
      $headers = $this->drupalGetHeaders();
2898
      if (isset($headers[$name])) {
2899
        $header = $headers[$name];
2900
      }
2901
    }
2902
    return $header;
2903
  }
2904

    
2905
  /**
2906
   * Gets the current raw HTML of requested page.
2907
   */
2908
  protected function drupalGetContent() {
2909
    return $this->content;
2910
  }
2911

    
2912
  /**
2913
   * Gets the value of the Drupal.settings JavaScript variable for the currently loaded page.
2914
   */
2915
  protected function drupalGetSettings() {
2916
    return $this->drupalSettings;
2917
  }
2918

    
2919
  /**
2920
   * Gets an array containing all e-mails sent during this test case.
2921
   *
2922
   * @param $filter
2923
   *   An array containing key/value pairs used to filter the e-mails that are returned.
2924
   * @return
2925
   *   An array containing e-mail messages captured during the current test.
2926
   */
2927
  protected function drupalGetMails($filter = array()) {
2928
    $captured_emails = variable_get('drupal_test_email_collector', array());
2929
    $filtered_emails = array();
2930

    
2931
    foreach ($captured_emails as $message) {
2932
      foreach ($filter as $key => $value) {
2933
        if (!isset($message[$key]) || $message[$key] != $value) {
2934
          continue 2;
2935
        }
2936
      }
2937
      $filtered_emails[] = $message;
2938
    }
2939

    
2940
    return $filtered_emails;
2941
  }
2942

    
2943
  /**
2944
   * Sets the raw HTML content. This can be useful when a page has been fetched
2945
   * outside of the internal browser and assertions need to be made on the
2946
   * returned page.
2947
   *
2948
   * A good example would be when testing drupal_http_request(). After fetching
2949
   * the page the content can be set and page elements can be checked to ensure
2950
   * that the function worked properly.
2951
   */
2952
  protected function drupalSetContent($content, $url = 'internal:') {
2953
    $this->content = $content;
2954
    $this->url = $url;
2955
    $this->plainTextContent = FALSE;
2956
    $this->elements = FALSE;
2957
    $this->drupalSettings = array();
2958
    if (preg_match('/jQuery\.extend\(Drupal\.settings, (.*?)\);/', $content, $matches)) {
2959
      $this->drupalSettings = drupal_json_decode($matches[1]);
2960
    }
2961
  }
2962

    
2963
  /**
2964
   * Sets the value of the Drupal.settings JavaScript variable for the currently loaded page.
2965
   */
2966
  protected function drupalSetSettings($settings) {
2967
    $this->drupalSettings = $settings;
2968
  }
2969

    
2970
  /**
2971
   * Pass if the internal browser's URL matches the given path.
2972
   *
2973
   * @param $path
2974
   *   The expected system path.
2975
   * @param $options
2976
   *   (optional) Any additional options to pass for $path to url().
2977
   * @param $message
2978
   *   Message to display.
2979
   * @param $group
2980
   *   The group this message belongs to, defaults to 'Other'.
2981
   *
2982
   * @return
2983
   *   TRUE on pass, FALSE on fail.
2984
   */
2985
  protected function assertUrl($path, array $options = array(), $message = '', $group = 'Other') {
2986
    if (!$message) {
2987
      $message = t('Current URL is @url.', array(
2988
        '@url' => var_export(url($path, $options), TRUE),
2989
      ));
2990
    }
2991
    $options['absolute'] = TRUE;
2992
    return $this->assertEqual($this->getUrl(), url($path, $options), $message, $group);
2993
  }
2994

    
2995
  /**
2996
   * Pass if the raw text IS found on the loaded page, fail otherwise. Raw text
2997
   * refers to the raw HTML that the page generated.
2998
   *
2999
   * @param $raw
3000
   *   Raw (HTML) string to look for.
3001
   * @param $message
3002
   *   Message to display.
3003
   * @param $group
3004
   *   The group this message belongs to, defaults to 'Other'.
3005
   * @return
3006
   *   TRUE on pass, FALSE on fail.
3007
   */
3008
  protected function assertRaw($raw, $message = '', $group = 'Other') {
3009
    if (!$message) {
3010
      $message = t('Raw "@raw" found', array('@raw' => $raw));
3011
    }
3012
    return $this->assert(strpos($this->drupalGetContent(), (string) $raw) !== FALSE, $message, $group);
3013
  }
3014

    
3015
  /**
3016
   * Pass if the raw text is NOT found on the loaded page, fail otherwise. Raw text
3017
   * refers to the raw HTML that the page generated.
3018
   *
3019
   * @param $raw
3020
   *   Raw (HTML) string to look for.
3021
   * @param $message
3022
   *   Message to display.
3023
   * @param $group
3024
   *   The group this message belongs to, defaults to 'Other'.
3025
   * @return
3026
   *   TRUE on pass, FALSE on fail.
3027
   */
3028
  protected function assertNoRaw($raw, $message = '', $group = 'Other') {
3029
    if (!$message) {
3030
      $message = t('Raw "@raw" not found', array('@raw' => $raw));
3031
    }
3032
    return $this->assert(strpos($this->drupalGetContent(), (string) $raw) === FALSE, $message, $group);
3033
  }
3034

    
3035
  /**
3036
   * Pass if the text IS found on the text version of the page. The text version
3037
   * is the equivalent of what a user would see when viewing through a web browser.
3038
   * In other words the HTML has been filtered out of the contents.
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, defaults to 'Other'.
3046
   * @return
3047
   *   TRUE on pass, FALSE on fail.
3048
   */
3049
  protected function assertText($text, $message = '', $group = 'Other') {
3050
    return $this->assertTextHelper($text, $message, $group, FALSE);
3051
  }
3052

    
3053
  /**
3054
   * Pass if the text is NOT found on the text version of the page. The text version
3055
   * is the equivalent of what a user would see when viewing through a web browser.
3056
   * In other words the HTML has been filtered out of the contents.
3057
   *
3058
   * @param $text
3059
   *   Plain text to look for.
3060
   * @param $message
3061
   *   Message to display.
3062
   * @param $group
3063
   *   The group this message belongs to, defaults to 'Other'.
3064
   * @return
3065
   *   TRUE on pass, FALSE on fail.
3066
   */
3067
  protected function assertNoText($text, $message = '', $group = 'Other') {
3068
    return $this->assertTextHelper($text, $message, $group, TRUE);
3069
  }
3070

    
3071
  /**
3072
   * Helper for assertText and assertNoText.
3073
   *
3074
   * It is not recommended to call this function directly.
3075
   *
3076
   * @param $text
3077
   *   Plain text to look for.
3078
   * @param $message
3079
   *   Message to display.
3080
   * @param $group
3081
   *   The group this message belongs to.
3082
   * @param $not_exists
3083
   *   TRUE if this text should not exist, FALSE if it should.
3084
   * @return
3085
   *   TRUE on pass, FALSE on fail.
3086
   */
3087
  protected function assertTextHelper($text, $message = '', $group, $not_exists) {
3088
    if ($this->plainTextContent === FALSE) {
3089
      $this->plainTextContent = filter_xss($this->drupalGetContent(), array());
3090
    }
3091
    if (!$message) {
3092
      $message = !$not_exists ? t('"@text" found', array('@text' => $text)) : t('"@text" not found', array('@text' => $text));
3093
    }
3094
    return $this->assert($not_exists == (strpos($this->plainTextContent, $text) === FALSE), $message, $group);
3095
  }
3096

    
3097
  /**
3098
   * Pass if the text is found ONLY ONCE on the text version of the page.
3099
   *
3100
   * The text version is the equivalent of what a user would see when viewing
3101
   * through a web browser. In other words the HTML has been filtered out of
3102
   * the contents.
3103
   *
3104
   * @param $text
3105
   *   Plain text to look for.
3106
   * @param $message
3107
   *   Message to display.
3108
   * @param $group
3109
   *   The group this message belongs to, defaults to 'Other'.
3110
   * @return
3111
   *   TRUE on pass, FALSE on fail.
3112
   */
3113
  protected function assertUniqueText($text, $message = '', $group = 'Other') {
3114
    return $this->assertUniqueTextHelper($text, $message, $group, TRUE);
3115
  }
3116

    
3117
  /**
3118
   * Pass if the text is found MORE THAN ONCE on the text version of the page.
3119
   *
3120
   * The text version is the equivalent of what a user would see when viewing
3121
   * through a web browser. In other words the HTML has been filtered out of
3122
   * the contents.
3123
   *
3124
   * @param $text
3125
   *   Plain text to look for.
3126
   * @param $message
3127
   *   Message to display.
3128
   * @param $group
3129
   *   The group this message belongs to, defaults to 'Other'.
3130
   * @return
3131
   *   TRUE on pass, FALSE on fail.
3132
   */
3133
  protected function assertNoUniqueText($text, $message = '', $group = 'Other') {
3134
    return $this->assertUniqueTextHelper($text, $message, $group, FALSE);
3135
  }
3136

    
3137
  /**
3138
   * Helper for assertUniqueText and assertNoUniqueText.
3139
   *
3140
   * It is not recommended to call this function directly.
3141
   *
3142
   * @param $text
3143
   *   Plain text to look for.
3144
   * @param $message
3145
   *   Message to display.
3146
   * @param $group
3147
   *   The group this message belongs to.
3148
   * @param $be_unique
3149
   *   TRUE if this text should be found only once, FALSE if it should be found more than once.
3150
   * @return
3151
   *   TRUE on pass, FALSE on fail.
3152
   */
3153
  protected function assertUniqueTextHelper($text, $message = '', $group, $be_unique) {
3154
    if ($this->plainTextContent === FALSE) {
3155
      $this->plainTextContent = filter_xss($this->drupalGetContent(), array());
3156
    }
3157
    if (!$message) {
3158
      $message = '"' . $text . '"' . ($be_unique ? ' found only once' : ' found more than once');
3159
    }
3160
    $first_occurance = strpos($this->plainTextContent, $text);
3161
    if ($first_occurance === FALSE) {
3162
      return $this->assert(FALSE, $message, $group);
3163
    }
3164
    $offset = $first_occurance + strlen($text);
3165
    $second_occurance = strpos($this->plainTextContent, $text, $offset);
3166
    return $this->assert($be_unique == ($second_occurance === FALSE), $message, $group);
3167
  }
3168

    
3169
  /**
3170
   * Will trigger a pass if the Perl regex pattern is found in the raw content.
3171
   *
3172
   * @param $pattern
3173
   *   Perl regex to look for including the regex delimiters.
3174
   * @param $message
3175
   *   Message to display.
3176
   * @param $group
3177
   *   The group this message belongs to.
3178
   * @return
3179
   *   TRUE on pass, FALSE on fail.
3180
   */
3181
  protected function assertPattern($pattern, $message = '', $group = 'Other') {
3182
    if (!$message) {
3183
      $message = t('Pattern "@pattern" found', array('@pattern' => $pattern));
3184
    }
3185
    return $this->assert((bool) preg_match($pattern, $this->drupalGetContent()), $message, $group);
3186
  }
3187

    
3188
  /**
3189
   * Will trigger a pass if the perl regex pattern is not present in raw content.
3190
   *
3191
   * @param $pattern
3192
   *   Perl regex to look for including the regex delimiters.
3193
   * @param $message
3194
   *   Message to display.
3195
   * @param $group
3196
   *   The group this message belongs to.
3197
   * @return
3198
   *   TRUE on pass, FALSE on fail.
3199
   */
3200
  protected function assertNoPattern($pattern, $message = '', $group = 'Other') {
3201
    if (!$message) {
3202
      $message = t('Pattern "@pattern" not found', array('@pattern' => $pattern));
3203
    }
3204
    return $this->assert(!preg_match($pattern, $this->drupalGetContent()), $message, $group);
3205
  }
3206

    
3207
  /**
3208
   * Pass if the page title is the given string.
3209
   *
3210
   * @param $title
3211
   *   The string the title should be.
3212
   * @param $message
3213
   *   Message to display.
3214
   * @param $group
3215
   *   The group this message belongs to.
3216
   * @return
3217
   *   TRUE on pass, FALSE on fail.
3218
   */
3219
  protected function assertTitle($title, $message = '', $group = 'Other') {
3220
    $actual = (string) current($this->xpath('//title'));
3221
    if (!$message) {
3222
      $message = t('Page title @actual is equal to @expected.', array(
3223
        '@actual' => var_export($actual, TRUE),
3224
        '@expected' => var_export($title, TRUE),
3225
      ));
3226
    }
3227
    return $this->assertEqual($actual, $title, $message, $group);
3228
  }
3229

    
3230
  /**
3231
   * Pass if the page title is not the given string.
3232
   *
3233
   * @param $title
3234
   *   The string the title should not be.
3235
   * @param $message
3236
   *   Message to display.
3237
   * @param $group
3238
   *   The group this message belongs to.
3239
   * @return
3240
   *   TRUE on pass, FALSE on fail.
3241
   */
3242
  protected function assertNoTitle($title, $message = '', $group = 'Other') {
3243
    $actual = (string) current($this->xpath('//title'));
3244
    if (!$message) {
3245
      $message = t('Page title @actual is not equal to @unexpected.', array(
3246
        '@actual' => var_export($actual, TRUE),
3247
        '@unexpected' => var_export($title, TRUE),
3248
      ));
3249
    }
3250
    return $this->assertNotEqual($actual, $title, $message, $group);
3251
  }
3252

    
3253
  /**
3254
   * Asserts themed output.
3255
   *
3256
   * @param $callback
3257
   *   The name of the theme function to invoke; e.g. 'links' for theme_links().
3258
   * @param $variables
3259
   *   (optional) An array of variables to pass to the theme function.
3260
   * @param $expected
3261
   *   The expected themed output string.
3262
   * @param $message
3263
   *   (optional) A message to display with the assertion. Do not translate
3264
   *   messages: use format_string() to embed variables in the message text, not
3265
   *   t(). If left blank, a default message will be displayed.
3266
   * @param $group
3267
   *   (optional) The group this message is in, which is displayed in a column
3268
   *   in test output. Use 'Debug' to indicate this is debugging output. Do not
3269
   *   translate this string. Defaults to 'Other'; most tests do not override
3270
   *   this default.
3271
   *
3272
   * @return
3273
   *   TRUE on pass, FALSE on fail.
3274
   */
3275
  protected function assertThemeOutput($callback, array $variables = array(), $expected, $message = '', $group = 'Other') {
3276
    $output = theme($callback, $variables);
3277
    $this->verbose('Variables:' . '<pre>' .  check_plain(var_export($variables, TRUE)) . '</pre>'
3278
      . '<hr />' . 'Result:' . '<pre>' .  check_plain(var_export($output, TRUE)) . '</pre>'
3279
      . '<hr />' . 'Expected:' . '<pre>' .  check_plain(var_export($expected, TRUE)) . '</pre>'
3280
      . '<hr />' . $output
3281
    );
3282
    if (!$message) {
3283
      $message = '%callback rendered correctly.';
3284
    }
3285
    $message = format_string($message, array('%callback' => 'theme_' . $callback . '()'));
3286
    return $this->assertIdentical($output, $expected, $message, $group);
3287
  }
3288

    
3289
  /**
3290
   * Asserts that a field exists in the current page by the given XPath.
3291
   *
3292
   * @param $xpath
3293
   *   XPath used to find the field.
3294
   * @param $value
3295
   *   (optional) Value of the field to assert. You may pass in NULL (default)
3296
   *   to skip checking the actual value, while still checking that the field
3297
   *   exists.
3298
   * @param $message
3299
   *   (optional) Message to display.
3300
   * @param $group
3301
   *   (optional) The group this message belongs to.
3302
   *
3303
   * @return
3304
   *   TRUE on pass, FALSE on fail.
3305
   */
3306
  protected function assertFieldByXPath($xpath, $value = NULL, $message = '', $group = 'Other') {
3307
    $fields = $this->xpath($xpath);
3308

    
3309
    // If value specified then check array for match.
3310
    $found = TRUE;
3311
    if (isset($value)) {
3312
      $found = FALSE;
3313
      if ($fields) {
3314
        foreach ($fields as $field) {
3315
          if (isset($field['value']) && $field['value'] == $value) {
3316
            // Input element with correct value.
3317
            $found = TRUE;
3318
          }
3319
          elseif (isset($field->option)) {
3320
            // Select element found.
3321
            if ($this->getSelectedItem($field) == $value) {
3322
              $found = TRUE;
3323
            }
3324
            else {
3325
              // No item selected so use first item.
3326
              $items = $this->getAllOptions($field);
3327
              if (!empty($items) && $items[0]['value'] == $value) {
3328
                $found = TRUE;
3329
              }
3330
            }
3331
          }
3332
          elseif ((string) $field == $value) {
3333
            // Text area with correct text.
3334
            $found = TRUE;
3335
          }
3336
        }
3337
      }
3338
    }
3339
    return $this->assertTrue($fields && $found, $message, $group);
3340
  }
3341

    
3342
  /**
3343
   * Get the selected value from a select field.
3344
   *
3345
   * @param $element
3346
   *   SimpleXMLElement select element.
3347
   * @return
3348
   *   The selected value or FALSE.
3349
   */
3350
  protected function getSelectedItem(SimpleXMLElement $element) {
3351
    foreach ($element->children() as $item) {
3352
      if (isset($item['selected'])) {
3353
        return $item['value'];
3354
      }
3355
      elseif ($item->getName() == 'optgroup') {
3356
        if ($value = $this->getSelectedItem($item)) {
3357
          return $value;
3358
        }
3359
      }
3360
    }
3361
    return FALSE;
3362
  }
3363

    
3364
  /**
3365
   * Asserts that a field doesn't exist or its value doesn't match, by XPath.
3366
   *
3367
   * @param $xpath
3368
   *   XPath used to find the field.
3369
   * @param $value
3370
   *   (optional) Value for the field, to assert that the field's value on the
3371
   *   page doesn't match it. You may pass in NULL to skip checking the
3372
   *   value, while still checking that the field doesn't exist.
3373
   * @param $message
3374
   *   (optional) Message to display.
3375
   * @param $group
3376
   *   (optional) The group this message belongs to.
3377
   *
3378
   * @return
3379
   *   TRUE on pass, FALSE on fail.
3380
   */
3381
  protected function assertNoFieldByXPath($xpath, $value = NULL, $message = '', $group = 'Other') {
3382
    $fields = $this->xpath($xpath);
3383

    
3384
    // If value specified then check array for match.
3385
    $found = TRUE;
3386
    if (isset($value)) {
3387
      $found = FALSE;
3388
      if ($fields) {
3389
        foreach ($fields as $field) {
3390
          if ($field['value'] == $value) {
3391
            $found = TRUE;
3392
          }
3393
        }
3394
      }
3395
    }
3396
    return $this->assertFalse($fields && $found, $message, $group);
3397
  }
3398

    
3399
  /**
3400
   * Asserts that a field exists in the current page with the given name and value.
3401
   *
3402
   * @param $name
3403
   *   Name of field to assert.
3404
   * @param $value
3405
   *   (optional) Value of the field to assert. You may pass in NULL (default)
3406
   *   to skip checking the actual value, while still checking that the field
3407
   *   exists.
3408
   * @param $message
3409
   *   Message to display.
3410
   * @param $group
3411
   *   The group this message belongs to.
3412
   * @return
3413
   *   TRUE on pass, FALSE on fail.
3414
   */
3415
  protected function assertFieldByName($name, $value = NULL, $message = NULL) {
3416
    if (!isset($message)) {
3417
      if (!isset($value)) {
3418
        $message = t('Found field with name @name', array(
3419
          '@name' => var_export($name, TRUE),
3420
        ));
3421
      }
3422
      else {
3423
        $message = t('Found field with name @name and value @value', array(
3424
          '@name' => var_export($name, TRUE),
3425
          '@value' => var_export($value, TRUE),
3426
        ));
3427
      }
3428
    }
3429
    return $this->assertFieldByXPath($this->constructFieldXpath('name', $name), $value, $message, t('Browser'));
3430
  }
3431

    
3432
  /**
3433
   * Asserts that a field does not exist with the given name and value.
3434
   *
3435
   * @param $name
3436
   *   Name of field to assert.
3437
   * @param $value
3438
   *   (optional) Value for the field, to assert that the field's value on the
3439
   *   page doesn't match it. You may pass in NULL to skip checking the
3440
   *   value, while still checking that the field doesn't exist. However, the
3441
   *   default value ('') asserts that the field value is not an empty string.
3442
   * @param $message
3443
   *   (optional) Message to display.
3444
   * @param $group
3445
   *   The group this message belongs to.
3446
   * @return
3447
   *   TRUE on pass, FALSE on fail.
3448
   */
3449
  protected function assertNoFieldByName($name, $value = '', $message = '') {
3450
    return $this->assertNoFieldByXPath($this->constructFieldXpath('name', $name), $value, $message ? $message : t('Did not find field by name @name', array('@name' => $name)), t('Browser'));
3451
  }
3452

    
3453
  /**
3454
   * Asserts that a field exists in the current page with the given ID and value.
3455
   *
3456
   * @param $id
3457
   *   ID of field to assert.
3458
   * @param $value
3459
   *   (optional) Value for the field to assert. You may pass in NULL to skip
3460
   *   checking the value, while still checking that the field exists.
3461
   *   However, the default value ('') asserts that the field value is an empty
3462
   *   string.
3463
   * @param $message
3464
   *   (optional) Message to display.
3465
   * @param $group
3466
   *   The group this message belongs to.
3467
   * @return
3468
   *   TRUE on pass, FALSE on fail.
3469
   */
3470
  protected function assertFieldById($id, $value = '', $message = '') {
3471
    return $this->assertFieldByXPath($this->constructFieldXpath('id', $id), $value, $message ? $message : t('Found field by id @id', array('@id' => $id)), t('Browser'));
3472
  }
3473

    
3474
  /**
3475
   * Asserts that a field does not exist with the given ID and value.
3476
   *
3477
   * @param $id
3478
   *   ID of field to assert.
3479
   * @param $value
3480
   *   (optional) Value for the field, to assert that the field's value on the
3481
   *   page doesn't match it. You may pass in NULL to skip checking the value,
3482
   *   while still checking that the field doesn't exist. However, the default
3483
   *   value ('') asserts that the field value is not an empty string.
3484
   * @param $message
3485
   *   (optional) Message to display.
3486
   * @param $group
3487
   *   The group this message belongs to.
3488
   * @return
3489
   *   TRUE on pass, FALSE on fail.
3490
   */
3491
  protected function assertNoFieldById($id, $value = '', $message = '') {
3492
    return $this->assertNoFieldByXPath($this->constructFieldXpath('id', $id), $value, $message ? $message : t('Did not find field by id @id', array('@id' => $id)), t('Browser'));
3493
  }
3494

    
3495
  /**
3496
   * Asserts that a checkbox field in the current page is checked.
3497
   *
3498
   * @param $id
3499
   *   ID of field to assert.
3500
   * @param $message
3501
   *   (optional) Message to display.
3502
   * @return
3503
   *   TRUE on pass, FALSE on fail.
3504
   */
3505
  protected function assertFieldChecked($id, $message = '') {
3506
    $elements = $this->xpath('//input[@id=:id]', array(':id' => $id));
3507
    return $this->assertTrue(isset($elements[0]) && !empty($elements[0]['checked']), $message ? $message : t('Checkbox field @id is checked.', array('@id' => $id)), t('Browser'));
3508
  }
3509

    
3510
  /**
3511
   * Asserts that a checkbox field in the current page is not checked.
3512
   *
3513
   * @param $id
3514
   *   ID of field to assert.
3515
   * @param $message
3516
   *   (optional) Message to display.
3517
   * @return
3518
   *   TRUE on pass, FALSE on fail.
3519
   */
3520
  protected function assertNoFieldChecked($id, $message = '') {
3521
    $elements = $this->xpath('//input[@id=:id]', array(':id' => $id));
3522
    return $this->assertTrue(isset($elements[0]) && empty($elements[0]['checked']), $message ? $message : t('Checkbox field @id is not checked.', array('@id' => $id)), t('Browser'));
3523
  }
3524

    
3525
  /**
3526
   * Asserts that a select option in the current page is checked.
3527
   *
3528
   * @param $id
3529
   *   ID of select field to assert.
3530
   * @param $option
3531
   *   Option to assert.
3532
   * @param $message
3533
   *   (optional) Message to display.
3534
   * @return
3535
   *   TRUE on pass, FALSE on fail.
3536
   *
3537
   * @todo $id is unusable. Replace with $name.
3538
   */
3539
  protected function assertOptionSelected($id, $option, $message = '') {
3540
    $elements = $this->xpath('//select[@id=:id]//option[@value=:option]', array(':id' => $id, ':option' => $option));
3541
    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'));
3542
  }
3543

    
3544
  /**
3545
   * Asserts that a select option in the current page is not checked.
3546
   *
3547
   * @param $id
3548
   *   ID of select field to assert.
3549
   * @param $option
3550
   *   Option to assert.
3551
   * @param $message
3552
   *   (optional) Message to display.
3553
   * @return
3554
   *   TRUE on pass, FALSE on fail.
3555
   */
3556
  protected function assertNoOptionSelected($id, $option, $message = '') {
3557
    $elements = $this->xpath('//select[@id=:id]//option[@value=:option]', array(':id' => $id, ':option' => $option));
3558
    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'));
3559
  }
3560

    
3561
  /**
3562
   * Asserts that a field exists with the given name or ID.
3563
   *
3564
   * @param $field
3565
   *   Name or ID of field to assert.
3566
   * @param $message
3567
   *   (optional) Message to display.
3568
   * @param $group
3569
   *   The group this message belongs to.
3570
   * @return
3571
   *   TRUE on pass, FALSE on fail.
3572
   */
3573
  protected function assertField($field, $message = '', $group = 'Other') {
3574
    return $this->assertFieldByXPath($this->constructFieldXpath('name', $field) . '|' . $this->constructFieldXpath('id', $field), NULL, $message, $group);
3575
  }
3576

    
3577
  /**
3578
   * Asserts that a field does not exist with the given name or ID.
3579
   *
3580
   * @param $field
3581
   *   Name or ID of field to assert.
3582
   * @param $message
3583
   *   (optional) Message to display.
3584
   * @param $group
3585
   *   The group this message belongs to.
3586
   * @return
3587
   *   TRUE on pass, FALSE on fail.
3588
   */
3589
  protected function assertNoField($field, $message = '', $group = 'Other') {
3590
    return $this->assertNoFieldByXPath($this->constructFieldXpath('name', $field) . '|' . $this->constructFieldXpath('id', $field), NULL, $message, $group);
3591
  }
3592

    
3593
  /**
3594
   * Asserts that each HTML ID is used for just a single element.
3595
   *
3596
   * @param $message
3597
   *   Message to display.
3598
   * @param $group
3599
   *   The group this message belongs to.
3600
   * @param $ids_to_skip
3601
   *   An optional array of ids to skip when checking for duplicates. It is
3602
   *   always a bug to have duplicate HTML IDs, so this parameter is to enable
3603
   *   incremental fixing of core code. Whenever a test passes this parameter,
3604
   *   it should add a "todo" comment above the call to this function explaining
3605
   *   the legacy bug that the test wishes to ignore and including a link to an
3606
   *   issue that is working to fix that legacy bug.
3607
   * @return
3608
   *   TRUE on pass, FALSE on fail.
3609
   */
3610
  protected function assertNoDuplicateIds($message = '', $group = 'Other', $ids_to_skip = array()) {
3611
    $status = TRUE;
3612
    foreach ($this->xpath('//*[@id]') as $element) {
3613
      $id = (string) $element['id'];
3614
      if (isset($seen_ids[$id]) && !in_array($id, $ids_to_skip)) {
3615
        $this->fail(t('The HTML ID %id is unique.', array('%id' => $id)), $group);
3616
        $status = FALSE;
3617
      }
3618
      $seen_ids[$id] = TRUE;
3619
    }
3620
    return $this->assert($status, $message, $group);
3621
  }
3622

    
3623
  /**
3624
   * Helper function: construct an XPath for the given set of attributes and value.
3625
   *
3626
   * @param $attribute
3627
   *   Field attributes.
3628
   * @param $value
3629
   *   Value of field.
3630
   * @return
3631
   *   XPath for specified values.
3632
   */
3633
  protected function constructFieldXpath($attribute, $value) {
3634
    $xpath = '//textarea[@' . $attribute . '=:value]|//input[@' . $attribute . '=:value]|//select[@' . $attribute . '=:value]';
3635
    return $this->buildXPathQuery($xpath, array(':value' => $value));
3636
  }
3637

    
3638
  /**
3639
   * Asserts the page responds with the specified response code.
3640
   *
3641
   * @param $code
3642
   *   Response code. For example 200 is a successful page request. For a list
3643
   *   of all codes see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html.
3644
   * @param $message
3645
   *   Message to display.
3646
   * @return
3647
   *   Assertion result.
3648
   */
3649
  protected function assertResponse($code, $message = '') {
3650
    $curl_code = curl_getinfo($this->curlHandle, CURLINFO_HTTP_CODE);
3651
    $match = is_array($code) ? in_array($curl_code, $code) : $curl_code == $code;
3652
    return $this->assertTrue($match, $message ? $message : t('HTTP response expected !code, actual !curl_code', array('!code' => $code, '!curl_code' => $curl_code)), t('Browser'));
3653
  }
3654

    
3655
  /**
3656
   * Asserts the page did not return the specified response code.
3657
   *
3658
   * @param $code
3659
   *   Response code. For example 200 is a successful page request. For a list
3660
   *   of all codes see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html.
3661
   * @param $message
3662
   *   Message to display.
3663
   *
3664
   * @return
3665
   *   Assertion result.
3666
   */
3667
  protected function assertNoResponse($code, $message = '') {
3668
    $curl_code = curl_getinfo($this->curlHandle, CURLINFO_HTTP_CODE);
3669
    $match = is_array($code) ? in_array($curl_code, $code) : $curl_code == $code;
3670
    return $this->assertFalse($match, $message ? $message : t('HTTP response not expected !code, actual !curl_code', array('!code' => $code, '!curl_code' => $curl_code)), t('Browser'));
3671
  }
3672

    
3673
  /**
3674
   * Asserts that the most recently sent e-mail message has the given value.
3675
   *
3676
   * The field in $name must have the content described in $value.
3677
   *
3678
   * @param $name
3679
   *   Name of field or message property to assert. Examples: subject, body, id, ...
3680
   * @param $value
3681
   *   Value of the field to assert.
3682
   * @param $message
3683
   *   Message to display.
3684
   *
3685
   * @return
3686
   *   TRUE on pass, FALSE on fail.
3687
   */
3688
  protected function assertMail($name, $value = '', $message = '') {
3689
    $captured_emails = variable_get('drupal_test_email_collector', array());
3690
    $email = end($captured_emails);
3691
    return $this->assertTrue($email && isset($email[$name]) && $email[$name] == $value, $message, t('E-mail'));
3692
  }
3693

    
3694
  /**
3695
   * Asserts that the most recently sent e-mail message has the string in it.
3696
   *
3697
   * @param $field_name
3698
   *   Name of field or message property to assert: subject, body, id, ...
3699
   * @param $string
3700
   *   String to search for.
3701
   * @param $email_depth
3702
   *   Number of emails to search for string, starting with most recent.
3703
   *
3704
   * @return
3705
   *   TRUE on pass, FALSE on fail.
3706
   */
3707
  protected function assertMailString($field_name, $string, $email_depth) {
3708
    $mails = $this->drupalGetMails();
3709
    $string_found = FALSE;
3710
    for ($i = sizeof($mails) -1; $i >= sizeof($mails) - $email_depth && $i >= 0; $i--) {
3711
      $mail = $mails[$i];
3712
      // Normalize whitespace, as we don't know what the mail system might have
3713
      // done. Any run of whitespace becomes a single space.
3714
      $normalized_mail = preg_replace('/\s+/', ' ', $mail[$field_name]);
3715
      $normalized_string = preg_replace('/\s+/', ' ', $string);
3716
      $string_found = (FALSE !== strpos($normalized_mail, $normalized_string));
3717
      if ($string_found) {
3718
        break;
3719
      }
3720
    }
3721
    return $this->assertTrue($string_found, t('Expected text found in @field of email message: "@expected".', array('@field' => $field_name, '@expected' => $string)));
3722
  }
3723

    
3724
  /**
3725
   * Asserts that the most recently sent e-mail message has the pattern in it.
3726
   *
3727
   * @param $field_name
3728
   *   Name of field or message property to assert: subject, body, id, ...
3729
   * @param $regex
3730
   *   Pattern to search for.
3731
   *
3732
   * @return
3733
   *   TRUE on pass, FALSE on fail.
3734
   */
3735
  protected function assertMailPattern($field_name, $regex, $message) {
3736
    $mails = $this->drupalGetMails();
3737
    $mail = end($mails);
3738
    $regex_found = preg_match("/$regex/", $mail[$field_name]);
3739
    return $this->assertTrue($regex_found, t('Expected text found in @field of email message: "@expected".', array('@field' => $field_name, '@expected' => $regex)));
3740
  }
3741

    
3742
  /**
3743
   * Outputs to verbose the most recent $count emails sent.
3744
   *
3745
   * @param $count
3746
   *   Optional number of emails to output.
3747
   */
3748
  protected function verboseEmail($count = 1) {
3749
    $mails = $this->drupalGetMails();
3750
    for ($i = sizeof($mails) -1; $i >= sizeof($mails) - $count && $i >= 0; $i--) {
3751
      $mail = $mails[$i];
3752
      $this->verbose(t('Email:') . '<pre>' . print_r($mail, TRUE) . '</pre>');
3753
    }
3754
  }
3755
}
3756

    
3757
/**
3758
 * Logs verbose message in a text file.
3759
 *
3760
 * If verbose mode is enabled then page requests will be dumped to a file and
3761
 * presented on the test result screen. The messages will be placed in a file
3762
 * located in the simpletest directory in the original file system.
3763
 *
3764
 * @param $message
3765
 *   The verbose message to be stored.
3766
 * @param $original_file_directory
3767
 *   The original file directory, before it was changed for testing purposes.
3768
 * @param $test_class
3769
 *   The active test case class.
3770
 *
3771
 * @return
3772
 *   The ID of the message to be placed in related assertion messages.
3773
 *
3774
 * @see DrupalTestCase->originalFileDirectory
3775
 * @see DrupalWebTestCase->verbose()
3776
 */
3777
function simpletest_verbose($message, $original_file_directory = NULL, $test_class = NULL) {
3778
  static $file_directory = NULL, $class = NULL, $id = 1, $verbose = NULL;
3779

    
3780
  // Will pass first time during setup phase, and when verbose is TRUE.
3781
  if (!isset($original_file_directory) && !$verbose) {
3782
    return FALSE;
3783
  }
3784

    
3785
  if ($message && $file_directory) {
3786
    $message = '<hr />ID #' . $id . ' (<a href="' . $class . '-' . ($id - 1) . '.html">Previous</a> | <a href="' . $class . '-' . ($id + 1) . '.html">Next</a>)<hr />' . $message;
3787
    file_put_contents($file_directory . "/simpletest/verbose/$class-$id.html", $message, FILE_APPEND);
3788
    return $id++;
3789
  }
3790

    
3791
  if ($original_file_directory) {
3792
    $file_directory = $original_file_directory;
3793
    $class = $test_class;
3794
    $verbose = variable_get('simpletest_verbose', TRUE);
3795
    $directory = $file_directory . '/simpletest/verbose';
3796
    $writable = file_prepare_directory($directory, FILE_CREATE_DIRECTORY);
3797
    if ($writable && !file_exists($directory . '/.htaccess')) {
3798
      file_put_contents($directory . '/.htaccess', "<IfModule mod_expires.c>\nExpiresActive Off\n</IfModule>\n");
3799
    }
3800
    return $writable;
3801
  }
3802
  return FALSE;
3803
}