Projet

Général

Profil

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

root / drupal7 / modules / simpletest / drupal_web_test_case.php @ c9e51f47

1
<?php
2

    
3
/**
4
 * Global variable that holds information about the tests being run.
5
 *
6
 * An array, with the following keys:
7
 *  - 'test_run_id': the ID of the test being run, in the form 'simpletest_%"
8
 *  - 'in_child_site': TRUE if the current request is a cURL request from
9
 *     the parent site.
10
 *
11
 * @var array
12
 */
13
global $drupal_test_info;
14

    
15
/**
16
 * Base class for Drupal tests.
17
 *
18
 * Do not extend this class, use one of the subclasses in this file.
19
 */
20
abstract class DrupalTestCase {
21
  /**
22
   * The test run ID.
23
   *
24
   * @var string
25
   */
26
  protected $testId;
27

    
28
  /**
29
   * The database prefix of this test run.
30
   *
31
   * @var string
32
   */
33
  protected $databasePrefix = NULL;
34

    
35
  /**
36
   * The original file directory, before it was changed for testing purposes.
37
   *
38
   * @var string
39
   */
40
  protected $originalFileDirectory = NULL;
41

    
42
  /**
43
   * Time limit for the test.
44
   */
45
  protected $timeLimit = 500;
46

    
47
  /**
48
   * Current results of this test case.
49
   *
50
   * @var Array
51
   */
52
  public $results = array(
53
    '#pass' => 0,
54
    '#fail' => 0,
55
    '#exception' => 0,
56
    '#debug' => 0,
57
  );
58

    
59
  /**
60
   * Assertions thrown in that test case.
61
   *
62
   * @var Array
63
   */
64
  protected $assertions = array();
65

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

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

    
88
  protected $setupDatabasePrefix = FALSE;
89

    
90
  protected $setupEnvironment = FALSE;
91

    
92
  /**
93
   * Constructor for DrupalTestCase.
94
   *
95
   * @param $test_id
96
   *   Tests with the same id are reported together.
97
   */
98
  public function __construct($test_id = NULL) {
99
    $this->testId = $test_id;
100
  }
101

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

    
125
    // Increment summary result counter.
126
    $this->results['#' . $status]++;
127

    
128
    // Get the function information about the call to the assertion method.
129
    if (!$caller) {
130
      $caller = $this->getAssertionCall();
131
    }
132

    
133
    // Creation assertion array that can be displayed while tests are running.
134
    $this->assertions[] = $assertion = array(
135
      'test_id' => $this->testId,
136
      'test_class' => get_class($this),
137
      'status' => $status,
138
      'message' => $message,
139
      'message_group' => $group,
140
      'function' => $caller['function'],
141
      'line' => $caller['line'],
142
      'file' => $caller['file'],
143
    );
144

    
145
    // Store assertion for display after the test has completed.
146
    self::getDatabaseConnection()
147
      ->insert('simpletest')
148
      ->fields($assertion)
149
      ->execute();
150

    
151
    // We do not use a ternary operator here to allow a breakpoint on
152
    // test failure.
153
    if ($status == 'pass') {
154
      return TRUE;
155
    }
156
    else {
157
      return FALSE;
158
    }
159
  }
160

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

    
177
    return $connection;
178
  }
179

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

    
202
    $caller += array(
203
      'function' => t('Unknown'),
204
      'line' => 0,
205
      'file' => t('Unknown'),
206
    );
207

    
208
    $assertion = array(
209
      'test_id' => $test_id,
210
      'test_class' => $test_class,
211
      'status' => $status,
212
      'message' => $message,
213
      'message_group' => $group,
214
      'function' => $caller['function'],
215
      'line' => $caller['line'],
216
      'file' => $caller['file'],
217
    );
218

    
219
    return self::getDatabaseConnection()
220
      ->insert('simpletest')
221
      ->fields($assertion)
222
      ->execute();
223
  }
224

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

    
242
  /**
243
   * Cycles through backtrace until the first non-assertion method is found.
244
   *
245
   * @return
246
   *   Array representing the true caller.
247
   */
248
  protected function getAssertionCall() {
249
    $backtrace = debug_backtrace();
250

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

    
261
    return _drupal_get_last_caller($backtrace);
262
  }
263

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

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

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

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

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

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

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

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

    
400
  /**
401
   * Fire an assertion that is always positive.
402
   *
403
   * @param $message
404
   *   The message to display along with the assertion.
405
   * @param $group
406
   *   The type of assertion - examples are "Browser", "PHP".
407
   * @return
408
   *   TRUE.
409
   */
410
  protected function pass($message = NULL, $group = 'Other') {
411
    return $this->assert(TRUE, $message, $group);
412
  }
413

    
414
  /**
415
   * Fire an assertion that is always negative.
416
   *
417
   * @param $message
418
   *   The message to display along with the assertion.
419
   * @param $group
420
   *   The type of assertion - examples are "Browser", "PHP".
421
   * @return
422
   *   FALSE.
423
   */
424
  protected function fail($message = NULL, $group = 'Other') {
425
    return $this->assert(FALSE, $message, $group);
426
  }
427

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

    
447
    return $this->assert('exception', $message, $group, $caller);
448
  }
449

    
450
  /**
451
   * Logs a verbose message in a text file.
452
   *
453
   * The link to the verbose message will be placed in the test results as a
454
   * passing assertion with the text '[verbose message]'.
455
   *
456
   * @param $message
457
   *   The verbose message to be stored.
458
   *
459
   * @see simpletest_verbose()
460
   */
461
  protected function verbose($message) {
462
    if ($id = simpletest_verbose($message)) {
463
      $class_safe = str_replace('\\', '_', get_class($this));
464
      $url = file_create_url($this->originalFileDirectory . '/simpletest/verbose/' . $class_safe . '-' . $id . '.html');
465
      $this->error(l(t('Verbose message'), $url, array('attributes' => array('target' => '_blank'))), 'User notice');
466
    }
467
  }
468

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

    
486
    // HTTP auth settings (<username>:<password>) for the simpletest browser
487
    // when sending requests to the test site.
488
    $this->httpauth_method = variable_get('simpletest_httpauth_method', CURLAUTH_BASIC);
489
    $username = variable_get('simpletest_httpauth_username', NULL);
490
    $password = variable_get('simpletest_httpauth_password', NULL);
491
    if ($username && $password) {
492
      $this->httpauth_credentials = $username . ':' . $password;
493
    }
494

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

    
537
  /**
538
   * Handle errors during test runs.
539
   *
540
   * Because this is registered in set_error_handler(), it has to be public.
541
   * @see set_error_handler
542
   */
543
  public function errorHandler($severity, $message, $file = NULL, $line = NULL) {
544
    if ($severity & error_reporting()) {
545
      $error_map = array(
546
        E_STRICT => 'Run-time notice',
547
        E_WARNING => 'Warning',
548
        E_NOTICE => 'Notice',
549
        E_CORE_ERROR => 'Core error',
550
        E_CORE_WARNING => 'Core warning',
551
        E_USER_ERROR => 'User error',
552
        E_USER_WARNING => 'User warning',
553
        E_USER_NOTICE => 'User notice',
554
        E_RECOVERABLE_ERROR => 'Recoverable error',
555
      );
556

    
557
      // PHP 5.3 adds new error logging constants. Add these conditionally for
558
      // backwards compatibility with PHP 5.2.
559
      if (defined('E_DEPRECATED')) {
560
        $error_map += array(
561
          E_DEPRECATED => 'Deprecated',
562
          E_USER_DEPRECATED => 'User deprecated',
563
        );
564
      }
565

    
566
      $backtrace = debug_backtrace();
567
      $this->error($message, $error_map[$severity], _drupal_get_last_caller($backtrace));
568
    }
569
    return TRUE;
570
  }
571

    
572
  /**
573
   * Handle exceptions.
574
   *
575
   * @see set_exception_handler
576
   */
577
  protected function exceptionHandler($exception) {
578
    $backtrace = $exception->getTrace();
579
    // Push on top of the backtrace the call that generated the exception.
580
    array_unshift($backtrace, array(
581
      'line' => $exception->getLine(),
582
      'file' => $exception->getFile(),
583
    ));
584
    require_once DRUPAL_ROOT . '/includes/errors.inc';
585
    // The exception message is run through check_plain() by _drupal_decode_exception().
586
    $this->error(t('%type: !message in %function (line %line of %file).', _drupal_decode_exception($exception)), 'Uncaught exception', _drupal_get_last_caller($backtrace));
587
  }
588

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

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

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

    
696
/**
697
 * Test case for Drupal unit tests.
698
 *
699
 * These tests can not access the database nor files. Calling any Drupal
700
 * function that needs the database will throw exceptions. These include
701
 * watchdog(), module_implements(), module_invoke_all() etc.
702
 */
