Projet

Général

Profil

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

root / drupal7 / modules / simpletest / drupal_web_test_case.php @ 582db59d

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
   * Additional cURL options.
858
   *
859
   * DrupalWebTestCase itself never sets this but always obeys what is set.
860
   */
861
  protected $additionalCurlOptions = array();
862

    
863
  /**
864
   * The original user, before it was changed to a clean uid = 1 for testing purposes.
865
   *
866
   * @var object
867
   */
868
  protected $originalUser = NULL;
869

    
870
  /**
871
   * The original shutdown handlers array, before it was cleaned for testing purposes.
872
   *
873
   * @var array
874
   */
875
  protected $originalShutdownCallbacks = array();
876

    
877
  /**
878
   * HTTP authentication method
879
   */
880
  protected $httpauth_method = CURLAUTH_BASIC;
881

    
882
  /**
883
   * HTTP authentication credentials (<username>:<password>).
884
   */
885
  protected $httpauth_credentials = NULL;
886

    
887
  /**
888
   * The current session name, if available.
889
   */
890
  protected $session_name = NULL;
891

    
892
  /**
893
   * The current session ID, if available.
894
   */
895
  protected $session_id = NULL;
896

    
897
  /**
898
   * Whether the files were copied to the test files directory.
899
   */
900
  protected $generatedTestFiles = FALSE;
901

    
902
  /**
903
   * The number of redirects followed during the handling of a request.
904
   */
905
  protected $redirect_count;
906

    
907
  /**
908
   * Constructor for DrupalWebTestCase.
909
   */
910
  function __construct($test_id = NULL) {
911
    parent::__construct($test_id);
912
    $this->skipClasses[__CLASS__] = TRUE;
913
  }
914

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

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

    
960
    // Use the original node's created time for existing nodes.
961
    if (isset($settings['created']) && !isset($settings['date'])) {
962
      $settings['date'] = format_date($settings['created'], 'custom', 'Y-m-d H:i:s O');
963
    }
964

    
965
    // If the node's user uid is not specified manually, use the currently
966
    // logged in user if available, or else the user running the test.
967
    if (!isset($settings['uid'])) {
968
      if ($this->loggedInUser) {
969
        $settings['uid'] = $this->loggedInUser->uid;
970
      }
971
      else {
972
        global $user;
973
        $settings['uid'] = $user->uid;
974
      }
975
    }
976

    
977
    // Merge body field value and format separately.
978
    $body = array(
979
      'value' => $this->randomName(32),
980
      'format' => filter_default_format(),
981
    );
982
    $settings['body'][$settings['language']][0] += $body;
983

    
984
    $node = (object) $settings;
985
    node_save($node);
986

    
987
    // Small hack to link revisions to our test user.
988
    db_update('node_revision')
989
      ->fields(array('uid' => $node->uid))
990
      ->condition('vid', $node->vid)
991
      ->execute();
992
    return $node;
993
  }
994

    
995
  /**
996
   * Creates a custom content type based on default settings.
997
   *
998
   * @param $settings
999
   *   An array of settings to change from the defaults.
1000
   *   Example: 'type' => 'foo'.
1001
   * @return
1002
   *   Created content type.
1003
   */
1004
  protected function drupalCreateContentType($settings = array()) {
1005
    // Find a non-existent random type name.
1006
    do {
1007
      $name = strtolower($this->randomName(8));
1008
    } while (node_type_get_type($name));
1009

    
1010
    // Populate defaults array.
1011
    $defaults = array(
1012
      'type' => $name,
1013
      'name' => $name,
1014
      'base' => 'node_content',
1015
      'description' => '',
1016
      'help' => '',
1017
      'title_label' => 'Title',
1018
      'has_title' => 1,
1019
    );
1020
    // Imposed values for a custom type.
1021
    $forced = array(
1022
      'orig_type' => '',
1023
      'old_type' => '',
1024
      'module' => 'node',
1025
      'custom' => 1,
1026
      'modified' => 1,
1027
      'locked' => 0,
1028
    );
1029
    $type = $forced + $settings + $defaults;
1030
    $type = (object) $type;
1031

    
1032
    $saved_type = node_type_save($type);
1033
    node_types_rebuild();
1034
    menu_rebuild();
1035
    node_add_body_field($type);
1036

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

    
1039
    // Reset permissions so that permissions for this content type are available.
1040
    $this->checkPermissions(array(), TRUE);
1041

    
1042
    return $type;
1043
  }
1044

    
1045
  /**
1046
   * Get a list files that can be used in tests.
1047
   *
1048
   * @param $type
1049
   *   File type, possible values: 'binary', 'html', 'image', 'javascript', 'php', 'sql', 'text'.
1050
   * @param $size
1051
   *   File size in bytes to match. Please check the tests/files folder.
1052
   * @return
1053
   *   List of files that match filter.
1054
   */
1055
  protected function drupalGetTestFiles($type, $size = NULL) {
1056
    if (empty($this->generatedTestFiles)) {
1057
      // Generate binary test files.
1058
      $lines = array(64, 1024);
1059
      $count = 0;
1060
      foreach ($lines as $line) {
1061
        simpletest_generate_file('binary-' . $count++, 64, $line, 'binary');
1062
      }
1063

    
1064
      // Generate text test files.
1065
      $lines = array(16, 256, 1024, 2048, 20480);
1066
      $count = 0;
1067
      foreach ($lines as $line) {
1068
        simpletest_generate_file('text-' . $count++, 64, $line, 'text');
1069
      }
1070

    
1071
      // Copy other test files from simpletest.
1072
      $original = drupal_get_path('module', 'simpletest') . '/files';
1073
      $files = file_scan_directory($original, '/(html|image|javascript|php|sql)-.*/');
1074
      foreach ($files as $file) {
1075
        file_unmanaged_copy($file->uri, variable_get('file_public_path', conf_path() . '/files'));
1076
      }
1077

    
1078
      $this->generatedTestFiles = TRUE;
1079
    }
1080

    
1081
    $files = array();
1082
    // Make sure type is valid.
1083
    if (in_array($type, array('binary', 'html', 'image', 'javascript', 'php', 'sql', 'text'))) {
1084
      $files = file_scan_directory('public://', '/' . $type . '\-.*/');
1085

    
1086
      // If size is set then remove any files that are not of that size.
1087
      if ($size !== NULL) {
1088
        foreach ($files as $file) {
1089
          $stats = stat($file->uri);
1090
          if ($stats['size'] != $size) {
1091
            unset($files[$file->uri]);
1092
          }
1093
        }
1094
      }
1095
    }
1096
    usort($files, array($this, 'drupalCompareFiles'));
1097
    return $files;
1098
  }
1099

    
1100
  /**
1101
   * Compare two files based on size and file name.
1102
   */
1103
  protected function drupalCompareFiles($file1, $file2) {
1104
    $compare_size = filesize($file1->uri) - filesize($file2->uri);
1105
    if ($compare_size) {
1106
      // Sort by file size.
1107
      return $compare_size;
1108
    }
1109
    else {
1110
      // The files were the same size, so sort alphabetically.
1111
      return strnatcmp($file1->name, $file2->name);
1112
    }
1113
  }
1114

    
1115
  /**
1116
   * Create a user with a given set of permissions.
1117
   *
1118
   * @param array $permissions
1119
   *   Array of permission names to assign to user. Note that the user always
1120
   *   has the default permissions derived from the "authenticated users" role.
1121
   *
1122
   * @return object|false
1123
   *   A fully loaded user object with pass_raw property, or FALSE if account
1124
   *   creation fails.
1125
   */
1126
  protected function drupalCreateUser(array $permissions = array()) {
1127
    // Create a role with the given permission set, if any.
1128
    $rid = FALSE;
1129
    if ($permissions) {
1130
      $rid = $this->drupalCreateRole($permissions);
1131
      if (!$rid) {
1132
        return FALSE;
1133
      }
1134
    }
1135

    
1136
    // Create a user assigned to that role.
1137
    $edit = array();
1138
    $edit['name']   = $this->randomName();
1139
    $edit['mail']   = $edit['name'] . '@example.com';
1140
    $edit['pass']   = user_password();
1141
    $edit['status'] = 1;
1142
    if ($rid) {
1143
      $edit['roles'] = array($rid => $rid);
1144
    }
1145

    
1146
    $account = user_save(drupal_anonymous_user(), $edit);
1147

    
1148
    $this->assertTrue(!empty($account->uid), t('User created with name %name and pass %pass', array('%name' => $edit['name'], '%pass' => $edit['pass'])), t('User login'));
1149
    if (empty($account->uid)) {
1150
      return FALSE;
1151
    }
1152

    
1153
    // Add the raw password so that we can log in as this user.
1154
    $account->pass_raw = $edit['pass'];
1155
    return $account;
1156
  }
1157

    
1158
  /**
1159
   * Creates a role with specified permissions.
1160
   *
1161
   * @param $permissions
1162
   *   Array of permission names to assign to role.
1163
   * @param $name
1164
   *   (optional) String for the name of the role.  Defaults to a random string.
1165
   * @return
1166
   *   Role ID of newly created role, or FALSE if role creation failed.
1167
   */
1168
  protected function drupalCreateRole(array $permissions, $name = NULL) {
1169
    // Generate random name if it was not passed.
1170
    if (!$name) {
1171
      $name = $this->randomName();
1172
    }
1173

    
1174
    // Check the all the permissions strings are valid.
1175
    if (!$this->checkPermissions($permissions)) {
1176
      return FALSE;
1177
    }
1178

    
1179
    // Create new role.
1180
    $role = new stdClass();
1181
    $role->name = $name;
1182
    user_role_save($role);
1183
    user_role_grant_permissions($role->rid, $permissions);
1184

    
1185
    $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'));
1186
    if ($role && !empty($role->rid)) {
1187
      $count = db_query('SELECT COUNT(*) FROM {role_permission} WHERE rid = :rid', array(':rid' => $role->rid))->fetchField();
1188
      $this->assertTrue($count == count($permissions), t('Created permissions: @perms', array('@perms' => implode(', ', $permissions))), t('Role'));
1189
      return $role->rid;
1190
    }
1191
    else {
1192
      return FALSE;
1193
    }
1194
  }
1195

    
1196
  /**
1197
   * Check to make sure that the array of permissions are valid.
1198
   *
1199
   * @param $permissions
1200
   *   Permissions to check.
1201
   * @param $reset
1202
   *   Reset cached available permissions.
1203
   * @return
1204
   *   TRUE or FALSE depending on whether the permissions are valid.
1205
   */
1206
  protected function checkPermissions(array $permissions, $reset = FALSE) {
1207
    $available = &drupal_static(__FUNCTION__);
1208

    
1209
    if (!isset($available) || $reset) {
1210
      $available = array_keys(module_invoke_all('permission'));
1211
    }
1212

    
1213
    $valid = TRUE;
1214
    foreach ($permissions as $permission) {
1215
      if (!in_array($permission, $available)) {
1216
        $this->fail(t('Invalid permission %permission.', array('%permission' => $permission)), t('Role'));
1217
        $valid = FALSE;
1218
      }
1219
    }
1220
    return $valid;
1221
  }
