PageRenderTime 35ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 1ms

/modules/simpletest/drupal_web_test_case.php

https://bitbucket.org/hjain/trinet
PHP | 3501 lines | 1513 code | 270 blank | 1718 comment | 232 complexity | 2b45e4f0908b3b0cd14da57e718ef436 MD5 | raw file
Possible License(s): GPL-2.0, LGPL-3.0, AGPL-1.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. // Clone the current connection and replace the current prefix.
  1154. $connection_info = Database::getConnectionInfo('default');
  1155. Database::renameConnection('default', 'simpletest_original_default');
  1156. foreach ($connection_info as $target => $value) {
  1157. $connection_info[$target]['prefix'] = array(
  1158. 'default' => $value['prefix']['default'] . $this->databasePrefix,
  1159. );
  1160. }
  1161. Database::addConnectionInfo('default', 'default', $connection_info['default']);
  1162. // Store necessary current values before switching to prefixed database.
  1163. $this->originalLanguage = $language;
  1164. $this->originalLanguageDefault = variable_get('language_default');
  1165. $this->originalFileDirectory = variable_get('file_public_path', conf_path() . '/files');
  1166. $this->originalProfile = drupal_get_profile();
  1167. $clean_url_original = variable_get('clean_url', 0);
  1168. // Set to English to prevent exceptions from utf8_truncate() from t()
  1169. // during install if the current language is not 'en'.
  1170. // The following array/object conversion is copied from language_default().
  1171. $language = (object) array('language' => 'en', 'name' => 'English', 'native' => 'English', 'direction' => 0, 'enabled' => 1, 'plurals' => 0, 'formula' => '', 'domain' => '', 'prefix' => '', 'weight' => 0, 'javascript' => '');
  1172. // Save and clean shutdown callbacks array because it static cached and
  1173. // will be changed by the test run. If we don't, then it will contain
  1174. // callbacks from both environments. So testing environment will try
  1175. // to call handlers from original environment.
  1176. $callbacks = &drupal_register_shutdown_function();
  1177. $this->originalShutdownCallbacks = $callbacks;
  1178. $callbacks = array();
  1179. // Create test directory ahead of installation so fatal errors and debug
  1180. // information can be logged during installation process.
  1181. // Use temporary files directory with the same prefix as the database.
  1182. $public_files_directory = $this->originalFileDirectory . '/simpletest/' . substr($this->databasePrefix, 10);
  1183. $private_files_directory = $public_files_directory . '/private';
  1184. $temp_files_directory = $private_files_directory . '/temp';
  1185. // Create the directories
  1186. file_prepare_directory($public_files_directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
  1187. file_prepare_directory($private_files_directory, FILE_CREATE_DIRECTORY);
  1188. file_prepare_directory($temp_files_directory, FILE_CREATE_DIRECTORY);
  1189. $this->generatedTestFiles = FALSE;
  1190. // Log fatal errors.
  1191. ini_set('log_errors', 1);
  1192. ini_set('error_log', $public_files_directory . '/error.log');
  1193. // Reset all statics and variables to perform tests in a clean environment.
  1194. $conf = array();
  1195. drupal_static_reset();
  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. // Include the testing profile.
  1214. variable_set('install_profile', $this->profile);
  1215. $profile_details = install_profile_info($this->profile, 'en');
  1216. // Install the modules specified by the testing profile.
  1217. module_enable($profile_details['dependencies'], FALSE);
  1218. // Install modules needed for this test. This could have been passed in as
  1219. // either a single array argument or a variable number of string arguments.
  1220. // @todo Remove this compatibility layer in Drupal 8, and only accept
  1221. // $modules as a single array argument.
  1222. $modules = func_get_args();
  1223. if (isset($modules[0]) && is_array($modules[0])) {
  1224. $modules = $modules[0];
  1225. }
  1226. if ($modules) {
  1227. $success = module_enable($modules, TRUE);
  1228. $this->assertTrue($success, t('Enabled modules: %modules', array('%modules' => implode(', ', $modules))));
  1229. }
  1230. // Run the profile tasks.
  1231. $install_profile_module_exists = db_query("SELECT 1 FROM {system} WHERE type = 'module' AND name = :name", array(
  1232. ':name' => $this->profile,
  1233. ))->fetchField();
  1234. if ($install_profile_module_exists) {
  1235. module_enable(array($this->profile), FALSE);
  1236. }
  1237. // Reset/rebuild all data structures after enabling the modules.
  1238. $this->resetAll();
  1239. // Run cron once in that environment, as install.php does at the end of
  1240. // the installation process.
  1241. drupal_cron_run();
  1242. // Log in with a clean $user.
  1243. $this->originalUser = $user;
  1244. drupal_save_session(FALSE);
  1245. $user = user_load(1);
  1246. // Restore necessary variables.
  1247. variable_set('install_task', 'done');
  1248. variable_set('clean_url', $clean_url_original);
  1249. variable_set('site_mail', 'simpletest@example.com');
  1250. variable_set('date_default_timezone', date_default_timezone_get());
  1251. // Set up English language.
  1252. unset($GLOBALS['conf']['language_default']);
  1253. $language = language_default();
  1254. // Use the test mail class instead of the default mail handler class.
  1255. variable_set('mail_system', array('default-system' => 'TestingMailSystem'));
  1256. drupal_set_time_limit($this->timeLimit);
  1257. $this->setup = TRUE;
  1258. }
  1259. /**
  1260. * Preload the registry from the testing site.
  1261. *
  1262. * This method is called by DrupalWebTestCase::setUp(), and preloads the
  1263. * registry from the testing site to cut down on the time it takes to
  1264. * set up a clean environment for the current test run.
  1265. */
  1266. protected function preloadRegistry() {
  1267. // Use two separate queries, each with their own connections: copy the
  1268. // {registry} and {registry_file} tables over from the parent installation
  1269. // to the child installation.
  1270. $original_connection = Database::getConnection('default', 'simpletest_original_default');
  1271. $test_connection = Database::getConnection();
  1272. foreach (array('registry', 'registry_file') as $table) {
  1273. // Find the records from the parent database.
  1274. $source_query = $original_connection
  1275. ->select($table, array(), array('fetch' => PDO::FETCH_ASSOC))
  1276. ->fields($table);
  1277. $dest_query = $test_connection->insert($table);
  1278. $first = TRUE;
  1279. foreach ($source_query->execute() as $row) {
  1280. if ($first) {
  1281. $dest_query->fields(array_keys($row));
  1282. $first = FALSE;
  1283. }
  1284. // Insert the records into the child database.
  1285. $dest_query->values($row);
  1286. }
  1287. $dest_query->execute();
  1288. }
  1289. }
  1290. /**
  1291. * Reset all data structures after having enabled new modules.
  1292. *
  1293. * This method is called by DrupalWebTestCase::setUp() after enabling
  1294. * the requested modules. It must be called again when additional modules
  1295. * are enabled later.
  1296. */
  1297. protected function resetAll() {
  1298. // Reset all static variables.
  1299. drupal_static_reset();
  1300. // Reset the list of enabled modules.
  1301. module_list(TRUE);
  1302. // Reset cached schema for new database prefix. This must be done before
  1303. // drupal_flush_all_caches() so rebuilds can make use of the schema of
  1304. // modules enabled on the cURL side.
  1305. drupal_get_schema(NULL, TRUE);
  1306. // Perform rebuilds and flush remaining caches.
  1307. drupal_flush_all_caches();
  1308. // Reload global $conf array and permissions.
  1309. $this->refreshVariables();
  1310. $this->checkPermissions(array(), TRUE);
  1311. }
  1312. /**
  1313. * Refresh the in-memory set of variables. Useful after a page request is made
  1314. * that changes a variable in a different thread.
  1315. *
  1316. * In other words calling a settings page with $this->drupalPost() with a changed
  1317. * value would update a variable to reflect that change, but in the thread that
  1318. * made the call (thread running the test) the changed variable would not be
  1319. * picked up.
  1320. *
  1321. * This method clears the variables cache and loads a fresh copy from the database
  1322. * to ensure that the most up-to-date set of variables is loaded.
  1323. */
  1324. protected function refreshVariables() {
  1325. global $conf;
  1326. cache_clear_all('variables', 'cache_bootstrap');
  1327. $conf = variable_initialize();
  1328. }
  1329. /**
  1330. * Delete created files and temporary files directory, delete the tables created by setUp(),
  1331. * and reset the database prefix.
  1332. */
  1333. protected function tearDown() {
  1334. global $user, $language;
  1335. // In case a fatal error occurred that was not in the test process read the
  1336. // log to pick up any fatal errors.
  1337. simpletest_log_read($this->testId, $this->databasePrefix, get_class($this), TRUE);
  1338. $emailCount = count(variable_get('drupal_test_email_collector', array()));
  1339. if ($emailCount) {
  1340. $message = format_plural($emailCount, '1 e-mail was sent during this test.', '@count e-mails were sent during this test.');
  1341. $this->pass($message, t('E-mail'));
  1342. }
  1343. // Delete temporary files directory.
  1344. file_unmanaged_delete_recursive($this->originalFileDirectory . '/simpletest/' . substr($this->databasePrefix, 10));
  1345. // Remove all prefixed tables (all the tables in the schema).
  1346. $schema = drupal_get_schema(NULL, TRUE);
  1347. foreach ($schema as $name => $table) {
  1348. db_drop_table($name);
  1349. }
  1350. // Get back to the original connection.
  1351. Database::removeConnection('default');
  1352. Database::renameConnection('simpletest_original_default', 'default');
  1353. // Restore original shutdown callbacks array to prevent original
  1354. // environment of calling handlers from test run.
  1355. $callbacks = &drupal_register_shutdown_function();
  1356. $callbacks = $this->originalShutdownCallbacks;
  1357. // Return the user to the original one.
  1358. $user = $this->originalUser;
  1359. drupal_save_session(TRUE);
  1360. // Ensure that internal logged in variable and cURL options are reset.
  1361. $this->loggedInUser = FALSE;
  1362. $this->additionalCurlOptions = array();
  1363. // Reload module list and implementations to ensure that test module hooks
  1364. // aren't called after tests.
  1365. module_list(TRUE);
  1366. module_implements('', FALSE, TRUE);
  1367. // Reset the Field API.
  1368. field_cache_clear();
  1369. // Rebuild caches.
  1370. $this->refreshVariables();
  1371. // Reset language.
  1372. $language = $this->originalLanguage;
  1373. if ($this->originalLanguageDefault) {
  1374. $GLOBALS['conf']['language_default'] = $this->originalLanguageDefault;
  1375. }
  1376. // Close the CURL handler.
  1377. $this->curlClose();
  1378. }
  1379. /**
  1380. * Initializes the cURL connection.
  1381. *
  1382. * If the simpletest_httpauth_credentials variable is set, this function will
  1383. * add HTTP authentication headers. This is necessary for testing sites that
  1384. * are protected by login credentials from public access.
  1385. * See the description of $curl_options for other options.
  1386. */
  1387. protected function curlInitialize() {
  1388. global $base_url;
  1389. if (!isset($this->curlHandle)) {
  1390. $this->curlHandle = curl_init();
  1391. $curl_options = array(
  1392. CURLOPT_COOKIEJAR => $this->cookieFile,
  1393. CURLOPT_URL => $base_url,
  1394. CURLOPT_FOLLOWLOCATION => FALSE,
  1395. CURLOPT_RETURNTRANSFER => TRUE,
  1396. CURLOPT_SSL_VERIFYPEER => FALSE, // Required to make the tests run on https.
  1397. CURLOPT_SSL_VERIFYHOST => FALSE, // Required to make the tests run on https.
  1398. CURLOPT_HEADERFUNCTION => array(&$this, 'curlHeaderCallback'),
  1399. CURLOPT_USERAGENT => $this->databasePrefix,
  1400. );
  1401. if (isset($this->httpauth_credentials)) {
  1402. $curl_options[CURLOPT_HTTPAUTH] = $this->httpauth_method;
  1403. $curl_options[CURLOPT_USERPWD] = $this->httpauth_credentials;
  1404. }
  1405. curl_setopt_array($this->curlHandle, $this->additionalCurlOptions + $curl_options);
  1406. // By default, the child session name should be the same as the parent.
  1407. $this->session_name = session_name();
  1408. }
  1409. // We set the user agent header on each request so as to use the current
  1410. // time and a new uniqid.
  1411. if (preg_match('/simpletest\d+/', $this->databasePrefix, $matches)) {
  1412. curl_setopt($this->curlHandle, CURLOPT_USERAGENT, drupal_generate_test_ua($matches[0]));
  1413. }
  1414. }
  1415. /**
  1416. * Initializes and executes a cURL request.
  1417. *
  1418. * @param $curl_options
  1419. * An associative array of cURL options to set, where the keys are constants
  1420. * defined by the cURL library. For a list of valid options, see
  1421. * http://www.php.net/manual/function.curl-setopt.php
  1422. * @param $redirect
  1423. * FALSE if this is an initial request, TRUE if this request is the result
  1424. * of a redirect.
  1425. *
  1426. * @return
  1427. * The content returned from the call to curl_exec().
  1428. *
  1429. * @see curlInitialize()
  1430. */
  1431. protected function curlExec($curl_options, $redirect = FALSE) {
  1432. $this->curlInitialize();
  1433. // cURL incorrectly handles URLs with a fragment by including the
  1434. // fragment in the request to the server, causing some web servers
  1435. // to reject the request citing "400 - Bad Request". To prevent
  1436. // this, we strip the fragment from the request.
  1437. // TODO: Remove this for Drupal 8, since fixed in curl 7.20.0.
  1438. if (!empty($curl_options[CURLOPT_URL]) && strpos($curl_options[CURLOPT_URL], '#')) {
  1439. $original_url = $curl_options[CURLOPT_URL];
  1440. $curl_options[CURLOPT_URL] = strtok($curl_options[CURLOPT_URL], '#');
  1441. }
  1442. $url = empty($curl_options[CURLOPT_URL]) ? curl_getinfo($this->curlHandle, CURLINFO_EFFECTIVE_URL) : $curl_options[CURLOPT_URL];
  1443. if (!empty($curl_options[CURLOPT_POST])) {
  1444. // This is a fix for the Curl library to prevent Expect: 100-continue
  1445. // headers in POST requests, that may cause unexpected HTTP response
  1446. // codes from some webservers (like lighttpd that returns a 417 error
  1447. // code). It is done by setting an empty "Expect" header field that is
  1448. // not overwritten by Curl.
  1449. $curl_options[CURLOPT_HTTPHEADER][] = 'Expect:';
  1450. }
  1451. curl_setopt_array($this->curlHandle, $this->additionalCurlOptions + $curl_options);
  1452. if (!$redirect) {
  1453. // Reset headers, the session ID and the redirect counter.
  1454. $this->session_id = NULL;
  1455. $this->headers = array();
  1456. $this->redirect_count = 0;
  1457. }
  1458. $content = curl_exec($this->curlHandle);
  1459. $status = curl_getinfo($this->curlHandle, CURLINFO_HTTP_CODE);
  1460. // cURL incorrectly handles URLs with fragments, so instead of
  1461. // letting cURL handle redirects we take of them ourselves to
  1462. // to prevent fragments being sent to the web server as part
  1463. // of the request.
  1464. // TODO: Remove this for Drupal 8, since fixed in curl 7.20.0.
  1465. if (in_array($status, array(300, 301, 302, 303, 305, 307)) && $this->redirect_count < variable_get('simpletest_maximum_redirects', 5)) {
  1466. if ($this->drupalGetHeader('location')) {
  1467. $this->redirect_count++;
  1468. $curl_options = array();
  1469. $curl_options[CURLOPT_URL] = $this->drupalGetHeader('location');
  1470. $curl_options[CURLOPT_HTTPGET] = TRUE;
  1471. return $this->curlExec($curl_options, TRUE);
  1472. }
  1473. }
  1474. $this->drupalSetContent($content, isset($original_url) ? $original_url : curl_getinfo($this->curlHandle, CURLINFO_EFFECTIVE_URL));
  1475. $message_vars = array(
  1476. '!method' => !empty($curl_options[CURLOPT_NOBODY]) ? 'HEAD' : (empty($curl_options[CURLOPT_POSTFIELDS]) ? 'GET' : 'POST'),
  1477. '@url' => isset($original_url) ? $original_url : $url,
  1478. '@status' => $status,
  1479. '!length' => format_size(strlen($this->drupalGetContent()))
  1480. );
  1481. $message = t('!method @url returned @status (!length).', $message_vars);
  1482. $this->assertTrue($this->drupalGetContent() !== FALSE, $message, t('Browser'));
  1483. return $this->drupalGetContent();
  1484. }
  1485. /**
  1486. * Reads headers and registers errors received from the tested site.
  1487. *
  1488. * @see _drupal_log_error().
  1489. *
  1490. * @param $curlHandler
  1491. * The cURL handler.
  1492. * @param $header
  1493. * An header.
  1494. */
  1495. protected function curlHeaderCallback($curlHandler, $header) {
  1496. // Header fields can be extended over multiple lines by preceding each
  1497. // extra line with at least one SP or HT. They should be joined on receive.
  1498. // Details are in RFC2616 section 4.
  1499. if ($header[0] == ' ' || $header[0] == "\t") {
  1500. // Normalize whitespace between chucks.
  1501. $this->headers[] = array_pop($this->headers) . ' ' . trim($header);
  1502. }
  1503. else {
  1504. $this->headers[] = $header;
  1505. }
  1506. // Errors are being sent via X-Drupal-Assertion-* headers,
  1507. // generated by _drupal_log_error() in the exact form required
  1508. // by DrupalWebTestCase::error().
  1509. if (preg_match('/^X-Drupal-Assertion-[0-9]+: (.*)$/', $header, $matches)) {
  1510. // Call DrupalWebTestCase::error() with the parameters from the header.
  1511. call_user_func_array(array(&$this, 'error'), unserialize(urldecode($matches[1])));
  1512. }
  1513. // Save cookies.
  1514. if (preg_match('/^Set-Cookie: ([^=]+)=(.+)/', $header, $matches)) {
  1515. $name = $matches[1];
  1516. $parts = array_map('trim', explode(';', $matches[2]));
  1517. $value = array_shift($parts);
  1518. $this->cookies[$name] = array('value' => $value, 'secure' => in_array('secure', $parts));
  1519. if ($name == $this->session_name) {
  1520. if ($value != 'deleted') {
  1521. $this->session_id = $value;
  1522. }
  1523. else {
  1524. $this->session_id = NULL;
  1525. }
  1526. }
  1527. }
  1528. // This is required by cURL.
  1529. return strlen($header);
  1530. }
  1531. /**
  1532. * Close the cURL handler and unset the handler.
  1533. */
  1534. protected function curlClose() {
  1535. if (isset($this->curlHandle)) {
  1536. curl_close($this->curlHandle);
  1537. unset($this->curlHandle);
  1538. }
  1539. }
  1540. /**
  1541. * Parse content returned from curlExec using DOM and SimpleXML.
  1542. *
  1543. * @return
  1544. * A SimpleXMLElement or FALSE on failure.
  1545. */
  1546. protected function parse() {
  1547. if (!$this->elements) {
  1548. // DOM can load HTML soup. But, HTML soup can throw warnings, suppress
  1549. // them.
  1550. $htmlDom = new DOMDocument();
  1551. @$htmlDom->loadHTML($this->drupalGetContent());
  1552. if ($htmlDom) {
  1553. $this->pass(t('Valid HTML found on "@path"', array('@path' => $this->getUrl())), t('Browser'));
  1554. // It's much easier to work with simplexml than DOM, luckily enough
  1555. // we can just simply import our DOM tree.
  1556. $this->elements = simplexml_import_dom($htmlDom);
  1557. }
  1558. }
  1559. if (!$this->elements) {
  1560. $this->fail(t('Parsed page successfully.'), t('Browser'));
  1561. }
  1562. return $this->elements;
  1563. }
  1564. /**
  1565. * Retrieves a Drupal path or an absolute path.
  1566. *
  1567. * @param $path
  1568. * Drupal path or URL to load into internal browser
  1569. * @param $options
  1570. * Options to be forwarded to url().
  1571. * @param $headers
  1572. * An array containing additional HTTP request headers, each formatted as
  1573. * "name: value".
  1574. * @return
  1575. * The retrieved HTML string, also available as $this->drupalGetContent()
  1576. */
  1577. protected function drupalGet($path, array $options = array(), array $headers = array()) {
  1578. $options['absolute'] = TRUE;
  1579. // We re-using a CURL connection here. If that connection still has certain
  1580. // options set, it might change the GET into a POST. Make sure we clear out
  1581. // previous options.
  1582. $out = $this->curlExec(array(CURLOPT_HTTPGET => TRUE, CURLOPT_URL => url($path, $options), CURLOPT_NOBODY => FALSE, CURLOPT_HTTPHEADER => $headers));
  1583. $this->refreshVariables(); // Ensure that any changes to variables in the other thread are picked up.
  1584. // Replace original page output with new output from redirected page(s).
  1585. if ($new = $this->checkForMetaRefresh()) {
  1586. $out = $new;
  1587. }
  1588. $this->verbose('GET request to: ' . $path .
  1589. '<hr />Ending URL: ' . $this->getUrl() .
  1590. '<hr />' . $out);
  1591. return $out;
  1592. }
  1593. /**
  1594. * Retrieve a Drupal path or an absolute path and JSON decode the result.
  1595. */
  1596. protected function drupalGetAJAX($path, array $options = array(), array $headers = array()) {
  1597. return drupal_json_decode($this->drupalGet($path, $options, $headers));
  1598. }
  1599. /**
  1600. * Execute a POST request on a Drupal page.
  1601. * It will be done as usual POST request with SimpleBrowser.
  1602. *
  1603. * @param $path
  1604. * Location of the post form. Either a Drupal path or an absolute path or
  1605. * NULL to post to the current page. For multi-stage forms you can set the
  1606. * path to NULL and have it post to the last received page. Example:
  1607. *
  1608. * @code
  1609. * // First step in form.
  1610. * $edit = array(...);
  1611. * $this->drupalPost('some_url', $edit, t('Save'));
  1612. *
  1613. * // Second step in form.
  1614. * $edit = array(...);
  1615. * $this->drupalPost(NULL, $edit, t('Save'));
  1616. * @endcode
  1617. * @param $edit
  1618. * Field data in an associative array. Changes the current input fields
  1619. * (where possible) to the values indicated. A checkbox can be set to
  1620. * TRUE to be checked and FALSE to be unchecked. Note that when a form
  1621. * contains file upload fields, other fields cannot start with the '@'
  1622. * character.
  1623. *
  1624. * Multiple select fields can be set using name[] and setting each of the
  1625. * possible values. Example:
  1626. * @code
  1627. * $edit = array();
  1628. * $edit['name[]'] = array('value1', 'value2');
  1629. * @endcode
  1630. * @param $submit
  1631. * Value of the submit button whose click is to be emulated. For example,
  1632. * t('Save'). The processing of the request depends on this value. For
  1633. * example, a form may have one button with the value t('Save') and another
  1634. * button with the value t('Delete'), and execute different code depending
  1635. * on which one is clicked.
  1636. *
  1637. * This function can also be called to emulate an Ajax submission. In this
  1638. * case, this value needs to be an array with the following keys:
  1639. * - path: A path to submit the form values to for Ajax-specific processing,
  1640. * which is likely different than the $path parameter used for retrieving
  1641. * the initial form. Defaults to 'system/ajax'.
  1642. * - triggering_element: If the value for the 'path' key is 'system/ajax' or
  1643. * another generic Ajax processing path, this needs to be set to the name
  1644. * of the element. If the name doesn't identify the element uniquely, then
  1645. * this should instead be an array with a single key/value pair,
  1646. * corresponding to the element name and value. The callback for the
  1647. * generic Ajax processing path uses this to find the #ajax information
  1648. * for the element, including which specific callback to use for
  1649. * processing the request.
  1650. *
  1651. * This can also be set to NULL in order to emulate an Internet Explorer
  1652. * submission of a form with a single text field, and pressing ENTER in that
  1653. * textfield: under these conditions, no button information is added to the
  1654. * POST data.
  1655. * @param $options
  1656. * Options to be forwarded to url().
  1657. * @param $headers
  1658. * An array containing additional HTTP request headers, each formatted as
  1659. * "name: value".
  1660. * @param $form_html_id
  1661. * (optional) HTML ID of the form to be submitted. On some pages
  1662. * there are many identical forms, so just using the value of the submit
  1663. * button is not enough. For example: 'trigger-node-presave-assign-form'.
  1664. * Note that this is not the Drupal $form_id, but rather the HTML ID of the
  1665. * form, which is typically the same thing but with hyphens replacing the
  1666. * underscores.
  1667. * @param $extra_post
  1668. * (optional) A string of additional data to append to the POST submission.
  1669. * This can be used to add POST data for which there are no HTML fields, as
  1670. * is done by drupalPostAJAX(). This string is literally appended to the
  1671. * POST data, so it must already be urlencoded and contain a leading "&"
  1672. * (e.g., "&extra_var1=hello+world&extra_var2=you%26me").
  1673. */
  1674. protected function drupalPost($path, $edit, $submit, array $options = array(), array $headers = array(), $form_html_id = NULL, $extra_post = NULL) {
  1675. $submit_matches = FALSE;
  1676. $ajax = is_array($submit);
  1677. if (isset($path)) {
  1678. $this->drupalGet($path, $options);
  1679. }
  1680. if ($this->parse()) {
  1681. $edit_save = $edit;
  1682. // Let's iterate over all the forms.
  1683. $xpath = "//form";
  1684. if (!empty($form_html_id)) {
  1685. $xpath .= "[@id='" . $form_html_id . "']";
  1686. }
  1687. $forms = $this->xpath($xpath);
  1688. foreach ($forms as $form) {
  1689. // We try to set the fields of this form as specified in $edit.
  1690. $edit = $edit_save;
  1691. $post = array();
  1692. $upload = array();
  1693. $submit_matches = $this->handleForm($post, $edit, $upload, $ajax ? NULL : $submit, $form);
  1694. $action = isset($form['action']) ? $this->getAbsoluteUrl((string) $form['action']) : $this->getUrl();
  1695. if ($ajax) {
  1696. $action = $this->getAbsoluteUrl(!empty($submit['path']) ? $submit['path'] : 'system/ajax');
  1697. // Ajax callbacks verify the triggering element if necessary, so while
  1698. // we may eventually want extra code that verifies it in the
  1699. // handleForm() function, it's not currently a requirement.
  1700. $submit_matches = TRUE;
  1701. }
  1702. // We post only if we managed to handle every field in edit and the
  1703. // submit button matches.
  1704. if (!$edit && ($submit_matches || !isset($submit))) {
  1705. $post_array = $post;
  1706. if ($upload) {
  1707. // TODO: cURL handles file uploads for us, but the implementation
  1708. // is broken. This is a less than elegant workaround. Alternatives
  1709. // are being explored at #253506.
  1710. foreach ($upload as $key => $file) {
  1711. $file = drupal_realpath($file);
  1712. if ($file && is_file($file)) {
  1713. $post[$key] = '@' . $file;
  1714. }
  1715. }
  1716. }
  1717. else {
  1718. foreach ($post as $key => $value) {
  1719. // Encode according to application/x-www-form-urlencoded
  1720. // Both names and values needs to be urlencoded, according to
  1721. // http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.1
  1722. $post[$key] = urlencode($key) . '=' . urlencode($value);
  1723. }
  1724. $post = implode('&', $post) . $extra_post;
  1725. }
  1726. $out = $this->curlExec(array(CURLOPT_URL => $action, CURLOPT_POST => TRUE, CURLOPT_POSTFIELDS => $post, CURLOPT_HTTPHEADER => $headers));
  1727. // Ensure that any changes to variables in the other thread are picked up.
  1728. $this->refreshVariables();
  1729. // Replace original page output with new output from redirected page(s).
  1730. if ($new = $this->checkForMetaRefresh()) {
  1731. $out = $new;
  1732. }
  1733. $this->verbose('POST request to: ' . $path .
  1734. '<hr />Ending URL: ' . $this->getUrl() .
  1735. '<hr />Fields: ' . highlight_string('<?php ' . var_export($post_array, TRUE), TRUE) .
  1736. '<hr />' . $out);
  1737. return $out;
  1738. }
  1739. }
  1740. // We have not found a form which contained all fields of $edit.
  1741. foreach ($edit as $name => $value) {
  1742. $this->fail(t('Failed to set field @name to @value', array('@name' => $name, '@value' => $value)));
  1743. }
  1744. if (!$ajax && isset($submit)) {
  1745. $this->assertTrue($submit_matches, t('Found the @submit button', array('@submit' => $submit)));
  1746. }
  1747. $this->fail(t('Found the requested form fields at @path', array('@path' => $path)));
  1748. }
  1749. }
  1750. /**
  1751. * Execute an Ajax submission.
  1752. *
  1753. * This executes a POST as ajax.js does. It uses the returned JSON data, an
  1754. * array of commands, to update $this->content using equivalent DOM
  1755. * manipulation as is used by ajax.js. It also returns the array of commands.
  1756. *
  1757. * @param $path
  1758. * Location of the form containing the Ajax enabled element to test. Can be
  1759. * either a Drupal path or an absolute path or NULL to use the current page.
  1760. * @param $edit
  1761. * Field data in an associative array. Changes the current input fields
  1762. * (where possible) to the values indicated.
  1763. * @param $triggering_element
  1764. * The name of the form element that is responsible for triggering the Ajax
  1765. * functionality to test. May be a string or, if the triggering element is
  1766. * a button, an associative array where the key is the name of the button
  1767. * and the value is the button label. i.e.) array('op' => t('Refresh')).
  1768. * @param $ajax_path
  1769. * (optional) Override the path set by the Ajax settings of the triggering
  1770. * element. In the absence of both the triggering element's Ajax path and
  1771. * $ajax_path 'system/ajax' will be used.
  1772. * @param $options
  1773. * (optional) Options to be forwarded to url().
  1774. * @param $headers
  1775. * (optional) An array containing additional HTTP request headers, each
  1776. * formatted as "name: value". Forwarded to drupalPost().
  1777. * @param $form_html_id
  1778. * (optional) HTML ID of the form to be submitted, use when there is more
  1779. * than one identical form on the same page and the value of the triggering
  1780. * element is not enough to identify the form. Note this is not the Drupal
  1781. * ID of the form but rather the HTML ID of the form.
  1782. * @param $ajax_settings
  1783. * (optional) An array of Ajax settings which if specified will be used in
  1784. * place of the Ajax settings of the triggering element.
  1785. *
  1786. * @return
  1787. * An array of Ajax commands.
  1788. *
  1789. * @see drupalPost()
  1790. * @see ajax.js
  1791. */
  1792. protected function drupalPostAJAX($path, $edit, $triggering_element, $ajax_path = NULL, array $options = array(), array $headers = array(), $form_html_id = NULL, $ajax_settings = NULL) {
  1793. // Get the content of the initial page prior to calling drupalPost(), since
  1794. // drupalPost() replaces $this->content.
  1795. if (isset($path)) {
  1796. $this->drupalGet($path, $options);
  1797. }
  1798. $content = $this->content;
  1799. $drupal_settings = $this->drupalSettings;
  1800. // Get the Ajax settings bound to the triggering element.
  1801. if (!isset($ajax_settings)) {
  1802. if (is_array($triggering_element)) {
  1803. $xpath = '//*[@name="' . key($triggering_element) . '" and @value="' . current($triggering_element) . '"]';
  1804. }
  1805. else {
  1806. $xpath = '//*[@name="' . $triggering_element . '"]';
  1807. }
  1808. if (isset($form_html_id)) {
  1809. $xpath = '//form[@id="' . $form_html_id . '"]' . $xpath;
  1810. }
  1811. $element = $this->xpath($xpath);
  1812. $element_id = (string) $element[0]['id'];
  1813. $ajax_settings = $drupal_settings['ajax'][$element_id];
  1814. }
  1815. // Add extra information to the POST data as ajax.js does.
  1816. $extra_post = '';
  1817. if (isset($ajax_settings['submit'])) {
  1818. foreach ($ajax_settings['submit'] as $key => $value) {
  1819. $extra_post .= '&' . urlencode($key) . '=' . urlencode($value);
  1820. }
  1821. }
  1822. foreach ($this->xpath('//*[@id]') as $element) {
  1823. $id = (string) $element['id'];
  1824. $extra_post .= '&' . urlencode('ajax_html_ids[]') . '=' . urlencode($id);
  1825. }
  1826. if (isset($drupal_settings['ajaxPageState'])) {
  1827. $extra_post .= '&' . urlencode('ajax_page_state[theme]') . '=' . urlencode($drupal_settings['ajaxPageState']['theme']);
  1828. $extra_post .= '&' . urlencode('ajax_page_state[theme_token]') . '=' . urlencode($drupal_settings['ajaxPageState']['theme_token']);
  1829. foreach ($drupal_settings['ajaxPageState']['css'] as $key => $value) {
  1830. $extra_post .= '&' . urlencode("ajax_page_state[css][$key]") . '=1';
  1831. }
  1832. foreach ($drupal_settings['ajaxPageState']['js'] as $key => $value) {
  1833. $extra_post .= '&' . urlencode("ajax_page_state[js][$key]") . '=1';
  1834. }
  1835. }
  1836. // Unless a particular path is specified, use the one specified by the
  1837. // Ajax settings, or else 'system/ajax'.
  1838. if (!isset($ajax_path)) {
  1839. $ajax_path = isset($ajax_settings['url']) ? $ajax_settings['url'] : 'system/ajax';
  1840. }
  1841. // Submit the POST request.
  1842. $return = drupal_json_decode($this->drupalPost(NULL, $edit, array('path' => $ajax_path, 'triggering_element' => $triggering_element), $options, $headers, $form_html_id, $extra_post));
  1843. // Change the page content by applying the returned commands.
  1844. if (!empty($ajax_settings) && !empty($return)) {
  1845. // ajax.js applies some defaults to the settings object, so do the same
  1846. // for what's used by this function.
  1847. $ajax_settings += array(
  1848. 'method' => 'replaceWith',
  1849. );
  1850. // DOM can load HTML soup. But, HTML soup can throw warnings, suppress
  1851. // them.
  1852. $dom = new DOMDocument();
  1853. @$dom->loadHTML($content);
  1854. foreach ($return as $command) {
  1855. switch ($command['command']) {
  1856. case 'settings':
  1857. $drupal_settings = drupal_array_merge_deep($drupal_settings, $command['settings']);
  1858. break;
  1859. case 'insert':
  1860. // @todo ajax.js can process commands that include a 'selector', but
  1861. // these are hard to emulate with DOMDocument. For now, we only
  1862. // implement 'insert' commands that use $ajax_settings['wrapper'].
  1863. if (!isset($command['selector'])) {
  1864. // $dom->getElementById() doesn't work when drupalPostAJAX() is
  1865. // invoked multiple times for a page, so use XPath instead. This
  1866. // also sets us up for adding support for $command['selector'] in
  1867. // the future, once we figure out how to transform a jQuery
  1868. // selector to XPath.
  1869. $xpath = new DOMXPath($dom);
  1870. $wrapperNode = $xpath->query('//*[@id="' . $ajax_settings['wrapper'] . '"]')->item(0);
  1871. if ($wrapperNode) {
  1872. // ajax.js adds an enclosing DIV to work around a Safari bug.
  1873. $newDom = new DOMDocument();
  1874. $newDom->loadHTML('<div>' . $command['data'] . '</div>');
  1875. $newNode = $dom->importNode($newDom->documentElement->firstChild->firstChild, TRUE);
  1876. $method = isset($command['method']) ? $command['method'] : $ajax_settings['method'];
  1877. // The "method" is a jQuery DOM manipulation function. Emulate
  1878. // each one using PHP's DOMNode API.
  1879. switch ($method) {
  1880. case 'replaceWith':
  1881. $wrapperNode->parentNode->replaceChild($newNode, $wrapperNode);
  1882. break;
  1883. case 'append':
  1884. $wrapperNode->appendChild($newNode);
  1885. break;
  1886. case 'prepend':
  1887. // If no firstChild, insertBefore() falls back to
  1888. // appendChild().
  1889. $wrapperNode->insertBefore($newNode, $wrapperNode->firstChild);
  1890. break;
  1891. case 'before':
  1892. $wrapperNode->parentNode->insertBefore($newNode, $wrapperNode);
  1893. break;
  1894. case 'after':
  1895. // If no nextSibling, insertBefore() falls back to
  1896. // appendChild().
  1897. $wrapperNode->parentNode->insertBefore($newNode, $wrapperNode->nextSibling);
  1898. break;
  1899. case 'html':
  1900. foreach ($wrapperNode->childNodes as $childNode) {
  1901. $wrapperNode->removeChild($childNode);
  1902. }
  1903. $wrapperNode->appendChild($newNode);
  1904. break;
  1905. }
  1906. }
  1907. }
  1908. break;
  1909. // @todo Add suitable implementations for these commands in order to
  1910. // have full test coverage of what ajax.js can do.
  1911. case 'remove':
  1912. break;
  1913. case 'changed':
  1914. break;
  1915. case 'css':
  1916. break;
  1917. case 'data':
  1918. break;
  1919. case 'restripe':
  1920. break;
  1921. }
  1922. }
  1923. $content = $dom->saveHTML();
  1924. }
  1925. $this->drupalSetContent($content);
  1926. $this->drupalSetSettings($drupal_settings);
  1927. return $return;
  1928. }
  1929. /**
  1930. * Runs cron in the Drupal installed by Simpletest.
  1931. */
  1932. protected function cronRun() {
  1933. $this->drupalGet($GLOBALS['base_url'] . '/cron.php', array('external' => TRUE, 'query' => array('cron_key' => variable_get('cron_key', 'drupal'))));
  1934. }
  1935. /**
  1936. * Check for meta refresh tag and if found call drupalGet() recursively. This
  1937. * function looks for the http-equiv attribute to be set to "Refresh"
  1938. * and is case-sensitive.
  1939. *
  1940. * @return
  1941. * Either the new page content or FALSE.
  1942. */
  1943. protected function checkForMetaRefresh() {
  1944. if (strpos($this->drupalGetContent(), '<meta ') && $this->parse()) {
  1945. $refresh = $this->xpath('//meta[@http-equiv="Refresh"]');
  1946. if (!empty($refresh)) {
  1947. // Parse the content attribute of the meta tag for the format:
  1948. // "[delay]: URL=[page_to_redirect_to]".
  1949. if (preg_match('/\d+;\s*URL=(?P<url>.*)/i', $refresh[0]['content'], $match)) {
  1950. return $this->drupalGet($this->getAbsoluteUrl(decode_entities($match['url'])));
  1951. }
  1952. }
  1953. }
  1954. return FALSE;
  1955. }
  1956. /**
  1957. * Retrieves only the headers for a Drupal path or an absolute path.
  1958. *
  1959. * @param $path
  1960. * Drupal path or URL to load into internal browser
  1961. * @param $options
  1962. * Options to be forwarded to url().
  1963. * @param $headers
  1964. * An array containing additional HTTP request headers, each formatted as
  1965. * "name: value".
  1966. * @return
  1967. * The retrieved headers, also available as $this->drupalGetContent()
  1968. */
  1969. protected function drupalHead($path, array $options = array(), array $headers = array()) {
  1970. $options['absolute'] = TRUE;
  1971. $out = $this->curlExec(array(CURLOPT_NOBODY => TRUE, CURLOPT_URL => url($path, $options), CURLOPT_HTTPHEADER => $headers));
  1972. $this->refreshVariables(); // Ensure that any changes to variables in the other thread are picked up.
  1973. return $out;
  1974. }
  1975. /**
  1976. * Handle form input related to drupalPost(). Ensure that the specified fields
  1977. * exist and attempt to create POST data in the correct manner for the particular
  1978. * field type.
  1979. *
  1980. * @param $post
  1981. * Reference to array of post values.
  1982. * @param $edit
  1983. * Reference to array of edit values to be checked against the form.
  1984. * @param $submit
  1985. * Form submit button value.
  1986. * @param $form
  1987. * Array of form elements.
  1988. * @return
  1989. * Submit value matches a valid submit input in the form.
  1990. */
  1991. protected function handleForm(&$post, &$edit, &$upload, $submit, $form) {
  1992. // Retrieve the form elements.
  1993. $elements = $form->xpath('.//input[not(@disabled)]|.//textarea[not(@disabled)]|.//select[not(@disabled)]');
  1994. $submit_matches = FALSE;
  1995. foreach ($elements as $element) {
  1996. // SimpleXML objects need string casting all the time.
  1997. $name = (string) $element['name'];
  1998. // This can either be the type of <input> or the name of the tag itself
  1999. // for <select> or <textarea>.
  2000. $type = isset($element['type']) ? (string) $element['type'] : $element->getName();
  2001. $value = isset($element['value']) ? (string) $element['value'] : '';
  2002. $done = FALSE;
  2003. if (isset($edit[$name])) {
  2004. switch ($type) {
  2005. case 'text':
  2006. case 'textarea':
  2007. case 'hidden':
  2008. case 'password':
  2009. $post[$name] = $edit[$name];
  2010. unset($edit[$name]);
  2011. break;
  2012. case 'radio':
  2013. if ($edit[$name] == $value) {
  2014. $post[$name] = $edit[$name];
  2015. unset($edit[$name]);
  2016. }
  2017. break;
  2018. case 'checkbox':
  2019. // To prevent checkbox from being checked.pass in a FALSE,
  2020. // otherwise the checkbox will be set to its value regardless
  2021. // of $edit.
  2022. if ($edit[$name] === FALSE) {
  2023. unset($edit[$name]);
  2024. continue 2;
  2025. }
  2026. else {
  2027. unset($edit[$name]);
  2028. $post[$name] = $value;
  2029. }
  2030. break;
  2031. case 'select':
  2032. $new_value = $edit[$name];
  2033. $options = $this->getAllOptions($element);
  2034. if (is_array($new_value)) {
  2035. // Multiple select box.
  2036. if (!empty($new_value)) {
  2037. $index = 0;
  2038. $key = preg_replace('/\[\]$/', '', $name);
  2039. foreach ($options as $option) {
  2040. $option_value = (string) $option['value'];
  2041. if (in_array($option_value, $new_value)) {
  2042. $post[$key . '[' . $index++ . ']'] = $option_value;
  2043. $done = TRUE;
  2044. unset($edit[$name]);
  2045. }
  2046. }
  2047. }
  2048. else {
  2049. // No options selected: do not include any POST data for the
  2050. // element.
  2051. $done = TRUE;
  2052. unset($edit[$name]);
  2053. }
  2054. }
  2055. else {
  2056. // Single select box.
  2057. foreach ($options as $option) {
  2058. if ($new_value == $option['value']) {
  2059. $post[$name] = $new_value;
  2060. unset($edit[$name]);
  2061. $done = TRUE;
  2062. break;
  2063. }
  2064. }
  2065. }
  2066. break;
  2067. case 'file':
  2068. $upload[$name] = $edit[$name];
  2069. unset($edit[$name]);
  2070. break;
  2071. }
  2072. }
  2073. if (!isset($post[$name]) && !$done) {
  2074. switch ($type) {
  2075. case 'textarea':
  2076. $post[$name] = (string) $element;
  2077. break;
  2078. case 'select':
  2079. $single = empty($element['multiple']);
  2080. $first = TRUE;
  2081. $index = 0;
  2082. $key = preg_replace('/\[\]$/', '', $name);
  2083. $options = $this->getAllOptions($element);
  2084. foreach ($options as $option) {
  2085. // For single select, we load the first option, if there is a
  2086. // selected option that will overwrite it later.
  2087. if ($option['selected'] || ($first && $single)) {
  2088. $first = FALSE;
  2089. if ($single) {
  2090. $post[$name] = (string) $option['value'];
  2091. }
  2092. else {
  2093. $post[$key . '[' . $index++ . ']'] = (string) $option['value'];
  2094. }
  2095. }
  2096. }
  2097. break;
  2098. case 'file':
  2099. break;
  2100. case 'submit':
  2101. case 'image':
  2102. if (isset($submit) && $submit == $value) {
  2103. $post[$name] = $value;
  2104. $submit_matches = TRUE;
  2105. }
  2106. break;
  2107. case 'radio':
  2108. case 'checkbox':
  2109. if (!isset($element['checked'])) {
  2110. break;
  2111. }
  2112. // Deliberate no break.
  2113. default:
  2114. $post[$name] = $value;
  2115. }
  2116. }
  2117. }
  2118. return $submit_matches;
  2119. }
  2120. /**
  2121. * Builds an XPath query.
  2122. *
  2123. * Builds an XPath query by replacing placeholders in the query by the value
  2124. * of the arguments.
  2125. *
  2126. * XPath 1.0 (the version supported by libxml2, the underlying XML library
  2127. * used by PHP) doesn't support any form of quotation. This function
  2128. * simplifies the building of XPath expression.
  2129. *
  2130. * @param $xpath
  2131. * An XPath query, possibly with placeholders in the form ':name'.
  2132. * @param $args
  2133. * An array of arguments with keys in the form ':name' matching the
  2134. * placeholders in the query. The values may be either strings or numeric
  2135. * values.
  2136. * @return
  2137. * An XPath query with arguments replaced.
  2138. */
  2139. protected function buildXPathQuery($xpath, array $args = array()) {
  2140. // Replace placeholders.
  2141. foreach ($args as $placeholder => $value) {
  2142. // XPath 1.0 doesn't support a way to escape single or double quotes in a
  2143. // string literal. We split double quotes out of the string, and encode
  2144. // them separately.
  2145. if (is_string($value)) {
  2146. // Explode the text at the quote characters.
  2147. $parts = explode('"', $value);
  2148. // Quote the parts.
  2149. foreach ($parts as &$part) {
  2150. $part = '"' . $part . '"';
  2151. }
  2152. // Return the string.
  2153. $value = count($parts) > 1 ? 'concat(' . implode(', \'"\', ', $parts) . ')' : $parts[0];
  2154. }
  2155. $xpath = preg_replace('/' . preg_quote($placeholder) . '\b/', $value, $xpath);
  2156. }
  2157. return $xpath;
  2158. }
  2159. /**
  2160. * Perform an xpath search on the contents of the internal browser. The search
  2161. * is relative to the root element (HTML tag normally) of the page.
  2162. *
  2163. * @param $xpath
  2164. * The xpath string to use in the search.
  2165. * @return
  2166. * The return value of the xpath search. For details on the xpath string
  2167. * format and return values see the SimpleXML documentation,
  2168. * http://us.php.net/manual/function.simplexml-element-xpath.php.
  2169. */
  2170. protected function xpath($xpath, array $arguments = array()) {
  2171. if ($this->parse()) {
  2172. $xpath = $this->buildXPathQuery($xpath, $arguments);
  2173. $result = $this->elements->xpath($xpath);
  2174. // Some combinations of PHP / libxml versions return an empty array
  2175. // instead of the documented FALSE. Forcefully convert any falsish values
  2176. // to an empty array to allow foreach(...) constructions.
  2177. return $result ? $result : array();
  2178. }
  2179. else {
  2180. return FALSE;
  2181. }
  2182. }
  2183. /**
  2184. * Get all option elements, including nested options, in a select.
  2185. *
  2186. * @param $element
  2187. * The element for which to get the options.
  2188. * @return
  2189. * Option elements in select.
  2190. */
  2191. protected function getAllOptions(SimpleXMLElement $element) {
  2192. $options = array();
  2193. // Add all options items.
  2194. foreach ($element->option as $option) {
  2195. $options[] = $option;
  2196. }
  2197. // Search option group children.
  2198. if (isset($element->optgroup)) {
  2199. foreach ($element->optgroup as $group) {
  2200. $options = array_merge($options, $this->getAllOptions($group));
  2201. }
  2202. }
  2203. return $options;
  2204. }
  2205. /**
  2206. * Pass if a link with the specified label is found, and optional with the
  2207. * specified index.
  2208. *
  2209. * @param $label
  2210. * Text between the anchor tags.
  2211. * @param $index
  2212. * Link position counting from zero.
  2213. * @param $message
  2214. * Message to display.
  2215. * @param $group
  2216. * The group this message belongs to, defaults to 'Other'.
  2217. * @return
  2218. * TRUE if the assertion succeeded, FALSE otherwise.
  2219. */
  2220. protected function assertLink($label, $index = 0, $message = '', $group = 'Other') {
  2221. $links = $this->xpath('//a[normalize-space(text())=:label]', array(':label' => $label));
  2222. $message = ($message ? $message : t('Link with label %label found.', array('%label' => $label)));
  2223. return $this->assert(isset($links[$index]), $message, $group);
  2224. }
  2225. /**
  2226. * Pass if a link with the specified label is not found.
  2227. *
  2228. * @param $label
  2229. * Text between the anchor tags.
  2230. * @param $index
  2231. * Link position counting from zero.
  2232. * @param $message
  2233. * Message to display.
  2234. * @param $group
  2235. * The group this message belongs to, defaults to 'Other'.
  2236. * @return
  2237. * TRUE if the assertion succeeded, FALSE otherwise.
  2238. */
  2239. protected function assertNoLink($label, $message = '', $group = 'Other') {
  2240. $links = $this->xpath('//a[normalize-space(text())=:label]', array(':label' => $label));
  2241. $message = ($message ? $message : t('Link with label %label not found.', array('%label' => $label)));
  2242. return $this->assert(empty($links), $message, $group);
  2243. }
  2244. /**
  2245. * Pass if a link containing a given href (part) is found.
  2246. *
  2247. * @param $href
  2248. * The full or partial value of the 'href' attribute of the anchor tag.
  2249. * @param $index
  2250. * Link position counting from zero.
  2251. * @param $message
  2252. * Message to display.
  2253. * @param $group
  2254. * The group this message belongs to, defaults to 'Other'.
  2255. *
  2256. * @return
  2257. * TRUE if the assertion succeeded, FALSE otherwise.
  2258. */
  2259. protected function assertLinkByHref($href, $index = 0, $message = '', $group = 'Other') {
  2260. $links = $this->xpath('//a[contains(@href, :href)]', array(':href' => $href));
  2261. $message = ($message ? $message : t('Link containing href %href found.', array('%href' => $href)));
  2262. return $this->assert(isset($links[$index]), $message, $group);
  2263. }
  2264. /**
  2265. * Pass if a link containing a given href (part) is not found.
  2266. *
  2267. * @param $href
  2268. * The full or partial value of the 'href' attribute of the anchor tag.
  2269. * @param $message
  2270. * Message to display.
  2271. * @param $group
  2272. * The group this message belongs to, defaults to 'Other'.
  2273. *
  2274. * @return
  2275. * TRUE if the assertion succeeded, FALSE otherwise.
  2276. */
  2277. protected function assertNoLinkByHref($href, $message = '', $group = 'Other') {
  2278. $links = $this->xpath('//a[contains(@href, :href)]', array(':href' => $href));
  2279. $message = ($message ? $message : t('No link containing href %href found.', array('%href' => $href)));
  2280. return $this->assert(empty($links), $message, $group);
  2281. }
  2282. /**
  2283. * Follows a link by name.
  2284. *
  2285. * Will click the first link found with this link text by default, or a
  2286. * later one if an index is given. Match is case insensitive with
  2287. * normalized space. The label is translated label. There is an assert
  2288. * for successful click.
  2289. *
  2290. * @param $label
  2291. * Text between the anchor tags.
  2292. * @param $index
  2293. * Link position counting from zero.
  2294. * @return
  2295. * Page on success, or FALSE on failure.
  2296. */
  2297. protected function clickLink($label, $index = 0) {
  2298. $url_before = $this->getUrl();
  2299. $urls = $this->xpath('//a[normalize-space(text())=:label]', array(':label' => $label));
  2300. if (isset($urls[$index])) {
  2301. $url_target = $this->getAbsoluteUrl($urls[$index]['href']);
  2302. }
  2303. $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'));
  2304. if (isset($url_target)) {
  2305. return $this->drupalGet($url_target);
  2306. }
  2307. return FALSE;
  2308. }
  2309. /**
  2310. * Takes a path and returns an absolute path.
  2311. *
  2312. * @param $path
  2313. * A path from the internal browser content.
  2314. * @return
  2315. * The $path with $base_url prepended, if necessary.
  2316. */
  2317. protected function getAbsoluteUrl($path) {
  2318. global $base_url, $base_path;
  2319. $parts = parse_url($path);
  2320. if (empty($parts['host'])) {
  2321. // Ensure that we have a string (and no xpath object).
  2322. $path = (string) $path;
  2323. // Strip $base_path, if existent.
  2324. $length = strlen($base_path);
  2325. if (substr($path, 0, $length) === $base_path) {
  2326. $path = substr($path, $length);
  2327. }
  2328. // Ensure that we have an absolute path.
  2329. if ($path[0] !== '/') {
  2330. $path = '/' . $path;
  2331. }
  2332. // Finally, prepend the $base_url.
  2333. $path = $base_url . $path;
  2334. }
  2335. return $path;
  2336. }
  2337. /**
  2338. * Get the current url from the cURL handler.
  2339. *
  2340. * @return
  2341. * The current url.
  2342. */
  2343. protected function getUrl() {
  2344. return $this->url;
  2345. }
  2346. /**
  2347. * Gets the HTTP response headers of the requested page. Normally we are only
  2348. * interested in the headers returned by the last request. However, if a page
  2349. * is redirected or HTTP authentication is in use, multiple requests will be
  2350. * required to retrieve the page. Headers from all requests may be requested
  2351. * by passing TRUE to this function.
  2352. *
  2353. * @param $all_requests
  2354. * Boolean value specifying whether to return headers from all requests
  2355. * instead of just the last request. Defaults to FALSE.
  2356. * @return
  2357. * A name/value array if headers from only the last request are requested.
  2358. * If headers from all requests are requested, an array of name/value
  2359. * arrays, one for each request.
  2360. *
  2361. * The pseudonym ":status" is used for the HTTP status line.
  2362. *
  2363. * Values for duplicate headers are stored as a single comma-separated list.
  2364. */
  2365. protected function drupalGetHeaders($all_requests = FALSE) {
  2366. $request = 0;
  2367. $headers = array($request => array());
  2368. foreach ($this->headers as $header) {
  2369. $header = trim($header);
  2370. if ($header === '') {
  2371. $request++;
  2372. }
  2373. else {
  2374. if (strpos($header, 'HTTP/') === 0) {
  2375. $name = ':status';
  2376. $value = $header;
  2377. }
  2378. else {
  2379. list($name, $value) = explode(':', $header, 2);
  2380. $name = strtolower($name);
  2381. }
  2382. if (isset($headers[$request][$name])) {
  2383. $headers[$request][$name] .= ',' . trim($value);
  2384. }
  2385. else {
  2386. $headers[$request][$name] = trim($value);
  2387. }
  2388. }
  2389. }
  2390. if (!$all_requests) {
  2391. $headers = array_pop($headers);
  2392. }
  2393. return $headers;
  2394. }
  2395. /**
  2396. * Gets the value of an HTTP response header. If multiple requests were
  2397. * required to retrieve the page, only the headers from the last request will
  2398. * be checked by default. However, if TRUE is passed as the second argument,
  2399. * all requests will be processed from last to first until the header is
  2400. * found.
  2401. *
  2402. * @param $name
  2403. * The name of the header to retrieve. Names are case-insensitive (see RFC
  2404. * 2616 section 4.2).
  2405. * @param $all_requests
  2406. * Boolean value specifying whether to check all requests if the header is
  2407. * not found in the last request. Defaults to FALSE.
  2408. * @return
  2409. * The HTTP header value or FALSE if not found.
  2410. */
  2411. protected function drupalGetHeader($name, $all_requests = FALSE) {
  2412. $name = strtolower($name);
  2413. $header = FALSE;
  2414. if ($all_requests) {
  2415. foreach (array_reverse($this->drupalGetHeaders(TRUE)) as $headers) {
  2416. if (isset($headers[$name])) {
  2417. $header = $headers[$name];
  2418. break;
  2419. }
  2420. }
  2421. }
  2422. else {
  2423. $headers = $this->drupalGetHeaders();
  2424. if (isset($headers[$name])) {
  2425. $header = $headers[$name];
  2426. }
  2427. }
  2428. return $header;
  2429. }
  2430. /**
  2431. * Gets the current raw HTML of requested page.
  2432. */
  2433. protected function drupalGetContent() {
  2434. return $this->content;
  2435. }
  2436. /**
  2437. * Gets the value of the Drupal.settings JavaScript variable for the currently loaded page.
  2438. */
  2439. protected function drupalGetSettings() {
  2440. return $this->drupalSettings;
  2441. }
  2442. /**
  2443. * Gets an array containing all e-mails sent during this test case.
  2444. *
  2445. * @param $filter
  2446. * An array containing key/value pairs used to filter the e-mails that are returned.
  2447. * @return
  2448. * An array containing e-mail messages captured during the current test.
  2449. */
  2450. protected function drupalGetMails($filter = array()) {
  2451. $captured_emails = variable_get('drupal_test_email_collector', array());
  2452. $filtered_emails = array();
  2453. foreach ($captured_emails as $message) {
  2454. foreach ($filter as $key => $value) {
  2455. if (!isset($message[$key]) || $message[$key] != $value) {
  2456. continue 2;
  2457. }
  2458. }
  2459. $filtered_emails[] = $message;
  2460. }
  2461. return $filtered_emails;
  2462. }
  2463. /**
  2464. * Sets the raw HTML content. This can be useful when a page has been fetched
  2465. * outside of the internal browser and assertions need to be made on the
  2466. * returned page.
  2467. *
  2468. * A good example would be when testing drupal_http_request(). After fetching
  2469. * the page the content can be set and page elements can be checked to ensure
  2470. * that the function worked properly.
  2471. */
  2472. protected function drupalSetContent($content, $url = 'internal:') {
  2473. $this->content = $content;
  2474. $this->url = $url;
  2475. $this->plainTextContent = FALSE;
  2476. $this->elements = FALSE;
  2477. $this->drupalSettings = array();
  2478. if (preg_match('/jQuery\.extend\(Drupal\.settings, (.*?)\);/', $content, $matches)) {
  2479. $this->drupalSettings = drupal_json_decode($matches[1]);
  2480. }
  2481. }
  2482. /**
  2483. * Sets the value of the Drupal.settings JavaScript variable for the currently loaded page.
  2484. */
  2485. protected function drupalSetSettings($settings) {
  2486. $this->drupalSettings = $settings;
  2487. }
  2488. /**
  2489. * Pass if the internal browser's URL matches the given path.
  2490. *
  2491. * @param $path
  2492. * The expected system path.
  2493. * @param $options
  2494. * (optional) Any additional options to pass for $path to url().
  2495. * @param $message
  2496. * Message to display.
  2497. * @param $group
  2498. * The group this message belongs to, defaults to 'Other'.
  2499. *
  2500. * @return
  2501. * TRUE on pass, FALSE on fail.
  2502. */
  2503. protected function assertUrl($path, array $options = array(), $message = '', $group = 'Other') {
  2504. if (!$message) {
  2505. $message = t('Current URL is @url.', array(
  2506. '@url' => var_export(url($path, $options), TRUE),
  2507. ));
  2508. }
  2509. $options['absolute'] = TRUE;
  2510. return $this->assertEqual($this->getUrl(), url($path, $options), $message, $group);
  2511. }
  2512. /**
  2513. * Pass if the raw text IS found on the loaded page, fail otherwise. Raw text
  2514. * refers to the raw HTML that the page generated.
  2515. *
  2516. * @param $raw
  2517. * Raw (HTML) string to look for.
  2518. * @param $message
  2519. * Message to display.
  2520. * @param $group
  2521. * The group this message belongs to, defaults to 'Other'.
  2522. * @return
  2523. * TRUE on pass, FALSE on fail.
  2524. */
  2525. protected function assertRaw($raw, $message = '', $group = 'Other') {
  2526. if (!$message) {
  2527. $message = t('Raw "@raw" found', array('@raw' => $raw));
  2528. }
  2529. return $this->assert(strpos($this->drupalGetContent(), $raw) !== FALSE, $message, $group);
  2530. }
  2531. /**
  2532. * Pass if the raw text is NOT found on the loaded page, fail otherwise. Raw text
  2533. * refers to the raw HTML that the page generated.
  2534. *
  2535. * @param $raw
  2536. * Raw (HTML) string to look for.
  2537. * @param $message
  2538. * Message to display.
  2539. * @param $group
  2540. * The group this message belongs to, defaults to 'Other'.
  2541. * @return
  2542. * TRUE on pass, FALSE on fail.
  2543. */
  2544. protected function assertNoRaw($raw, $message = '', $group = 'Other') {
  2545. if (!$message) {
  2546. $message = t('Raw "@raw" not found', array('@raw' => $raw));
  2547. }
  2548. return $this->assert(strpos($this->drupalGetContent(), $raw) === FALSE, $message, $group);
  2549. }
  2550. /**
  2551. * Pass if the text IS found on the text version of the page. The text version
  2552. * is the equivalent of what a user would see when viewing through a web browser.
  2553. * In other words the HTML has been filtered out of the contents.
  2554. *
  2555. * @param $text
  2556. * Plain text to look for.
  2557. * @param $message
  2558. * Message to display.
  2559. * @param $group
  2560. * The group this message belongs to, defaults to 'Other'.
  2561. * @return
  2562. * TRUE on pass, FALSE on fail.
  2563. */
  2564. protected function assertText($text, $message = '', $group = 'Other') {
  2565. return $this->assertTextHelper($text, $message, $group, FALSE);
  2566. }
  2567. /**
  2568. * Pass if the text is NOT found on the text version of the page. The text version
  2569. * is the equivalent of what a user would see when viewing through a web browser.
  2570. * In other words the HTML has been filtered out of the contents.
  2571. *
  2572. * @param $text
  2573. * Plain text to look for.
  2574. * @param $message
  2575. * Message to display.
  2576. * @param $group
  2577. * The group this message belongs to, defaults to 'Other'.
  2578. * @return
  2579. * TRUE on pass, FALSE on fail.
  2580. */
  2581. protected function assertNoText($text, $message = '', $group = 'Other') {
  2582. return $this->assertTextHelper($text, $message, $group, TRUE);
  2583. }
  2584. /**
  2585. * Helper for assertText and assertNoText.
  2586. *
  2587. * It is not recommended to call this function directly.
  2588. *
  2589. * @param $text
  2590. * Plain text to look for.
  2591. * @param $message
  2592. * Message to display.
  2593. * @param $group
  2594. * The group this message belongs to.
  2595. * @param $not_exists
  2596. * TRUE if this text should not exist, FALSE if it should.
  2597. * @return
  2598. * TRUE on pass, FALSE on fail.
  2599. */
  2600. protected function assertTextHelper($text, $message = '', $group, $not_exists) {
  2601. if ($this->plainTextContent === FALSE) {
  2602. $this->plainTextContent = filter_xss($this->drupalGetContent(), array());
  2603. }
  2604. if (!$message) {
  2605. $message = !$not_exists ? t('"@text" found', array('@text' => $text)) : t('"@text" not found', array('@text' => $text));
  2606. }
  2607. return $this->assert($not_exists == (strpos($this->plainTextContent, $text) === FALSE), $message, $group);
  2608. }
  2609. /**
  2610. * Pass if the text is found ONLY ONCE on the text version of the page.
  2611. *
  2612. * The text version is the equivalent of what a user would see when viewing
  2613. * through a web browser. In other words the HTML has been filtered out of
  2614. * the contents.
  2615. *
  2616. * @param $text
  2617. * Plain text to look for.
  2618. * @param $message
  2619. * Message to display.
  2620. * @param $group
  2621. * The group this message belongs to, defaults to 'Other'.
  2622. * @return
  2623. * TRUE on pass, FALSE on fail.
  2624. */
  2625. protected function assertUniqueText($text, $message = '', $group = 'Other') {
  2626. return $this->assertUniqueTextHelper($text, $message, $group, TRUE);
  2627. }
  2628. /**
  2629. * Pass if the text is found MORE THAN ONCE on the text version of the page.
  2630. *
  2631. * The text version is the equivalent of what a user would see when viewing
  2632. * through a web browser. In other words the HTML has been filtered out of
  2633. * the contents.
  2634. *
  2635. * @param $text
  2636. * Plain text to look for.
  2637. * @param $message
  2638. * Message to display.
  2639. * @param $group
  2640. * The group this message belongs to, defaults to 'Other'.
  2641. * @return
  2642. * TRUE on pass, FALSE on fail.
  2643. */
  2644. protected function assertNoUniqueText($text, $message = '', $group = 'Other') {
  2645. return $this->assertUniqueTextHelper($text, $message, $group, FALSE);
  2646. }
  2647. /**
  2648. * Helper for assertUniqueText and assertNoUniqueText.
  2649. *
  2650. * It is not recommended to call this function directly.
  2651. *
  2652. * @param $text
  2653. * Plain text to look for.
  2654. * @param $message
  2655. * Message to display.
  2656. * @param $group
  2657. * The group this message belongs to.
  2658. * @param $be_unique
  2659. * TRUE if this text should be found only once, FALSE if it should be found more than once.
  2660. * @return
  2661. * TRUE on pass, FALSE on fail.
  2662. */
  2663. protected function assertUniqueTextHelper($text, $message = '', $group, $be_unique) {
  2664. if ($this->plainTextContent === FALSE) {
  2665. $this->plainTextContent = filter_xss($this->drupalGetContent(), array());
  2666. }
  2667. if (!$message) {
  2668. $message = '"' . $text . '"' . ($be_unique ? ' found only once' : ' found more than once');
  2669. }
  2670. $first_occurance = strpos($this->plainTextContent, $text);
  2671. if ($first_occurance === FALSE) {
  2672. return $this->assert(FALSE, $message, $group);
  2673. }
  2674. $offset = $first_occurance + strlen($text);
  2675. $second_occurance = strpos($this->plainTextContent, $text, $offset);
  2676. return $this->assert($be_unique == ($second_occurance === FALSE), $message, $group);
  2677. }
  2678. /**
  2679. * Will trigger a pass if the Perl regex pattern is found in the raw content.
  2680. *
  2681. * @param $pattern
  2682. * Perl regex to look for including the regex delimiters.
  2683. * @param $message
  2684. * Message to display.
  2685. * @param $group
  2686. * The group this message belongs to.
  2687. * @return
  2688. * TRUE on pass, FALSE on fail.
  2689. */
  2690. protected function assertPattern($pattern, $message = '', $group = 'Other') {
  2691. if (!$message) {
  2692. $message = t('Pattern "@pattern" found', array('@pattern' => $pattern));
  2693. }
  2694. return $this->assert((bool) preg_match($pattern, $this->drupalGetContent()), $message, $group);
  2695. }
  2696. /**
  2697. * Will trigger a pass if the perl regex pattern is not present in raw content.
  2698. *
  2699. * @param $pattern
  2700. * Perl regex to look for including the regex delimiters.
  2701. * @param $message
  2702. * Message to display.
  2703. * @param $group
  2704. * The group this message belongs to.
  2705. * @return
  2706. * TRUE on pass, FALSE on fail.
  2707. */
  2708. protected function assertNoPattern($pattern, $message = '', $group = 'Other') {
  2709. if (!$message) {
  2710. $message = t('Pattern "@pattern" not found', array('@pattern' => $pattern));
  2711. }
  2712. return $this->assert(!preg_match($pattern, $this->drupalGetContent()), $message, $group);
  2713. }
  2714. /**
  2715. * Pass if the page title is the given string.
  2716. *
  2717. * @param $title
  2718. * The string the title should be.
  2719. * @param $message
  2720. * Message to display.
  2721. * @param $group
  2722. * The group this message belongs to.
  2723. * @return
  2724. * TRUE on pass, FALSE on fail.
  2725. */
  2726. protected function assertTitle($title, $message = '', $group = 'Other') {
  2727. $actual = (string) current($this->xpath('//title'));
  2728. if (!$message) {
  2729. $message = t('Page title @actual is equal to @expected.', array(
  2730. '@actual' => var_export($actual, TRUE),
  2731. '@expected' => var_export($title, TRUE),
  2732. ));
  2733. }
  2734. return $this->assertEqual($actual, $title, $message, $group);
  2735. }
  2736. /**
  2737. * Pass if the page title is not the given string.
  2738. *
  2739. * @param $title
  2740. * The string the title should not be.
  2741. * @param $message
  2742. * Message to display.
  2743. * @param $group
  2744. * The group this message belongs to.
  2745. * @return
  2746. * TRUE on pass, FALSE on fail.
  2747. */
  2748. protected function assertNoTitle($title, $message = '', $group = 'Other') {
  2749. $actual = (string) current($this->xpath('//title'));
  2750. if (!$message) {
  2751. $message = t('Page title @actual is not equal to @unexpected.', array(
  2752. '@actual' => var_export($actual, TRUE),
  2753. '@unexpected' => var_export($title, TRUE),
  2754. ));
  2755. }
  2756. return $this->assertNotEqual($actual, $title, $message, $group);
  2757. }
  2758. /**
  2759. * Asserts that a field exists in the current page by the given XPath.
  2760. *
  2761. * @param $xpath
  2762. * XPath used to find the field.
  2763. * @param $value
  2764. * (optional) Value of the field to assert.
  2765. * @param $message
  2766. * (optional) Message to display.
  2767. * @param $group
  2768. * (optional) The group this message belongs to.
  2769. *
  2770. * @return
  2771. * TRUE on pass, FALSE on fail.
  2772. */
  2773. protected function assertFieldByXPath($xpath, $value = NULL, $message = '', $group = 'Other') {
  2774. $fields = $this->xpath($xpath);
  2775. // If value specified then check array for match.
  2776. $found = TRUE;
  2777. if (isset($value)) {
  2778. $found = FALSE;
  2779. if ($fields) {
  2780. foreach ($fields as $field) {
  2781. if (isset($field['value']) && $field['value'] == $value) {
  2782. // Input element with correct value.
  2783. $found = TRUE;
  2784. }
  2785. elseif (isset($field->option)) {
  2786. // Select element found.
  2787. if ($this->getSelectedItem($field) == $value) {
  2788. $found = TRUE;
  2789. }
  2790. else {
  2791. // No item selected so use first item.
  2792. $items = $this->getAllOptions($field);
  2793. if (!empty($items) && $items[0]['value'] == $value) {
  2794. $found = TRUE;
  2795. }
  2796. }
  2797. }
  2798. elseif ((string) $field == $value) {
  2799. // Text area with correct text.
  2800. $found = TRUE;
  2801. }
  2802. }
  2803. }
  2804. }
  2805. return $this->assertTrue($fields && $found, $message, $group);
  2806. }
  2807. /**
  2808. * Get the selected value from a select field.
  2809. *
  2810. * @param $element
  2811. * SimpleXMLElement select element.
  2812. * @return
  2813. * The selected value or FALSE.
  2814. */
  2815. protected function getSelectedItem(SimpleXMLElement $element) {
  2816. foreach ($element->children() as $item) {
  2817. if (isset($item['selected'])) {
  2818. return $item['value'];
  2819. }
  2820. elseif ($item->getName() == 'optgroup') {
  2821. if ($value = $this->getSelectedItem($item)) {
  2822. return $value;
  2823. }
  2824. }
  2825. }
  2826. return FALSE;
  2827. }
  2828. /**
  2829. * Asserts that a field does not exist in the current page by the given XPath.
  2830. *
  2831. * @param $xpath
  2832. * XPath used to find the field.
  2833. * @param $value
  2834. * (optional) Value of the field to assert.
  2835. * @param $message
  2836. * (optional) Message to display.
  2837. * @param $group
  2838. * (optional) The group this message belongs to.
  2839. *
  2840. * @return
  2841. * TRUE on pass, FALSE on fail.
  2842. */
  2843. protected function assertNoFieldByXPath($xpath, $value = NULL, $message = '', $group = 'Other') {
  2844. $fields = $this->xpath($xpath);
  2845. // If value specified then check array for match.
  2846. $found = TRUE;
  2847. if (isset($value)) {
  2848. $found = FALSE;
  2849. if ($fields) {
  2850. foreach ($fields as $field) {
  2851. if ($field['value'] == $value) {
  2852. $found = TRUE;
  2853. }
  2854. }
  2855. }
  2856. }
  2857. return $this->assertFalse($fields && $found, $message, $group);
  2858. }
  2859. /**
  2860. * Asserts that a field exists in the current page with the given name and value.
  2861. *
  2862. * @param $name
  2863. * Name of field to assert.
  2864. * @param $value
  2865. * Value of the field to assert.
  2866. * @param $message
  2867. * Message to display.
  2868. * @param $group
  2869. * The group this message belongs to.
  2870. * @return
  2871. * TRUE on pass, FALSE on fail.
  2872. */
  2873. protected function assertFieldByName($name, $value = NULL, $message = NULL) {
  2874. if (!isset($message)) {
  2875. if (!isset($value)) {
  2876. $message = t('Found field with name @name', array(
  2877. '@name' => var_export($name, TRUE),
  2878. ));
  2879. }
  2880. else {
  2881. $message = t('Found field with name @name and value @value', array(
  2882. '@name' => var_export($name, TRUE),
  2883. '@value' => var_export($value, TRUE),
  2884. ));
  2885. }
  2886. }
  2887. return $this->assertFieldByXPath($this->constructFieldXpath('name', $name), $value, $message, t('Browser'));
  2888. }
  2889. /**
  2890. * Asserts that a field does not exist with the given name and value.
  2891. *
  2892. * @param $name
  2893. * Name of field to assert.
  2894. * @param $value
  2895. * Value of the field to assert.
  2896. * @param $message
  2897. * Message to display.
  2898. * @param $group
  2899. * The group this message belongs to.
  2900. * @return
  2901. * TRUE on pass, FALSE on fail.
  2902. */
  2903. protected function assertNoFieldByName($name, $value = '', $message = '') {
  2904. return $this->assertNoFieldByXPath($this->constructFieldXpath('name', $name), $value, $message ? $message : t('Did not find field by name @name', array('@name' => $name)), t('Browser'));
  2905. }
  2906. /**
  2907. * Asserts that a field exists in the current page with the given id and value.
  2908. *
  2909. * @param $id
  2910. * Id of field to assert.
  2911. * @param $value
  2912. * Value of the field to assert.
  2913. * @param $message
  2914. * Message to display.
  2915. * @param $group
  2916. * The group this message belongs to.
  2917. * @return
  2918. * TRUE on pass, FALSE on fail.
  2919. */
  2920. protected function assertFieldById($id, $value = '', $message = '') {
  2921. return $this->assertFieldByXPath($this->constructFieldXpath('id', $id), $value, $message ? $message : t('Found field by id @id', array('@id' => $id)), t('Browser'));
  2922. }
  2923. /**
  2924. * Asserts that a field does not exist with the given id and value.
  2925. *
  2926. * @param $id
  2927. * Id of field to assert.
  2928. * @param $value
  2929. * Value of the field to assert.
  2930. * @param $message
  2931. * Message to display.
  2932. * @param $group
  2933. * The group this message belongs to.
  2934. * @return
  2935. * TRUE on pass, FALSE on fail.
  2936. */
  2937. protected function assertNoFieldById($id, $value = '', $message = '') {
  2938. return $this->assertNoFieldByXPath($this->constructFieldXpath('id', $id), $value, $message ? $message : t('Did not find field by id @id', array('@id' => $id)), t('Browser'));
  2939. }
  2940. /**
  2941. * Asserts that a checkbox field in the current page is checked.
  2942. *
  2943. * @param $id
  2944. * Id of field to assert.
  2945. * @param $message
  2946. * Message to display.
  2947. * @return
  2948. * TRUE on pass, FALSE on fail.
  2949. */
  2950. protected function assertFieldChecked($id, $message = '') {
  2951. $elements = $this->xpath('//input[@id=:id]', array(':id' => $id));
  2952. return $this->assertTrue(isset($elements[0]) && !empty($elements[0]['checked']), $message ? $message : t('Checkbox field @id is checked.', array('@id' => $id)), t('Browser'));
  2953. }
  2954. /**
  2955. * Asserts that a checkbox field in the current page is not checked.
  2956. *
  2957. * @param $id
  2958. * Id of field to assert.
  2959. * @param $message
  2960. * Message to display.
  2961. * @return
  2962. * TRUE on pass, FALSE on fail.
  2963. */
  2964. protected function assertNoFieldChecked($id, $message = '') {
  2965. $elements = $this->xpath('//input[@id=:id]', array(':id' => $id));
  2966. return $this->assertTrue(isset($elements[0]) && empty($elements[0]['checked']), $message ? $message : t('Checkbox field @id is not checked.', array('@id' => $id)), t('Browser'));
  2967. }
  2968. /**
  2969. * Asserts that a select option in the current page is checked.
  2970. *
  2971. * @param $id
  2972. * Id of select field to assert.
  2973. * @param $option
  2974. * Option to assert.
  2975. * @param $message
  2976. * Message to display.
  2977. * @return
  2978. * TRUE on pass, FALSE on fail.
  2979. *
  2980. * @todo $id is unusable. Replace with $name.
  2981. */
  2982. protected function assertOptionSelected($id, $option, $message = '') {
  2983. $elements = $this->xpath('//select[@id=:id]//option[@value=:option]', array(':id' => $id, ':option' => $option));
  2984. 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'));
  2985. }
  2986. /**
  2987. * Asserts that a select option in the current page is not checked.
  2988. *
  2989. * @param $id
  2990. * Id of select field to assert.
  2991. * @param $option
  2992. * Option to assert.
  2993. * @param $message
  2994. * Message to display.
  2995. * @return
  2996. * TRUE on pass, FALSE on fail.
  2997. */
  2998. protected function assertNoOptionSelected($id, $option, $message = '') {
  2999. $elements = $this->xpath('//select[@id=:id]//option[@value=:option]', array(':id' => $id, ':option' => $option));
  3000. 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'));
  3001. }
  3002. /**
  3003. * Asserts that a field exists with the given name or id.
  3004. *
  3005. * @param $field
  3006. * Name or id of field to assert.
  3007. * @param $message
  3008. * Message to display.
  3009. * @param $group
  3010. * The group this message belongs to.
  3011. * @return
  3012. * TRUE on pass, FALSE on fail.
  3013. */
  3014. protected function assertField($field, $message = '', $group = 'Other') {
  3015. return $this->assertFieldByXPath($this->constructFieldXpath('name', $field) . '|' . $this->constructFieldXpath('id', $field), NULL, $message, $group);
  3016. }
  3017. /**
  3018. * Asserts that a field does not exist with the given name or id.
  3019. *
  3020. * @param $field
  3021. * Name or id of field to assert.
  3022. * @param $message
  3023. * Message to display.
  3024. * @param $group
  3025. * The group this message belongs to.
  3026. * @return
  3027. * TRUE on pass, FALSE on fail.
  3028. */
  3029. protected function assertNoField($field, $message = '', $group = 'Other') {
  3030. return $this->assertNoFieldByXPath($this->constructFieldXpath('name', $field) . '|' . $this->constructFieldXpath('id', $field), NULL, $message, $group);
  3031. }
  3032. /**
  3033. * Asserts that each HTML ID is used for just a single element.
  3034. *
  3035. * @param $message
  3036. * Message to display.
  3037. * @param $group
  3038. * The group this message belongs to.
  3039. * @param $ids_to_skip
  3040. * An optional array of ids to skip when checking for duplicates. It is
  3041. * always a bug to have duplicate HTML IDs, so this parameter is to enable
  3042. * incremental fixing of core code. Whenever a test passes this parameter,
  3043. * it should add a "todo" comment above the call to this function explaining
  3044. * the legacy bug that the test wishes to ignore and including a link to an
  3045. * issue that is working to fix that legacy bug.
  3046. * @return
  3047. * TRUE on pass, FALSE on fail.
  3048. */
  3049. protected function assertNoDuplicateIds($message = '', $group = 'Other', $ids_to_skip = array()) {
  3050. $status = TRUE;
  3051. foreach ($this->xpath('//*[@id]') as $element) {
  3052. $id = (string) $element['id'];
  3053. if (isset($seen_ids[$id]) && !in_array($id, $ids_to_skip)) {
  3054. $this->fail(t('The HTML ID %id is unique.', array('%id' => $id)), $group);
  3055. $status = FALSE;
  3056. }
  3057. $seen_ids[$id] = TRUE;
  3058. }
  3059. return $this->assert($status, $message, $group);
  3060. }
  3061. /**
  3062. * Helper function: construct an XPath for the given set of attributes and value.
  3063. *
  3064. * @param $attribute
  3065. * Field attributes.
  3066. * @param $value
  3067. * Value of field.
  3068. * @return
  3069. * XPath for specified values.
  3070. */
  3071. protected function constructFieldXpath($attribute, $value) {
  3072. $xpath = '//textarea[@' . $attribute . '=:value]|//input[@' . $attribute . '=:value]|//select[@' . $attribute . '=:value]';
  3073. return $this->buildXPathQuery($xpath, array(':value' => $value));
  3074. }
  3075. /**
  3076. * Asserts the page responds with the specified response code.
  3077. *
  3078. * @param $code
  3079. * Response code. For example 200 is a successful page request. For a list
  3080. * of all codes see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html.
  3081. * @param $message
  3082. * Message to display.
  3083. * @return
  3084. * Assertion result.
  3085. */
  3086. protected function assertResponse($code, $message = '') {
  3087. $curl_code = curl_getinfo($this->curlHandle, CURLINFO_HTTP_CODE);
  3088. $match = is_array($code) ? in_array($curl_code, $code) : $curl_code == $code;
  3089. return $this->assertTrue($match, $message ? $message : t('HTTP response expected !code, actual !curl_code', array('!code' => $code, '!curl_code' => $curl_code)), t('Browser'));
  3090. }
  3091. /**
  3092. * Asserts the page did not return the specified response code.
  3093. *
  3094. * @param $code
  3095. * Response code. For example 200 is a successful page request. For a list
  3096. * of all codes see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html.
  3097. * @param $message
  3098. * Message to display.
  3099. *
  3100. * @return
  3101. * Assertion result.
  3102. */
  3103. protected function assertNoResponse($code, $message = '') {
  3104. $curl_code = curl_getinfo($this->curlHandle, CURLINFO_HTTP_CODE);
  3105. $match = is_array($code) ? in_array($curl_code, $code) : $curl_code == $code;
  3106. return $this->assertFalse($match, $message ? $message : t('HTTP response not expected !code, actual !curl_code', array('!code' => $code, '!curl_code' => $curl_code)), t('Browser'));
  3107. }
  3108. /**
  3109. * Asserts that the most recently sent e-mail message has the given value.
  3110. *
  3111. * The field in $name must have the content described in $value.
  3112. *
  3113. * @param $name
  3114. * Name of field or message property to assert. Examples: subject, body, id, ...
  3115. * @param $value
  3116. * Value of the field to assert.
  3117. * @param $message
  3118. * Message to display.
  3119. *
  3120. * @return
  3121. * TRUE on pass, FALSE on fail.
  3122. */
  3123. protected function assertMail($name, $value = '', $message = '') {
  3124. $captured_emails = variable_get('drupal_test_email_collector', array());
  3125. $email = end($captured_emails);
  3126. return $this->assertTrue($email && isset($email[$name]) && $email[$name] == $value, $message, t('E-mail'));
  3127. }
  3128. /**
  3129. * Asserts that the most recently sent e-mail message has the string in it.
  3130. *
  3131. * @param $field_name
  3132. * Name of field or message property to assert: subject, body, id, ...
  3133. * @param $string
  3134. * String to search for.
  3135. * @param $email_depth
  3136. * Number of emails to search for string, starting with most recent.
  3137. *
  3138. * @return
  3139. * TRUE on pass, FALSE on fail.
  3140. */
  3141. protected function assertMailString($field_name, $string, $email_depth) {
  3142. $mails = $this->drupalGetMails();
  3143. $string_found = FALSE;
  3144. for ($i = sizeof($mails) -1; $i >= sizeof($mails) - $email_depth && $i >= 0; $i--) {
  3145. $mail = $mails[$i];
  3146. // Normalize whitespace, as we don't know what the mail system might have
  3147. // done. Any run of whitespace becomes a single space.
  3148. $normalized_mail = preg_replace('/\s+/', ' ', $mail[$field_name]);
  3149. $normalized_string = preg_replace('/\s+/', ' ', $string);
  3150. $string_found = (FALSE !== strpos($normalized_mail, $normalized_string));
  3151. if ($string_found) {
  3152. break;
  3153. }
  3154. }
  3155. return $this->assertTrue($string_found, t('Expected text found in @field of email message: "@expected".', array('@field' => $field_name, '@expected' => $string)));
  3156. }
  3157. /**
  3158. * Asserts that the most recently sent e-mail message has the pattern in it.
  3159. *
  3160. * @param $field_name
  3161. * Name of field or message property to assert: subject, body, id, ...
  3162. * @param $regex
  3163. * Pattern to search for.
  3164. *
  3165. * @return
  3166. * TRUE on pass, FALSE on fail.
  3167. */
  3168. protected function assertMailPattern($field_name, $regex, $message) {
  3169. $mails = $this->drupalGetMails();
  3170. $mail = end($mails);
  3171. $regex_found = preg_match("/$regex/", $mail[$field_name]);
  3172. return $this->assertTrue($regex_found, t('Expected text found in @field of email message: "@expected".', array('@field' => $field_name, '@expected' => $regex)));
  3173. }
  3174. /**
  3175. * Outputs to verbose the most recent $count emails sent.
  3176. *
  3177. * @param $count
  3178. * Optional number of emails to output.
  3179. */
  3180. protected function verboseEmail($count = 1) {
  3181. $mails = $this->drupalGetMails();
  3182. for ($i = sizeof($mails) -1; $i >= sizeof($mails) - $count && $i >= 0; $i--) {
  3183. $mail = $mails[$i];
  3184. $this->verbose(t('Email:') . '<pre>' . print_r($mail, TRUE) . '</pre>');
  3185. }
  3186. }
  3187. }
  3188. /**
  3189. * Logs verbose message in a text file.
  3190. *
  3191. * If verbose mode is enabled then page requests will be dumped to a file and
  3192. * presented on the test result screen. The messages will be placed in a file
  3193. * located in the simpletest directory in the original file system.
  3194. *
  3195. * @param $message
  3196. * The verbose message to be stored.
  3197. * @param $original_file_directory
  3198. * The original file directory, before it was changed for testing purposes.
  3199. * @param $test_class
  3200. * The active test case class.
  3201. *
  3202. * @return
  3203. * The ID of the message to be placed in related assertion messages.
  3204. *
  3205. * @see DrupalTestCase->originalFileDirectory
  3206. * @see DrupalWebTestCase->verbose()
  3207. */
  3208. function simpletest_verbose($message, $original_file_directory = NULL, $test_class = NULL) {
  3209. static $file_directory = NULL, $class = NULL, $id = 1, $verbose = NULL;
  3210. // Will pass first time during setup phase, and when verbose is TRUE.
  3211. if (!isset($original_file_directory) && !$verbose) {
  3212. return FALSE;
  3213. }
  3214. if ($message && $file_directory) {
  3215. $message = '<hr />ID #' . $id . ' (<a href="' . $class . '-' . ($id - 1) . '.html">Previous</a> | <a href="' . $class . '-' . ($id + 1) . '.html">Next</a>)<hr />' . $message;
  3216. file_put_contents($file_directory . "/simpletest/verbose/$class-$id.html", $message, FILE_APPEND);
  3217. return $id++;
  3218. }
  3219. if ($original_file_directory) {
  3220. $file_directory = $original_file_directory;
  3221. $class = $test_class;
  3222. $verbose = variable_get('simpletest_verbose', TRUE);
  3223. $directory = $file_directory . '/simpletest/verbose';
  3224. $writable = file_prepare_directory($directory, FILE_CREATE_DIRECTORY);
  3225. if ($writable && !file_exists($directory . '/.htaccess')) {
  3226. file_put_contents($directory . '/.htaccess', "<IfModule mod_expires.c>\nExpiresActive Off\n</IfModule>\n");
  3227. }
  3228. return $writable;
  3229. }
  3230. return FALSE;
  3231. }