PageRenderTime 73ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

/modules/simpletest/drupal_web_test_case.php

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