1222

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

    
1255
    $edit = array(
1256
      'name' => $account->name,
1257
      'pass' => $account->pass_raw
1258
    );
1259
    $this->drupalPost('user', $edit, t('Log in'));
1260

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

    
1265
    if ($pass) {
1266
      $this->loggedInUser = $account;
1267
    }
1268
  }
1269

    
1270
  /**
1271
   * Generate a token for the currently logged in user.
1272
   */
1273
  protected function drupalGetToken($value = '') {
1274
    $private_key = drupal_get_private_key();
1275
    return drupal_hmac_base64($value, $this->session_id . $private_key);
1276
  }
1277

    
1278
  /*
1279
   * Logs a user out of the internal browser, then check the login page to confirm logout.
1280
   */
1281
  protected function drupalLogout() {
1282
    // Make a request to the logout page, and redirect to the user page, the
1283
    // idea being if you were properly logged out you should be seeing a login
1284
    // screen.
1285
    $this->drupalGet('user/logout');
1286
    $this->drupalGet('user');
1287
    $pass = $this->assertField('name', t('Username field found.'), t('Logout'));
1288
    $pass = $pass && $this->assertField('pass', t('Password field found.'), t('Logout'));
1289

    
1290
    if ($pass) {
1291
      $this->loggedInUser = FALSE;
1292
    }
1293
  }
1294

    
1295
  /**
1296
   * Generates a database prefix for running tests.
1297
   *
1298
   * The generated database table prefix is used for the Drupal installation
1299
   * being performed for the test. It is also used as user agent HTTP header
1300
   * value by the cURL-based browser of DrupalWebTestCase, which is sent
1301
   * to the Drupal installation of the test. During early Drupal bootstrap, the
1302
   * user agent HTTP header is parsed, and if it matches, all database queries
1303
   * use the database table prefix that has been generated here.
1304
   *
1305
   * @see DrupalWebTestCase::curlInitialize()
1306
   * @see drupal_valid_test_ua()
1307
   * @see DrupalWebTestCase::setUp()
1308
   */
1309
  protected function prepareDatabasePrefix() {
1310
    $this->databasePrefix = 'simpletest' . mt_rand(1000, 1000000);
1311

    
1312
    // As soon as the database prefix is set, the test might start to execute.
1313
    // All assertions as well as the SimpleTest batch operations are associated
1314
    // with the testId, so the database prefix has to be associated with it.
1315
    db_update('simpletest_test_id')
1316
      ->fields(array('last_prefix' => $this->databasePrefix))
1317
      ->condition('test_id', $this->testId)
1318
      ->execute();
1319
  }
1320

    
1321
  /**
1322
   * Changes the database connection to the prefixed one.
1323
   *
1324
   * @see DrupalWebTestCase::setUp()
1325
   */
1326
  protected function changeDatabasePrefix() {
1327
    if (empty($this->databasePrefix)) {
1328
      $this->prepareDatabasePrefix();
1329
      // If $this->prepareDatabasePrefix() failed to work, return without
1330
      // setting $this->setupDatabasePrefix to TRUE, so setUp() methods will
1331
      // know to bail out.
1332
      if (empty($this->databasePrefix)) {
1333
        return;
1334
      }
1335
    }
1336

    
1337
    // Clone the current connection and replace the current prefix.
1338
    $connection_info = Database::getConnectionInfo('default');
1339
    Database::renameConnection('default', 'simpletest_original_default');
1340
    foreach ($connection_info as $target => $value) {
1341
      $connection_info[$target]['prefix'] = array(
1342
        'default' => $value['prefix']['default'] . $this->databasePrefix,
1343
      );
1344
    }
1345
    Database::addConnectionInfo('default', 'default', $connection_info['default']);
1346

    
1347
    // Indicate the database prefix was set up correctly.
1348
    $this->setupDatabasePrefix = TRUE;
1349
  }
1350

    
1351
  /**
1352
   * Prepares the current environment for running the test.
1353
   *
1354
   * Backups various current environment variables and resets them, so they do
1355
   * not interfere with the Drupal site installation in which tests are executed
1356
   * and can be restored in tearDown().
1357
   *
1358
   * Also sets up new resources for the testing environment, such as the public
1359
   * filesystem and configuration directories.
1360
   *
1361
   * @see DrupalWebTestCase::setUp()
1362
   * @see DrupalWebTestCase::tearDown()
1363
   */
