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

/core/modules/simpletest/drupal_web_test_case.php

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