703
class DrupalUnitTestCase extends DrupalTestCase {
704

    
705
  /**
706
   * Constructor for DrupalUnitTestCase.
707
   */
708
  function __construct($test_id = NULL) {
709
    parent::__construct($test_id);
710
    $this->skipClasses[__CLASS__] = TRUE;
711
  }
712

    
713
  /**
714
   * Sets up unit test environment.
715
   *
716
   * Unlike DrupalWebTestCase::setUp(), DrupalUnitTestCase::setUp() does not
717
   * install modules because tests are performed without accessing the database.
718
   * Any required files must be explicitly included by the child class setUp()
719
   * method.
720
   */
721
  protected function setUp() {
722
    global $conf;
723

    
724
    // Store necessary current values before switching to the test environment.
725
    $this->originalFileDirectory = variable_get('file_public_path', conf_path() . '/files');
726

    
727
    // Reset all statics so that test is performed with a clean environment.
728
    drupal_static_reset();
729

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

    
733
    // Create test directory.
734
    $public_files_directory = $this->originalFileDirectory . '/simpletest/' . substr($this->databasePrefix, 10);
735
    file_prepare_directory($public_files_directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
736
    $conf['file_public_path'] = $public_files_directory;
737

    
738
    // Clone the current connection and replace the current prefix.
739
    $connection_info = Database::getConnectionInfo('default');
740
    Database::renameConnection('default', 'simpletest_original_default');
741
    foreach ($connection_info as $target => $value) {
742
      $connection_info[$target]['prefix'] = array(
743
        'default' => $value['prefix']['default'] . $this->databasePrefix,
744
      );
745
    }
746
    Database::addConnectionInfo('default', 'default', $connection_info['default']);
747

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

    
751
    // If locale is enabled then t() will try to access the database and
752
    // subsequently will fail as the database is not accessible.
753
    $module_list = module_list();
754
    if (isset($module_list['locale'])) {
755
      // Transform the list into the format expected as input to module_list().
756
      foreach ($module_list as &$module) {
757
        $module = array('filename' => drupal_get_filename('module', $module));
758
      }
759
      $this->originalModuleList = $module_list;
760
      unset($module_list['locale']);
761
      module_list(TRUE, FALSE, FALSE, $module_list);
762
    }
763
    $this->setup = TRUE;
764
  }
765

    
766
  protected function tearDown() {
767
    global $conf;
768

    
769
    // Get back to the original connection.
770
    Database::removeConnection('default');
771
    Database::renameConnection('simpletest_original_default', 'default');
772

    
773
    $conf['file_public_path'] = $this->originalFileDirectory;
774
    // Restore modules if necessary.
775
    if (isset($this->originalModuleList)) {
776
      module_list(TRUE, FALSE, FALSE, $this->originalModuleList);
777
    }
778
  }
779
}
780

    
781
/**
782
 * Test case for typical Drupal tests.
783
 */
784
class DrupalWebTestCase extends DrupalTestCase {
785
  /**
786
   * The profile to install as a basis for testing.
787
   *
788
   * @var string
789
   */
790
  protected $profile = 'standard';
791

    
792
  /**
793
   * The URL currently loaded in the internal browser.
794
   *
795
   * @var string
796
   */
797
  protected $url;
798

    
799
  /**
800
   * The handle of the current cURL connection.
801
   *
802
   * @var resource
803
   */
804
  protected $curlHandle;
805

    
806
  /**
807
   * The headers of the page currently loaded in the internal browser.
808
   *
809
   * @var Array
810
   */
811
  protected $headers;
812

    
813
  /**
814
   * The content of the page currently loaded in the internal browser.
815
   *
816
   * @var string
817
   */
818
  protected $content;
819

    
820
  /**
821
   * The content of the page currently loaded in the internal browser (plain text version).
822
   *
823
   * @var string
824
   */
825
  protected $plainTextContent;
826

    
827
  /**
828
   * The value of the Drupal.settings JavaScript variable for the page currently loaded in the internal browser.
829
   *
830
   * @var Array
831
   */
832
  protected $drupalSettings;
833

    
834
  /**
835
   * The parsed version of the page.
836
   *
837
   * @var SimpleXMLElement
838
   */
839
  protected $elements = NULL;
840

    
841
  /**
842
   * The current user logged in using the internal browser.
843
   *
844
   * @var bool
845
   */
846
  protected $loggedInUser = FALSE;
847

    
848
  /**
849
   * The current cookie file used by cURL.
850
   *
851
   * We do not reuse the cookies in further runs, so we do not need a file
852
   * but we still need cookie handling, so we set the jar to NULL.
853
   */
854
  protected $cookieFile = NULL;
855

    
856
  /**
857
   * The cookies of the page currently loaded in the internal browser.
858
   *
859
   * @var array
860
   */
861
  protected $cookies = array();
862

    
863
  /**
864
   * Additional cURL options.
865
   *
866
   * DrupalWebTestCase itself never sets this but always obeys what is set.
867
   */
868
  protected $additionalCurlOptions = array();
869

    
870
  /**
871
   * The original user, before it was changed to a clean uid = 1 for testing purposes.
872
   *
873
   * @var object
874
   */
875
  protected $originalUser = NULL;
876

    
877
  /**
878
   * The original shutdown handlers array, before it was cleaned for testing purposes.
879
   *
880
   * @var array
881
   */
882
  protected $originalShutdownCallbacks = array();
883

    
884
  /**
885
   * HTTP authentication method
886
   */
887
  protected $httpauth_method = CURLAUTH_BASIC;
888

    
889
  /**
890
   * HTTP authentication credentials (<username>:<password>).
891
   */
892
  protected $httpauth_credentials = NULL;
893

    
894
  /**
895
   * The current session name, if available.
896
   */
897
  protected $session_name = NULL;
898

    
899
  /**
900
   * The current session ID, if available.
901
   */
902
  protected $session_id = NULL;
903

    
904
  /**
905
   * Whether the files were copied to the test files directory.
906
   */
907
  protected $generatedTestFiles = FALSE;
908

    
909
  /**
910
   * The number of redirects followed during the handling of a request.
911
   */
912
  protected $redirect_count;
913

    
914
  /**
915
   * Constructor for DrupalWebTestCase.
916
   */
917
  function __construct($test_id = NULL) {
918
    parent::__construct($test_id);
919
    $this->skipClasses[__CLASS__] = TRUE;
920
  }
921

    
922
  /**
923
   * Get a node from the database based on its title.
924
   *
925
   * @param $title
926
   *   A node title, usually generated by $this->randomName().
927
   * @param $reset
928
   *   (optional) Whether to reset the internal node_load() cache.
929
   *
930
   * @return
931
   *   A node object matching $title.
932
   */
933
  function drupalGetNodeByTitle($title, $reset = FALSE) {
934
    $nodes = node_load_multiple(array(), array('title' => $title), $reset);
935
    // Load the first node returned from the database.
936
    $returned_node = reset($nodes);
937
    return $returned_node;
938
  }
939

    
940
  /**
941
   * Creates a node based on default settings.
942
   *
943
   * @param $settings
944
   *   An associative array of settings to change from the defaults, keys are
945
   *   node properties, for example 'title' => 'Hello, world!'.
946
   * @return
947
   *   Created node object.
948
   */
949
  protected function drupalCreateNode($settings = array()) {
950
    // Populate defaults array.
951
    $settings += array(
952
      'title'     => $this->randomName(8),
953
      'comment'   => 2,
954
      'changed'   => REQUEST_TIME,
955
      'moderate'  => 0,
956
      'promote'   => 0,
957
      'revision'  => 1,
958
      'log'       => '',
959
      'status'    => 1,
960
      'sticky'    => 0,
961
      'type'      => 'page',
962
      'revisions' => NULL,
963
      'language'  => LANGUAGE_NONE,
964
    );
965

    
966
    // Add the body after the language is defined so that it may be set
967
    // properly.
968
    $settings += array(
969
      'body' => array($settings['language'] => array(array())),
970
    );
971

    
972
    // Use the original node's created time for existing nodes.
973
    if (isset($settings['created']) && !isset($settings['date'])) {
974
      $settings['date'] = format_date($settings['created'], 'custom', 'Y-m-d H:i:s O');
975
    }
976

    
977
    // If the node's user uid is not specified manually, use the currently
978
    // logged in user if available, or else the user running the test.
979
    if (!isset($settings['uid'])) {
980
      if ($this->loggedInUser) {
981
        $settings['uid'] = $this->loggedInUser->uid;
982
      }
983
      else {
984
        global $user;
985
        $settings['uid'] = $user->uid;
986
      }
987
    }
988

    
989
    // Merge body field value and format separately.
990
    $body = array(
991
      'value' => $this->randomName(32),
992
      'format' => filter_default_format(),
993
    );
994
    $settings['body'][$settings['language']][0] += $body;
995

    
996
    $node = (object) $settings;
997
    node_save($node);
998

    
999
    // Small hack to link revisions to our test user.
1000
    db_update('node_revision')
1001
      ->fields(array('uid' => $node->uid))
1002
      ->condition('vid', $node->vid)
1003
      ->execute();
1004
    return $node;
1005
  }
1006

    
1007
  /**
1008
   * Creates a custom content type based on default settings.
1009
   *
1010
   * @param $settings
1011
   *   An array of settings to change from the defaults.
1012
   *   Example: 'type' => 'foo'.
1013
   * @return
1014
   *   Created content type.
1015
   */
1016
  protected function drupalCreateContentType($settings = array()) {
1017
    // Find a non-existent random type name.
1018
    do {
1019
      $name = strtolower($this->randomName(8));
1020
    } while (node_type_get_type($name));
1021

    
1022
    // Populate defaults array.
1023
    $defaults = array(
1024
      'type' => $name,
1025
      'name' => $name,
1026
      'base' => 'node_content',
1027
      'description' => '',
1028
      'help' => '',
1029
      'title_label' => 'Title',
1030
      'has_title' => 1,
1031
    );
1032
    // Imposed values for a custom type.
1033
    $forced = array(
1034
      'orig_type' => '',
1035
      'old_type' => '',
1036
      'module' => 'node',
1037
      'custom' => 1,
1038
      'modified' => 1,
1039
      'locked' => 0,
1040
    );
1041
    $type = $forced + $settings + $defaults;
1042
    $type = (object) $type;
1043

    
1044
    $saved_type = node_type_save($type);
1045
    node_types_rebuild();
1046
    menu_rebuild();
1047
    node_add_body_field($type);
1048

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

    
1051
    // Reset permissions so that permissions for this content type are available.
1052
    $this->checkPermissions(array(), TRUE);
1053

    
1054
    return $type;
1055
  }
1056

    
1057
  /**
1058
   * Get a list files that can be used in tests.
1059
   *
1060
   * @param $type
1061
   *   File type, possible values: 'binary', 'html', 'image', 'javascript', 'php', 'sql', 'text'.
1062
   * @param $size
1063
   *   File size in bytes to match. Please check the tests/files folder.
1064
   * @return
1065
   *   List of files that match filter.
1066
   */
1067
  protected function drupalGetTestFiles($type, $size = NULL) {
1068
    if (empty($this->generatedTestFiles)) {
1069
      // Generate binary test files.
1070
      $lines = array(64, 1024);
1071
      $count = 0;
1072
      foreach ($lines as $line) {
1073
        simpletest_generate_file('binary-' . $count++, 64, $line, 'binary');
1074
      }
1075

    
1076
      // Generate text test files.
1077
      $lines = array(16, 256, 1024, 2048, 20480);
1078
      $count = 0;
1079
      foreach ($lines as $line) {
1080
        simpletest_generate_file('text-' . $count++, 64, $line, 'text');
1081
      }
1082

    
1083
      // Copy other test files from simpletest.
1084
      $original = drupal_get_path('module', 'simpletest') . '/files';
1085
      $files = file_scan_directory($original, '/(html|image|javascript|php|sql)-.*/');
1086
      foreach ($files as $file) {
1087
        file_unmanaged_copy($file->uri, variable_get('file_public_path', conf_path() . '/files'));
1088
      }
1089

    
1090
      $this->generatedTestFiles = TRUE;
1091
    }
1092

    
1093
    $files = array();
1094
    // Make sure type is valid.
1095
    if (in_array($type, array('binary', 'html', 'image', 'javascript', 'php', 'sql', 'text'))) {
1096
      $files = file_scan_directory('public://', '/' . $type . '\-.*/');
1097

    
1098
      // If size is set then remove any files that are not of that size.
1099
      if ($size !== NULL) {
1100
        foreach ($files as $file) {
1101
          $stats = stat($file->uri);
1102
          if ($stats['size'] != $size) {
1103
            unset($files[$file->uri]);
1104
          }
1105
        }
1106
      }
1107
    }
1108
    usort($files, array($this, 'drupalCompareFiles'));
1109
    return $files;
1110
  }
1111

    
1112
  /**
1113
   * Compare two files based on size and file name.
1114
   */
1115
  protected function drupalCompareFiles($file1, $file2) {
1116
    $compare_size = filesize($file1->uri) - filesize($file2->uri);
1117
    if ($compare_size) {
1118
      // Sort by file size.
1119
      return $compare_size;
1120
    }
1121
    else {
1122
      // The files were the same size, so sort alphabetically.
1123
      return strnatcmp($file1->name, $file2->name);
1124
    }
1125
  }
1126

    
1127
  /**
1128
   * Create a user with a given set of permissions.
1129
   *
1130
   * @param array $permissions
1131
   *   Array of permission names to assign to user. Note that the user always
1132
   *   has the default permissions derived from the "authenticated users" role.
1133
   *
1134
   * @return object|false
1135
   *   A fully loaded user object with pass_raw property, or FALSE if account
1136
   *   creation fails.
1137
   */
1138
  protected function drupalCreateUser(array $permissions = array()) {
1139
    // Create a role with the given permission set, if any.
1140
    $rid = FALSE;
1141
    if ($permissions) {
1142
      $rid = $this->drupalCreateRole($permissions);
1143
      if (!$rid) {
1144
        return FALSE;
1145
      }
1146
    }
1147

    
1148
    // Create a user assigned to that role.
1149
    $edit = array();
1150
    $edit['name']   = $this->randomName();
1151
    $edit['mail']   = $edit['name'] . '@example.com';
1152
    $edit['pass']   = user_password();
1153
    $edit['status'] = 1;
1154
    if ($rid) {
1155
      $edit['roles'] = array($rid => $rid);
1156
    }
1157

    
1158
    $account = user_save(drupal_anonymous_user(), $edit);
1159

    
1160
    $this->assertTrue(!empty($account->uid), t('User created with name %name and pass %pass', array('%name' => $edit['name'], '%pass' => $edit['pass'])), t('User login'));
1161
    if (empty($account->uid)) {
1162
      return FALSE;
1163
    }
1164

    
1165
    // Add the raw password so that we can log in as this user.
1166
    $account->pass_raw = $edit['pass'];
1167
    return $account;
1168
  }
1169

    
1170
  /**
1171
   * Creates a role with specified permissions.
1172
   *
1173
   * @param $permissions
1174
   *   Array of permission names to assign to role.
1175
   * @param $name
1176
   *   (optional) String for the name of the role.  Defaults to a random string.
1177
   * @return
1178
   *   Role ID of newly created role, or FALSE if role creation failed.
1179
   */
1180
  protected function drupalCreateRole(array $permissions, $name = NULL) {
1181
    // Generate random name if it was not passed.
1182
    if (!$name) {
1183
      $name = $this->randomName();
1184
    }
1185

    
1186
    // Check the all the permissions strings are valid.
1187
    if (!$this->checkPermissions($permissions)) {
1188
      return FALSE;
1189
    }
1190

    
1191
    // Create new role.
1192
    $role = new stdClass();
1193
    $role->name = $name;
1194
    user_role_save($role);
1195
    user_role_grant_permissions($role->rid, $permissions);
1196

    
1197
    $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'));
1198
    if ($role && !empty($role->rid)) {
1199
      $count = db_query('SELECT COUNT(*) FROM {role_permission} WHERE rid = :rid', array(':rid' => $role->rid))->fetchField();
1200
      $this->assertTrue($count == count($permissions), t('Created permissions: @perms', array('@perms' => implode(', ', $permissions))), t('Role'));
1201
      return $role->rid;
1202
    }
1203
    else {
1204
      return FALSE;
1205
    }
1206
  }
1207

    
1208
  /**
1209
   * Check to make sure that the array of permissions are valid.
1210
   *
1211
   * @param $permissions
1212
   *   Permissions to check.
1213
   * @param $reset
1214
   *   Reset cached available permissions.
1215
   * @return
1216
   *   TRUE or FALSE depending on whether the permissions are valid.
1217
   */
1218
  protected function checkPermissions(array $permissions, $reset = FALSE) {
1219
    $available = &drupal_static(__FUNCTION__);
1220

    
1221
    if (!isset($available) || $reset) {
1222
      $available = array_keys(module_invoke_all('permission'));
1223
    }
1224

    
1225
    $valid = TRUE;
1226
    foreach ($permissions as $permission) {
1227
      if (!in_array($permission, $available)) {
1228
        $this->fail(t('Invalid permission %permission.', array('%permission' => $permission)), t('Role'));
1229
        $valid = FALSE;
1230
      }
1231
    }
1232
    return $valid;
1233
  }
1234

    
1235
  /**
1236
   * Log in a user with the internal browser.
1237
   *
1238
   * If a user is already logged in, then the current user is logged out before
1239
   * logging in the specified user.
1240
   *
1241
   * Please note that neither the global $user nor the passed-in user object is
1242
   * populated with data of the logged in user. If you need full access to the
1243
   * user object after logging in, it must be updated manually. If you also need
1244
   * access to the plain-text password of the user (set by drupalCreateUser()),
1245
   * e.g. to log in the same user again, then it must be re-assigned manually.
1246
   * For example:
1247
   * @code
1248
   *   // Create a user.
1249
   *   $account = $this->drupalCreateUser(array());
1250
   *   $this->drupalLogin($account);
1251
   *   // Load real user object.
1252
   *   $pass_raw = $account->pass_raw;
1253
   *   $account = user_load($account->uid);
1254
   *   $account->pass_raw = $pass_raw;
1255
   * @endcode
1256
   *
1257
   * @param $account
1258
   *   User object representing the user to log in.
1259
   *
1260
   * @see drupalCreateUser()
1261
   */
1262
  protected function drupalLogin(stdClass $account) {
1263
    if ($this->loggedInUser) {
1264
      $this->drupalLogout();
1265
    }
1266

    
1267
    $edit = array(
1268
      'name' => $account->name,
1269
      'pass' => $account->pass_raw
1270
    );
1271
    $this->drupalPost('user', $edit, t('Log in'));
1272

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

    
1277
    if ($pass) {
1278
      $this->loggedInUser = $account;
1279
    }
1280
  }
1281

    
1282
  /**
1283
   * Generate a token for the currently logged in user.
1284
   */
1285
  protected function drupalGetToken($value = '') {
1286
    $private_key = drupal_get_private_key();
1287
    return drupal_hmac_base64($value, $this->session_id . $private_key);
1288
  }
1289

    
1290
  /*
1291
   * Logs a user out of the internal browser, then check the login page to confirm logout.
1292
   */
1293
  protected function drupalLogout() {
1294
    // Make a request to the logout page, and redirect to the user page, the
1295
    // idea being if you were properly logged out you should be seeing a login
1296
    // screen.
1297
    $this->drupalGet('user/logout');
1298
    $this->drupalGet('user');
1299
    $pass = $this->assertField('name', t('Username field found.'), t('Logout'));
1300
    $pass = $pass && $this->assertField('pass', t('Password field found.'), t('Logout'));
1301

    
1302
    if ($pass) {
1303
      $this->loggedInUser = FALSE;
1304
    }
1305
  }
1306

    
1307
  /**
1308
   * Generates a database prefix for running tests.
1309
   *
1310
   * The generated database table prefix is used for the Drupal installation
1311
   * being performed for the test. It is also used as user agent HTTP header
1312
   * value by the cURL-based browser of DrupalWebTestCase, which is sent
1313
   * to the Drupal installation of the test. During early Drupal bootstrap, the
1314
   * user agent HTTP header is parsed, and if it matches, all database queries
1315
   * use the database table prefix that has been generated here.
1316
   *
1317
   * @see DrupalWebTestCase::curlInitialize()
1318
   * @see drupal_valid_test_ua()
1319
   * @see DrupalWebTestCase::setUp()
1320
   */
1321
  protected function prepareDatabasePrefix() {
1322
    $this->databasePrefix = 'simpletest' . mt_rand(1000, 1000000);
1323

    
1324
    // As soon as the database prefix is set, the test might start to execute.
1325
    // All assertions as well as the SimpleTest batch operations are associated
1326
    // with the testId, so the database prefix has to be associated with it.
1327
    db_update('simpletest_test_id')
1328
      ->fields(array('last_prefix' => $this->databasePrefix))
1329
      ->condition('test_id', $this->testId)
1330
      ->execute();
1331
  }
1332

    
1333
  /**
1334
   * Changes the database connection to the prefixed one.
1335
   *
1336
   * @see DrupalWebTestCase::setUp()
1337
   */
1338
  protected function changeDatabasePrefix() {
1339
    if (empty($this->databasePrefix)) {
1340
      $this->prepareDatabasePrefix();
1341
      // If $this->prepareDatabasePrefix() failed to work, return without
1342
      // setting $this->setupDatabasePrefix to TRUE, so setUp() methods will
1343
      // know to bail out.
1344
      if (empty($this->databasePrefix)) {
1345
        return;
1346
      }
1347
    }
1348

    
1349
    // Clone the current connection and replace the current prefix.
1350
    $connection_info = Database::getConnectionInfo('default');
1351
    Database::renameConnection('default', 'simpletest_original_default');
1352
    foreach ($connection_info as $target => $value) {
1353
      $connection_info[$target]['prefix'] = array(
1354
        'default' => $value['prefix']['default'] . $this->databasePrefix,
1355
      );
1356
    }
1357
    Database::addConnectionInfo('default', 'default', $connection_info['default']);
1358

    
1359
    // Indicate the database prefix was set up correctly.
1360
    $this->setupDatabasePrefix = TRUE;
1361
  }
1362

    
1363
  /**
1364
   * Prepares the current environment for running the test.
1365
   *
1366
   * Backups various current environment variables and resets them, so they do
1367
   * not interfere with the Drupal site installation in which tests are executed
1368
   * and can be restored in tearDown().
1369
   *
1370
   * Also sets up new resources for the testing environment, such as the public
1371
   * filesystem and configuration directories.
1372
   *
1373
   * @see DrupalWebTestCase::setUp()
1374
   * @see DrupalWebTestCase::tearDown()
1375
   */
1376
  protected function prepareEnvironment() {
1377
    global $user, $language, $language_url, $conf;
1378

    
1379
    // Store necessary current values before switching to prefixed database.
1380
    $this->originalLanguage = $language;
1381
    $this->originalLanguageUrl = $language_url;
1382
    $this->originalLanguageDefault = variable_get('language_default');
1383
    $this->originalFileDirectory = variable_get('file_public_path', conf_path() . '/files');
1384
    $this->originalProfile = drupal_get_profile();
1385
    $this->originalCleanUrl = variable_get('clean_url', 0);
1386
    $this->originalUser = $user;
1387

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

    
1393
    // Save and clean the shutdown callbacks array because it is static cached
1394
    // and will be changed by the test run. Otherwise it will contain callbacks
1395
    // from both environments and the testing environment will try to call the
1396
    // handlers defined by the original one.
1397
    $callbacks = &drupal_register_shutdown_function();
1398
    $this->originalShutdownCallbacks = $callbacks;
1399
    $callbacks = array();
1400

    
1401
    // Create test directory ahead of installation so fatal errors and debug
1402
    // information can be logged during installation process.
1403
    // Use temporary files directory with the same prefix as the database.
1404
    $this->public_files_directory = $this->originalFileDirectory . '/simpletest/' . substr($this->databasePrefix, 10);
1405
    $this->private_files_directory = $this->public_files_directory . '/private';
1406
    $this->temp_files_directory = $this->private_files_directory . '/temp';
1407

    
1408
    // Create the directories
1409
    file_prepare_directory($this->public_files_directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
1410
    file_prepare_directory($this->private_files_directory, FILE_CREATE_DIRECTORY);
1411
    file_prepare_directory($this->temp_files_directory, FILE_CREATE_DIRECTORY);
1412
    $this->generatedTestFiles = FALSE;
1413

    
1414
    // Log fatal errors.
1415
    ini_set('log_errors', 1);
1416
    ini_set('error_log', $this->public_files_directory . '/error.log');
1417

    
1418
    // Set the test information for use in other parts of Drupal.
1419
    $test_info = &$GLOBALS['drupal_test_info'];
1420
    $test_info['test_run_id'] = $this->databasePrefix;
1421
    $test_info['in_child_site'] = FALSE;
1422

    
1423
    // Indicate the environment was set up correctly.
1424
    $this->setupEnvironment = TRUE;
1425
  }
1426

    
1427
  /**
1428
   * Sets up a Drupal site for running functional and integration tests.
1429
   *
1430
   * Generates a random database prefix and installs Drupal with the specified
1431
   * installation profile in DrupalWebTestCase::$profile into the
1432
   * prefixed database. Afterwards, installs any additional modules specified by
1433
   * the test.
1434
   *
1435
   * After installation all caches are flushed and several configuration values
1436
   * are reset to the values of the parent site executing the test, since the
1437
   * default values may be incompatible with the environment in which tests are
1438
   * being executed.
1439
   *
1440
   * @param ...
1441
   *   List of modules to enable for the duration of the test. This can be
1442
   *   either a single array or a variable number of string arguments.
1443
   *
1444
   * @see DrupalWebTestCase::prepareDatabasePrefix()
1445
   * @see DrupalWebTestCase::changeDatabasePrefix()
1446
   * @see DrupalWebTestCase::prepareEnvironment()
1447
   */
1448
  protected function setUp() {
1449
    global $user, $language, $language_url, $conf;
1450

    
1451
    // Create the database prefix for this test.
1452
    $this->prepareDatabasePrefix();
1453

    
1454
    // Prepare the environment for running tests.
1455
    $this->prepareEnvironment();
1456
    if (!$this->setupEnvironment) {
1457
      return FALSE;
1458
    }
1459

    
1460
    // Reset all statics and variables to perform tests in a clean environment.
1461
    $conf = array();
1462
    drupal_static_reset();
1463

    
1464
    // Change the database prefix.
1465
    // All static variables need to be reset before the database prefix is
1466
    // changed, since DrupalCacheArray implementations attempt to
1467
    // write back to persistent caches when they are destructed.
1468
    $this->changeDatabasePrefix();
1469
    if (!$this->setupDatabasePrefix) {
1470
      return FALSE;
1471
    }
1472

    
1473
    // Preset the 'install_profile' system variable, so the first call into
1474
    // system_rebuild_module_data() (in drupal_install_system()) will register
1475
    // the test's profile as a module. Without this, the installation profile of
1476
    // the parent site (executing the test) is registered, and the test
1477
    // profile's hook_install() and other hook implementations are never invoked.
1478
    $conf['install_profile'] = $this->profile;
1479

    
1480
    // Perform the actual Drupal installation.
1481
    include_once DRUPAL_ROOT . '/includes/install.inc';
1482
    drupal_install_system();
1483

    
1484
    $this->preloadRegistry();
1485

    
1486
    // Set path variables.
1487
    variable_set('file_public_path', $this->public_files_directory);
1488
    variable_set('file_private_path', $this->private_files_directory);
1489
    variable_set('file_temporary_path', $this->temp_files_directory);
1490

    
1491
    // Set the 'simpletest_parent_profile' variable to add the parent profile's
1492
    // search path to the child site's search paths.
1493
    // @see drupal_system_listing()
1494
    // @todo This may need to be primed like 'install_profile' above.
1495
    variable_set('simpletest_parent_profile', $this->originalProfile);
1496

    
1497
    // Include the testing profile.
1498
    variable_set('install_profile', $this->profile);
1499
    $profile_details = install_profile_info($this->profile, 'en');
1500

    
1501
    // Install the modules specified by the testing profile.
1502
    module_enable($profile_details['dependencies'], FALSE);
1503

    
1504
    // Install modules needed for this test. This could have been passed in as
1505
    // either a single array argument or a variable number of string arguments.
1506
    // @todo Remove this compatibility layer in Drupal 8, and only accept
1507
    // $modules as a single array argument.
1508
    $modules = func_get_args();
1509
    if (isset($modules[0]) && is_array($modules[0])) {
1510
      $modules = $modules[0];
1511
    }
1512
    if ($modules) {
1513
      $success = module_enable($modules, TRUE);
1514
      $this->assertTrue($success, t('Enabled modules: %modules', array('%modules' => implode(', ', $modules))));
1515
    }
1516

    
1517
    // Run the profile tasks.
1518
    $install_profile_module_exists = db_query("SELECT 1 FROM {system} WHERE type = 'module' AND name = :name", array(
1519
      ':name' => $this->profile,
1520
    ))->fetchField();
1521
    if ($install_profile_module_exists) {
1522
      module_enable(array($this->profile), FALSE);
1523
    }
1524

    
1525
    // Reset/rebuild all data structures after enabling the modules.
1526
    $this->resetAll();
1527

    
1528
    // Run cron once in that environment, as install.php does at the end of
1529
    // the installation process.
1530
    drupal_cron_run();
1531

    
1532
    // Ensure that the session is not written to the new environment and replace
1533
    // the global $user session with uid 1 from the new test site.
1534
    drupal_save_session(FALSE);
1535
    // Login as uid 1.
1536
    $user = user_load(1);
1537

    
1538
    // Restore necessary variables.
1539
    variable_set('install_task', 'done');
1540
    variable_set('clean_url', $this->originalCleanUrl);
1541
    variable_set('site_mail', 'simpletest@example.com');
1542
    variable_set('date_default_timezone', date_default_timezone_get());
1543

    
1544
    // Set up English language.
1545
    unset($conf['language_default']);
1546
    $language_url = $language = language_default();
1547

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

    
1551
    drupal_set_time_limit($this->timeLimit);
1552
    $this->setup = TRUE;
1553
  }
1554

    
1555
  /**
1556
   * Preload the registry from the testing site.
1557
   *
1558
   * This method is called by DrupalWebTestCase::setUp(), and preloads the
1559
   * registry from the testing site to cut down on the time it takes to
1560
   * set up a clean environment for the current test run.
1561
   */
1562
  protected function preloadRegistry() {
1563
    // Use two separate queries, each with their own connections: copy the
1564
    // {registry} and {registry_file} tables over from the parent installation
1565
    // to the child installation.
1566
    $original_connection = Database::getConnection('default', 'simpletest_original_default');
1567
    $test_connection = Database::getConnection();
1568

    
1569
    foreach (array('registry', 'registry_file') as $table) {
1570
      // Find the records from the parent database.
1571
      $source_query = $original_connection
1572
        ->select($table, array(), array('fetch' => PDO::FETCH_ASSOC))
1573
        ->fields($table);
1574

    
1575
      $dest_query = $test_connection->insert($table);
1576

    
1577
      $first = TRUE;
1578
      foreach ($source_query->execute() as $row) {
1579
        if ($first) {
1580
          $dest_query->fields(array_keys($row));
1581
          $first = FALSE;
1582
        }
1583
        // Insert the records into the child database.
1584
        $dest_query->values($row);
1585
      }
1586

    
1587
      $dest_query->execute();
1588
    }
1589
  }
1590

    
1591
  /**
1592
   * Reset all data structures after having enabled new modules.
1593
   *
1594
   * This method is called by DrupalWebTestCase::setUp() after enabling
1595
   * the requested modules. It must be called again when additional modules
1596
   * are enabled later.
1597
   */
1598
  protected function resetAll() {
1599
    // Reset all static variables.
1600
    drupal_static_reset();
1601
    // Reset the list of enabled modules.
1602
    module_list(TRUE);
1603

    
1604
    // Reset cached schema for new database prefix. This must be done before
1605
    // drupal_flush_all_caches() so rebuilds can make use of the schema of
1606
    // modules enabled on the cURL side.
1607
    drupal_get_schema(NULL, TRUE);
1608

    
1609
    // Perform rebuilds and flush remaining caches.
1610
    drupal_flush_all_caches();
1611

    
1612
    // Reload global $conf array and permissions.
1613
    $this->refreshVariables();
1614
    $this->checkPermissions(array(), TRUE);
1615
  }
1616

    
1617
  /**
1618
   * Refresh the in-memory set of variables. Useful after a page request is made
1619
   * that changes a variable in a different thread.
1620
   *
1621
   * In other words calling a settings page with $this->drupalPost() with a changed
1622
   * value would update a variable to reflect that change, but in the thread that
1623
   * made the call (thread running the test) the changed variable would not be
1624
   * picked up.
1625
   *
1626
   * This method clears the variables cache and loads a fresh copy from the database
1627
   * to ensure that the most up-to-date set of variables is loaded.
1628
   */
1629
  protected function refreshVariables() {
1630
    global $conf;
1631
    cache_clear_all('variables', 'cache_bootstrap');
1632
    $conf = variable_initialize();
1633
  }
1634

    
1635
  /**
1636
   * Delete created files and temporary files directory, delete the tables created by setUp(),
1637
   * and reset the database prefix.
1638
   */
1639
  protected function tearDown() {
1640
    global $user, $language, $language_url;
1641

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

    
1646
    $emailCount = count(variable_get('drupal_test_email_collector', array()));
1647
    if ($emailCount) {
1648
      $message = format_plural($emailCount, '1 e-mail was sent during this test.', '@count e-mails were sent during this test.');
1649
      $this->pass($message, t('E-mail'));
1650
    }
1651

    
1652
    // Delete temporary files directory.
1653
    file_unmanaged_delete_recursive($this->originalFileDirectory . '/simpletest/' . substr($this->databasePrefix, 10));
1654

    
1655
    // Remove all prefixed tables.
1656
    $tables = db_find_tables($this->databasePrefix . '%');
1657
    $connection_info = Database::getConnectionInfo('default');
1658
    $tables = db_find_tables($connection_info['default']['prefix']['default'] . '%');
1659
    if (empty($tables)) {
1660
      $this->fail('Failed to find test tables to drop.');
1661
    }
1662
    $prefix_length = strlen($connection_info['default']['prefix']['default']);
1663
    foreach ($tables as $table) {
1664
      if (db_drop_table(substr($table, $prefix_length))) {
1665
        unset($tables[$table]);
1666
      }
1667
    }
1668
    if (!empty($tables)) {
1669
      $this->fail('Failed to drop all prefixed tables.');
1670
    }
1671

    
1672
    // Get back to the original connection.
1673
    Database::removeConnection('default');
1674
    Database::renameConnection('simpletest_original_default', 'default');
1675

    
1676
    // Restore original shutdown callbacks array to prevent original
1677
    // environment of calling handlers from test run.
1678
    $callbacks = &drupal_register_shutdown_function();
1679
    $callbacks = $this->originalShutdownCallbacks;
1680

    
1681
    // Return the user to the original one.
1682
    $user = $this->originalUser;
1683
    drupal_save_session(TRUE);
1684

    
1685
    // Ensure that internal logged in variable and cURL options are reset.
1686
    $this->loggedInUser = FALSE;
1687
    $this->additionalCurlOptions = array();
1688

    
1689
    // Reload module list and implementations to ensure that test module hooks
1690
    // aren't called after tests.
1691
    module_list(TRUE);
1692
    module_implements('', FALSE, TRUE);
1693

    
1694
    // Reset the Field API.
1695
    field_cache_clear();
1696

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

    
1700
    // Reset public files directory.
1701
    $GLOBALS['conf']['file_public_path'] = $this->originalFileDirectory;
1702

    
1703
    // Reset language.
1704
    $language = $this->originalLanguage;
1705
    $language_url = $this->originalLanguageUrl;
1706
    if ($this->originalLanguageDefault) {
1707
      $GLOBALS['conf']['language_default'] = $this->originalLanguageDefault;
1708
    }
1709

    
1710
    // Close the CURL handler and reset the cookies array so test classes
1711
    // containing multiple tests are not polluted.
1712
    $this->curlClose();
1713
    $this->cookies = array();
1714
  }
1715

    
1716
  /**
1717
   * Initializes the cURL connection.
1718
   *
1719
   * If the simpletest_httpauth_credentials variable is set, this function will
1720
   * add HTTP authentication headers. This is necessary for testing sites that
1721
   * are protected by login credentials from public access.
1722
   * See the description of $curl_options for other options.
1723
   */
1724
  protected function curlInitialize() {
1725
    global $base_url;
1726

    
1727
    if (!isset($this->curlHandle)) {
1728
      $this->curlHandle = curl_init();
1729

    
1730
      // Some versions/configurations of cURL break on a NULL cookie jar, so
1731
      // supply a real file.
1732
      if (empty($this->cookieFile)) {
1733
        $this->cookieFile = $this->public_files_directory . '/cookie.jar';
1734
      }
1735

    
1736
      $curl_options = array(
1737
        CURLOPT_COOKIEJAR => $this->cookieFile,
1738
        CURLOPT_URL => $base_url,
1739
        CURLOPT_FOLLOWLOCATION => FALSE,
1740
        CURLOPT_RETURNTRANSFER => TRUE,
1741
        CURLOPT_SSL_VERIFYPEER => FALSE, // Required to make the tests run on HTTPS.
1742
        CURLOPT_SSL_VERIFYHOST => FALSE, // Required to make the tests run on HTTPS.
1743
        CURLOPT_HEADERFUNCTION => array(&$this, 'curlHeaderCallback'),
1744
        CURLOPT_USERAGENT => $this->databasePrefix,
1745
      );
1746
      if (isset($this->httpauth_credentials)) {
1747
        $curl_options[CURLOPT_HTTPAUTH] = $this->httpauth_method;
1748
        $curl_options[CURLOPT_USERPWD] = $this->httpauth_credentials;
1749
      }
1750
      // curl_setopt_array() returns FALSE if any of the specified options
1751
      // cannot be set, and stops processing any further options.
1752
      $result = curl_setopt_array($this->curlHandle, $this->additionalCurlOptions + $curl_options);
1753
      if (!$result) {
1754
        throw new Exception('One or more cURL options could not be set.');
1755
      }
1756

    
1757
      // By default, the child session name should be the same as the parent.
1758
      $this->session_name = session_name();
1759
    }
1760
    // We set the user agent header on each request so as to use the current
1761
    // time and a new uniqid.
1762
    if (preg_match('/simpletest\d+/', $this->databasePrefix, $matches)) {
1763
      curl_setopt($this->curlHandle, CURLOPT_USERAGENT, drupal_generate_test_ua($matches[0]));
1764
    }
1765
  }
1766

    
1767
  /**
1768
   * Initializes and executes a cURL request.
1769
   *
1770
   * @param $curl_options
1771
   *   An associative array of cURL options to set, where the keys are constants
1772
   *   defined by the cURL library. For a list of valid options, see
1773
   *   http://www.php.net/manual/function.curl-setopt.php
1774
   * @param $redirect
1775
   *   FALSE if this is an initial request, TRUE if this request is the result
1776
   *   of a redirect.
1777
   *
1778
   * @return
1779
   *   The content returned from the call to curl_exec().
1780
   *
1781
   * @see curlInitialize()
1782
   */
1783
  protected function curlExec($curl_options, $redirect = FALSE) {
1784
    $this->curlInitialize();
1785

    
1786
    if (!empty($curl_options[CURLOPT_URL])) {
1787
      // Forward XDebug activation if present.
1788
      if (isset($_COOKIE['XDEBUG_SESSION'])) {
1789
        $options = drupal_parse_url($curl_options[CURLOPT_URL]);
1790
        $options += array('query' => array());
1791
        $options['query'] += array('XDEBUG_SESSION_START' => $_COOKIE['XDEBUG_SESSION']);
1792
        $curl_options[CURLOPT_URL] = url($options['path'], $options);
1793
      }
1794

    
1795
      // cURL incorrectly handles URLs with a fragment by including the
1796
      // fragment in the request to the server, causing some web servers
1797
      // to reject the request citing "400 - Bad Request". To prevent
1798
      // this, we strip the fragment from the request.
1799
      // TODO: Remove this for Drupal 8, since fixed in curl 7.20.0.
1800
      if (strpos($curl_options[CURLOPT_URL], '#')) {
1801
        $original_url = $curl_options[CURLOPT_URL];
1802
        $curl_options[CURLOPT_URL] = strtok($curl_options[CURLOPT_URL], '#');
1803
      }
1804
    }
1805

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

    
1808
    if (!empty($curl_options[CURLOPT_POST])) {
1809
      // This is a fix for the Curl library to prevent Expect: 100-continue
1810
      // headers in POST requests, that may cause unexpected HTTP response
1811
      // codes from some webservers (like lighttpd that returns a 417 error
1812
      // code). It is done by setting an empty "Expect" header field that is
1813
      // not overwritten by Curl.
1814
      $curl_options[CURLOPT_HTTPHEADER][] = 'Expect:';
1815
    }
1816
    curl_setopt_array($this->curlHandle, $this->additionalCurlOptions + $curl_options);
1817

    
1818
    if (!$redirect) {
1819
      // Reset headers, the session ID and the redirect counter.
1820
      $this->session_id = NULL;
1821
      $this->headers = array();
1822
      $this->redirect_count = 0;
1823
    }
1824

    
1825
    $content = curl_exec($this->curlHandle);
1826
    $status = curl_getinfo($this->curlHandle, CURLINFO_HTTP_CODE);
1827

    
1828
    // cURL incorrectly handles URLs with fragments, so instead of
1829
    // letting cURL handle redirects we take of them ourselves to
1830
    // to prevent fragments being sent to the web server as part
1831
    // of the request.
1832
    // TODO: Remove this for Drupal 8, since fixed in curl 7.20.0.
1833
    if (in_array($status, array(300, 301, 302, 303, 305, 307)) && $this->redirect_count < variable_get('simpletest_maximum_redirects', 5)) {
1834
      if ($this->drupalGetHeader('location')) {
1835
        $this->redirect_count++;
1836
        $curl_options = array();
1837
        $curl_options[CURLOPT_URL] = $this->drupalGetHeader('location');
1838
        $curl_options[CURLOPT_HTTPGET] = TRUE;
1839
        return $this->curlExec($curl_options, TRUE);
1840
      }
1841
    }
1842

    
1843
    $this->drupalSetContent($content, isset($original_url) ? $original_url : curl_getinfo($this->curlHandle, CURLINFO_EFFECTIVE_URL));
1844
    $message_vars = array(
1845
      '!method' => !empty($curl_options[CURLOPT_NOBODY]) ? 'HEAD' : (empty($curl_options[CURLOPT_POSTFIELDS]) ? 'GET' : 'POST'),
1846
      '@url' => isset($original_url) ? $original_url : $url,
1847
      '@status' => $status,
1848
      '!length' => format_size(strlen($this->drupalGetContent()))
1849
    );
1850
    $message = t('!method @url returned @status (!length).', $message_vars);
1851
    $this->assertTrue($this->drupalGetContent() !== FALSE, $message, t('Browser'));
1852
    return $this->drupalGetContent();
1853
  }
1854

    
1855
  /**
1856
   * Reads headers and registers errors received from the tested site.
1857
   *
1858
   * @see _drupal_log_error().
1859
   *
1860
   * @param $curlHandler
1861
   *   The cURL handler.
1862
   * @param $header
1863
   *   An header.
1864
   */
1865
  protected function curlHeaderCallback($curlHandler, $header) {
1866
    // Header fields can be extended over multiple lines by preceding each
1867
    // extra line with at least one SP or HT. They should be joined on receive.
1868
    // Details are in RFC2616 section 4.
1869
    if ($header[0] == ' ' || $header[0] == "\t") {
1870
      // Normalize whitespace between chucks.
1871
      $this->headers[] = array_pop($this->headers) . ' ' . trim($header);
1872
    }
1873
    else {
1874
      $this->headers[] = $header;
1875
    }
1876

    
1877
    // Errors are being sent via X-Drupal-Assertion-* headers,
1878
    // generated by _drupal_log_error() in the exact form required
1879
    // by DrupalWebTestCase::error().
1880
    if (preg_match('/^X-Drupal-Assertion-[0-9]+: (.*)$/', $header, $matches)) {
1881
      // Call DrupalWebTestCase::error() with the parameters from the header.
1882
      call_user_func_array(array(&$this, 'error'), unserialize(urldecode($matches[1])));
1883
    }
1884

    
1885
    // Save cookies.
1886
    if (preg_match('/^Set-Cookie: ([^=]+)=(.+)/', $header, $matches)) {
1887
      $name = $matches[1];
1888
      $parts = array_map('trim', explode(';', $matches[2]));
1889
      $value = array_shift($parts);
1890
      $this->cookies[$name] = array('value' => $value, 'secure' => in_array('secure', $parts));
1891
      if ($name == $this->session_name) {
1892
        if ($value != 'deleted') {
1893
          $this->session_id = $value;
1894
        }
1895
        else {
1896
          $this->session_id = NULL;
1897
        }
1898
      }
1899
    }
1900

    
1901
    // This is required by cURL.
1902
    return strlen($header);
1903
  }
1904

    
1905
  /**
1906
   * Close the cURL handler and unset the handler.
1907
   */
1908
  protected function curlClose() {
1909
    if (isset($this->curlHandle)) {
1910
      curl_close($this->curlHandle);
1911
      unset($this->curlHandle);
1912
    }
1913
  }
1914

    
1915
  /**
1916
   * Parse content returned from curlExec using DOM and SimpleXML.
1917
   *
1918
   * @return
1919
   *   A SimpleXMLElement or FALSE on failure.
1920
   */
1921
  protected function parse() {
1922
    if (!$this->elements) {
1923
      // DOM can load HTML soup. But, HTML soup can throw warnings, suppress
1924
      // them.
1925
      $htmlDom = new DOMDocument();
1926
      @$htmlDom->loadHTML($this->drupalGetContent());
1927
      if ($htmlDom) {
1928
        $this->pass(t('Valid HTML found on "@path"', array('@path' => $this->getUrl())), t('Browser'));
1929
        // It's much easier to work with simplexml than DOM, luckily enough
1930
        // we can just simply import our DOM tree.
1931
        $this->elements = simplexml_import_dom($htmlDom);
1932
      }
1933
    }
1934
    if (!$this->elements) {
1935
      $this->fail(t('Parsed page successfully.'), t('Browser'));
1936
    }
1937

    
1938
    return $this->elements;
1939
  }
1940

    
1941
  /**
1942
   * Retrieves a Drupal path or an absolute path.
1943
   *
1944
   * @param $path
1945
   *   Drupal path or URL to load into internal browser
1946
   * @param $options
1947
   *   Options to be forwarded to url().
1948
   * @param $headers
1949
   *   An array containing additional HTTP request headers, each formatted as
1950
   *   "name: value".
1951
   * @return
1952
   *   The retrieved HTML string, also available as $this->drupalGetContent()
1953
   */
1954
  protected function drupalGet($path, array $options = array(), array $headers = array()) {
1955
    $options['absolute'] = TRUE;
1956

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

    
1963
    // Replace original page output with new output from redirected page(s).
1964
    if ($new = $this->checkForMetaRefresh()) {
1965
      $out = $new;
1966
    }
1967
    $this->verbose('GET request to: ' . $path .
1968
                   '<hr />Ending URL: ' . $this->getUrl() .
1969
                   '<hr />' . $out);
1970
    return $out;
1971
  }
1972

    
1973
  /**
1974
   * Retrieve a Drupal path or an absolute path and JSON decode the result.
1975
   */
1976
  protected function drupalGetAJAX($path, array $options = array(), array $headers = array()) {
1977
    return drupal_json_decode($this->drupalGet($path, $options, $headers));
1978
  }
1979

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

    
2084
        // We post only if we managed to handle every field in edit and the
2085
        // submit button matches.
2086
        if (!$edit && ($submit_matches || !isset($submit))) {
2087
          $post_array = $post;
2088
          if ($upload) {
2089
            // TODO: cURL handles file uploads for us, but the implementation
2090
            // is broken. This is a less than elegant workaround. Alternatives
2091
            // are being explored at #253506.
2092
            foreach ($upload as $key => $file) {
2093
              $file = drupal_realpath($file);
2094
              if ($file && is_file($file)) {
2095
                // Use the new CurlFile class for file uploads when using PHP
2096
                // 5.5 or higher.
2097
                if (class_exists('CurlFile')) {
2098
                  $post[$key] = curl_file_create($file);
2099
                }
2100
                else {
2101
                  $post[$key] = '@' . $file;
2102
                }
2103
              }
2104
            }
2105
          }
2106
          else {
2107
            foreach ($post as $key => $value) {
2108
              // Encode according to application/x-www-form-urlencoded
2109
              // Both names and values needs to be urlencoded, according to
2110
              // http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.1
2111
              $post[$key] = urlencode($key) . '=' . urlencode($value);
2112
            }
2113
            $post = implode('&', $post) . $extra_post;
2114
          }
2115
          $out = $this->curlExec(array(CURLOPT_URL => $action, CURLOPT_POST => TRUE, CURLOPT_POSTFIELDS => $post, CURLOPT_HTTPHEADER => $headers));
2116
          // Ensure that any changes to variables in the other thread are picked up.
2117
          $this->refreshVariables();
2118

    
2119
          // Replace original page output with new output from redirected page(s).
2120
          if ($new = $this->checkForMetaRefresh()) {
2121
            $out = $new;
2122
          }
2123
          $this->verbose('POST request to: ' . $path .
2124
                         '<hr />Ending URL: ' . $this->getUrl() .
2125
                         '<hr />Fields: ' . highlight_string('<?php ' . var_export($post_array, TRUE), TRUE) .
2126
                         '<hr />' . $out);
2127
          return $out;
2128
        }
2129
      }
2130
      // We have not found a form which contained all fields of $edit.
2131
      foreach ($edit as $name => $value) {
2132
        $this->fail(t('Failed to set field @name to @value', array('@name' => $name, '@value' => $value)));
2133
      }
2134
      if (!$ajax && isset($submit)) {
2135
        $this->assertTrue($submit_matches, t('Found the @submit button', array('@submit' => $submit)));
2136
      }
2137
      $this->fail(t('Found the requested form fields at @path', array('@path' => $path)));
2138
    }
2139
  }
