Projet

Général

Profil

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

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

1
<?php
2

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

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

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

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

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

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

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

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

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

    
88
  protected $setupDatabasePrefix = FALSE;
89

    
90
  protected $setupEnvironment = FALSE;
91

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

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

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

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

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

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

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

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

    
177
    return $connection;
178
  }
179

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

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

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

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

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

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

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

    
261
    return _drupal_get_last_caller($backtrace);
262
  }
263

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1054
    return $type;
1055
  }
1056

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1197
    $this->assertTrue(isset($role->rid), t('Created role of name: @name, id: @rid', array('@name' => $name, '@rid' => (isset($role->rid) ? $role->rid : t('-n/a-')))), t('Role'));
1198
    if ($role && !empty($role->rid)) {
1199
      $count = db_query('SELECT COUNT(*) FROM {role_permission} WHERE rid = :rid', array(':rid' => $role->rid))->fetchField();
1200
      $this->assertTrue($count == count($permissions), t('Created permissions: @perms', array('@perms' => implode(', ', $permissions))), t('Role'));
1201
      return $role->rid;
1202
    }
1203
    else {
1204
      return FALSE;
1205
    }
1206
  }
1207

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1483
    $this->preloadRegistry();
1484

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1725
    if (!isset($this->curlHandle)) {
1726
      $this->curlHandle = curl_init();
1727

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1936
    return $this->elements;
1937
  }
1938

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2346
    $this->verbose($verbose);
2347

    
2348
    return $return;
2349
  }
2350

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

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

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

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

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

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

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

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

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

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

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

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

    
2688
  /**
2689
   * Pass if a link containing a given href (part) is found.
2690
   *
2691
   * @param $href
2692
   *   The full or partial value of the 'href' attribute of the anchor tag.
2693
   * @param $index
2694
   *   Link position counting from zero.
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 assertLinkByHref($href, $index = 0, $message = '', $group = 'Other') {
2704
    $links = $this->xpath('//a[contains(@href, :href)]', array(':href' => $href));
2705
    $message = ($message ?  $message : t('Link containing href %href found.', array('%href' => $href)));
2706
    return $this->assert(isset($links[$index]), $message, $group);
2707
  }
2708

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

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

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

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

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

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

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

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

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

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

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

    
2917
    return $filtered_emails;
2918
  }
2919

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

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

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

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

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

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

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

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

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

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

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

    
3146
  /**
3147
   * Will trigger a pass if the Perl regex pattern is found in the 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 assertPattern($pattern, $message = '', $group = 'Other') {
3159
    if (!$message) {
3160
      $message = t('Pattern "@pattern" found', array('@pattern' => $pattern));
3161
    }
3162
    return $this->assert((bool) preg_match($pattern, $this->drupalGetContent()), $message, $group);
3163
  }
3164

    
3165
  /**
3166
   * Will trigger a pass if the perl regex pattern is not present in raw content.
3167
   *
3168
   * @param $pattern
3169
   *   Perl regex to look for including the regex delimiters.
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 assertNoPattern($pattern, $message = '', $group = 'Other') {
3178
    if (!$message) {
3179
      $message = t('Pattern "@pattern" not found', array('@pattern' => $pattern));
3180
    }
3181
    return $this->assert(!preg_match($pattern, $this->drupalGetContent()), $message, $group);
3182
  }
3183

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

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

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

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

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

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

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

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

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

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

    
3430
  /**
3431
   * Asserts that a field exists in the current page with the given ID and value.
3432
   *
3433
   * @param $id
3434
   *   ID of field to assert.
3435
   * @param $value
3436
   *   (optional) Value for the field to assert. You may pass in NULL to skip
3437
   *   checking the value, while still checking that the field exists.
3438
   *   However, the default value ('') asserts that the field value is an empty
3439
   *   string.
3440
   * @param $message
3441
   *   (optional) Message to display.
3442
   * @param $group
3443
   *   The group this message belongs to.
3444
   * @return
3445
   *   TRUE on pass, FALSE on fail.
3446
   */
3447
  protected function assertFieldById($id, $value = '', $message = '') {
3448
    return $this->assertFieldByXPath($this->constructFieldXpath('id', $id), $value, $message ? $message : t('Found field by id @id', array('@id' => $id)), t('Browser'));
3449
  }
3450

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

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

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

    
3502
  /**
3503
   * Asserts that a select option in the current page is 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
   * @todo $id is unusable. Replace with $name.
3515
   */
3516
  protected function assertOptionSelected($id, $option, $message = '') {
3517
    $elements = $this->xpath('//select[@id=:id]//option[@value=:option]', array(':id' => $id, ':option' => $option));
3518
    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'));
3519
  }
3520

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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