drupal_web_test_case.php

You are here

  1. 7 modules/simpletest/drupal_web_test_case.php
  2. 8 core/modules/simpletest/drupal_web_test_case.php

Functions

Namesort descending Description
simpletest_verbose Logs verbose message in a text file.

Globals

Namesort descending Description
$drupal_test_info Global variable that holds information about the tests being run.

Classes

Namesort descending Description
DrupalTestCase Base class for Drupal tests.
DrupalUnitTestCase Test case for Drupal unit tests.
DrupalWebTestCase Test case for typical Drupal tests.

File

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