2140

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

    
2192
    // Get the Ajax settings bound to the triggering element.
2193
    if (!isset($ajax_settings)) {
2194
      if (is_array($triggering_element)) {
2195
        $xpath = '//*[@name="' . key($triggering_element) . '" and @value="' . current($triggering_element) . '"]';
2196
      }
2197
      else {
2198
        $xpath = '//*[@name="' . $triggering_element . '"]';
2199
      }
2200
      if (isset($form_html_id)) {
2201
        $xpath = '//form[@id="' . $form_html_id . '"]' . $xpath;
2202
      }
2203
      $element = $this->xpath($xpath);
2204
      $element_id = (string) $element[0]['id'];
2205
      $ajax_settings = $drupal_settings['ajax'][$element_id];
2206
    }
2207

    
2208
    // Add extra information to the POST data as ajax.js does.
2209
    $extra_post = '';
2210
    if (isset($ajax_settings['submit'])) {
2211
      foreach ($ajax_settings['submit'] as $key => $value) {
2212
        $extra_post .= '&' . urlencode($key) . '=' . urlencode($value);
2213
      }
2214
    }
2215
    foreach ($this->xpath('//*[@id]') as $element) {
2216
      $id = (string) $element['id'];
2217
      $extra_post .= '&' . urlencode('ajax_html_ids[]') . '=' . urlencode($id);
2218
    }
