PageRenderTime 39ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/vigilantmedia.com/drupal/modules/simpletest/drupal_web_test_case.php

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