PageRenderTime 100ms CodeModel.GetById 27ms RepoModel.GetById 1ms app.codeStats 0ms

/drupal-7.14/modules/simpletest/drupal_web_test_case.php

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