2219
    if (isset($drupal_settings['ajaxPageState'])) {
2220
      $extra_post .= '&' . urlencode('ajax_page_state[theme]') . '=' . urlencode($drupal_settings['ajaxPageState']['theme']);
2221
      $extra_post .= '&' . urlencode('ajax_page_state[theme_token]') . '=' . urlencode($drupal_settings['ajaxPageState']['theme_token']);
2222
      foreach ($drupal_settings['ajaxPageState']['css'] as $key => $value) {
2223
        $extra_post .= '&' . urlencode("ajax_page_state[css][$key]") . '=1';
2224
      }
2225
      foreach ($drupal_settings['ajaxPageState']['js'] as $key => $value) {
2226
        $extra_post .= '&' . urlencode("ajax_page_state[js][$key]") . '=1';
2227
      }
2228
    }
2229

    
2230
    // Unless a particular path is specified, use the one specified by the
2231
    // Ajax settings, or else 'system/ajax'.
2232
    if (!isset($ajax_path)) {
2233
      $ajax_path = isset($ajax_settings['url']) ? $ajax_settings['url'] : 'system/ajax';
2234
    }
2235

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

    
2240
    // Change the page content by applying the returned commands.
2241
    if (!empty($ajax_settings) && !empty($return)) {
2242
      // ajax.js applies some defaults to the settings object, so do the same
2243
      // for what's used by this function.
2244
      $ajax_settings += array(
2245
        'method' => 'replaceWith',
2246
      );
2247
      // DOM can load HTML soup. But, HTML soup can throw warnings, suppress
2248
      // them.
2249
      $dom = new DOMDocument();
2250
      @$dom->loadHTML($content);
2251
      // XPath allows for finding wrapper nodes better than DOM does.
2252
      $xpath = new DOMXPath($dom);
2253
      foreach ($return as $command) {
2254
        switch ($command['command']) {
2255
          case 'settings':
2256
            $drupal_settings = drupal_array_merge_deep($drupal_settings, $command['settings']);
2257
            break;
2258

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

    
2315
          case 'updateBuildId':
2316
            $buildId = $xpath->query('//input[@name="form_build_id" and @value="' . $command['old'] . '"]')->item(0);
2317
            if ($buildId) {
2318
              $buildId->setAttribute('value', $command['new']);
2319
            }
2320
            break;
2321

    
2322
          // @todo Add suitable implementations for these commands in order to
2323
          //   have full test coverage of what ajax.js can do.
2324
          case 'remove':
2325
            break;
2326
          case 'changed':
2327
            break;
2328
          case 'css':
2329
            break;
2330
          case 'data':
2331
            break;
2332
          case 'restripe':
2333
            break;
2334
          case 'add_css':
2335
            break;
2336
        }
2337
      }
2338
      $content = $dom->saveHTML();
2339
    }
