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