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