2340
    $this->drupalSetContent($content);
2341
    $this->drupalSetSettings($drupal_settings);
2342

    
2343
    $verbose = 'AJAX POST request to: ' . $path;
2344
    $verbose .= '<br />AJAX callback path: ' . $ajax_path;
2345
    $verbose .= '<hr />Ending URL: ' . $this->getUrl();
2346
    $verbose .= '<hr />' . $this->content;
2347

    
2348
    $this->verbose($verbose);
2349

    
2350
    return $return;
2351
  }
2352

    
2353
  /**
2354
   * Runs cron in the Drupal installed by Simpletest.
2355
   */
2356
  protected function cronRun() {
2357
    $this->drupalGet($GLOBALS['base_url'] . '/cron.php', array('external' => TRUE, 'query' => array('cron_key' => variable_get('cron_key', 'drupal'))));
2358
  }
2359

    
2360
  /**
2361
   * Check for meta refresh tag and if found call drupalGet() recursively. This
2362
   * function looks for the http-equiv attribute to be set to "Refresh"
2363
   * and is case-sensitive.
2364
   *
2365
   * @return
2366
   *   Either the new page content or FALSE.
2367
   */
2368
  protected function checkForMetaRefresh() {
2369
    if (strpos($this->drupalGetContent(), '<meta ') && $this->parse()) {
2370
      $refresh = $this->xpath('//meta[@http-equiv="Refresh"]');
2371
      if (!empty($refresh)) {
2372
        // Parse the content attribute of the meta tag for the format:
2373
        // "[delay]: URL=[page_to_redirect_to]".
2374
        if (preg_match('/\d+;\s*URL=(?P<url>.*)/i', $refresh[0]['content'], $match)) {
2375
          return $this->drupalGet($this->getAbsoluteUrl(decode_entities($match['url'])));
2376
        }
2377
      }
2378
    }
2379
    return FALSE;
2380
  }
2381

    
2382
  /**
2383
   * Retrieves only the headers for a Drupal path or an absolute path.
2384
   *
2385
   * @param $path
2386
   *   Drupal path or URL to load into internal browser
2387
   * @param $options
2388
   *   Options to be forwarded to url().
2389
   * @param $headers
2390
   *   An array containing additional HTTP request headers, each formatted as
2391
   *   "name: value".
2392
   * @return
2393
   *   The retrieved headers, also available as $this->drupalGetContent()
2394
   */
2395
  protected function drupalHead($path, array $options = array(), array $headers = array()) {
2396
    $options['absolute'] = TRUE;
2397
    $out = $this->curlExec(array(CURLOPT_NOBODY => TRUE, CURLOPT_URL => url($path, $options), CURLOPT_HTTPHEADER => $headers));
2398
    $this->refreshVariables(); // Ensure that any changes to variables in the other thread are picked up.
2399
    return $out;
2400
  }
2401

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

    
2555
  /**
2556
   * Builds an XPath query.
2557
   *
2558
   * Builds an XPath query by replacing placeholders in the query by the value
2559
   * of the arguments.
2560
   *
2561
   * XPath 1.0 (the version supported by libxml2, the underlying XML library
2562
   * used by PHP) doesn't support any form of quotation. This function
2563
   * simplifies the building of XPath expression.
2564
   *
2565
   * @param $xpath
2566
   *   An XPath query, possibly with placeholders in the form ':name'.
2567
   * @param $args
2568
   *   An array of arguments with keys in the form ':name' matching the
2569
   *   placeholders in the query. The values may be either strings or numeric
2570
   *   values.
2571
   * @return
2572
   *   An XPath query with arguments replaced.
2573
   */