1364
  protected function prepareEnvironment() {
1365
    global $user, $language, $conf;
1366

    
1367
    // Store necessary current values before switching to prefixed database.
1368
    $this->originalLanguage = $language;
1369
    $this->originalLanguageDefault = variable_get('language_default');
1370
    $this->originalFileDirectory = variable_get('file_public_path', conf_path() . '/files');
1371
    $this->originalProfile = drupal_get_profile();
1372
    $this->originalCleanUrl = variable_get('clean_url', 0);
1373
    $this->originalUser = $user;
1374

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

    
1380
    // Save and clean the shutdown callbacks array because it is static cached
1381
    // and will be changed by the test run. Otherwise it will contain callbacks
1382
    // from both environments and the testing environment will try to call the
1383
    // handlers defined by the original one.
1384
    $callbacks = &drupal_register_shutdown_function();
1385
    $this->originalShutdownCallbacks = $callbacks;
1386
    $callbacks = array();
1387

    
1388
    // Create test directory ahead of installation so fatal errors and debug
1389
    // information can be logged during installation process.
1390
    // Use temporary files directory with the same prefix as the database.
1391
    $this->public_files_directory = $this->originalFileDirectory . '/simpletest/' . substr($this->databasePrefix, 10);
1392
    $this->private_files_directory = $this->public_files_directory . '/private';
1393
    $this->temp_files_directory = $this->private_files_directory . '/temp';
1394

    
1395
    // Create the directories
1396
    file_prepare_directory($this->public_files_directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
1397
    file_prepare_directory($this->private_files_directory, FILE_CREATE_DIRECTORY);
1398
    file_prepare_directory($this->temp_files_directory, FILE_CREATE_DIRECTORY);
1399
    $this->generatedTestFiles = FALSE;
1400

    
1401
    // Log fatal errors.
1402
    ini_set('log_errors', 1);
1403
    ini_set('error_log', $this->public_files_directory . '/error.log');
1404

    
1405
    // Set the test information for use in other parts of Drupal.
1406
    $test_info = &$GLOBALS['drupal_test_info'];
1407
    $test_info['test_run_id'] = $this->databasePrefix;
1408
    $test_info['in_child_site'] = FALSE;
1409

    
1410
    // Indicate the environment was set up correctly.
1411
    $this->setupEnvironment = TRUE;
1412
  }
1413

    
1414
  /**
1415
   * Sets up a Drupal site for running functional and integration tests.
1416
   *
1417
   * Generates a random database prefix and installs Drupal with the specified
1418
   * installation profile in DrupalWebTestCase::$profile into the
1419
   * prefixed database. Afterwards, installs any additional modules specified by
1420
   * the test.
1421
   *
1422
   * After installation all caches are flushed and several configuration values
1423
   * are reset to the values of the parent site executing the test, since the
1424
   * default values may be incompatible with the environment in which tests are
1425
   * being executed.
1426
   *
1427
   * @param ...
1428
   *   List of modules to enable for the duration of the test. This can be
1429
   *   either a single array or a variable number of string arguments.
1430
   *
1431
   * @see DrupalWebTestCase::prepareDatabasePrefix()
1432
   * @see DrupalWebTestCase::changeDatabasePrefix()
1433
   * @see DrupalWebTestCase::prepareEnvironment()
1434
   */
1435
  protected function setUp() {
1436
    global $user, $language, $conf;
1437

    
1438
    // Create the database prefix for this test.
1439
    $this->prepareDatabasePrefix();
1440

    
1441
    // Prepare the environment for running tests.
1442
    $this->prepareEnvironment();
1443
    if (!$this->setupEnvironment) {
1444
      return FALSE;
1445
    }
1446

    
1447
    // Reset all statics and variables to perform tests in a clean environment.
1448
    $conf = array();
1449
    drupal_static_reset();
1450

    
1451
    // Change the database prefix.
1452
    // All static variables need to be reset before the database prefix is
1453
    // changed, since DrupalCacheArray implementations attempt to
1454
    // write back to persistent caches when they are destructed.
1455
    $this->changeDatabasePrefix();
1456
    if (!$this->setupDatabasePrefix) {
1457
      return FALSE;
1458
    }
1459

    
1460
    // Preset the 'install_profile' system variable, so the first call into
1461
    // system_rebuild_module_data() (in drupal_install_system()) will register
1462
    // the test's profile as a module. Without this, the installation profile of
1463
    // the parent site (executing the test) is registered, and the test
1464
    // profile's hook_install() and other hook implementations are never invoked.
1465
    $conf['install_profile'] = $this->profile;
1466

    
1467
    // Perform the actual Drupal installation.
1468
    include_once DRUPAL_ROOT . '/includes/install.inc';
1469
    drupal_install_system();
1470

    
1471
    $this->preloadRegistry();
1472

    
1473
    // Set path variables.
1474
    variable_set('file_public_path', $this->public_files_directory);
1475
    variable_set('file_private_path', $this->private_files_directory);
1476
    variable_set('file_temporary_path', $this->temp_files_directory);
1477

    
1478
    // Set the 'simpletest_parent_profile' variable to add the parent profile's
1479
    // search path to the child site's search paths.
1480
    // @see drupal_system_listing()
1481
    // @todo This may need to be primed like 'install_profile' above.
1482
    variable_set('simpletest_parent_profile', $this->originalProfile);
1483

    
1484
    // Include the testing profile.
1485
    variable_set('install_profile', $this->profile);
1486
    $profile_details = install_profile_info($this->profile, 'en');
1487

    
1488
    // Install the modules specified by the testing profile.
1489
    module_enable($profile_details['dependencies'], FALSE);
1490

    
1491
    // Install modules needed for this test. This could have been passed in as
1492
    // either a single array argument or a variable number of string arguments.
1493
    // @todo Remove this compatibility layer in Drupal 8, and only accept
1494
    // $modules as a single array argument.
1495
    $modules = func_get_args();
1496
    if (isset($modules[0]) && is_array($modules[0])) {
1497
      $modules = $modules[0];
1498
    }
1499
    if ($modules) {
1500
      $success = module_enable($modules, TRUE);
1501
      $this->assertTrue($success, t('Enabled modules: %modules', array('%modules' => implode(', ', $modules))));
1502
    }
1503

    
1504
    // Run the profile tasks.
1505
    $install_profile_module_exists = db_query("SELECT 1 FROM {system} WHERE type = 'module' AND name = :name", array(
1506
      ':name' => $this->profile,
1507
    ))->fetchField();
1508
    if ($install_profile_module_exists) {
1509
      module_enable(array($this->profile), FALSE);
1510
    }
1511

    
1512
    // Reset/rebuild all data structures after enabling the modules.
1513
    $this->resetAll();
1514

    
1515
    // Run cron once in that environment, as install.php does at the end of
1516
    // the installation process.
1517
    drupal_cron_run();
1518

    
1519
    // Ensure that the session is not written to the new environment and replace
1520
    // the global $user session with uid 1 from the new test site.
1521
    drupal_save_session(FALSE);
1522
    // Login as uid 1.
1523
    $user = user_load(1);
1524

    
1525
    // Restore necessary variables.
1526
    variable_set('install_task', 'done');
1527
    variable_set('clean_url', $this->originalCleanUrl);
1528
    variable_set('site_mail', 'simpletest@example.com');
1529
    variable_set('date_default_timezone', date_default_timezone_get());
1530

    
1531
    // Set up English language.
1532
    unset($conf['language_default']);
1533
    $language = language_default();
1534

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

    
1538
    drupal_set_time_limit($this->timeLimit);
1539
    $this->setup = TRUE;
1540
  }
1541

    
1542
  /**
1543
   * Preload the registry from the testing site.
1544
   *
1545
   * This method is called by DrupalWebTestCase::setUp(), and preloads the
1546
   * registry from the testing site to cut down on the time it takes to
1547
   * set up a clean environment for the current test run.
1548
   */
1549
  protected function preloadRegistry() {
1550
    // Use two separate queries, each with their own connections: copy the
1551
    // {registry} and {registry_file} tables over from the parent installation
1552
    // to the child installation.
1553
    $original_connection = Database::getConnection('default', 'simpletest_original_default');
1554
    $test_connection = Database::getConnection();
1555

    
1556
    foreach (array('registry', 'registry_file') as $table) {
1557
      // Find the records from the parent database.
1558
      $source_query = $original_connection
1559
        ->select($table, array(), array('fetch' => PDO::FETCH_ASSOC))
1560
        ->fields($table);
1561

    
1562
      $dest_query = $test_connection->insert($table);
1563

    
1564
      $first = TRUE;
1565
      foreach ($source_query->execute() as $row) {
1566
        if ($first) {
1567
          $dest_query->fields(array_keys($row));
1568
          $first = FALSE;
1569
        }
1570
        // Insert the records into the child database.
1571
        $dest_query->values($row);
1572
      }
1573

    
1574
      $dest_query->execute();
1575
    }
1576
  }
1577

    
1578
  /**
1579
   * Reset all data structures after having enabled new modules.
1580
   *
1581
   * This method is called by DrupalWebTestCase::setUp() after enabling
1582
   * the requested modules. It must be called again when additional modules
1583
   * are enabled later.
1584
   */
1585
  protected function resetAll() {
1586
    // Reset all static variables.
1587
    drupal_static_reset();
1588
    // Reset the list of enabled modules.
1589
    module_list(TRUE);
1590

    
1591
    // Reset cached schema for new database prefix. This must be done before
1592
    // drupal_flush_all_caches() so rebuilds can make use of the schema of
1593
    // modules enabled on the cURL side.
1594
    drupal_get_schema(NULL, TRUE);
1595

    
1596
    // Perform rebuilds and flush remaining caches.
1597
    drupal_flush_all_caches();
1598

    
1599
    // Reload global $conf array and permissions.
1600
    $this->refreshVariables();
1601
    $this->checkPermissions(array(), TRUE);
1602
  }
1603

    
1604
  /**
1605
   * Refresh the in-memory set of variables. Useful after a page request is made
1606
   * that changes a variable in a different thread.
1607
   *
1608
   * In other words calling a settings page with $this->drupalPost() with a changed
1609
   * value would update a variable to reflect that change, but in the thread that
1610
   * made the call (thread running the test) the changed variable would not be
1611
   * picked up.
1612
   *
1613
   * This method clears the variables cache and loads a fresh copy from the database
1614
   * to ensure that the most up-to-date set of variables is loaded.
1615
   */
1616
  protected function refreshVariables() {
1617
    global $conf;
1618
    cache_clear_all('variables', 'cache_bootstrap');
1619
    $conf = variable_initialize();
1620
  }
1621

    
1622
  /**
1623
   * Delete created files and temporary files directory, delete the tables created by setUp(),
1624
   * and reset the database prefix.
1625
   */
1626
  protected function tearDown() {
1627
    global $user, $language;
1628

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

    
1633
    $emailCount = count(variable_get('drupal_test_email_collector', array()));
1634
    if ($emailCount) {
1635
      $message = format_plural($emailCount, '1 e-mail was sent during this test.', '@count e-mails were sent during this test.');
1636
      $this->pass($message, t('E-mail'));
1637
    }
1638

    
1639
    // Delete temporary files directory.
1640
    file_unmanaged_delete_recursive($this->originalFileDirectory . '/simpletest/' . substr($this->databasePrefix, 10));
1641

    
1642
    // Remove all prefixed tables.
1643
    $tables = db_find_tables($this->databasePrefix . '%');
1644
    $connection_info = Database::getConnectionInfo('default');
1645
    $tables = db_find_tables($connection_info['default']['prefix']['default'] . '%');
1646
    if (empty($tables)) {
1647
      $this->fail('Failed to find test tables to drop.');
1648
    }
1649
    $prefix_length = strlen($connection_info['default']['prefix']['default']);
1650
    foreach ($tables as $table) {
1651
      if (db_drop_table(substr($table, $prefix_length))) {
1652
        unset($tables[$table]);
1653
      }
1654
    }
1655
    if (!empty($tables)) {
1656
      $this->fail('Failed to drop all prefixed tables.');
1657
    }
1658

    
1659
    // Get back to the original connection.
1660
    Database::removeConnection('default');
1661
    Database::renameConnection('simpletest_original_default', 'default');
1662

    
1663
    // Restore original shutdown callbacks array to prevent original
1664
    // environment of calling handlers from test run.
1665
    $callbacks = &drupal_register_shutdown_function();
1666
    $callbacks = $this->originalShutdownCallbacks;
1667

    
1668
    // Return the user to the original one.
1669
    $user = $this->originalUser;
1670
    drupal_save_session(TRUE);
1671

    
1672
    // Ensure that internal logged in variable and cURL options are reset.
1673
    $this->loggedInUser = FALSE;
1674
    $this->additionalCurlOptions = array();
1675

    
1676
    // Reload module list and implementations to ensure that test module hooks
1677
    // aren't called after tests.
1678
    module_list(TRUE);
1679
    module_implements('', FALSE, TRUE);
1680

    
1681
    // Reset the Field API.
1682
    field_cache_clear();
1683

    
1684
    // Rebuild caches.
1685
    $this->refreshVariables();
1686

    
1687
    // Reset public files directory.
1688
    $GLOBALS['conf']['file_public_path'] = $this->originalFileDirectory;
1689

    
1690
    // Reset language.
1691
    $language = $this->originalLanguage;
1692
    if ($this->originalLanguageDefault) {
1693
      $GLOBALS['conf']['language_default'] = $this->originalLanguageDefault;
1694
    }
1695

    
1696
    // Close the CURL handler.
1697
    $this->curlClose();
1698
  }
1699

    
1700
  /**
1701
   * Initializes the cURL connection.
1702
   *
1703
   * If the simpletest_httpauth_credentials variable is set, this function will
1704
   * add HTTP authentication headers. This is necessary for testing sites that
1705
   * are protected by login credentials from public access.
1706
   * See the description of $curl_options for other options.
1707
   */
1708
  protected function curlInitialize() {
1709
    global $base_url;
1710

    
1711
    if (!isset($this->curlHandle)) {
1712
      $this->curlHandle = curl_init();
1713

    
1714
      // Some versions/configurations of cURL break on a NULL cookie jar, so
1715
      // supply a real file.
1716
      if (empty($this->cookieFile)) {
1717
        $this->cookieFile = $this->public_files_directory . '/cookie.jar';
1718
      }
1719

    
1720
      $curl_options = array(
1721
        CURLOPT_COOKIEJAR => $this->cookieFile,
1722
        CURLOPT_URL => $base_url,
1723
        CURLOPT_FOLLOWLOCATION => FALSE,
1724
        CURLOPT_RETURNTRANSFER => TRUE,
1725
        CURLOPT_SSL_VERIFYPEER => FALSE, // Required to make the tests run on HTTPS.
1726
        CURLOPT_SSL_VERIFYHOST => FALSE, // Required to make the tests run on HTTPS.
1727
        CURLOPT_HEADERFUNCTION => array(&$this, 'curlHeaderCallback'),
1728
        CURLOPT_USERAGENT => $this->databasePrefix,
1729
      );
1730
      if (isset($this->httpauth_credentials)) {
1731
        $curl_options[CURLOPT_HTTPAUTH] = $this->httpauth_method;
1732
        $curl_options[CURLOPT_USERPWD] = $this->httpauth_credentials;
1733
      }
1734
      // curl_setopt_array() returns FALSE if any of the specified options
1735
      // cannot be set, and stops processing any further options.
1736
      $result = curl_setopt_array($this->curlHandle, $this->additionalCurlOptions + $curl_options);
1737
      if (!$result) {
1738
        throw new Exception('One or more cURL options could not be set.');
1739
      }
1740

    
1741
      // By default, the child session name should be the same as the parent.
1742
      $this->session_name = session_name();
1743
    }
1744
    // We set the user agent header on each request so as to use the current
1745
    // time and a new uniqid.
1746
    if (preg_match('/simpletest\d+/', $this->databasePrefix, $matches)) {
1747
      curl_setopt($this->curlHandle, CURLOPT_USERAGENT, drupal_generate_test_ua($matches[0]));
1748
    }
1749
  }
1750

    
1751
  /**
1752
   * Initializes and executes a cURL request.
1753
   *
1754
   * @param $curl_options
1755
   *   An associative array of cURL options to set, where the keys are constants
1756
   *   defined by the cURL library. For a list of valid options, see
1757
   *   http://www.php.net/manual/function.curl-setopt.php
1758
   * @param $redirect
1759
   *   FALSE if this is an initial request, TRUE if this request is the result
1760
   *   of a redirect.
1761
   *
1762
   * @return
1763
   *   The content returned from the call to curl_exec().
1764
   *
1765
   * @see curlInitialize()
1766
   */
1767
  protected function curlExec($curl_options, $redirect = FALSE) {
1768
    $this->curlInitialize();
1769

    
1770
    if (!empty($curl_options[CURLOPT_URL])) {
1771
      // Forward XDebug activation if present.
1772
      if (isset($_COOKIE['XDEBUG_SESSION'])) {
1773
        $options = drupal_parse_url($curl_options[CURLOPT_URL]);
1774
        $options += array('query' => array());
1775
        $options['query'] += array('XDEBUG_SESSION_START' => $_COOKIE['XDEBUG_SESSION']);
1776
        $curl_options[CURLOPT_URL] = url($options['path'], $options);
1777
      }
1778

    
1779
      // cURL incorrectly handles URLs with a fragment by including the
1780
      // fragment in the request to the server, causing some web servers
1781
      // to reject the request citing "400 - Bad Request". To prevent
1782
      // this, we strip the fragment from the request.
1783
      // TODO: Remove this for Drupal 8, since fixed in curl 7.20.0.
1784
      if (strpos($curl_options[CURLOPT_URL], '#')) {
1785
        $original_url = $curl_options[CURLOPT_URL];
1786
        $curl_options[CURLOPT_URL] = strtok($curl_options[CURLOPT_URL], '#');
1787
      }
1788
    }
1789

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

    
1792
    if (!empty($curl_options[CURLOPT_POST])) {
1793
      // This is a fix for the Curl library to prevent Expect: 100-continue
1794
      // headers in POST requests, that may cause unexpected HTTP response
1795
      // codes from some webservers (like lighttpd that returns a 417 error
1796
      // code). It is done by setting an empty "Expect" header field that is
1797
      // not overwritten by Curl.
1798
      $curl_options[CURLOPT_HTTPHEADER][] = 'Expect:';
1799
    }
1800
    curl_setopt_array($this->curlHandle, $this->additionalCurlOptions + $curl_options);
1801

    
1802
    if (!$redirect) {
1803
      // Reset headers, the session ID and the redirect counter.
1804
      $this->session_id = NULL;
1805
      $this->headers = array();
1806
      $this->redirect_count = 0;
1807
    }
1808

    
1809
    $content = curl_exec($this->curlHandle);
1810
    $status = curl_getinfo($this->curlHandle, CURLINFO_HTTP_CODE);
1811

    
1812
    // cURL incorrectly handles URLs with fragments, so instead of
1813
    // letting cURL handle redirects we take of them ourselves to
1814
    // to prevent fragments being sent to the web server as part
1815
    // of the request.
1816
    // TODO: Remove this for Drupal 8, since fixed in curl 7.20.0.
1817
    if (in_array($status, array(300, 301, 302, 303, 305, 307)) && $this->redirect_count < variable_get('simpletest_maximum_redirects', 5)) {
1818
      if ($this->drupalGetHeader('location')) {
1819
        $this->redirect_count++;
1820
        $curl_options = array();
1821
        $curl_options[CURLOPT_URL] = $this->drupalGetHeader('location');
1822
        $curl_options[CURLOPT_HTTPGET] = TRUE;
1823
        return $this->curlExec($curl_options, TRUE);
1824
      }
1825
    }
1826

    
1827
    $this->drupalSetContent($content, isset($original_url) ? $original_url : curl_getinfo($this->curlHandle, CURLINFO_EFFECTIVE_URL));
1828
    $message_vars = array(
1829
      '!method' => !empty($curl_options[CURLOPT_NOBODY]) ? 'HEAD' : (empty($curl_options[CURLOPT_POSTFIELDS]) ? 'GET' : 'POST'),
1830
      '@url' => isset($original_url) ? $original_url : $url,
1831
      '@status' => $status,
1832
      '!length' => format_size(strlen($this->drupalGetContent()))
1833
    );
1834
    $message = t('!method @url returned @status (!length).', $message_vars);
1835
    $this->assertTrue($this->drupalGetContent() !== FALSE, $message, t('Browser'));
1836
    return $this->drupalGetContent();
1837
  }
1838

    
1839
  /**
1840
   * Reads headers and registers errors received from the tested site.
1841
   *
1842
   * @see _drupal_log_error().
1843
   *
1844
   * @param $curlHandler
1845
   *   The cURL handler.
1846
   * @param $header
1847
   *   An header.
1848
   */
1849
  protected function curlHeaderCallback($curlHandler, $header) {
1850
    // Header fields can be extended over multiple lines by preceding each
1851
    // extra line with at least one SP or HT. They should be joined on receive.
1852
    // Details are in RFC2616 section 4.
1853
    if ($header[0] == ' ' || $header[0] == "\t") {
1854
      // Normalize whitespace between chucks.
1855
      $this->headers[] = array_pop($this->headers) . ' ' . trim($header);
1856
    }
1857
    else {
1858
      $this->headers[] = $header;
1859
    }
1860

    
1861
    // Errors are being sent via X-Drupal-Assertion-* headers,
1862
    // generated by _drupal_log_error() in the exact form required
1863
    // by DrupalWebTestCase::error().
1864
    if (preg_match('/^X-Drupal-Assertion-[0-9]+: (.*)$/', $header, $matches)) {
1865
      // Call DrupalWebTestCase::error() with the parameters from the header.
1866
      call_user_func_array(array(&$this, 'error'), unserialize(urldecode($matches[1])));
1867
    }
1868

    
1869
    // Save cookies.
1870
    if (preg_match('/^Set-Cookie: ([^=]+)=(.+)/', $header, $matches)) {
1871
      $name = $matches[1];
1872
      $parts = array_map('trim', explode(';', $matches[2]));
1873
      $value = array_shift($parts);
1874
      $this->cookies[$name] = array('value' => $value, 'secure' => in_array('secure', $parts));
1875
      if ($name == $this->session_name) {
1876
        if ($value != 'deleted') {
1877
          $this->session_id = $value;
1878
        }
1879
        else {
1880
          $this->session_id = NULL;
1881
        }
1882
      }
1883
    }
1884

    
1885
    // This is required by cURL.
1886
    return strlen($header);
1887
  }
1888

    
1889
  /**
1890
   * Close the cURL handler and unset the handler.
1891
   */
1892
  protected function curlClose() {
1893
    if (isset($this->curlHandle)) {
1894
      curl_close($this->curlHandle);
1895
      unset($this->curlHandle);
1896
    }
1897
  }
1898

    
1899
  /**
1900
   * Parse content returned from curlExec using DOM and SimpleXML.
1901
   *
1902
   * @return
1903
   *   A SimpleXMLElement or FALSE on failure.
1904
   */
1905
  protected function parse() {
1906
    if (!$this->elements) {
1907
      // DOM can load HTML soup. But, HTML soup can throw warnings, suppress
1908
      // them.
1909
      $htmlDom = new DOMDocument();
1910
      @$htmlDom->loadHTML($this->drupalGetContent());
1911
      if ($htmlDom) {
1912
        $this->pass(t('Valid HTML found on "@path"', array('@path' => $this->getUrl())), t('Browser'));
1913
        // It's much easier to work with simplexml than DOM, luckily enough
1914
        // we can just simply import our DOM tree.
1915
        $this->elements = simplexml_import_dom($htmlDom);
1916
      }
1917
    }
1918
    if (!$this->elements) {
1919
      $this->fail(t('Parsed page successfully.'), t('Browser'));
1920
    }
1921

    
1922
    return $this->elements;
1923
  }
1924

    
1925
  /**
1926
   * Retrieves a Drupal path or an absolute path.
1927
   *
1928
   * @param $path
1929
   *   Drupal path or URL to load into internal browser
1930
   * @param $options
1931
   *   Options to be forwarded to url().
1932
   * @param $headers
1933
   *   An array containing additional HTTP request headers, each formatted as
1934
   *   "name: value".
1935
   * @return
1936
   *   The retrieved HTML string, also available as $this->drupalGetContent()
1937
   */
1938
  protected function drupalGet($path, array $options = array(), array $headers = array()) {
1939
    $options['absolute'] = TRUE;
1940

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

    
1947
    // Replace original page output with new output from redirected page(s).
1948
    if ($new = $this->checkForMetaRefresh()) {
1949
      $out = $new;
1950
    }
1951
    $this->verbose('GET request to: ' . $path .
1952
                   '<hr />Ending URL: ' . $this->getUrl() .
1953
                   '<hr />' . $out);
1954
    return $out;
1955
  }
1956

    
1957
  /**
1958
   * Retrieve a Drupal path or an absolute path and JSON decode the result.
1959
   */
1960
  protected function drupalGetAJAX($path, array $options = array(), array $headers = array()) {
1961
    return drupal_json_decode($this->drupalGet($path, $options, $headers));
1962
  }
1963

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

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

    
2103
          // Replace original page output with new output from redirected page(s).
2104
          if ($new = $this->checkForMetaRefresh()) {
2105
            $out = $new;
2106
          }
2107
          $this->verbose('POST request to: ' . $path .
2108
                         '<hr />Ending URL: ' . $this->getUrl() .
2109
                         '<hr />Fields: ' . highlight_string('<?php ' . var_export($post_array, TRUE), TRUE) .
2110
                         '<hr />' . $out);
2111
          return $out;
2112
        }
