PageRenderTime 47ms CodeModel.GetById 38ms RepoModel.GetById 2ms app.codeStats 0ms

/modules/simpletest/drupal_web_test_case.php

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