2574
  protected function buildXPathQuery($xpath, array $args = array()) {
2575
    // Replace placeholders.
2576
    foreach ($args as $placeholder => $value) {
2577
      // XPath 1.0 doesn't support a way to escape single or double quotes in a
2578
      // string literal. We split double quotes out of the string, and encode
2579
      // them separately.
2580
      if (is_string($value)) {
2581
        // Explode the text at the quote characters.
2582
        $parts = explode('"', $value);
2583

    
2584
        // Quote the parts.
2585
        foreach ($parts as &$part) {
2586
          $part = '"' . $part . '"';
2587
        }
2588

    
2589
        // Return the string.
2590
        $value = count($parts) > 1 ? 'concat(' . implode(', \'"\', ', $parts) . ')' : $parts[0];
2591
      }
2592
      $xpath = preg_replace('/' . preg_quote($placeholder) . '\b/', $value, $xpath);
2593
    }
2594
    return $xpath;
2595
  }
2596

    
2597
  /**
2598
   * Perform an xpath search on the contents of the internal browser. The search
2599
   * is relative to the root element (HTML tag normally) of the page.
2600
   *
2601
   * @param $xpath
2602
   *   The xpath string to use in the search.
2603
   * @param array $arguments
2604
   *   An array of arguments with keys in the form ':name' matching the
2605
   *   placeholders in the query. The values may be either strings or numeric
2606
   *   values.
2607
   *
2608
   * @return
2609
   *   The return value of the xpath search. For details on the xpath string
2610
   *   format and return values see the SimpleXML documentation,
2611
   *   http://us.php.net/manual/function.simplexml-element-xpath.php.
2612
   */
2613
  protected function xpath($xpath, array $arguments = array()) {
2614
    if ($this->parse()) {
2615
      $xpath = $this->buildXPathQuery($xpath, $arguments);
2616
      $result = $this->elements->xpath($xpath);
2617
      // Some combinations of PHP / libxml versions return an empty array
2618
      // instead of the documented FALSE. Forcefully convert any falsish values
2619
      // to an empty array to allow foreach(...) constructions.
2620
      return $result ? $result : array();
2621
    }
2622
    else {
2623
      return FALSE;
2624
    }
2625
  }
2626

    
2627
  /**
2628
   * Get all option elements, including nested options, in a select.
2629
   *
2630
   * @param $element
2631
   *   The element for which to get the options.
2632
   * @return
2633
   *   Option elements in select.
2634
   */
2635
  protected function getAllOptions(SimpleXMLElement $element) {
2636
    $options = array();
2637
    // Add all options items.
2638
    foreach ($element->option as $option) {
2639
      $options[] = $option;
2640
    }
2641

    
2642
    // Search option group children.
2643
    if (isset($element->optgroup)) {
2644
      foreach ($element->optgroup as $group) {
2645
        $options = array_merge($options, $this->getAllOptions($group));
2646
      }
2647
    }
2648
    return $options;
2649
  }
2650

    
2651
  /**
2652
   * Pass if a link with the specified label is found, and optional with the
2653
   * specified index.
2654
   *
2655
   * @param $label
2656
   *   Text between the anchor tags.
2657
   * @param $index
2658
   *   Link position counting from zero.
2659
   * @param $message
2660
   *   Message to display.
2661
   * @param $group
2662
   *   The group this message belongs to, defaults to 'Other'.
2663
   * @return
2664
   *   TRUE if the assertion succeeded, FALSE otherwise.
2665
   */
2666
  protected function assertLink($label, $index = 0, $message = '', $group = 'Other') {
2667
    $links = $this->xpath('//a[normalize-space(text())=:label]', array(':label' => $label));
2668
    $message = ($message ?  $message : t('Link with label %label found.', array('%label' => $label)));
2669
    return $this->assert(isset($links[$index]), $message, $group);
2670
  }
2671

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

    
2690
  /**
2691
   * Pass if a link containing a given href (part) is found.
2692
   *
2693
   * @param $href
2694
   *   The full or partial value of the 'href' attribute of the anchor tag.
2695
   * @param $index
2696
   *   Link position counting from zero.
2697
   * @param $message
2698
   *   Message to display.
2699
   * @param $group
2700
   *   The group this message belongs to, defaults to 'Other'.
2701
   *
2702
   * @return
2703
   *   TRUE if the assertion succeeded, FALSE otherwise.
2704
   */
2705
  protected function assertLinkByHref($href, $index = 0, $message = '', $group = 'Other') {
2706
    $links = $this->xpath('//a[contains(@href, :href)]', array(':href' => $href));
2707
    $message = ($message ?  $message : t('Link containing href %href found.', array('%href' => $href)));
2708
    return $this->assert(isset($links[$index]), $message, $group);
2709
  }
2710

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

    
2730
  /**
2731
   * Follows a link by name.
2732
   *
2733
   * Will click the first link found with this link text by default, or a later
2734
   * one if an index is given. Match is case sensitive with normalized space.
2735
   * The label is translated label.
2736
   *
2737
   * If the link is discovered and clicked, the test passes. Fail otherwise.
2738
   *
2739
   * @param $label
2740
   *   Text between the anchor tags.
2741
   * @param $index
2742
   *   Link position counting from zero.
2743
   * @return
2744
   *   Page contents on success, or FALSE on failure.
2745
   */
2746
  protected function clickLink($label, $index = 0) {
2747
    $url_before = $this->getUrl();
2748
    $urls = $this->xpath('//a[normalize-space(text())=:label]', array(':label' => $label));
2749
    if (isset($urls[$index])) {
2750
      $url_target = $this->getAbsoluteUrl($urls[$index]['href']);
2751
      $this->pass(t('Clicked link %label (@url_target) from @url_before', array('%label' => $label, '@url_target' => $url_target, '@url_before' => $url_before)), 'Browser');
2752
      return $this->drupalGet($url_target);
2753
    }
2754
    $this->fail(t('Link %label does not exist on @url_before', array('%label' => $label, '@url_before' => $url_before)), 'Browser');
2755
    return FALSE;
2756
  }
2757

    
2758
  /**
2759
   * Takes a path and returns an absolute path.
2760
   *
2761
   * @param $path
2762
   *   A path from the internal browser content.
2763
   * @return
2764
   *   The $path with $base_url prepended, if necessary.
2765
   */
2766
  protected function getAbsoluteUrl($path) {
2767
    global $base_url, $base_path;
2768

    
2769
    $parts = parse_url($path);
2770
    if (empty($parts['host'])) {
2771
      // Ensure that we have a string (and no xpath object).
2772
      $path = (string) $path;
2773
      // Strip $base_path, if existent.
2774
      $length = strlen($base_path);
2775
      if (substr($path, 0, $length) === $base_path) {
2776
        $path = substr($path, $length);
2777
      }
2778
      // Ensure that we have an absolute path.
2779
      if (empty($path) || $path[0] !== '/') {
2780
        $path = '/' . $path;
2781
      }
2782
      // Finally, prepend the $base_url.
2783
      $path = $base_url . $path;
2784
    }
2785
    return $path;
2786
  }
2787

    
2788
  /**
2789
   * Get the current URL from the cURL handler.
2790
   *
2791
   * @return
2792
   *   The current URL.
2793
   */
2794
  protected function getUrl() {
2795
    return $this->url;
2796
  }
2797

    
2798
  /**
2799
   * Gets the HTTP response headers of the requested page. Normally we are only
2800
   * interested in the headers returned by the last request. However, if a page
2801
   * is redirected or HTTP authentication is in use, multiple requests will be
2802
   * required to retrieve the page. Headers from all requests may be requested
2803
   * by passing TRUE to this function.
2804
   *
2805
   * @param $all_requests
2806
   *   Boolean value specifying whether to return headers from all requests
2807
   *   instead of just the last request. Defaults to FALSE.
2808
   * @return
2809
   *   A name/value array if headers from only the last request are requested.
2810
   *   If headers from all requests are requested, an array of name/value
2811
   *   arrays, one for each request.
2812
   *
2813
   *   The pseudonym ":status" is used for the HTTP status line.
2814
   *
2815
   *   Values for duplicate headers are stored as a single comma-separated list.
2816
   */
2817
  protected function drupalGetHeaders($all_requests = FALSE) {
2818
    $request = 0;
2819
    $headers = array($request => array());
2820
    foreach ($this->headers as $header) {
2821
      $header = trim($header);
2822
      if ($header === '') {
2823
        $request++;
2824
      }
2825
      else {
2826
        if (strpos($header, 'HTTP/') === 0) {
2827
          $name = ':status';
2828
          $value = $header;
2829
        }
2830
        else {
2831
          list($name, $value) = explode(':', $header, 2);
2832
          $name = strtolower($name);
2833
        }
2834
        if (isset($headers[$request][$name])) {
2835
          $headers[$request][$name] .= ',' . trim($value);
2836
        }
2837
        else {
2838
          $headers[$request][$name] = trim($value);
2839
        }
2840
      }
2841
    }
2842
    if (!$all_requests) {
2843
      $headers = array_pop($headers);
2844
    }
2845
    return $headers;
2846
  }
2847

    
2848
  /**
2849
   * Gets the value of an HTTP response header. If multiple requests were
2850
   * required to retrieve the page, only the headers from the last request will
2851
   * be checked by default. However, if TRUE is passed as the second argument,
2852
   * all requests will be processed from last to first until the header is
2853
   * found.
2854
   *
2855
   * @param $name
2856
   *   The name of the header to retrieve. Names are case-insensitive (see RFC
2857
   *   2616 section 4.2).
2858
   * @param $all_requests
2859
   *   Boolean value specifying whether to check all requests if the header is
2860
   *   not found in the last request. Defaults to FALSE.
2861
   * @return
2862
   *   The HTTP header value or FALSE if not found.
2863
   */
2864
  protected function drupalGetHeader($name, $all_requests = FALSE) {
2865
    $name = strtolower($name);
2866
    $header = FALSE;
2867
    if ($all_requests) {
2868
      foreach (array_reverse($this->drupalGetHeaders(TRUE)) as $headers) {
2869
        if (isset($headers[$name])) {
2870
          $header = $headers[$name];
2871
          break;
2872
        }
2873
      }
2874
    }
2875
    else {
2876
      $headers = $this->drupalGetHeaders();
2877
      if (isset($headers[$name])) {
2878
        $header = $headers[$name];
2879
      }
2880
    }
2881
    return $header;
2882
  }
2883

    
2884
  /**
2885
   * Gets the current raw HTML of requested page.
2886
   */
2887
  protected function drupalGetContent() {
2888
    return $this->content;
2889
  }
2890

    
2891
  /**
2892
   * Gets the value of the Drupal.settings JavaScript variable for the currently loaded page.
2893
   */
2894
  protected function drupalGetSettings() {
2895
    return $this->drupalSettings;
2896
  }
2897

    
2898
  /**
2899
   * Gets an array containing all e-mails sent during this test case.
2900
   *
2901
   * @param $filter
2902
   *   An array containing key/value pairs used to filter the e-mails that are returned.
2903
   * @return
2904
   *   An array containing e-mail messages captured during the current test.
2905
   */
2906
  protected function drupalGetMails($filter = array()) {
2907
    $captured_emails = variable_get('drupal_test_email_collector', array());
2908
    $filtered_emails = array();
2909

    
2910
    foreach ($captured_emails as $message) {
2911
      foreach ($filter as $key => $value) {
2912
        if (!isset($message[$key]) || $message[$key] != $value) {
2913
          continue 2;
2914
        }
2915
      }
2916
      $filtered_emails[] = $message;
2917
    }
2918

    
2919
    return $filtered_emails;
2920
  }
2921

    
2922
  /**
2923
   * Sets the raw HTML content. This can be useful when a page has been fetched
2924
   * outside of the internal browser and assertions need to be made on the
2925
   * returned page.
2926
   *
2927
   * A good example would be when testing drupal_http_request(). After fetching
2928
   * the page the content can be set and page elements can be checked to ensure
2929
   * that the function worked properly.
2930
   */
2931
  protected function drupalSetContent($content, $url = 'internal:') {
2932
    $this->content = $content;
2933
    $this->url = $url;
2934
    $this->plainTextContent = FALSE;
2935
    $this->elements = FALSE;
2936
    $this->drupalSettings = array();
2937
    if (preg_match('/jQuery\.extend\(Drupal\.settings, (.*?)\);/', $content, $matches)) {
2938
      $this->drupalSettings = drupal_json_decode($matches[1]);
2939
    }
2940
  }
2941

    
2942
  /**
2943
   * Sets the value of the Drupal.settings JavaScript variable for the currently loaded page.
2944
   */
2945
  protected function drupalSetSettings($settings) {
2946
    $this->drupalSettings = $settings;
2947
  }
2948

    
2949
  /**
2950
   * Pass if the internal browser's URL matches the given path.
2951
   *
2952
   * @param $path
2953
   *   The expected system path.
2954
   * @param $options
2955
   *   (optional) Any additional options to pass for $path to url().
2956
   * @param $message
2957
   *   Message to display.
2958
   * @param $group
2959
   *   The group this message belongs to, defaults to 'Other'.
2960
   *
2961
   * @return
2962
   *   TRUE on pass, FALSE on fail.
2963
   */
2964
  protected function assertUrl($path, array $options = array(), $message = '', $group = 'Other') {
2965
    if (!$message) {
2966
      $message = t('Current URL is @url.', array(
2967
        '@url' => var_export(url($path, $options), TRUE),
2968
      ));
2969
    }
2970
    $options['absolute'] = TRUE;
2971
    return $this->assertEqual($this->getUrl(), url($path, $options), $message, $group);
2972
  }