2113
      }
2114
      // We have not found a form which contained all fields of $edit.
2115
      foreach ($edit as $name => $value) {
2116
        $this->fail(t('Failed to set field @name to @value', array('@name' => $name, '@value' => $value)));
2117
      }
2118
      if (!$ajax && isset($submit)) {
2119
        $this->assertTrue($submit_matches, t('Found the @submit button', array('@submit' => $submit)));
2120
      }
2121
      $this->fail(t('Found the requested form fields at @path', array('@path' => $path)));
2122
    }
2123
  }
2124

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

    
2176
    // Get the Ajax settings bound to the triggering element.
2177
    if (!isset($ajax_settings)) {
2178
      if (is_array($triggering_element)) {
2179
        $xpath = '//*[@name="' . key($triggering_element) . '" and @value="' . current($triggering_element) . '"]';
2180
      }
2181
      else {
2182
        $xpath = '//*[@name="' . $triggering_element . '"]';
2183
      }
2184
      if (isset($form_html_id)) {
2185
        $xpath = '//form[@id="' . $form_html_id . '"]' . $xpath;
2186
      }
2187
      $element = $this->xpath($xpath);
2188
      $element_id = (string) $element[0]['id'];
2189
      $ajax_settings = $drupal_settings['ajax'][$element_id];
2190
    }
2191

    
2192
    // Add extra information to the POST data as ajax.js does.
2193
    $extra_post = '';
2194
    if (isset($ajax_settings['submit'])) {
2195
      foreach ($ajax_settings['submit'] as $key => $value) {
2196
        $extra_post .= '&' . urlencode($key) . '=' . urlencode($value);
2197
      }
2198
    }
2199
    foreach ($this->xpath('//*[@id]') as $element) {
2200
      $id = (string) $element['id'];
2201
      $extra_post .= '&' . urlencode('ajax_html_ids[]') . '=' . urlencode($id);
2202
    }
2203
    if (isset($drupal_settings['ajaxPageState'])) {
2204
      $extra_post .= '&' . urlencode('ajax_page_state[theme]') . '=' . urlencode($drupal_settings['ajaxPageState']['theme']);
2205
      $extra_post .= '&' . urlencode('ajax_page_state[theme_token]') . '=' . urlencode($drupal_settings['ajaxPageState']['theme_token']);
2206
      foreach ($drupal_settings['ajaxPageState']['css'] as $key => $value) {
2207
        $extra_post .= '&' . urlencode("ajax_page_state[css][$key]") . '=1';
2208
      }
2209
      foreach ($drupal_settings['ajaxPageState']['js'] as $key => $value) {
2210
        $extra_post .= '&' . urlencode("ajax_page_state[js][$key]") . '=1';
2211
      }
2212
    }
2213

    
2214
    // Unless a particular path is specified, use the one specified by the
2215
    // Ajax settings, or else 'system/ajax'.
2216
    if (!isset($ajax_path)) {
2217
      $ajax_path = isset($ajax_settings['url']) ? $ajax_settings['url'] : 'system/ajax';
2218
    }
2219

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

    
2224
    // Change the page content by applying the returned commands.