2973

    
2974
  /**
2975
   * Pass if the raw text IS found on the loaded page, fail otherwise. Raw text
2976
   * refers to the raw HTML that the page generated.
2977
   *
2978
   * @param $raw
2979
   *   Raw (HTML) string to look for.
2980
   * @param $message
2981
   *   Message to display.
2982
   * @param $group
2983
   *   The group this message belongs to, defaults to 'Other'.
2984
   * @return
2985
   *   TRUE on pass, FALSE on fail.
2986
   */
2987
  protected function assertRaw($raw, $message = '', $group = 'Other') {
2988
    if (!$message) {
2989
      $message = t('Raw "@raw" found', array('@raw' => $raw));
2990
    }
2991
    return $this->assert(strpos($this->drupalGetContent(), $raw) !== FALSE, $message, $group);
2992
  }
2993

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

    
3014
  /**
3015
   * Pass if the text IS found on the text version of the page. The text version
3016
   * is the equivalent of what a user would see when viewing through a web browser.
3017
   * In other words the HTML has been filtered out of the contents.
3018
   *
3019
   * @param $text
3020
   *   Plain text 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 assertText($text, $message = '', $group = 'Other') {
3029
    return $this->assertTextHelper($text, $message, $group, FALSE);
3030
  }
3031

    
3032
  /**
3033
   * Pass if the text is NOT found on the text version of the page. The text version
3034
   * is the equivalent of what a user would see when viewing through a web browser.
3035
   * In other words the HTML has been filtered out of the contents.
3036
   *
3037
   * @param $text
3038
   *   Plain text to look for.
3039
   * @param $message
3040
   *   Message to display.
3041
   * @param $group
3042
   *   The group this message belongs to, defaults to 'Other'.
3043
   * @return
3044
   *   TRUE on pass, FALSE on fail.
3045
   */
3046
  protected function assertNoText($text, $message = '', $group = 'Other') {
3047
    return $this->assertTextHelper($text, $message, $group, TRUE);
3048
  }
3049

    
3050
  /**
3051
   * Helper for assertText and assertNoText.
3052
   *
3053
   * It is not recommended to call this function directly.
3054
   *
3055
   * @param $text
3056
   *   Plain text to look for.
3057
   * @param $message
3058
   *   Message to display.
3059
   * @param $group
3060
   *   The group this message belongs to.
3061
   * @param $not_exists
3062
   *   TRUE if this text should not exist, FALSE if it should.
3063
   * @return
3064
   *   TRUE on pass, FALSE on fail.
3065
   */
3066
  protected function assertTextHelper($text, $message = '', $group, $not_exists) {
3067
    if ($this->plainTextContent === FALSE) {
3068
      $this->plainTextContent = filter_xss($this->drupalGetContent(), array());
3069
    }
3070
    if (!$message) {
3071
      $message = !$not_exists ? t('"@text" found', array('@text' => $text)) : t('"@text" not found', array('@text' => $text));
3072
    }
3073
    return $this->assert($not_exists == (strpos($this->plainTextContent, $text) === FALSE), $message, $group);
3074
  }
3075

    
3076
  /**
3077
   * Pass if the text is found ONLY ONCE on the text version of the page.
3078
   *
3079
   * The text version is the equivalent of what a user would see when viewing
3080
   * through a web browser. In other words the HTML has been filtered out of
3081
   * the contents.
3082
   *
3083
   * @param $text
3084
   *   Plain text to look for.
3085
   * @param $message
3086
   *   Message to display.
3087
   * @param $group
3088
   *   The group this message belongs to, defaults to 'Other'.
3089
   * @return
3090
   *   TRUE on pass, FALSE on fail.
3091
   */
3092
  protected function assertUniqueText($text, $message = '', $group = 'Other') {
3093
    return $this->assertUniqueTextHelper($text, $message, $group, TRUE);
3094
  }
3095

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

    
3116
  /**
3117
   * Helper for assertUniqueText and assertNoUniqueText.
3118
   *
3119
   * It is not recommended to call this function directly.
3120
   *
3121
   * @param $text
3122
   *   Plain text to look for.
3123
   * @param $message
3124
   *   Message to display.
3125
   * @param $group
3126
   *   The group this message belongs to.
3127
   * @param $be_unique
3128
   *   TRUE if this text should be found only once, FALSE if it should be found more than once.
3129
   * @return
3130
   *   TRUE on pass, FALSE on fail.
3131
   */
3132
  protected function assertUniqueTextHelper($text, $message = '', $group, $be_unique) {
3133
    if ($this->plainTextContent === FALSE) {
3134
      $this->plainTextContent = filter_xss($this->drupalGetContent(), array());
3135
    }
3136
    if (!$message) {
3137
      $message = '"' . $text . '"' . ($be_unique ? ' found only once' : ' found more than once');
3138
    }
3139
    $first_occurance = strpos($this->plainTextContent, $text);
3140
    if ($first_occurance === FALSE) {
3141
      return $this->assert(FALSE, $message, $group);
3142
    }
3143
    $offset = $first_occurance + strlen($text);
3144
    $second_occurance = strpos($this->plainTextContent, $text, $offset);
3145
    return $this->assert($be_unique == ($second_occurance === FALSE), $message, $group);
3146
  }
3147

    
3148
  /**
3149
   * Will trigger a pass if the Perl regex pattern is found in the raw content.
3150
   *
3151
   * @param $pattern
3152
   *   Perl regex to look for including the regex delimiters.
3153
   * @param $message
3154
   *   Message to display.
3155
   * @param $group
3156
   *   The group this message belongs to.
3157
   * @return
3158
   *   TRUE on pass, FALSE on fail.
3159
   */
3160
  protected function assertPattern($pattern, $message = '', $group = 'Other') {
3161
    if (!$message) {
3162
      $message = t('Pattern "@pattern" found', array('@pattern' => $pattern));
3163
    }
3164
    return $this->assert((bool) preg_match($pattern, $this->drupalGetContent()), $message, $group);
3165
  }
3166

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

    
3186
  /**
3187
   * Pass if the page title is the given string.
3188
   *
3189
   * @param $title
3190
   *   The string the title should be.
3191
   * @param $message
3192
   *   Message to display.
3193
   * @param $group
3194
   *   The group this message belongs to.
3195
   * @return
3196
   *   TRUE on pass, FALSE on fail.
3197
   */
3198
  protected function assertTitle($title, $message = '', $group = 'Other') {
3199
    $actual = (string) current($this->xpath('//title'));
3200
    if (!$message) {
3201
      $message = t('Page title @actual is equal to @expected.', array(
3202
        '@actual' => var_export($actual, TRUE),
3203
        '@expected' => var_export($title, TRUE),
3204
      ));
3205
    }
3206
    return $this->assertEqual($actual, $title, $message, $group);
3207
  }
3208

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

    
3232
  /**
3233
   * Asserts themed output.
3234
   *
3235
   * @param $callback
3236
   *   The name of the theme function to invoke; e.g. 'links' for theme_links().
3237
   * @param $variables
3238
   *   (optional) An array of variables to pass to the theme function.
3239
   * @param $expected
3240
   *   The expected themed output string.
3241
   * @param $message
3242
   *   (optional) A message to display with the assertion. Do not translate
3243
   *   messages: use format_string() to embed variables in the message text, not
3244
   *   t(). If left blank, a default message will be displayed.
3245
   * @param $group
3246
   *   (optional) The group this message is in, which is displayed in a column
3247
   *   in test output. Use 'Debug' to indicate this is debugging output. Do not
3248
   *   translate this string. Defaults to 'Other'; most tests do not override
3249
   *   this default.
3250
   *
3251
   * @return
3252
   *   TRUE on pass, FALSE on fail.
3253
   */
3254
  protected function assertThemeOutput($callback, array $variables = array(), $expected, $message = '', $group = 'Other') {
3255
    $output = theme($callback, $variables);
3256
    $this->verbose('Variables:' . '<pre>' .  check_plain(var_export($variables, TRUE)) . '</pre>'
3257
      . '<hr />' . 'Result:' . '<pre>' .  check_plain(var_export($output, TRUE)) . '</pre>'
3258
      . '<hr />' . 'Expected:' . '<pre>' .  check_plain(var_export($expected, TRUE)) . '</pre>'
3259
      . '<hr />' . $output
3260
    );
3261
    if (!$message) {
3262
      $message = '%callback rendered correctly.';
3263
    }
3264
    $message = format_string($message, array('%callback' => 'theme_' . $callback . '()'));
3265
    return $this->assertIdentical($output, $expected, $message, $group);
3266
  }
3267

    
3268
  /**
3269
   * Asserts that a field exists in the current page by the given XPath.
3270
   *
3271
   * @param $xpath
3272
   *   XPath used to find the field.
3273
   * @param $value
3274
   *   (optional) Value of the field to assert. You may pass in NULL (default)
3275
   *   to skip checking the actual value, while still checking that the field
3276
   *   exists.
3277
   * @param $message
3278
   *   (optional) Message to display.
3279
   * @param $group
3280
   *   (optional) The group this message belongs to.
3281
   *
3282
   * @return
3283
   *   TRUE on pass, FALSE on fail.
3284
   */
3285
  protected function assertFieldByXPath($xpath, $value = NULL, $message = '', $group = 'Other') {
3286
    $fields = $this->xpath($xpath);
3287

    
3288
    // If value specified then check array for match.
3289
    $found = TRUE;
3290
    if (isset($value)) {
3291
      $found = FALSE;
3292
      if ($fields) {
3293
        foreach ($fields as $field) {
3294
          if (isset($field['value']) && $field['value'] == $value) {
3295
            // Input element with correct value.
3296
            $found = TRUE;
3297
          }
3298
          elseif (isset($field->option)) {
3299
            // Select element found.
3300
            if ($this->getSelectedItem($field) == $value) {
3301
              $found = TRUE;
3302
            }
3303
            else {
3304
              // No item selected so use first item.
3305
              $items = $this->getAllOptions($field);
3306
              if (!empty($items) && $items[0]['value'] == $value) {
3307
                $found = TRUE;
3308
              }
3309
            }
3310
          }
3311
          elseif ((string) $field == $value) {
3312
            // Text area with correct text.
3313
            $found = TRUE;
3314
          }
3315
        }
3316
      }
3317
    }
3318
    return $this->assertTrue($fields && $found, $message, $group);
3319
  }
3320

    
3321
  /**
3322
   * Get the selected value from a select field.
3323
   *
3324
   * @param $element
3325
   *   SimpleXMLElement select element.
3326
   * @return
3327
   *   The selected value or FALSE.
3328
   */
3329
  protected function getSelectedItem(SimpleXMLElement $element) {
3330
    foreach ($element->children() as $item) {
3331
      if (isset($item['selected'])) {
3332
        return $item['value'];
3333
      }
3334
      elseif ($item->getName() == 'optgroup') {
3335
        if ($value = $this->getSelectedItem($item)) {
3336
          return $value;
3337
        }
3338
      }
3339
    }
3340
    return FALSE;
3341
  }
3342

    
3343
  /**
3344
   * Asserts that a field doesn't exist or its value doesn't match, by XPath.
3345
   *
3346
   * @param $xpath
3347
   *   XPath used to find the field.
3348
   * @param $value
3349
   *   (optional) Value for the field, to assert that the field's value on the
3350
   *   page doesn't match it. You may pass in NULL to skip checking the
3351
   *   value, while still checking that the field doesn't exist.
3352
   * @param $message
3353
   *   (optional) Message to display.
3354
   * @param $group
3355
   *   (optional) The group this message belongs to.
3356
   *
3357
   * @return
3358
   *   TRUE on pass, FALSE on fail.
3359
   */
3360
  protected function assertNoFieldByXPath($xpath, $value = NULL, $message = '', $group = 'Other') {
3361
    $fields = $this->xpath($xpath);
3362

    
3363
    // If value specified then check array for match.
3364
    $found = TRUE;
3365
    if (isset($value)) {
3366
      $found = FALSE;
3367
      if ($fields) {
3368
        foreach ($fields as $field) {
3369
          if ($field['value'] == $value) {
3370
            $found = TRUE;
3371
          }
3372
        }
3373
      }
3374
    }
3375
    return $this->assertFalse($fields && $found, $message, $group);
3376
  }
3377

    
3378
  /**
3379
   * Asserts that a field exists in the current page with the given name and value.
3380
   *
3381
   * @param $name
3382
   *   Name of field to assert.
3383
   * @param $value
3384
   *   (optional) Value of the field to assert. You may pass in NULL (default)
3385
   *   to skip checking the actual value, while still checking that the field
3386
   *   exists.
3387
   * @param $message
3388
   *   Message to display.
3389
   * @param $group
3390
   *   The group this message belongs to.
3391
   * @return
3392
   *   TRUE on pass, FALSE on fail.
3393
   */
3394
  protected function assertFieldByName($name, $value = NULL, $message = NULL) {
3395
    if (!isset($message)) {
3396
      if (!isset($value)) {
3397
        $message = t('Found field with name @name', array(
3398
          '@name' => var_export($name, TRUE),
3399
        ));
3400
      }
3401
      else {
3402
        $message = t('Found field with name @name and value @value', array(
3403
          '@name' => var_export($name, TRUE),
3404
          '@value' => var_export($value, TRUE),
3405
        ));
3406
      }
3407
    }
3408
    return $this->assertFieldByXPath($this->constructFieldXpath('name', $name), $value, $message, t('Browser'));
3409
  }
3410

    
3411
  /**
3412
   * Asserts that a field does not exist with the given name and value.
3413
   *
3414
   * @param $name
3415
   *   Name of field to assert.
3416
   * @param $value
3417
   *   (optional) Value for the field, to assert that the field's value on the
3418
   *   page doesn't match it. You may pass in NULL to skip checking the
3419
   *   value, while still checking that the field doesn't exist. However, the
3420
   *   default value ('') asserts that the field value is not an empty string.
3421
   * @param $message
3422
   *   (optional) Message to display.
3423
   * @param $group
3424
   *   The group this message belongs to.
3425
   * @return
3426
   *   TRUE on pass, FALSE on fail.
3427
   */
3428
  protected function assertNoFieldByName($name, $value = '', $message = '') {
3429
    return $this->assertNoFieldByXPath($this->constructFieldXpath('name', $name), $value, $message ? $message : t('Did not find field by name @name', array('@name' => $name)), t('Browser'));
3430
  }
3431

    
3432
  /**
3433
   * Asserts that a field exists in the current page with the given ID and value.
3434
   *
3435
   * @param $id
3436
   *   ID of field to assert.
3437
   * @param $value
3438
   *   (optional) Value for the field to assert. You may pass in NULL to skip
3439
   *   checking the value, while still checking that the field exists.
3440
   *   However, the default value ('') asserts that the field value is an empty
3441
   *   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 assertFieldById($id, $value = '', $message = '') {
3450
    return $this->assertFieldByXPath($this->constructFieldXpath('id', $id), $value, $message ? $message : t('Found field by id @id', array('@id' => $id)), t('Browser'));
3451
  }
3452

    
3453
  /**
3454
   * Asserts that a field does not exist 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 that the field's value on the
3460
   *   page doesn't match it. You may pass in NULL to skip checking the value,
3461
   *   while still checking that the field doesn't exist. However, the default
3462
   *   value ('') asserts that the field value is not an empty 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 assertNoFieldById($id, $value = '', $message = '') {
3471
    return $this->assertNoFieldByXPath($this->constructFieldXpath('id', $id), $value, $message ? $message : t('Did not find field by id @id', array('@id' => $id)), t('Browser'));
3472
  }
3473

    
3474
  /**
3475
   * Asserts that a checkbox field in the current page is checked.
3476
   *
3477
   * @param $id
3478
   *   ID of field to assert.
3479
   * @param $message
3480
   *   (optional) Message to display.
3481
   * @return
3482
   *   TRUE on pass, FALSE on fail.
3483
   */
3484
  protected function assertFieldChecked($id, $message = '') {
3485
    $elements = $this->xpath('//input[@id=:id]', array(':id' => $id));
3486
    return $this->assertTrue(isset($elements[0]) && !empty($elements[0]['checked']), $message ? $message : t('Checkbox field @id is checked.', array('@id' => $id)), t('Browser'));
3487
  }
3488

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

    
3504
  /**
3505
   * Asserts that a select option in the current page is checked.
3506
   *
3507
   * @param $id
3508
   *   ID of select field to assert.
3509
   * @param $option
3510
   *   Option to assert.
3511
   * @param $message
3512
   *   (optional) Message to display.
3513
   * @return
3514
   *   TRUE on pass, FALSE on fail.
3515
   *
3516
   * @todo $id is unusable. Replace with $name.
3517
   */
3518
  protected function assertOptionSelected($id, $option, $message = '') {
3519
    $elements = $this->xpath('//select[@id=:id]//option[@value=:option]', array(':id' => $id, ':option' => $option));
3520
    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'));
3521
  }
3522

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

    
3540
  /**
3541
   * Asserts that a field exists with the given name or ID.
3542
   *
3543
   * @param $field
3544
   *   Name or ID of field to assert.
3545
   * @param $message
3546
   *   (optional) Message to display.
3547
   * @param $group
3548
   *   The group this message belongs to.
3549
   * @return
3550
   *   TRUE on pass, FALSE on fail.
3551
   */
3552
  protected function assertField($field, $message = '', $group = 'Other') {
3553
    return $this->assertFieldByXPath($this->constructFieldXpath('name', $field) . '|' . $this->constructFieldXpath('id', $field), NULL, $message, $group);
3554
  }
3555

    
3556
  /**
3557
   * Asserts that a field does not exist with the given name or ID.
3558
   *
3559
   * @param $field
3560
   *   Name or ID of field to assert.
3561
   * @param $message
3562
   *   (optional) Message to display.
3563
   * @param $group
3564
   *   The group this message belongs to.
3565
   * @return
3566
   *   TRUE on pass, FALSE on fail.
3567
   */
3568
  protected function assertNoField($field, $message = '', $group = 'Other') {
3569
    return $this->assertNoFieldByXPath($this->constructFieldXpath('name', $field) . '|' . $this->constructFieldXpath('id', $field), NULL, $message, $group);
3570
  }
3571

    
3572
  /**
3573
   * Asserts that each HTML ID is used for just a single element.
3574
   *
3575
   * @param $message
3576
   *   Message to display.
3577
   * @param $group
3578
   *   The group this message belongs to.
3579
   * @param $ids_to_skip
3580
   *   An optional array of ids to skip when checking for duplicates. It is
3581
   *   always a bug to have duplicate HTML IDs, so this parameter is to enable
3582
   *   incremental fixing of core code. Whenever a test passes this parameter,
3583
   *   it should add a "todo" comment above the call to this function explaining
3584
   *   the legacy bug that the test wishes to ignore and including a link to an
3585
   *   issue that is working to fix that legacy bug.
3586
   * @return
3587
   *   TRUE on pass, FALSE on fail.
3588
   */
3589
  protected function assertNoDuplicateIds($message = '', $group = 'Other', $ids_to_skip = array()) {
3590
    $status = TRUE;
3591
    foreach ($this->xpath('//*[@id]') as $element) {
3592
      $id = (string) $element['id'];
3593
      if (isset($seen_ids[$id]) && !in_array($id, $ids_to_skip)) {
3594
        $this->fail(t('The HTML ID %id is unique.', array('%id' => $id)), $group);
3595
        $status = FALSE;
3596
      }
3597
      $seen_ids[$id] = TRUE;
3598
    }
3599
    return $this->assert($status, $message, $group);
3600
  }
3601

    
3602
  /**
3603
   * Helper function: construct an XPath for the given set of attributes and value.
3604
   *
3605
   * @param $attribute
3606
   *   Field attributes.
3607
   * @param $value
3608
   *   Value of field.
3609
   * @return
3610
   *   XPath for specified values.
3611
   */
3612
  protected function constructFieldXpath($attribute, $value) {
3613
    $xpath = '//textarea[@' . $attribute . '=:value]|//input[@' . $attribute . '=:value]|//select[@' . $attribute . '=:value]';
3614
    return $this->buildXPathQuery($xpath, array(':value' => $value));
3615
  }
3616

    
3617
  /**
3618
   * Asserts the page responds with the specified response code.
3619
   *
3620
   * @param $code
3621
   *   Response code. For example 200 is a successful page request. For a list
3622
   *   of all codes see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html.
3623
   * @param $message
3624
   *   Message to display.
3625
   * @return
3626
   *   Assertion result.
3627
   */
3628
  protected function assertResponse($code, $message = '') {
3629
    $curl_code = curl_getinfo($this->curlHandle, CURLINFO_HTTP_CODE);
3630
    $match = is_array($code) ? in_array($curl_code, $code) : $curl_code == $code;
3631
    return $this->assertTrue($match, $message ? $message : t('HTTP response expected !code, actual !curl_code', array('!code' => $code, '!curl_code' => $curl_code)), t('Browser'));
3632
  }
3633

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

    
3652
  /**
3653
   * Asserts that the most recently sent e-mail message has the given value.
3654
   *
3655
   * The field in $name must have the content described in $value.
3656
   *
3657
   * @param $name
3658
   *   Name of field or message property to assert. Examples: subject, body, id, ...
3659
   * @param $value
3660
   *   Value of the field to assert.
3661
   * @param $message
3662
   *   Message to display.
3663
   *
3664
   * @return
3665
   *   TRUE on pass, FALSE on fail.
3666
   */
3667
  protected function assertMail($name, $value = '', $message = '') {
3668
    $captured_emails = variable_get('drupal_test_email_collector', array());
3669
    $email = end($captured_emails);
3670
    return $this->assertTrue($email && isset($email[$name]) && $email[$name] == $value, $message, t('E-mail'));
3671
  }
3672

    
3673
  /**
3674
   * Asserts that the most recently sent e-mail message has the string in it.
3675
   *
3676
   * @param $field_name
3677
   *   Name of field or message property to assert: subject, body, id, ...
3678
   * @param $string
3679
   *   String to search for.
3680
   * @param $email_depth
3681
   *   Number of emails to search for string, starting with most recent.
3682
   *
3683
   * @return
3684
   *   TRUE on pass, FALSE on fail.
3685
   */
3686
  protected function assertMailString($field_name, $string, $email_depth) {
3687
    $mails = $this->drupalGetMails();
3688
    $string_found = FALSE;
3689
    for ($i = sizeof($mails) -1; $i >= sizeof($mails) - $email_depth && $i >= 0; $i--) {
3690
      $mail = $mails[$i];
3691
      // Normalize whitespace, as we don't know what the mail system might have
3692
      // done. Any run of whitespace becomes a single space.
3693
      $normalized_mail = preg_replace('/\s+/', ' ', $mail[$field_name]);
3694
      $normalized_string = preg_replace('/\s+/', ' ', $string);
3695
      $string_found = (FALSE !== strpos($normalized_mail, $normalized_string));
3696
      if ($string_found) {
3697
        break;
3698
      }
3699
    }
3700
    return $this->assertTrue($string_found, t('Expected text found in @field of email message: "@expected".', array('@field' => $field_name, '@expected' => $string)));
3701
  }
3702

    
3703
  /**
3704
   * Asserts that the most recently sent e-mail message has the pattern in it.
3705
   *
3706
   * @param $field_name
3707
   *   Name of field or message property to assert: subject, body, id, ...
3708
   * @param $regex
3709
   *   Pattern to search for.
3710
   *
3711
   * @return
3712
   *   TRUE on pass, FALSE on fail.
3713
   */
3714
  protected function assertMailPattern($field_name, $regex, $message) {
3715
    $mails = $this->drupalGetMails();
3716
    $mail = end($mails);
3717
    $regex_found = preg_match("/$regex/", $mail[$field_name]);
3718
    return $this->assertTrue($regex_found, t('Expected text found in @field of email message: "@expected".', array('@field' => $field_name, '@expected' => $regex)));
3719
  }
3720

    
3721
  /**
3722
   * Outputs to verbose the most recent $count emails sent.
3723
   *
3724
   * @param $count
3725
   *   Optional number of emails to output.
3726
   */
3727
  protected function verboseEmail($count = 1) {
3728
    $mails = $this->drupalGetMails();
3729
    for ($i = sizeof($mails) -1; $i >= sizeof($mails) - $count && $i >= 0; $i--) {
3730
      $mail = $mails[$i];
3731
      $this->verbose(t('Email:') . '<pre>' . print_r($mail, TRUE) . '</pre>');
3732
    }
3733
  }
3734
}
3735

    
3736
/**
3737
 * Logs verbose message in a text file.
3738
 *
3739
 * If verbose mode is enabled then page requests will be dumped to a file and
3740
 * presented on the test result screen. The messages will be placed in a file
3741
 * located in the simpletest directory in the original file system.
3742
 *
3743
 * @param $message
3744
 *   The verbose message to be stored.
3745
 * @param $original_file_directory
3746
 *   The original file directory, before it was changed for testing purposes.
3747
 * @param $test_class
3748
 *   The active test case class.
3749
 *
3750
 * @return
3751
 *   The ID of the message to be placed in related assertion messages.
3752
 *
3753
 * @see DrupalTestCase->originalFileDirectory
3754
 * @see DrupalWebTestCase->verbose()
3755
 */
3756
function simpletest_verbose($message, $original_file_directory = NULL, $test_class = NULL) {
3757
  static $file_directory = NULL, $class = NULL, $id = 1, $verbose = NULL;
3758

    
3759
  // Will pass first time during setup phase, and when verbose is TRUE.
3760
  if (!isset($original_file_directory) && !$verbose) {
3761
    return FALSE;
3762
  }
3763

    
3764
  if ($message && $file_directory) {
3765
    $message = '<hr />ID #' . $id . ' (<a href="' . $class . '-' . ($id - 1) . '.html">Previous</a> | <a href="' . $class . '-' . ($id + 1) . '.html">Next</a>)<hr />' . $message;
3766
    file_put_contents($file_directory . "/simpletest/verbose/$class-$id.html", $message, FILE_APPEND);
3767
    return $id++;
3768
  }
3769

    
3770
  if ($original_file_directory) {
3771
    $file_directory = $original_file_directory;
3772
    $class = $test_class;
3773
    $verbose = variable_get('simpletest_verbose', TRUE);
3774
    $directory = $file_directory . '/simpletest/verbose';
3775
    $writable = file_prepare_directory($directory, FILE_CREATE_DIRECTORY);
3776
    if ($writable && !file_exists($directory . '/.htaccess')) {
3777
      file_put_contents($directory . '/.htaccess', "<IfModule mod_expires.c>\nExpiresActive Off\n</IfModule>\n");
3778
    }
3779
    return $writable;
3780
  }
3781
  return FALSE;
3782
}