2225
    if (!empty($ajax_settings) && !empty($return)) {
2226
      // ajax.js applies some defaults to the settings object, so do the same
2227
      // for what's used by this function.
2228
      $ajax_settings += array(
2229
        'method' => 'replaceWith',
2230
      );
2231
      // DOM can load HTML soup. But, HTML soup can throw warnings, suppress
2232
      // them.
2233
      $dom = new DOMDocument();
2234
      @$dom->loadHTML($content);
2235
      // XPath allows for finding wrapper nodes better than DOM does.
2236
      $xpath = new DOMXPath($dom);
2237
      foreach ($return as $command) {
2238
        switch ($command['command']) {
2239
          case 'settings':
2240
            $drupal_settings = drupal_array_merge_deep($drupal_settings, $command['settings']);
2241
            break;
2242

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

    
2299
          case 'updateBuildId':
2300
            $buildId = $xpath->query('//input[@name="form_build_id" and @value="' . $command['old'] . '"]')->item(0);
2301
            if ($buildId) {
2302
              $buildId->setAttribute('value', $command['new']);
2303
            }
2304
            break;
2305

    
2306
          // @todo Add suitable implementations for these commands in order to
2307
          //   have full test coverage of what ajax.js can do.
2308
          case 'remove':
2309
            break;
2310
          case 'changed':
2311
            break;
2312
          case 'css':
2313
            break;
2314
          case 'data':
2315
            break;
2316
          case 'restripe':
2317
            break;
2318
          case 'add_css':
2319
            break;
2320
        }
2321
      }
2322
      $content = $dom->saveHTML();
2323
    }
2324
    $this->drupalSetContent($content);
2325
    $this->drupalSetSettings($drupal_settings);
2326

    
2327
    $verbose = 'AJAX POST request to: ' . $path;
2328
    $verbose .= '<br />AJAX callback path: ' . $ajax_path;
2329
    $verbose .= '<hr />Ending URL: ' . $this->getUrl();
2330
    $verbose .= '<hr />' . $this->content;
2331

    
2332
    $this->verbose($verbose);
2333

    
2334
    return $return;
2335
  }
2336

    
2337
  /**
2338
   * Runs cron in the Drupal installed by Simpletest.
2339
   */
2340
  protected function cronRun() {
2341
    $this->drupalGet($GLOBALS['base_url'] . '/cron.php', array('external' => TRUE, 'query' => array('cron_key' => variable_get('cron_key', 'drupal'))));
2342
  }
2343

    
2344
  /**
2345
   * Check for meta refresh tag and if found call drupalGet() recursively. This
2346
   * function looks for the http-equiv attribute to be set to "Refresh"
2347
   * and is case-sensitive.
2348
   *
2349
   * @return
2350
   *   Either the new page content or FALSE.
2351
   */
2352
  protected function checkForMetaRefresh() {
2353
    if (strpos($this->drupalGetContent(), '<meta ') && $this->parse()) {
2354
      $refresh = $this->xpath('//meta[@http-equiv="Refresh"]');
2355
      if (!empty($refresh)) {
2356
        // Parse the content attribute of the meta tag for the format:
2357
        // "[delay]: URL=[page_to_redirect_to]".
2358
        if (preg_match('/\d+;\s*URL=(?P<url>.*)/i', $refresh[0]['content'], $match)) {
2359
          return $this->drupalGet($this->getAbsoluteUrl(decode_entities($match['url'])));
2360
        }
2361
      }
2362
    }
2363
    return FALSE;
2364
  }
2365

    
2366
  /**
2367
   * Retrieves only the headers for a Drupal path or an absolute path.
2368
   *
2369
   * @param $path
2370
   *   Drupal path or URL to load into internal browser
2371
   * @param $options
2372
   *   Options to be forwarded to url().
2373
   * @param $headers
2374
   *   An array containing additional HTTP request headers, each formatted as
2375
   *   "name: value".
2376
   * @return
2377
   *   The retrieved headers, also available as $this->drupalGetContent()
2378
   */
2379
  protected function drupalHead($path, array $options = array(), array $headers = array()) {
2380
    $options['absolute'] = TRUE;
2381
    $out = $this->curlExec(array(CURLOPT_NOBODY => TRUE, CURLOPT_URL => url($path, $options), CURLOPT_HTTPHEADER => $headers));
2382
    $this->refreshVariables(); // Ensure that any changes to variables in the other thread are picked up.
2383
    return $out;
2384
  }
2385

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

    
2539
  /**
2540
   * Builds an XPath query.
2541
   *
2542
   * Builds an XPath query by replacing placeholders in the query by the value
2543
   * of the arguments.
2544
   *
2545
   * XPath 1.0 (the version supported by libxml2, the underlying XML library
2546
   * used by PHP) doesn't support any form of quotation. This function
2547
   * simplifies the building of XPath expression.
2548
   *
2549
   * @param $xpath
2550
   *   An XPath query, possibly with placeholders in the form ':name'.
2551
   * @param $args
2552
   *   An array of arguments with keys in the form ':name' matching the
2553
   *   placeholders in the query. The values may be either strings or numeric
2554
   *   values.
2555
   * @return
2556
   *   An XPath query with arguments replaced.
2557
   */
2558
  protected function buildXPathQuery($xpath, array $args = array()) {
2559
    // Replace placeholders.
2560
    foreach ($args as $placeholder => $value) {
2561
      // XPath 1.0 doesn't support a way to escape single or double quotes in a
2562
      // string literal. We split double quotes out of the string, and encode
2563
      // them separately.
2564
      if (is_string($value)) {
2565
        // Explode the text at the quote characters.
2566
        $parts = explode('"', $value);
2567

    
2568
        // Quote the parts.
2569
        foreach ($parts as &$part) {
2570
          $part = '"' . $part . '"';
2571
        }
2572

    
2573
        // Return the string.
2574
        $value = count($parts) > 1 ? 'concat(' . implode(', \'"\', ', $parts) . ')' : $parts[0];
2575
      }
2576
      $xpath = preg_replace('/' . preg_quote($placeholder) . '\b/', $value, $xpath);
2577
    }
2578
    return $xpath;
2579
  }
2580

    
2581
  /**
2582
   * Perform an xpath search on the contents of the internal browser. The search
2583
   * is relative to the root element (HTML tag normally) of the page.
2584
   *
2585
   * @param $xpath
2586
   *   The xpath string to use in the search.
2587
   * @return
2588
   *   The return value of the xpath search. For details on the xpath string
2589
   *   format and return values see the SimpleXML documentation,
2590
   *   http://us.php.net/manual/function.simplexml-element-xpath.php.
2591
   */
2592
  protected function xpath($xpath, array $arguments = array()) {
2593
    if ($this->parse()) {
2594
      $xpath = $this->buildXPathQuery($xpath, $arguments);
2595
      $result = $this->elements->xpath($xpath);
2596
      // Some combinations of PHP / libxml versions return an empty array
2597
      // instead of the documented FALSE. Forcefully convert any falsish values
2598
      // to an empty array to allow foreach(...) constructions.
2599
      return $result ? $result : array();
2600
    }
2601
    else {
2602
      return FALSE;
2603
    }
2604
  }
2605

    
2606
  /**
2607
   * Get all option elements, including nested options, in a select.
2608
   *
2609
   * @param $element
2610
   *   The element for which to get the options.
2611
   * @return
2612
   *   Option elements in select.
2613
   */
2614
  protected function getAllOptions(SimpleXMLElement $element) {
2615
    $options = array();
2616
    // Add all options items.
2617
    foreach ($element->option as $option) {
2618
      $options[] = $option;
2619
    }
2620

    
2621
    // Search option group children.
2622
    if (isset($element->optgroup)) {
2623
      foreach ($element->optgroup as $group) {
2624
        $options = array_merge($options, $this->getAllOptions($group));
2625
      }
2626
    }
2627
    return $options;
2628
  }
2629

    
2630
  /**
2631
   * Pass if a link with the specified label is found, and optional with the
2632
   * specified index.
2633
   *
2634
   * @param $label
2635
   *   Text between the anchor tags.
2636
   * @param $index
2637
   *   Link position counting from zero.
2638
   * @param $message
2639
   *   Message to display.
2640
   * @param $group
2641
   *   The group this message belongs to, defaults to 'Other'.
2642
   * @return
2643
   *   TRUE if the assertion succeeded, FALSE otherwise.
2644
   */
2645
  protected function assertLink($label, $index = 0, $message = '', $group = 'Other') {
2646
    $links = $this->xpath('//a[normalize-space(text())=:label]', array(':label' => $label));
2647
    $message = ($message ?  $message : t('Link with label %label found.', array('%label' => $label)));
2648
    return $this->assert(isset($links[$index]), $message, $group);
2649
  }
2650

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

    
2669
  /**
2670
   * Pass if a link containing a given href (part) is found.
2671
   *
2672
   * @param $href
2673
   *   The full or partial value of the 'href' attribute of the anchor tag.
2674
   * @param $index
2675
   *   Link position counting from zero.
2676
   * @param $message
2677
   *   Message to display.
2678
   * @param $group
2679
   *   The group this message belongs to, defaults to 'Other'.
2680
   *
2681
   * @return
2682
   *   TRUE if the assertion succeeded, FALSE otherwise.
2683
   */
2684
  protected function assertLinkByHref($href, $index = 0, $message = '', $group = 'Other') {
2685
    $links = $this->xpath('//a[contains(@href, :href)]', array(':href' => $href));
2686
    $message = ($message ?  $message : t('Link containing href %href found.', array('%href' => $href)));
2687
    return $this->assert(isset($links[$index]), $message, $group);
2688
  }
2689

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

    
2709
  /**
2710
   * Follows a link by name.
2711
   *
2712
   * Will click the first link found with this link text by default, or a later
2713
   * one if an index is given. Match is case sensitive with normalized space.
2714
   * The label is translated label.
2715
   *
2716
   * If the link is discovered and clicked, the test passes. Fail otherwise.
2717
   *
2718
   * @param $label
2719
   *   Text between the anchor tags.
2720
   * @param $index
2721
   *   Link position counting from zero.
2722
   * @return
2723
   *   Page contents on success, or FALSE on failure.
2724
   */
2725
  protected function clickLink($label, $index = 0) {
2726
    $url_before = $this->getUrl();
2727
    $urls = $this->xpath('//a[normalize-space(text())=:label]', array(':label' => $label));
2728
    if (isset($urls[$index])) {
2729
      $url_target = $this->getAbsoluteUrl($urls[$index]['href']);
2730
      $this->pass(t('Clicked link %label (@url_target) from @url_before', array('%label' => $label, '@url_target' => $url_target, '@url_before' => $url_before)), 'Browser');
2731
      return $this->drupalGet($url_target);
2732
    }
2733
    $this->fail(t('Link %label does not exist on @url_before', array('%label' => $label, '@url_before' => $url_before)), 'Browser');
2734
    return FALSE;
2735
  }
2736

    
2737
  /**
2738
   * Takes a path and returns an absolute path.
2739
   *
2740
   * @param $path
2741
   *   A path from the internal browser content.
2742
   * @return
2743
   *   The $path with $base_url prepended, if necessary.
2744
   */
2745
  protected function getAbsoluteUrl($path) {
2746
    global $base_url, $base_path;
2747

    
2748
    $parts = parse_url($path);
2749
    if (empty($parts['host'])) {
2750
      // Ensure that we have a string (and no xpath object).
2751
      $path = (string) $path;
2752
      // Strip $base_path, if existent.
2753
      $length = strlen($base_path);
2754
      if (substr($path, 0, $length) === $base_path) {
2755
        $path = substr($path, $length);
2756
      }
2757
      // Ensure that we have an absolute path.
2758
      if ($path[0] !== '/') {
2759
        $path = '/' . $path;
2760
      }
2761
      // Finally, prepend the $base_url.
2762
      $path = $base_url . $path;
2763
    }
2764
    return $path;
2765
  }
2766

    
2767
  /**
2768
   * Get the current URL from the cURL handler.
2769
   *
2770
   * @return
2771
   *   The current URL.
2772
   */
2773
  protected function getUrl() {
2774
    return $this->url;
2775
  }
2776

    
2777
  /**
2778
   * Gets the HTTP response headers of the requested page. Normally we are only
2779
   * interested in the headers returned by the last request. However, if a page
2780
   * is redirected or HTTP authentication is in use, multiple requests will be
2781
   * required to retrieve the page. Headers from all requests may be requested
2782
   * by passing TRUE to this function.
2783
   *
2784
   * @param $all_requests
2785
   *   Boolean value specifying whether to return headers from all requests
2786
   *   instead of just the last request. Defaults to FALSE.
2787
   * @return
2788
   *   A name/value array if headers from only the last request are requested.
2789
   *   If headers from all requests are requested, an array of name/value
2790
   *   arrays, one for each request.
2791
   *
2792
   *   The pseudonym ":status" is used for the HTTP status line.
2793
   *
2794
   *   Values for duplicate headers are stored as a single comma-separated list.
2795
   */
2796
  protected function drupalGetHeaders($all_requests = FALSE) {
2797
    $request = 0;
2798
    $headers = array($request => array());
2799
    foreach ($this->headers as $header) {
2800
      $header = trim($header);
2801
      if ($header === '') {
2802
        $request++;
2803
      }
2804
      else {
2805
        if (strpos($header, 'HTTP/') === 0) {
2806
          $name = ':status';
2807
          $value = $header;
2808
        }
2809
        else {
2810
          list($name, $value) = explode(':', $header, 2);
2811
          $name = strtolower($name);
2812
        }
2813
        if (isset($headers[$request][$name])) {
2814
          $headers[$request][$name] .= ',' . trim($value);
2815
        }
2816
        else {
2817
          $headers[$request][$name] = trim($value);
2818
        }
2819
      }
2820
    }
2821
    if (!$all_requests) {
2822
      $headers = array_pop($headers);
2823
    }
2824
    return $headers;
2825
  }
2826

    
2827
  /**
2828
   * Gets the value of an HTTP response header. If multiple requests were
2829
   * required to retrieve the page, only the headers from the last request will
2830
   * be checked by default. However, if TRUE is passed as the second argument,
2831
   * all requests will be processed from last to first until the header is
2832
   * found.
2833
   *
2834
   * @param $name
2835
   *   The name of the header to retrieve. Names are case-insensitive (see RFC
2836
   *   2616 section 4.2).
2837
   * @param $all_requests
2838
   *   Boolean value specifying whether to check all requests if the header is
2839
   *   not found in the last request. Defaults to FALSE.
2840
   * @return
2841
   *   The HTTP header value or FALSE if not found.
2842
   */
2843
  protected function drupalGetHeader($name, $all_requests = FALSE) {
2844
    $name = strtolower($name);
2845
    $header = FALSE;
2846
    if ($all_requests) {
2847
      foreach (array_reverse($this->drupalGetHeaders(TRUE)) as $headers) {
2848
        if (isset($headers[$name])) {
2849
          $header = $headers[$name];
2850
          break;
2851
        }
2852
      }
2853
    }
2854
    else {
2855
      $headers = $this->drupalGetHeaders();
2856
      if (isset($headers[$name])) {
2857
        $header = $headers[$name];
2858
      }
2859
    }
2860
    return $header;
2861
  }
2862

    
2863
  /**
2864
   * Gets the current raw HTML of requested page.
2865
   */
2866
  protected function drupalGetContent() {
2867
    return $this->content;
2868
  }
2869

    
2870
  /**
2871
   * Gets the value of the Drupal.settings JavaScript variable for the currently loaded page.
2872
   */
2873
  protected function drupalGetSettings() {
2874
    return $this->drupalSettings;
2875
  }
2876

    
2877
  /**
2878
   * Gets an array containing all e-mails sent during this test case.
2879
   *
2880
   * @param $filter
2881
   *   An array containing key/value pairs used to filter the e-mails that are returned.
2882
   * @return
2883
   *   An array containing e-mail messages captured during the current test.
2884
   */
2885
  protected function drupalGetMails($filter = array()) {
2886
    $captured_emails = variable_get('drupal_test_email_collector', array());
2887
    $filtered_emails = array();
2888

    
2889
    foreach ($captured_emails as $message) {
2890
      foreach ($filter as $key => $value) {
2891
        if (!isset($message[$key]) || $message[$key] != $value) {
2892
          continue 2;
2893
        }
2894
      }
2895
      $filtered_emails[] = $message;
2896
    }
2897

    
2898
    return $filtered_emails;
2899
  }
2900

    
2901
  /**
2902
   * Sets the raw HTML content. This can be useful when a page has been fetched
2903
   * outside of the internal browser and assertions need to be made on the
2904
   * returned page.
2905
   *
2906
   * A good example would be when testing drupal_http_request(). After fetching
2907
   * the page the content can be set and page elements can be checked to ensure
2908
   * that the function worked properly.
2909
   */
2910
  protected function drupalSetContent($content, $url = 'internal:') {
2911
    $this->content = $content;
2912
    $this->url = $url;
2913
    $this->plainTextContent = FALSE;
2914
    $this->elements = FALSE;
2915
    $this->drupalSettings = array();
2916
    if (preg_match('/jQuery\.extend\(Drupal\.settings, (.*?)\);/', $content, $matches)) {
2917
      $this->drupalSettings = drupal_json_decode($matches[1]);
2918
    }
2919
  }
2920

    
2921
  /**
2922
   * Sets the value of the Drupal.settings JavaScript variable for the currently loaded page.
2923
   */
2924
  protected function drupalSetSettings($settings) {
2925
    $this->drupalSettings = $settings;
2926
  }
2927

    
2928
  /**
2929
   * Pass if the internal browser's URL matches the given path.
2930
   *
2931
   * @param $path
2932
   *   The expected system path.
2933
   * @param $options
2934
   *   (optional) Any additional options to pass for $path to url().
2935
   * @param $message
2936
   *   Message to display.
2937
   * @param $group
2938
   *   The group this message belongs to, defaults to 'Other'.
2939
   *
2940
   * @return
2941
   *   TRUE on pass, FALSE on fail.
2942
   */
2943
  protected function assertUrl($path, array $options = array(), $message = '', $group = 'Other') {
2944
    if (!$message) {
2945
      $message = t('Current URL is @url.', array(
2946
        '@url' => var_export(url($path, $options), TRUE),
2947
      ));
2948
    }
2949
    $options['absolute'] = TRUE;
2950
    return $this->assertEqual($this->getUrl(), url($path, $options), $message, $group);
2951
  }
2952

    
2953
  /**
2954
   * Pass if the raw text IS found on the loaded page, fail otherwise. Raw text
2955
   * refers to the raw HTML that the page generated.
2956
   *
2957
   * @param $raw
2958
   *   Raw (HTML) string to look for.
2959
   * @param $message
2960
   *   Message to display.
2961
   * @param $group
2962
   *   The group this message belongs to, defaults to 'Other'.
2963
   * @return
2964
   *   TRUE on pass, FALSE on fail.
2965
   */
2966
  protected function assertRaw($raw, $message = '', $group = 'Other') {
2967
    if (!$message) {
2968
      $message = t('Raw "@raw" found', array('@raw' => $raw));
2969
    }
2970
    return $this->assert(strpos($this->drupalGetContent(), $raw) !== FALSE, $message, $group);
2971
  }
2972

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

    
2993
  /**
2994
   * Pass if the text IS found on the text version of the page. The text version
2995
   * is the equivalent of what a user would see when viewing through a web browser.
2996
   * In other words the HTML has been filtered out of the contents.
2997
   *
2998
   * @param $text
2999
   *   Plain text 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 assertText($text, $message = '', $group = 'Other') {
3008
    return $this->assertTextHelper($text, $message, $group, FALSE);
3009
  }
3010

    
3011
  /**
3012
   * Pass if the text is NOT found on the text version of the page. The text version
3013
   * is the equivalent of what a user would see when viewing through a web browser.
3014
   * In other words the HTML has been filtered out of the contents.
3015
   *
3016
   * @param $text
3017
   *   Plain text to look for.
3018
   * @param $message
3019
   *   Message to display.
3020
   * @param $group
3021
   *   The group this message belongs to, defaults to 'Other'.
3022
   * @return
3023
   *   TRUE on pass, FALSE on fail.
3024
   */
3025
  protected function assertNoText($text, $message = '', $group = 'Other') {
3026
    return $this->assertTextHelper($text, $message, $group, TRUE);
3027
  }
3028

    
3029
  /**
3030
   * Helper for assertText and assertNoText.
3031
   *
3032
   * It is not recommended to call this function directly.
3033
   *
3034
   * @param $text
3035
   *   Plain text to look for.
3036
   * @param $message
3037
   *   Message to display.
3038
   * @param $group
3039
   *   The group this message belongs to.
3040
   * @param $not_exists
3041
   *   TRUE if this text should not exist, FALSE if it should.
3042
   * @return
3043
   *   TRUE on pass, FALSE on fail.
3044
   */
3045
  protected function assertTextHelper($text, $message = '', $group, $not_exists) {
3046
    if ($this->plainTextContent === FALSE) {
3047
      $this->plainTextContent = filter_xss($this->drupalGetContent(), array());
3048
    }
3049
    if (!$message) {
3050
      $message = !$not_exists ? t('"@text" found', array('@text' => $text)) : t('"@text" not found', array('@text' => $text));
3051
    }
3052
    return $this->assert($not_exists == (strpos($this->plainTextContent, $text) === FALSE), $message, $group);
3053
  }
3054

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

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

    
3095
  /**
3096
   * Helper for assertUniqueText and assertNoUniqueText.
3097
   *
3098
   * It is not recommended to call this function directly.
3099
   *
3100
   * @param $text
3101
   *   Plain text to look for.
3102
   * @param $message
3103
   *   Message to display.
3104
   * @param $group
3105
   *   The group this message belongs to.
3106
   * @param $be_unique
3107
   *   TRUE if this text should be found only once, FALSE if it should be found more than once.
3108
   * @return
3109
   *   TRUE on pass, FALSE on fail.
3110
   */
3111
  protected function assertUniqueTextHelper($text, $message = '', $group, $be_unique) {
3112
    if ($this->plainTextContent === FALSE) {
3113
      $this->plainTextContent = filter_xss($this->drupalGetContent(), array());
3114
    }
3115
    if (!$message) {
3116
      $message = '"' . $text . '"' . ($be_unique ? ' found only once' : ' found more than once');
3117
    }
3118
    $first_occurance = strpos($this->plainTextContent, $text);
3119
    if ($first_occurance === FALSE) {
3120
      return $this->assert(FALSE, $message, $group);
3121
    }
3122
    $offset = $first_occurance + strlen($text);
3123
    $second_occurance = strpos($this->plainTextContent, $text, $offset);
3124
    return $this->assert($be_unique == ($second_occurance === FALSE), $message, $group);
3125
  }
3126

    
3127
  /**
3128
   * Will trigger a pass if the Perl regex pattern is found in the raw content.
3129
   *
3130
   * @param $pattern
3131
   *   Perl regex to look for including the regex delimiters.
3132
   * @param $message
3133
   *   Message to display.
3134
   * @param $group
3135
   *   The group this message belongs to.
3136
   * @return
3137
   *   TRUE on pass, FALSE on fail.
3138
   */
3139
  protected function assertPattern($pattern, $message = '', $group = 'Other') {
3140
    if (!$message) {
3141
      $message = t('Pattern "@pattern" found', array('@pattern' => $pattern));
3142
    }
3143
    return $this->assert((bool) preg_match($pattern, $this->drupalGetContent()), $message, $group);
3144
  }
3145

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

    
3165
  /**
3166
   * Pass if the page title is the given string.
3167
   *
3168
   * @param $title
3169
   *   The string the title should be.
3170
   * @param $message
3171
   *   Message to display.
3172
   * @param $group
3173
   *   The group this message belongs to.
3174
   * @return
3175
   *   TRUE on pass, FALSE on fail.
3176
   */
3177
  protected function assertTitle($title, $message = '', $group = 'Other') {
3178
    $actual = (string) current($this->xpath('//title'));
3179
    if (!$message) {
3180
      $message = t('Page title @actual is equal to @expected.', array(
3181
        '@actual' => var_export($actual, TRUE),
3182
        '@expected' => var_export($title, TRUE),
3183
      ));
3184
    }
3185
    return $this->assertEqual($actual, $title, $message, $group);
3186
  }
3187

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

    
3211
  /**
3212
   * Asserts themed output.
3213
   *
3214
   * @param $callback
3215
   *   The name of the theme function to invoke; e.g. 'links' for theme_links().
3216
   * @param $variables
3217
   *   (optional) An array of variables to pass to the theme function.
3218
   * @param $expected
3219
   *   The expected themed output string.
3220
   * @param $message
3221
   *   (optional) A message to display with the assertion. Do not translate
3222
   *   messages: use format_string() to embed variables in the message text, not
3223
   *   t(). If left blank, a default message will be displayed.
3224
   * @param $group
3225
   *   (optional) The group this message is in, which is displayed in a column
3226
   *   in test output. Use 'Debug' to indicate this is debugging output. Do not
3227
   *   translate this string. Defaults to 'Other'; most tests do not override
3228
   *   this default.
3229
   *
3230
   * @return
3231
   *   TRUE on pass, FALSE on fail.
3232
   */
3233
  protected function assertThemeOutput($callback, array $variables = array(), $expected, $message = '', $group = 'Other') {
3234
    $output = theme($callback, $variables);
3235
    $this->verbose('Variables:' . '<pre>' .  check_plain(var_export($variables, TRUE)) . '</pre>'
3236
      . '<hr />' . 'Result:' . '<pre>' .  check_plain(var_export($output, TRUE)) . '</pre>'
3237
      . '<hr />' . 'Expected:' . '<pre>' .  check_plain(var_export($expected, TRUE)) . '</pre>'
3238
      . '<hr />' . $output
3239
    );
3240
    if (!$message) {
3241
      $message = '%callback rendered correctly.';
3242
    }
3243
    $message = format_string($message, array('%callback' => 'theme_' . $callback . '()'));
3244
    return $this->assertIdentical($output, $expected, $message, $group);
3245
  }
3246

    
3247
  /**
3248
   * Asserts that a field exists in the current page by the given XPath.
3249
   *
3250
   * @param $xpath
3251
   *   XPath used to find the field.
3252
   * @param $value
3253
   *   (optional) Value of the field to assert. You may pass in NULL (default)
3254
   *   to skip checking the actual value, while still checking that the field
3255
   *   exists.
3256
   * @param $message
3257
   *   (optional) Message to display.
3258
   * @param $group
3259
   *   (optional) The group this message belongs to.
3260
   *
3261
   * @return
3262
   *   TRUE on pass, FALSE on fail.
3263
   */
3264
  protected function assertFieldByXPath($xpath, $value = NULL, $message = '', $group = 'Other') {
3265
    $fields = $this->xpath($xpath);
3266

    
3267
    // If value specified then check array for match.
3268
    $found = TRUE;
3269
    if (isset($value)) {
3270
      $found = FALSE;
3271
      if ($fields) {
3272
        foreach ($fields as $field) {
3273
          if (isset($field['value']) && $field['value'] == $value) {
3274
            // Input element with correct value.
3275
            $found = TRUE;
3276
          }
3277
          elseif (isset($field->option)) {
3278
            // Select element found.
3279
            if ($this->getSelectedItem($field) == $value) {
3280
              $found = TRUE;
3281
            }
3282
            else {
3283
              // No item selected so use first item.
3284
              $items = $this->getAllOptions($field);
3285
              if (!empty($items) && $items[0]['value'] == $value) {
3286
                $found = TRUE;
3287
              }
3288
            }
3289
          }
3290
          elseif ((string) $field == $value) {
3291
            // Text area with correct text.
3292
            $found = TRUE;
3293
          }
3294
        }
3295
      }
3296
    }
3297
    return $this->assertTrue($fields && $found, $message, $group);
3298
  }
3299

    
3300
  /**
3301
   * Get the selected value from a select field.
3302
   *
3303
   * @param $element
3304
   *   SimpleXMLElement select element.
3305
   * @return
3306
   *   The selected value or FALSE.
3307
   */
3308
  protected function getSelectedItem(SimpleXMLElement $element) {
3309
    foreach ($element->children() as $item) {
3310
      if (isset($item['selected'])) {
3311
        return $item['value'];
3312
      }
3313
      elseif ($item->getName() == 'optgroup') {
3314
        if ($value = $this->getSelectedItem($item)) {
3315
          return $value;
3316
        }
3317
      }
3318
    }
3319
    return FALSE;
3320
  }
3321

    
3322
  /**
3323
   * Asserts that a field doesn't exist or its value doesn't match, by XPath.
3324
   *
3325
   * @param $xpath
3326
   *   XPath used to find the field.
3327
   * @param $value
3328
   *   (optional) Value for the field, to assert that the field's value on the
3329
   *   page doesn't match it. You may pass in NULL to skip checking the
3330
   *   value, while still checking that the field doesn't exist.
3331
   * @param $message
3332
   *   (optional) Message to display.
3333
   * @param $group
3334
   *   (optional) The group this message belongs to.
3335
   *
3336
   * @return
3337
   *   TRUE on pass, FALSE on fail.
3338
   */
3339
  protected function assertNoFieldByXPath($xpath, $value = NULL, $message = '', $group = 'Other') {
3340
    $fields = $this->xpath($xpath);
3341

    
3342
    // If value specified then check array for match.
3343
    $found = TRUE;
3344
    if (isset($value)) {
3345
      $found = FALSE;
3346
      if ($fields) {
3347
        foreach ($fields as $field) {
3348
          if ($field['value'] == $value) {
3349
            $found = TRUE;
3350
          }
3351
        }
3352
      }
3353
    }
3354
    return $this->assertFalse($fields && $found, $message, $group);
3355
  }
3356

    
3357
  /**
3358
   * Asserts that a field exists in the current page with the given name and value.
3359
   *
3360
   * @param $name
3361
   *   Name of field to assert.
3362
   * @param $value
3363
   *   (optional) Value of the field to assert. You may pass in NULL (default)
3364
   *   to skip checking the actual value, while still checking that the field
3365
   *   exists.
3366
   * @param $message
3367
   *   Message to display.
3368
   * @param $group
3369
   *   The group this message belongs to.
3370
   * @return
3371
   *   TRUE on pass, FALSE on fail.
3372
   */
3373
  protected function assertFieldByName($name, $value = NULL, $message = NULL) {
3374
    if (!isset($message)) {
3375
      if (!isset($value)) {
3376
        $message = t('Found field with name @name', array(
3377
          '@name' => var_export($name, TRUE),
3378
        ));
3379
      }
3380
      else {
3381
        $message = t('Found field with name @name and value @value', array(
3382
          '@name' => var_export($name, TRUE),
3383
          '@value' => var_export($value, TRUE),
3384
        ));
3385
      }
3386
    }
3387
    return $this->assertFieldByXPath($this->constructFieldXpath('name', $name), $value, $message, t('Browser'));
3388
  }
3389

    
3390
  /**
3391
   * Asserts that a field does not exist with the given name and value.
3392
   *
3393
   * @param $name
3394
   *   Name of field to assert.
3395
   * @param $value
3396
   *   (optional) Value for the field, to assert that the field's value on the
3397
   *   page doesn't match it. You may pass in NULL to skip checking the
3398
   *   value, while still checking that the field doesn't exist. However, the
3399
   *   default value ('') asserts that the field value is not an empty string.
3400
   * @param $message
3401
   *   (optional) Message to display.
3402
   * @param $group
3403
   *   The group this message belongs to.
3404
   * @return
3405
   *   TRUE on pass, FALSE on fail.
3406
   */
3407
  protected function assertNoFieldByName($name, $value = '', $message = '') {
3408
    return $this->assertNoFieldByXPath($this->constructFieldXpath('name', $name), $value, $message ? $message : t('Did not find field by name @name', array('@name' => $name)), t('Browser'));
3409
  }
3410

    
3411
  /**
3412
   * Asserts that a field exists in the current page with the given ID and value.
3413
   *
3414
   * @param $id
3415
   *   ID of field to assert.
3416
   * @param $value
3417
   *   (optional) Value for the field to assert. You may pass in NULL to skip
3418
   *   checking the value, while still checking that the field exists.
3419
   *   However, the default value ('') asserts that the field value is an empty
3420
   *   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 assertFieldById($id, $value = '', $message = '') {
3429
    return $this->assertFieldByXPath($this->constructFieldXpath('id', $id), $value, $message ? $message : t('Found field by id @id', array('@id' => $id)), t('Browser'));
3430
  }
3431

    
3432
  /**
3433
   * Asserts that a field does not exist 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 that the field's value on the
3439
   *   page doesn't match it. You may pass in NULL to skip checking the value,
3440
   *   while still checking that the field doesn't exist. However, the default
3441
   *   value ('') asserts that the field value is not an empty string.
3442
   * @param $message
3443
   *   (optional) Message to display.
3444
   * @param $group
3445
   *   The group this message belongs to.
3446
   * @return
3447
   *   TRUE on pass, FALSE on fail.
3448
   */
3449
  protected function assertNoFieldById($id, $value = '', $message = '') {
3450
    return $this->assertNoFieldByXPath($this->constructFieldXpath('id', $id), $value, $message ? $message : t('Did not find field by id @id', array('@id' => $id)), t('Browser'));
3451
  }
3452

    
3453
  /**
3454
   * Asserts that a checkbox field in the current page is checked.
3455
   *
3456
   * @param $id
3457
   *   ID of field to assert.
3458
   * @param $message
3459
   *   (optional) Message to display.
3460
   * @return
3461
   *   TRUE on pass, FALSE on fail.
3462
   */
3463
  protected function assertFieldChecked($id, $message = '') {
3464
    $elements = $this->xpath('//input[@id=:id]', array(':id' => $id));
3465
    return $this->assertTrue(isset($elements[0]) && !empty($elements[0]['checked']), $message ? $message : t('Checkbox field @id is checked.', array('@id' => $id)), t('Browser'));
3466
  }
3467

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

    
3483
  /**
3484
   * Asserts that a select option in the current page is checked.
3485
   *
3486
   * @param $id
3487
   *   ID of select field to assert.
3488
   * @param $option
3489
   *   Option to assert.
3490
   * @param $message
3491
   *   (optional) Message to display.
3492
   * @return
3493
   *   TRUE on pass, FALSE on fail.
3494
   *
3495
   * @todo $id is unusable. Replace with $name.
3496
   */
3497
  protected function assertOptionSelected($id, $option, $message = '') {
3498
    $elements = $this->xpath('//select[@id=:id]//option[@value=:option]', array(':id' => $id, ':option' => $option));
3499
    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'));
3500
  }
3501

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

    
3519
  /**
3520
   * Asserts that a field exists with the given name or ID.
3521
   *
3522
   * @param $field
3523
   *   Name or ID of field to assert.
3524
   * @param $message
3525
   *   (optional) Message to display.
3526
   * @param $group
3527
   *   The group this message belongs to.
3528
   * @return
3529
   *   TRUE on pass, FALSE on fail.
3530
   */
3531
  protected function assertField($field, $message = '', $group = 'Other') {
3532
    return $this->assertFieldByXPath($this->constructFieldXpath('name', $field) . '|' . $this->constructFieldXpath('id', $field), NULL, $message, $group);
3533
  }
3534

    
3535
  /**
3536
   * Asserts that a field does not exist with the given name or ID.
3537
   *
3538
   * @param $field
3539
   *   Name or ID of field to assert.
3540
   * @param $message
3541
   *   (optional) Message to display.
3542
   * @param $group
3543
   *   The group this message belongs to.
3544
   * @return
3545
   *   TRUE on pass, FALSE on fail.
3546
   */
3547
  protected function assertNoField($field, $message = '', $group = 'Other') {
3548
    return $this->assertNoFieldByXPath($this->constructFieldXpath('name', $field) . '|' . $this->constructFieldXpath('id', $field), NULL, $message, $group);
3549
  }
3550

    
3551
  /**
3552
   * Asserts that each HTML ID is used for just a single element.
3553
   *
3554
   * @param $message
3555
   *   Message to display.
3556
   * @param $group
3557
   *   The group this message belongs to.
3558
   * @param $ids_to_skip
3559
   *   An optional array of ids to skip when checking for duplicates. It is
3560
   *   always a bug to have duplicate HTML IDs, so this parameter is to enable
3561
   *   incremental fixing of core code. Whenever a test passes this parameter,
3562
   *   it should add a "todo" comment above the call to this function explaining
3563
   *   the legacy bug that the test wishes to ignore and including a link to an
3564
   *   issue that is working to fix that legacy bug.
3565
   * @return
3566
   *   TRUE on pass, FALSE on fail.
3567
   */
3568
  protected function assertNoDuplicateIds($message = '', $group = 'Other', $ids_to_skip = array()) {
3569
    $status = TRUE;
3570
    foreach ($this->xpath('//*[@id]') as $element) {
3571
      $id = (string) $element['id'];
3572
      if (isset($seen_ids[$id]) && !in_array($id, $ids_to_skip)) {
3573
        $this->fail(t('The HTML ID %id is unique.', array('%id' => $id)), $group);
3574
        $status = FALSE;
3575
      }
3576
      $seen_ids[$id] = TRUE;
3577
    }
3578
    return $this->assert($status, $message, $group);
3579
  }
3580

    
3581
  /**
3582
   * Helper function: construct an XPath for the given set of attributes and value.
3583
   *
3584
   * @param $attribute
3585
   *   Field attributes.
3586
   * @param $value
3587
   *   Value of field.
3588
   * @return
3589
   *   XPath for specified values.
3590
   */
3591
  protected function constructFieldXpath($attribute, $value) {
3592
    $xpath = '//textarea[@' . $attribute . '=:value]|//input[@' . $attribute . '=:value]|//select[@' . $attribute . '=:value]';
3593
    return $this->buildXPathQuery($xpath, array(':value' => $value));
3594
  }
3595

    
3596
  /**
3597
   * Asserts the page responds with the specified response code.
3598
   *
3599
   * @param $code
3600
   *   Response code. For example 200 is a successful page request. For a list
3601
   *   of all codes see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html.
3602
   * @param $message
3603
   *   Message to display.
3604
   * @return
3605
   *   Assertion result.
3606
   */
3607
  protected function assertResponse($code, $message = '') {
3608
    $curl_code = curl_getinfo($this->curlHandle, CURLINFO_HTTP_CODE);
3609
    $match = is_array($code) ? in_array($curl_code, $code) : $curl_code == $code;
3610
    return $this->assertTrue($match, $message ? $message : t('HTTP response expected !code, actual !curl_code', array('!code' => $code, '!curl_code' => $curl_code)), t('Browser'));
3611
  }
3612

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

    
3631
  /**
3632
   * Asserts that the most recently sent e-mail message has the given value.
3633
   *
3634
   * The field in $name must have the content described in $value.
3635
   *
3636
   * @param $name
3637
   *   Name of field or message property to assert. Examples: subject, body, id, ...
3638
   * @param $value
3639
   *   Value of the field to assert.
3640
   * @param $message
3641
   *   Message to display.
3642
   *
3643
   * @return
3644
   *   TRUE on pass, FALSE on fail.
3645
   */
3646
  protected function assertMail($name, $value = '', $message = '') {
3647
    $captured_emails = variable_get('drupal_test_email_collector', array());
3648
    $email = end($captured_emails);
3649
    return $this->assertTrue($email && isset($email[$name]) && $email[$name] == $value, $message, t('E-mail'));
3650
  }
3651

    
3652
  /**
3653
   * Asserts that the most recently sent e-mail message has the string in it.
3654
   *
3655
   * @param $field_name
3656
   *   Name of field or message property to assert: subject, body, id, ...
3657
   * @param $string
3658
   *   String to search for.
3659
   * @param $email_depth
3660
   *   Number of emails to search for string, starting with most recent.
3661
   *
3662
   * @return
3663
   *   TRUE on pass, FALSE on fail.
3664
   */
3665
  protected function assertMailString($field_name, $string, $email_depth) {
3666
    $mails = $this->drupalGetMails();
3667
    $string_found = FALSE;
3668
    for ($i = sizeof($mails) -1; $i >= sizeof($mails) - $email_depth && $i >= 0; $i--) {
3669
      $mail = $mails[$i];
3670
      // Normalize whitespace, as we don't know what the mail system might have
3671
      // done. Any run of whitespace becomes a single space.
3672
      $normalized_mail = preg_replace('/\s+/', ' ', $mail[$field_name]);
3673
      $normalized_string = preg_replace('/\s+/', ' ', $string);
3674
      $string_found = (FALSE !== strpos($normalized_mail, $normalized_string));
3675
      if ($string_found) {
3676
        break;
3677
      }
3678
    }
3679
    return $this->assertTrue($string_found, t('Expected text found in @field of email message: "@expected".', array('@field' => $field_name, '@expected' => $string)));
3680
  }
3681

    
3682
  /**
3683
   * Asserts that the most recently sent e-mail message has the pattern in it.
3684
   *
3685
   * @param $field_name
3686
   *   Name of field or message property to assert: subject, body, id, ...
3687
   * @param $regex
3688
   *   Pattern to search for.
3689
   *
3690
   * @return
3691
   *   TRUE on pass, FALSE on fail.
3692
   */
3693
  protected function assertMailPattern($field_name, $regex, $message) {
3694
    $mails = $this->drupalGetMails();
3695
    $mail = end($mails);
3696
    $regex_found = preg_match("/$regex/", $mail[$field_name]);
3697
    return $this->assertTrue($regex_found, t('Expected text found in @field of email message: "@expected".', array('@field' => $field_name, '@expected' => $regex)));
3698
  }
3699

    
3700
  /**
3701
   * Outputs to verbose the most recent $count emails sent.
3702
   *
3703
   * @param $count
3704
   *   Optional number of emails to output.
3705
   */
3706
  protected function verboseEmail($count = 1) {
3707
    $mails = $this->drupalGetMails();
3708
    for ($i = sizeof($mails) -1; $i >= sizeof($mails) - $count && $i >= 0; $i--) {
3709
      $mail = $mails[$i];
3710
      $this->verbose(t('Email:') . '<pre>' . print_r($mail, TRUE) . '</pre>');
3711
    }
3712
  }
3713
}
3714

    
3715
/**
3716
 * Logs verbose message in a text file.
3717
 *
3718
 * If verbose mode is enabled then page requests will be dumped to a file and
3719
 * presented on the test result screen. The messages will be placed in a file
3720
 * located in the simpletest directory in the original file system.
3721
 *
3722
 * @param $message
3723
 *   The verbose message to be stored.
3724
 * @param $original_file_directory
3725
 *   The original file directory, before it was changed for testing purposes.
3726
 * @param $test_class
3727
 *   The active test case class.
3728
 *
3729
 * @return
3730
 *   The ID of the message to be placed in related assertion messages.
3731
 *
3732
 * @see DrupalTestCase->originalFileDirectory
3733
 * @see DrupalWebTestCase->verbose()
3734
 */
3735
function simpletest_verbose($message, $original_file_directory = NULL, $test_class = NULL) {
3736
  static $file_directory = NULL, $class = NULL, $id = 1, $verbose = NULL;
3737

    
3738
  // Will pass first time during setup phase, and when verbose is TRUE.
3739
  if (!isset($original_file_directory) && !$verbose) {
3740
    return FALSE;
3741
  }
3742

    
3743
  if ($message && $file_directory) {
3744
    $message = '<hr />ID #' . $id . ' (<a href="' . $class . '-' . ($id - 1) . '.html">Previous</a> | <a href="' . $class . '-' . ($id + 1) . '.html">Next</a>)<hr />' . $message;
3745
    file_put_contents($file_directory . "/simpletest/verbose/$class-$id.html", $message, FILE_APPEND);
3746
    return $id++;
3747
  }
3748

    
3749
  if ($original_file_directory) {
3750
    $file_directory = $original_file_directory;
3751
    $class = $test_class;
3752
    $verbose = variable_get('simpletest_verbose', TRUE);
3753
    $directory = $file_directory . '/simpletest/verbose';
3754
    $writable = file_prepare_directory($directory, FILE_CREATE_DIRECTORY);
3755
    if ($writable && !file_exists($directory . '/.htaccess')) {
3756
      file_put_contents($directory . '/.htaccess', "<IfModule mod_expires.c>\nExpiresActive Off\n</IfModule>\n");
3757
    }
3758
    return $writable;
3759
  }
3760
  return FALSE;
3761
}