PageRenderTime 61ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/core/modules/simpletest/drupal_web_test_case.php

https://bitbucket.org/andytruong/drupal
PHP | 3438 lines | 1474 code | 268 blank | 1696 comment | 220 complexity | 767cf9ef995f33d9f3dcee0fc21799f5 MD5 | raw file
Possible License(s): GPL-2.0

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /**
  3. * Global variable that holds information about the tests being run.
  4. *
  5. * An array, with the following keys:
  6. * - 'test_run_id': the ID of the test being run, in the form 'simpletest_%"
  7. * - 'in_child_site': TRUE if the current request is a cURL request from
  8. * the parent site.
  9. *
  10. * @var array
  11. */
  12. global $drupal_test_info;
  13. /**
  14. * Base class for Drupal tests.
  15. *
  16. * Do not extend this class, use one of the subclasses in this file.
  17. */
  18. abstract class DrupalTestCase {
  19. /**
  20. * The test run ID.
  21. *
  22. * @var string
  23. */
  24. protected $testId;
  25. /**
  26. * The database prefix of this test run.
  27. *
  28. * @var string
  29. */
  30. protected $databasePrefix = NULL;
  31. /**
  32. * The original file directory, before it was changed for testing purposes.
  33. *
  34. * @var string
  35. */
  36. protected $originalFileDirectory = NULL;
  37. /**
  38. * Time limit for the test.
  39. */
  40. protected $timeLimit = 500;
  41. /**
  42. * Current results of this test case.
  43. *
  44. * @var Array
  45. */
  46. public $results = array(
  47. '#pass' => 0,
  48. '#fail' => 0,
  49. '#exception' => 0,
  50. '#debug' => 0,
  51. );
  52. /**
  53. * Assertions thrown in that test case.
  54. *
  55. * @var Array
  56. */
  57. protected $assertions = array();
  58. /**
  59. * This class is skipped when looking for the source of an assertion.
  60. *
  61. * When displaying which function an assert comes from, it's not too useful
  62. * to see "drupalWebTestCase->drupalLogin()', we would like to see the test
  63. * that called it. So we need to skip the classes defining these helper
  64. * methods.
  65. */
  66. protected $skipClasses = array(__CLASS__ => TRUE);
  67. /**
  68. * Constructor for DrupalTestCase.
  69. *
  70. * @param $test_id
  71. * Tests with the same id are reported together.
  72. */
  73. public function __construct($test_id = NULL) {
  74. $this->testId = $test_id;
  75. }
  76. /**
  77. * Internal helper: stores the assert.
  78. *
  79. * @param $status
  80. * Can be 'pass', 'fail', 'exception'.
  81. * TRUE is a synonym for 'pass', FALSE for 'fail'.
  82. * @param $message
  83. * The message string.
  84. * @param $group
  85. * Which group this assert belongs to.
  86. * @param $caller
  87. * By default, the assert comes from a function whose name starts with
  88. * 'test'. Instead, you can specify where this assert originates from
  89. * by passing in an associative array as $caller. Key 'file' is
  90. * the name of the source file, 'line' is the line number and 'function'
  91. * is the caller function itself.
  92. */
  93. protected function assert($status, $message = '', $group = 'Other', array $caller = NULL) {
  94. // Convert boolean status to string status.
  95. if (is_bool($status)) {
  96. $status = $status ? 'pass' : 'fail';
  97. }
  98. // Increment summary result counter.
  99. $this->results['#' . $status]++;
  100. // Get the function information about the call to the assertion method.
  101. if (!$caller) {
  102. $caller = $this->getAssertionCall();
  103. }
  104. // Creation assertion array that can be displayed while tests are running.
  105. $this->assertions[] = $assertion = array(
  106. 'test_id' => $this->testId,
  107. 'test_class' => get_class($this),
  108. 'status' => $status,
  109. 'message' => $message,
  110. 'message_group' => $group,
  111. 'function' => $caller['function'],
  112. 'line' => $caller['line'],
  113. 'file' => $caller['file'],
  114. );
  115. // Store assertion for display after the test has completed.
  116. Database::getConnection('default', 'simpletest_original_default')
  117. ->insert('simpletest')
  118. ->fields($assertion)
  119. ->execute();
  120. // We do not use a ternary operator here to allow a breakpoint on
  121. // test failure.
  122. if ($status == 'pass') {
  123. return TRUE;
  124. }
  125. else {
  126. return FALSE;
  127. }
  128. }
  129. /**
  130. * Store an assertion from outside the testing context.
  131. *
  132. * This is useful for inserting assertions that can only be recorded after
  133. * the test case has been destroyed, such as PHP fatal errors. The caller
  134. * information is not automatically gathered since the caller is most likely
  135. * inserting the assertion on behalf of other code. In all other respects
  136. * the method behaves just like DrupalTestCase::assert() in terms of storing
  137. * the assertion.
  138. *
  139. * @return
  140. * Message ID of the stored assertion.
  141. *
  142. * @see DrupalTestCase::assert()
  143. * @see DrupalTestCase::deleteAssert()
  144. */
  145. public static function insertAssert($test_id, $test_class, $status, $message = '', $group = 'Other', array $caller = array()) {
  146. // Convert boolean status to string status.
  147. if (is_bool($status)) {
  148. $status = $status ? 'pass' : 'fail';
  149. }
  150. $caller += array(
  151. 'function' => t('Unknown'),
  152. 'line' => 0,
  153. 'file' => t('Unknown'),
  154. );
  155. $assertion = array(
  156. 'test_id' => $test_id,
  157. 'test_class' => $test_class,
  158. 'status' => $status,
  159. 'message' => $message,
  160. 'message_group' => $group,
  161. 'function' => $caller['function'],
  162. 'line' => $caller['line'],
  163. 'file' => $caller['file'],
  164. );
  165. return db_insert('simpletest')
  166. ->fields($assertion)
  167. ->execute();
  168. }
  169. /**
  170. * Delete an assertion record by message ID.
  171. *
  172. * @param $message_id
  173. * Message ID of the assertion to delete.
  174. * @return
  175. * TRUE if the assertion was deleted, FALSE otherwise.
  176. *
  177. * @see DrupalTestCase::insertAssert()
  178. */
  179. public static function deleteAssert($message_id) {
  180. return (bool) db_delete('simpletest')
  181. ->condition('message_id', $message_id)
  182. ->execute();
  183. }
  184. /**
  185. * Cycles through backtrace until the first non-assertion method is found.
  186. *
  187. * @return
  188. * Array representing the true caller.
  189. */
  190. protected function getAssertionCall() {
  191. $backtrace = debug_backtrace();
  192. // The first element is the call. The second element is the caller.
  193. // We skip calls that occurred in one of the methods of our base classes
  194. // or in an assertion function.
  195. while (($caller = $backtrace[1]) &&
  196. ((isset($caller['class']) && isset($this->skipClasses[$caller['class']])) ||
  197. substr($caller['function'], 0, 6) == 'assert')) {
  198. // We remove that call.
  199. array_shift($backtrace);
  200. }
  201. return _drupal_get_last_caller($backtrace);
  202. }
  203. /**
  204. * Check to see if a value is not false (not an empty string, 0, NULL, or FALSE).
  205. *
  206. * @param $value
  207. * The value on which the assertion is to be done.
  208. * @param $message
  209. * The message to display along with the assertion.
  210. * @param $group
  211. * The type of assertion - examples are "Browser", "PHP".
  212. * @return
  213. * TRUE if the assertion succeeded, FALSE otherwise.
  214. */
  215. protected function assertTrue($value, $message = '', $group = 'Other') {
  216. return $this->assert((bool) $value, $message ? $message : t('Value @value is TRUE.', array('@value' => var_export($value, TRUE))), $group);
  217. }
  218. /**
  219. * Check to see if a value is false (an empty string, 0, NULL, or FALSE).
  220. *
  221. * @param $value
  222. * The value on which the assertion is to be done.
  223. * @param $message
  224. * The message to display along with the assertion.
  225. * @param $group
  226. * The type of assertion - examples are "Browser", "PHP".
  227. * @return
  228. * TRUE if the assertion succeeded, FALSE otherwise.
  229. */
  230. protected function assertFalse($value, $message = '', $group = 'Other') {
  231. return $this->assert(!$value, $message ? $message : t('Value @value is FALSE.', array('@value' => var_export($value, TRUE))), $group);
  232. }
  233. /**
  234. * Check to see if a value is NULL.
  235. *
  236. * @param $value
  237. * The value on which the assertion is to be done.
  238. * @param $message
  239. * The message to display along with the assertion.
  240. * @param $group
  241. * The type of assertion - examples are "Browser", "PHP".
  242. * @return
  243. * TRUE if the assertion succeeded, FALSE otherwise.
  244. */
  245. protected function assertNull($value, $message = '', $group = 'Other') {
  246. return $this->assert(!isset($value), $message ? $message : t('Value @value is NULL.', array('@value' => var_export($value, TRUE))), $group);
  247. }
  248. /**
  249. * Check to see if a value is not NULL.
  250. *
  251. * @param $value
  252. * The value on which the assertion is to be done.
  253. * @param $message
  254. * The message to display along with the assertion.
  255. * @param $group
  256. * The type of assertion - examples are "Browser", "PHP".
  257. * @return
  258. * TRUE if the assertion succeeded, FALSE otherwise.
  259. */
  260. protected function assertNotNull($value, $message = '', $group = 'Other') {
  261. return $this->assert(isset($value), $message ? $message : t('Value @value is not NULL.', array('@value' => var_export($value, TRUE))), $group);
  262. }
  263. /**
  264. * Check to see if two values are equal.
  265. *
  266. * @param $first
  267. * The first value to check.
  268. * @param $second
  269. * The second value to check.
  270. * @param $message
  271. * The message to display along with the assertion.
  272. * @param $group
  273. * The type of assertion - examples are "Browser", "PHP".
  274. * @return
  275. * TRUE if the assertion succeeded, FALSE otherwise.
  276. */
  277. protected function assertEqual($first, $second, $message = '', $group = 'Other') {
  278. return $this->assert($first == $second, $message ? $message : t('Value @first is equal to value @second.', array('@first' => var_export($first, TRUE), '@second' => var_export($second, TRUE))), $group);
  279. }
  280. /**
  281. * Check to see if two values are not equal.
  282. *
  283. * @param $first
  284. * The first value to check.
  285. * @param $second
  286. * The second value to check.
  287. * @param $message
  288. * The message to display along with the assertion.
  289. * @param $group
  290. * The type of assertion - examples are "Browser", "PHP".
  291. * @return
  292. * TRUE if the assertion succeeded, FALSE otherwise.
  293. */
  294. protected function assertNotEqual($first, $second, $message = '', $group = 'Other') {
  295. return $this->assert($first != $second, $message ? $message : t('Value @first is not equal to value @second.', array('@first' => var_export($first, TRUE), '@second' => var_export($second, TRUE))), $group);
  296. }
  297. /**
  298. * Check to see if two values are identical.
  299. *
  300. * @param $first
  301. * The first value to check.
  302. * @param $second
  303. * The second value to check.
  304. * @param $message
  305. * The message to display along with the assertion.
  306. * @param $group
  307. * The type of assertion - examples are "Browser", "PHP".
  308. * @return
  309. * TRUE if the assertion succeeded, FALSE otherwise.
  310. */
  311. protected function assertIdentical($first, $second, $message = '', $group = 'Other') {
  312. return $this->assert($first === $second, $message ? $message : t('Value @first is identical to value @second.', array('@first' => var_export($first, TRUE), '@second' => var_export($second, TRUE))), $group);
  313. }
  314. /**
  315. * Check to see if two values are not identical.
  316. *
  317. * @param $first
  318. * The first value to check.
  319. * @param $second
  320. * The second value to check.
  321. * @param $message
  322. * The message to display along with the assertion.
  323. * @param $group
  324. * The type of assertion - examples are "Browser", "PHP".
  325. * @return
  326. * TRUE if the assertion succeeded, FALSE otherwise.
  327. */
  328. protected function assertNotIdentical($first, $second, $message = '', $group = 'Other') {
  329. return $this->assert($first !== $second, $message ? $message : t('Value @first is not identical to value @second.', array('@first' => var_export($first, TRUE), '@second' => var_export($second, TRUE))), $group);
  330. }
  331. /**
  332. * Fire an assertion that is always positive.
  333. *
  334. * @param $message
  335. * The message to display along with the assertion.
  336. * @param $group
  337. * The type of assertion - examples are "Browser", "PHP".
  338. * @return
  339. * TRUE.
  340. */
  341. protected function pass($message = NULL, $group = 'Other') {
  342. return $this->assert(TRUE, $message, $group);
  343. }
  344. /**
  345. * Fire an assertion that is always negative.
  346. *
  347. * @param $message
  348. * The message to display along with the assertion.
  349. * @param $group
  350. * The type of assertion - examples are "Browser", "PHP".
  351. * @return
  352. * FALSE.
  353. */
  354. protected function fail($message = NULL, $group = 'Other') {
  355. return $this->assert(FALSE, $message, $group);
  356. }
  357. /**
  358. * Fire an error assertion.
  359. *
  360. * @param $message
  361. * The message to display along with the assertion.
  362. * @param $group
  363. * The type of assertion - examples are "Browser", "PHP".
  364. * @param $caller
  365. * The caller of the error.
  366. * @return
  367. * FALSE.
  368. */
  369. protected function error($message = '', $group = 'Other', array $caller = NULL) {
  370. if ($group == 'User notice') {
  371. // Since 'User notice' is set by trigger_error() which is used for debug
  372. // set the message to a status of 'debug'.
  373. return $this->assert('debug', $message, 'Debug', $caller);
  374. }
  375. return $this->assert('exception', $message, $group, $caller);
  376. }
  377. /**
  378. * Logs verbose message in a text file.
  379. *
  380. * The a link to the vebose message will be placed in the test results via
  381. * as a passing assertion with the text '[verbose message]'.
  382. *
  383. * @param $message
  384. * The verbose message to be stored.
  385. *
  386. * @see simpletest_verbose()
  387. */
  388. protected function verbose($message) {
  389. if ($id = simpletest_verbose($message)) {
  390. $url = file_create_url($this->originalFileDirectory . '/simpletest/verbose/' . get_class($this) . '-' . $id . '.html');
  391. $this->error(l(t('Verbose message'), $url, array('attributes' => array('target' => '_blank'))), 'User notice');
  392. }
  393. }
  394. /**
  395. * Run all tests in this class.
  396. *
  397. * Regardless of whether $methods are passed or not, only method names
  398. * starting with "test" are executed.
  399. *
  400. * @param $methods
  401. * (optional) A list of method names in the test case class to run; e.g.,
  402. * array('testFoo', 'testBar'). By default, all methods of the class are
  403. * taken into account, but it can be useful to only run a few selected test
  404. * methods during debugging.
  405. */
  406. public function run(array $methods = array()) {
  407. // Initialize verbose debugging.
  408. simpletest_verbose(NULL, variable_get('file_public_path', conf_path() . '/files'), get_class($this));
  409. // HTTP auth settings (<username>:<password>) for the simpletest browser
  410. // when sending requests to the test site.
  411. $this->httpauth_method = variable_get('simpletest_httpauth_method', CURLAUTH_BASIC);
  412. $username = variable_get('simpletest_httpauth_username', NULL);
  413. $password = variable_get('simpletest_httpauth_password', NULL);
  414. if ($username && $password) {
  415. $this->httpauth_credentials = $username . ':' . $password;
  416. }
  417. set_error_handler(array($this, 'errorHandler'));
  418. $class = get_class($this);
  419. // Iterate through all the methods in this class, unless a specific list of
  420. // methods to run was passed.
  421. $class_methods = get_class_methods($class);
  422. if ($methods) {
  423. $class_methods = array_intersect($class_methods, $methods);
  424. }
  425. foreach ($class_methods as $method) {
  426. // If the current method starts with "test", run it - it's a test.
  427. if (strtolower(substr($method, 0, 4)) == 'test') {
  428. // Insert a fail record. This will be deleted on completion to ensure
  429. // that testing completed.
  430. $method_info = new ReflectionMethod($class, $method);
  431. $caller = array(
  432. 'file' => $method_info->getFileName(),
  433. 'line' => $method_info->getStartLine(),
  434. 'function' => $class . '->' . $method . '()',
  435. );
  436. $completion_check_id = DrupalTestCase::insertAssert($this->testId, $class, FALSE, t('The test did not complete due to a fatal error.'), 'Completion check', $caller);
  437. $this->setUp();
  438. try {
  439. $this->$method();
  440. // Finish up.
  441. }
  442. catch (Exception $e) {
  443. $this->exceptionHandler($e);
  444. }
  445. $this->tearDown();
  446. // Remove the completion check record.
  447. DrupalTestCase::deleteAssert($completion_check_id);
  448. }
  449. }
  450. // Clear out the error messages and restore error handler.
  451. drupal_get_messages();
  452. restore_error_handler();
  453. }
  454. /**
  455. * Handle errors during test runs.
  456. *
  457. * Because this is registered in set_error_handler(), it has to be public.
  458. * @see set_error_handler
  459. */
  460. public function errorHandler($severity, $message, $file = NULL, $line = NULL) {
  461. if ($severity & error_reporting()) {
  462. $error_map = array(
  463. E_STRICT => 'Run-time notice',
  464. E_WARNING => 'Warning',
  465. E_NOTICE => 'Notice',
  466. E_CORE_ERROR => 'Core error',
  467. E_CORE_WARNING => 'Core warning',
  468. E_USER_ERROR => 'User error',
  469. E_USER_WARNING => 'User warning',
  470. E_USER_NOTICE => 'User notice',
  471. E_RECOVERABLE_ERROR => 'Recoverable error',
  472. );
  473. $backtrace = debug_backtrace();
  474. $this->error($message, $error_map[$severity], _drupal_get_last_caller($backtrace));
  475. }
  476. return TRUE;
  477. }
  478. /**
  479. * Handle exceptions.
  480. *
  481. * @see set_exception_handler
  482. */
  483. protected function exceptionHandler($exception) {
  484. $backtrace = $exception->getTrace();
  485. // Push on top of the backtrace the call that generated the exception.
  486. array_unshift($backtrace, array(
  487. 'line' => $exception->getLine(),
  488. 'file' => $exception->getFile(),
  489. ));
  490. require_once DRUPAL_ROOT . '/core/includes/errors.inc';
  491. // The exception message is run through check_plain() by _drupal_decode_exception().
  492. $this->error(t('%type: !message in %function (line %line of %file).', _drupal_decode_exception($exception)), 'Uncaught exception', _drupal_get_last_caller($backtrace));
  493. }
  494. /**
  495. * Generates a random string of ASCII characters of codes 32 to 126.
  496. *
  497. * The generated string includes alpha-numeric characters and common misc
  498. * characters. Use this method when testing general input where the content
  499. * is not restricted.
  500. *
  501. * @param $length
  502. * Length of random string to generate.
  503. * @return
  504. * Randomly generated string.
  505. */
  506. public static function randomString($length = 8) {
  507. $str = '';
  508. for ($i = 0; $i < $length; $i++) {
  509. $str .= chr(mt_rand(32, 126));
  510. }
  511. return $str;
  512. }
  513. /**
  514. * Generates a random string containing letters and numbers.
  515. *
  516. * The string will always start with a letter. The letters may be upper or
  517. * lower case. This method is better for restricted inputs that do not
  518. * accept certain characters. For example, when testing input fields that
  519. * require machine readable values (i.e. without spaces and non-standard
  520. * characters) this method is best.
  521. *
  522. * @param $length
  523. * Length of random string to generate.
  524. * @return
  525. * Randomly generated string.
  526. */
  527. public static function randomName($length = 8) {
  528. $values = array_merge(range(65, 90), range(97, 122), range(48, 57));
  529. $max = count($values) - 1;
  530. $str = chr(mt_rand(97, 122));
  531. for ($i = 1; $i < $length; $i++) {
  532. $str .= chr($values[mt_rand(0, $max)]);
  533. }
  534. return $str;
  535. }
  536. /**
  537. * Converts a list of possible parameters into a stack of permutations.
  538. *
  539. * Takes a list of parameters containing possible values, and converts all of
  540. * them into a list of items containing every possible permutation.
  541. *
  542. * Example:
  543. * @code
  544. * $parameters = array(
  545. * 'one' => array(0, 1),
  546. * 'two' => array(2, 3),
  547. * );
  548. * $permutations = $this->permute($parameters);
  549. * // Result:
  550. * $permutations == array(
  551. * array('one' => 0, 'two' => 2),
  552. * array('one' => 1, 'two' => 2),
  553. * array('one' => 0, 'two' => 3),
  554. * array('one' => 1, 'two' => 3),
  555. * )
  556. * @endcode
  557. *
  558. * @param $parameters
  559. * An associative array of parameters, keyed by parameter name, and whose
  560. * values are arrays of parameter values.
  561. *
  562. * @return
  563. * A list of permutations, which is an array of arrays. Each inner array
  564. * contains the full list of parameters that have been passed, but with a
  565. * single value only.
  566. */
  567. public static function generatePermutations($parameters) {
  568. $all_permutations = array(array());
  569. foreach ($parameters as $parameter => $values) {
  570. $new_permutations = array();
  571. // Iterate over all values of the parameter.
  572. foreach ($values as $value) {
  573. // Iterate over all existing permutations.
  574. foreach ($all_permutations as $permutation) {
  575. // Add the new parameter value to existing permutations.
  576. $new_permutations[] = $permutation + array($parameter => $value);
  577. }
  578. }
  579. // Replace the old permutations with the new permutations.
  580. $all_permutations = $new_permutations;
  581. }
  582. return $all_permutations;
  583. }
  584. }
  585. /**
  586. * Test case for Drupal unit tests.
  587. *
  588. * These tests can not access the database nor files. Calling any Drupal
  589. * function that needs the database will throw exceptions. These include
  590. * watchdog(), module_implements(), module_invoke_all() etc.
  591. */
  592. class DrupalUnitTestCase extends DrupalTestCase {
  593. /**
  594. * Constructor for DrupalUnitTestCase.
  595. */
  596. function __construct($test_id = NULL) {
  597. parent::__construct($test_id);
  598. $this->skipClasses[__CLASS__] = TRUE;
  599. }
  600. /**
  601. * Sets up unit test environment.
  602. *
  603. * Unlike DrupalWebTestCase::setUp(), DrupalUnitTestCase::setUp() does not
  604. * install modules because tests are performed without accessing the database.
  605. * Any required files must be explicitly included by the child class setUp()
  606. * method.
  607. */
  608. protected function setUp() {
  609. global $conf;
  610. // Store necessary current values before switching to the test environment.
  611. $this->originalFileDirectory = variable_get('file_public_path', conf_path() . '/files');
  612. // Reset all statics so that test is performed with a clean environment.
  613. drupal_static_reset();
  614. // Generate temporary prefixed database to ensure that tests have a clean starting point.
  615. $this->databasePrefix = Database::getConnection()->prefixTables('{simpletest' . mt_rand(1000, 1000000) . '}');
  616. // Create test directory.
  617. $public_files_directory = $this->originalFileDirectory . '/simpletest/' . substr($this->databasePrefix, 10);
  618. file_prepare_directory($public_files_directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
  619. $conf['file_public_path'] = $public_files_directory;
  620. // Clone the current connection and replace the current prefix.
  621. $connection_info = Database::getConnectionInfo('default');
  622. Database::renameConnection('default', 'simpletest_original_default');
  623. foreach ($connection_info as $target => $value) {
  624. $connection_info[$target]['prefix'] = array(
  625. 'default' => $value['prefix']['default'] . $this->databasePrefix,
  626. );
  627. }
  628. Database::addConnectionInfo('default', 'default', $connection_info['default']);
  629. // Set user agent to be consistent with web test case.
  630. $_SERVER['HTTP_USER_AGENT'] = $this->databasePrefix;
  631. // If locale is enabled then t() will try to access the database and
  632. // subsequently will fail as the database is not accessible.
  633. $module_list = module_list();
  634. if (isset($module_list['locale'])) {
  635. $this->originalModuleList = $module_list;
  636. unset($module_list['locale']);
  637. module_list(TRUE, FALSE, FALSE, $module_list);
  638. }
  639. }
  640. protected function tearDown() {
  641. global $conf;
  642. // Get back to the original connection.
  643. Database::removeConnection('default');
  644. Database::renameConnection('simpletest_original_default', 'default');
  645. $conf['file_public_path'] = $this->originalFileDirectory;
  646. // Restore modules if necessary.
  647. if (isset($this->originalModuleList)) {
  648. module_list(TRUE, FALSE, FALSE, $this->originalModuleList);
  649. }
  650. }
  651. }
  652. /**
  653. * Test case for typical Drupal tests.
  654. */
  655. class DrupalWebTestCase extends DrupalTestCase {
  656. /**
  657. * The profile to install as a basis for testing.
  658. *
  659. * @var string
  660. */
  661. protected $profile = 'standard';
  662. /**
  663. * The URL currently loaded in the internal browser.
  664. *
  665. * @var string
  666. */
  667. protected $url;
  668. /**
  669. * The handle of the current cURL connection.
  670. *
  671. * @var resource
  672. */
  673. protected $curlHandle;
  674. /**
  675. * The headers of the page currently loaded in the internal browser.
  676. *
  677. * @var Array
  678. */
  679. protected $headers;
  680. /**
  681. * The content of the page currently loaded in the internal browser.
  682. *
  683. * @var string
  684. */
  685. protected $content;
  686. /**
  687. * The content of the page currently loaded in the internal browser (plain text version).
  688. *
  689. * @var string
  690. */
  691. protected $plainTextContent;
  692. /**
  693. * The value of the Drupal.settings JavaScript variable for the page currently loaded in the internal browser.
  694. *
  695. * @var Array
  696. */
  697. protected $drupalSettings;
  698. /**
  699. * The parsed version of the page.
  700. *
  701. * @var SimpleXMLElement
  702. */
  703. protected $elements = NULL;
  704. /**
  705. * The current user logged in using the internal browser.
  706. *
  707. * @var bool
  708. */
  709. protected $loggedInUser = FALSE;
  710. /**
  711. * The current cookie file used by cURL.
  712. *
  713. * We do not reuse the cookies in further runs, so we do not need a file
  714. * but we still need cookie handling, so we set the jar to NULL.
  715. */
  716. protected $cookieFile = NULL;
  717. /**
  718. * Additional cURL options.
  719. *
  720. * DrupalWebTestCase itself never sets this but always obeys what is set.
  721. */
  722. protected $additionalCurlOptions = array();
  723. /**
  724. * The original user, before it was changed to a clean uid = 1 for testing purposes.
  725. *
  726. * @var object
  727. */
  728. protected $originalUser = NULL;
  729. /**
  730. * The original shutdown handlers array, before it was cleaned for testing purposes.
  731. *
  732. * @var array
  733. */
  734. protected $originalShutdownCallbacks = array();
  735. /**
  736. * HTTP authentication method
  737. */
  738. protected $httpauth_method = CURLAUTH_BASIC;
  739. /**
  740. * HTTP authentication credentials (<username>:<password>).
  741. */
  742. protected $httpauth_credentials = NULL;
  743. /**
  744. * The current session name, if available.
  745. */
  746. protected $session_name = NULL;
  747. /**
  748. * The current session ID, if available.
  749. */
  750. protected $session_id = NULL;
  751. /**
  752. * Whether the files were copied to the test files directory.
  753. */
  754. protected $generatedTestFiles = FALSE;
  755. /**
  756. * The number of redirects followed during the handling of a request.
  757. */
  758. protected $redirect_count;
  759. /**
  760. * Constructor for DrupalWebTestCase.
  761. */
  762. function __construct($test_id = NULL) {
  763. parent::__construct($test_id);
  764. $this->skipClasses[__CLASS__] = TRUE;
  765. }
  766. /**
  767. * Get a node from the database based on its title.
  768. *
  769. * @param $title
  770. * A node title, usually generated by $this->randomName().
  771. * @param $reset
  772. * (optional) Whether to reset the internal node_load() cache.
  773. *
  774. * @return
  775. * A node object matching $title.
  776. */
  777. function drupalGetNodeByTitle($title, $reset = FALSE) {
  778. $nodes = node_load_multiple(array(), array('title' => $title), $reset);
  779. // Load the first node returned from the database.
  780. $returned_node = reset($nodes);
  781. return $returned_node;
  782. }
  783. /**
  784. * Creates a node based on default settings.
  785. *
  786. * @param $settings
  787. * An associative array of settings to change from the defaults, keys are
  788. * node properties, for example 'title' => 'Hello, world!'.
  789. * @return
  790. * Created node object.
  791. */
  792. protected function drupalCreateNode($settings = array()) {
  793. // Populate defaults array.
  794. $settings += array(
  795. 'body' => array(LANGUAGE_NONE => array(array())),
  796. 'title' => $this->randomName(8),
  797. 'comment' => 2,
  798. 'changed' => REQUEST_TIME,
  799. 'moderate' => 0,
  800. 'promote' => 0,
  801. 'revision' => 1,
  802. 'log' => '',
  803. 'status' => 1,
  804. 'sticky' => 0,
  805. 'type' => 'page',
  806. 'revisions' => NULL,
  807. 'language' => LANGUAGE_NONE,
  808. );
  809. // Use the original node's created time for existing nodes.
  810. if (isset($settings['created']) && !isset($settings['date'])) {
  811. $settings['date'] = format_date($settings['created'], 'custom', 'Y-m-d H:i:s O');
  812. }
  813. // If the node's user uid is not specified manually, use the currently
  814. // logged in user if available, or else the user running the test.
  815. if (!isset($settings['uid'])) {
  816. if ($this->loggedInUser) {
  817. $settings['uid'] = $this->loggedInUser->uid;
  818. }
  819. else {
  820. global $user;
  821. $settings['uid'] = $user->uid;
  822. }
  823. }
  824. // Merge body field value and format separately.
  825. $body = array(
  826. 'value' => $this->randomName(32),
  827. 'format' => filter_default_format(),
  828. );
  829. $settings['body'][$settings['language']][0] += $body;
  830. $node = (object) $settings;
  831. node_save($node);
  832. // Small hack to link revisions to our test user.
  833. db_update('node_revision')
  834. ->fields(array('uid' => $node->uid))
  835. ->condition('vid', $node->vid)
  836. ->execute();
  837. return $node;
  838. }
  839. /**
  840. * Creates a custom content type based on default settings.
  841. *
  842. * @param $settings
  843. * An array of settings to change from the defaults.
  844. * Example: 'type' => 'foo'.
  845. * @return
  846. * Created content type.
  847. */
  848. protected function drupalCreateContentType($settings = array()) {
  849. // Find a non-existent random type name.
  850. do {
  851. $name = strtolower($this->randomName(8));
  852. } while (node_type_get_type($name));
  853. // Populate defaults array.
  854. $defaults = array(
  855. 'type' => $name,
  856. 'name' => $name,
  857. 'base' => 'node_content',
  858. 'description' => '',
  859. 'help' => '',
  860. 'title_label' => 'Title',
  861. 'body_label' => 'Body',
  862. 'has_title' => 1,
  863. 'has_body' => 1,
  864. );
  865. // Imposed values for a custom type.
  866. $forced = array(
  867. 'orig_type' => '',
  868. 'old_type' => '',
  869. 'module' => 'node',
  870. 'custom' => 1,
  871. 'modified' => 1,
  872. 'locked' => 0,
  873. );
  874. $type = $forced + $settings + $defaults;
  875. $type = (object) $type;
  876. $saved_type = node_type_save($type);
  877. node_types_rebuild();
  878. menu_rebuild();
  879. node_add_body_field($type);
  880. $this->assertEqual($saved_type, SAVED_NEW, t('Created content type %type.', array('%type' => $type->type)));
  881. // Reset permissions so that permissions for this content type are available.
  882. $this->checkPermissions(array(), TRUE);
  883. return $type;
  884. }
  885. /**
  886. * Get a list files that can be used in tests.
  887. *
  888. * @param $type
  889. * File type, possible values: 'binary', 'html', 'image', 'javascript', 'php', 'sql', 'text'.
  890. * @param $size
  891. * File size in bytes to match. Please check the tests/files folder.
  892. * @return
  893. * List of files that match filter.
  894. */
  895. protected function drupalGetTestFiles($type, $size = NULL) {
  896. if (empty($this->generatedTestFiles)) {
  897. // Generate binary test files.
  898. $lines = array(64, 1024);
  899. $count = 0;
  900. foreach ($lines as $line) {
  901. simpletest_generate_file('binary-' . $count++, 64, $line, 'binary');
  902. }
  903. // Generate text test files.
  904. $lines = array(16, 256, 1024, 2048, 20480);
  905. $count = 0;
  906. foreach ($lines as $line) {
  907. simpletest_generate_file('text-' . $count++, 64, $line);
  908. }
  909. // Copy other test files from simpletest.
  910. $original = drupal_get_path('module', 'simpletest') . '/files';
  911. $files = file_scan_directory($original, '/(html|image|javascript|php|sql)-.*/');
  912. foreach ($files as $file) {
  913. file_unmanaged_copy($file->uri, variable_get('file_public_path', conf_path() . '/files'));
  914. }
  915. $this->generatedTestFiles = TRUE;
  916. }
  917. $files = array();
  918. // Make sure type is valid.
  919. if (in_array($type, array('binary', 'html', 'image', 'javascript', 'php', 'sql', 'text'))) {
  920. $files = file_scan_directory('public://', '/' . $type . '\-.*/');
  921. // If size is set then remove any files that are not of that size.
  922. if ($size !== NULL) {
  923. foreach ($files as $file) {
  924. $stats = stat($file->uri);
  925. if ($stats['size'] != $size) {
  926. unset($files[$file->uri]);
  927. }
  928. }
  929. }
  930. }
  931. usort($files, array($this, 'drupalCompareFiles'));
  932. return $files;
  933. }
  934. /**
  935. * Compare two files based on size and file name.
  936. */
  937. protected function drupalCompareFiles($file1, $file2) {
  938. $compare_size = filesize($file1->uri) - filesize($file2->uri);
  939. if ($compare_size) {
  940. // Sort by file size.
  941. return $compare_size;
  942. }
  943. else {
  944. // The files were the same size, so sort alphabetically.
  945. return strnatcmp($file1->name, $file2->name);
  946. }
  947. }
  948. /**
  949. * Create a user with a given set of permissions. The permissions correspond to the
  950. * names given on the privileges page.
  951. *
  952. * @param $permissions
  953. * Array of permission names to assign to user.
  954. * @return
  955. * A fully loaded user object with pass_raw property, or FALSE if account
  956. * creation fails.
  957. */
  958. protected function drupalCreateUser($permissions = array('access comments', 'access content', 'post comments', 'skip comment approval')) {
  959. // Create a role with the given permission set.
  960. if (!($rid = $this->drupalCreateRole($permissions))) {
  961. return FALSE;
  962. }
  963. // Create a user assigned to that role.
  964. $edit = array();
  965. $edit['name'] = $this->randomName();
  966. $edit['mail'] = $edit['name'] . '@example.com';
  967. $edit['roles'] = array($rid => $rid);
  968. $edit['pass'] = user_password();
  969. $edit['status'] = 1;
  970. $account = user_save(drupal_anonymous_user(), $edit);
  971. $this->assertTrue(!empty($account->uid), t('User created with name %name and pass %pass', array('%name' => $edit['name'], '%pass' => $edit['pass'])), t('User login'));
  972. if (empty($account->uid)) {
  973. return FALSE;
  974. }
  975. // Add the raw password so that we can log in as this user.
  976. $account->pass_raw = $edit['pass'];
  977. return $account;
  978. }
  979. /**
  980. * Internal helper function; Create a role with specified permissions.
  981. *
  982. * @param $permissions
  983. * Array of permission names to assign to role.
  984. * @param $name
  985. * (optional) String for the name of the role. Defaults to a random string.
  986. * @return
  987. * Role ID of newly created role, or FALSE if role creation failed.
  988. */
  989. protected function drupalCreateRole(array $permissions, $name = NULL) {
  990. // Generate random name if it was not passed.
  991. if (!$name) {
  992. $name = $this->randomName();
  993. }
  994. // Check the all the permissions strings are valid.
  995. if (!$this->checkPermissions($permissions)) {
  996. return FALSE;
  997. }
  998. // Create new role.
  999. $role = new stdClass();
  1000. $role->name = $name;
  1001. user_role_save($role);
  1002. user_role_grant_permissions($role->rid, $permissions);
  1003. $this->assertTrue(isset($role->rid), t('Created role of name: @name, id: @rid', array('@name' => $name, '@rid' => (isset($role->rid) ? $role->rid : t('-n/a-')))), t('Role'));
  1004. if ($role && !empty($role->rid)) {
  1005. $count = db_query('SELECT COUNT(*) FROM {role_permission} WHERE rid = :rid', array(':rid' => $role->rid))->fetchField();
  1006. $this->assertTrue($count == count($permissions), t('Created permissions: @perms', array('@perms' => implode(', ', $permissions))), t('Role'));
  1007. return $role->rid;
  1008. }
  1009. else {
  1010. return FALSE;
  1011. }
  1012. }
  1013. /**
  1014. * Check to make sure that the array of permissions are valid.
  1015. *
  1016. * @param $permissions
  1017. * Permissions to check.
  1018. * @param $reset
  1019. * Reset cached available permissions.
  1020. * @return
  1021. * TRUE or FALSE depending on whether the permissions are valid.
  1022. */
  1023. protected function checkPermissions(array $permissions, $reset = FALSE) {
  1024. $available = &drupal_static(__FUNCTION__);
  1025. if (!isset($available) || $reset) {
  1026. $available = array_keys(module_invoke_all('permission'));
  1027. }
  1028. $valid = TRUE;
  1029. foreach ($permissions as $permission) {
  1030. if (!in_array($permission, $available)) {
  1031. $this->fail(t('Invalid permission %permission.', array('%permission' => $permission)), t('Role'));
  1032. $valid = FALSE;
  1033. }
  1034. }
  1035. return $valid;
  1036. }
  1037. /**
  1038. * Log in a user with the internal browser.
  1039. *
  1040. * If a user is already logged in, then the current user is logged out before
  1041. * logging in the specified user.
  1042. *
  1043. * Please note that neither the global $user nor the passed-in user object is
  1044. * populated with data of the logged in user. If you need full access to the
  1045. * user object after logging in, it must be updated manually. If you also need
  1046. * access to the plain-text password of the user (set by drupalCreateUser()),
  1047. * e.g. to log in the same user again, then it must be re-assigned manually.
  1048. * For example:
  1049. * @code
  1050. * // Create a user.
  1051. * $account = $this->drupalCreateUser(array());
  1052. * $this->drupalLogin($account);
  1053. * // Load real user object.
  1054. * $pass_raw = $account->pass_raw;
  1055. * $account = user_load($account->uid);
  1056. * $account->pass_raw = $pass_raw;
  1057. * @endcode
  1058. *
  1059. * @param $user
  1060. * User object representing the user to log in.
  1061. *
  1062. * @see drupalCreateUser()
  1063. */
  1064. protected function drupalLogin(stdClass $user) {
  1065. if ($this->loggedInUser) {
  1066. $this->drupalLogout();
  1067. }
  1068. $edit = array(
  1069. 'name' => $user->name,
  1070. 'pass' => $user->pass_raw
  1071. );
  1072. $this->drupalPost('user', $edit, t('Log in'));
  1073. // If a "log out" link appears on the page, it is almost certainly because
  1074. // the login was successful.
  1075. $pass = $this->assertLink(t('Log out'), 0, t('User %name successfully logged in.', array('%name' => $user->name)), t('User login'));
  1076. if ($pass) {
  1077. $this->loggedInUser = $user;
  1078. }
  1079. }
  1080. /**
  1081. * Generate a token for the currently logged in user.
  1082. */
  1083. protected function drupalGetToken($value = '') {
  1084. $private_key = drupal_get_private_key();
  1085. return drupal_hmac_base64($value, $this->session_id . $private_key);
  1086. }
  1087. /*
  1088. * Logs a user out of the internal browser, then check the login page to confirm logout.
  1089. */
  1090. protected function drupalLogout() {
  1091. // Make a request to the logout page, and redirect to the user page, the
  1092. // idea being if you were properly logged out you should be seeing a login
  1093. // screen.
  1094. $this->drupalGet('user/logout');
  1095. $this->drupalGet('user');
  1096. $pass = $this->assertField('name', t('Username field found.'), t('Logout'));
  1097. $pass = $pass && $this->assertField('pass', t('Password field found.'), t('Logout'));
  1098. if ($pass) {
  1099. $this->loggedInUser = FALSE;
  1100. }
  1101. }
  1102. /**
  1103. * Generates a random database prefix, runs the install scripts on the
  1104. * prefixed database and enable the specified modules. After installation
  1105. * many caches are flushed and the internal browser is setup so that the
  1106. * page requests will run on the new prefix. A temporary files directory
  1107. * is created with the same name as the database prefix.
  1108. *
  1109. * @param ...
  1110. * List of modules to enable for the duration of the test. This can be
  1111. * either a single array or a variable number of string arguments.
  1112. */
  1113. protected function setUp() {
  1114. global $user, $language, $conf;
  1115. // Generate a temporary prefixed database to ensure that tests have a clean starting point.
  1116. $this->databasePrefix = 'simpletest' . mt_rand(1000, 1000000);
  1117. db_update('simpletest_test_id')
  1118. ->fields(array('last_prefix' => $this->databasePrefix))
  1119. ->condition('test_id', $this->testId)
  1120. ->execute();
  1121. // Reset all statics and variables to perform tests in a clean environment.
  1122. $conf = array();
  1123. drupal_static_reset();
  1124. // Clone the current connection and replace the current prefix.
  1125. $connection_info = Database::getConnectionInfo('default');
  1126. Database::renameConnection('default', 'simpletest_original_default');
  1127. foreach ($connection_info as $target => $value) {
  1128. $connection_info[$target]['prefix'] = array(
  1129. 'default' => $value['prefix']['default'] . $this->databasePrefix,
  1130. );
  1131. }
  1132. Database::addConnectionInfo('default', 'default', $connection_info['default']);
  1133. // Store necessary current values before switching to prefixed database.
  1134. $this->originalLanguage = $language;
  1135. $this->originalLanguageDefault = variable_get('language_default');
  1136. $this->originalFileDirectory = variable_get('file_public_path', conf_path() . '/files');
  1137. $this->originalProfile = drupal_get_profile();
  1138. $clean_url_original = variable_get('clean_url', 0);
  1139. // Set to English to prevent exceptions from utf8_truncate() from t()
  1140. // during install if the current language is not 'en'.
  1141. // The following array/object conversion is copied from language_default().
  1142. $language = (object) array('language' => 'en', 'name' => 'English', 'native' => 'English', 'direction' => 0, 'enabled' => 1, 'plurals' => 0, 'formula' => '', 'domain' => '', 'prefix' => '', 'weight' => 0, 'javascript' => '');
  1143. // Save and clean shutdown callbacks array because it static cached and
  1144. // will be changed by the test run. If we don't, then it will contain
  1145. // callbacks from both environments. So testing environment will try
  1146. // to call handlers from original environment.
  1147. $callbacks = &drupal_register_shutdown_function();
  1148. $this->originalShutdownCallbacks = $callbacks;
  1149. $callbacks = array();
  1150. // Create test directory ahead of installation so fatal errors and debug
  1151. // information can be logged during installation process.
  1152. // Use temporary files directory with the same prefix as the database.
  1153. $public_files_directory = $this->originalFileDirectory . '/simpletest/' . substr($this->databasePrefix, 10);
  1154. $private_files_directory = $public_files_directory . '/private';
  1155. $temp_files_directory = $private_files_directory . '/temp';
  1156. // Create the directories
  1157. file_prepare_directory($public_files_directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
  1158. file_prepare_directory($private_files_directory, FILE_CREATE_DIRECTORY);
  1159. file_prepare_directory($temp_files_directory, FILE_CREATE_DIRECTORY);
  1160. $this->generatedTestFiles = FALSE;
  1161. // Log fatal errors.
  1162. ini_set('log_errors', 1);
  1163. ini_set('error_log', $public_files_directory . '/error.log');
  1164. // Set the test information for use in other parts of Drupal.
  1165. $test_info = &$GLOBALS['drupal_test_info'];
  1166. $test_info['test_run_id'] = $this->databasePrefix;
  1167. $test_info['in_child_site'] = FALSE;
  1168. include_once DRUPAL_ROOT . '/core/includes/install.inc';
  1169. drupal_install_system();
  1170. $this->preloadRegistry();
  1171. // Set path variables.
  1172. variable_set('file_public_path', $public_files_directory);
  1173. variable_set('file_private_path', $private_files_directory);
  1174. variable_set('file_temporary_path', $temp_files_directory);
  1175. // Include the testing profile.
  1176. variable_set('install_profile', $this->profile);
  1177. $profile_details = install_profile_info($this->profile, 'en');
  1178. // Install the modules specified by the testing profile.
  1179. module_enable($profile_details['dependencies'], FALSE);
  1180. // Install modules needed for this test. This could have been passed in as
  1181. // either a single array argument or a variable number of string arguments.
  1182. // @todo Remove this compatibility layer in Drupal 8, and only accept
  1183. // $modules as a single array argument.
  1184. $modules = func_get_args();
  1185. if (isset($modules[0]) && is_array($modules[0])) {
  1186. $modules = $modules[0];
  1187. }
  1188. if ($modules) {
  1189. $success = module_enable($modules, TRUE);
  1190. $this->assertTrue($success, t('Enabled modules: %modules', array('%modules' => implode(', ', $modules))));
  1191. }
  1192. // Run the profile tasks.
  1193. $install_profile_module_exists = db_query("SELECT 1 FROM {system} WHERE type = 'module' AND name = :name", array(
  1194. ':name' => $this->profile,
  1195. ))->fetchField();
  1196. if ($install_profile_module_exists) {
  1197. module_enable(array($this->profile), FALSE);
  1198. }
  1199. // Reset/rebuild all data structures after enabling the modules.
  1200. $this->resetAll();
  1201. // Run cron once in that environment, as install.php does at the end of
  1202. // the installation process.
  1203. drupal_cron_run();
  1204. // Log in with a clean $user.
  1205. $this->originalUser = $user;
  1206. drupal_save_session(FALSE);
  1207. $user = user_load(1);
  1208. // Restore necessary variables.
  1209. variable_set('install_task', 'done');
  1210. variable_set('clean_url', $clean_url_original);
  1211. variable_set('site_mail', 'simpletest@example.com');
  1212. variable_set('date_default_timezone', date_default_timezone_get());
  1213. // Set up English language.
  1214. unset($GLOBALS['conf']['language_default']);
  1215. $language = language_default();
  1216. // Use the test mail class instead of the default mail handler class.
  1217. variable_set('mail_system', array('default-system' => 'TestingMailSystem'));
  1218. drupal_set_time_limit($this->timeLimit);
  1219. }
  1220. /**
  1221. * Preload the registry from the testing site.
  1222. *
  1223. * This method is called by DrupalWebTestCase::setUp(), and preloads the
  1224. * registry from the testing site to cut down on the time it takes to
  1225. * set up a clean environment for the current test run.
  1226. */
  1227. protected function preloadRegistry() {
  1228. // Use two separate queries, each with their own connections: copy the
  1229. // {registry} and {registry_file} tables over from the parent installation
  1230. // to the child installation.
  1231. $original_connection = Database::getConnection('default', 'simpletest_original_default');
  1232. $test_connection = Database::getConnection();
  1233. foreach (array('registry', 'registry_file') as $table) {
  1234. // Find the records from the parent database.
  1235. $source_query = $original_connection
  1236. ->select($table, array(), array('fetch' => PDO::FETCH_ASSOC))
  1237. ->fields($table);
  1238. $dest_query = $test_connection->insert($table);
  1239. $first = TRUE;
  1240. foreach ($source_query->execute() as $row) {
  1241. if ($first) {
  1242. $dest_query->fields(array_keys($row));
  1243. $first = FALSE;
  1244. }
  1245. // Insert the records into the child database.
  1246. $dest_query->values($row);
  1247. }
  1248. $dest_query->execute();
  1249. }
  1250. }
  1251. /**
  1252. * Reset all data structures after having enabled new modules.
  1253. *
  1254. * This method is called by DrupalWebTestCase::setUp() after enabling
  1255. * the requested modules. It must be called again when additional modules
  1256. * are enabled later.
  1257. */
  1258. protected function resetAll() {
  1259. // Reset all static variables.
  1260. drupal_static_reset();
  1261. // Reset the list of enabled modules.
  1262. module_list(TRUE);
  1263. // Reset cached schema for new database prefix. This must be done before
  1264. // drupal_flush_all_caches() so rebuilds can make use of the schema of
  1265. // modules enabled on the cURL side.
  1266. drupal_get_schema(NULL, TRUE);
  1267. // Perform rebuilds and flush remaining caches.
  1268. drupal_flush_all_caches();
  1269. // Reload global $conf array and permissions.
  1270. $this->refreshVariables();
  1271. $this->checkPermissions(array(), TRUE);
  1272. }
  1273. /**
  1274. * Refresh the in-memory set of variables. Useful after a page request is made
  1275. * that changes a variable in a different thread.
  1276. *
  1277. * In other words calling a settings page with $this->drupalPost() with a changed
  1278. * value would update a variable to reflect that change, but in the thread that
  1279. * made the call (thread running the test) the changed variable would not be
  1280. * picked up.
  1281. *
  1282. * This method clears the variables cache and loads a fresh copy from the database
  1283. * to ensure that the most up-to-date set of variables is loaded.
  1284. */
  1285. protected function refreshVariables() {
  1286. global $conf;
  1287. cache('bootstrap')->delete('variables');
  1288. $conf = variable_initialize();
  1289. }
  1290. /**
  1291. * Delete created files and temporary files directory, delete the tables created by setUp(),
  1292. * and reset the database prefix.
  1293. */
  1294. protected function tearDown() {
  1295. global $user, $language;
  1296. // In case a fatal error occurred that was not in the test process read the
  1297. // log to pick up any fatal errors.
  1298. simpletest_log_read($this->testId, $this->databasePrefix, get_class($this), TRUE);
  1299. $emailCount = count(variable_get('drupal_test_email_collector', array()));
  1300. if ($emailCount) {
  1301. $message = format_plural($emailCount, '1 e-mail was sent during this test.', '@count e-mails were sent during this test.');
  1302. $this->pass($message, t('E-mail'));
  1303. }
  1304. // Delete temporary files directory.
  1305. file_unmanaged_delete_recursive($this->originalFileDirectory . '/simpletest/' . substr($this->databasePrefix, 10));
  1306. // Remove all prefixed tables (all the tables in the schema).
  1307. $schema = drupal_get_schema(NULL, TRUE);
  1308. foreach ($schema as $name => $table) {
  1309. db_drop_table($name);
  1310. }
  1311. // Get back to the original connection.
  1312. Database::removeConnection('default');
  1313. Database::renameConnection('simpletest_original_default', 'default');
  1314. // Restore original shutdown callbacks array to prevent original
  1315. // environment of calling handlers from test run.
  1316. $callbacks = &drupal_register_shutdown_function();
  1317. $callbacks = $this->originalShutdownCallbacks;
  1318. // Return the user to the original one.
  1319. $user = $this->originalUser;
  1320. drupal_save_session(TRUE);
  1321. // Ensure that internal logged in variable and cURL options are reset.
  1322. $this->loggedInUser = FALSE;
  1323. $this->additionalCurlOptions = array();
  1324. // Reload module list and implementations to ensure that test module hooks
  1325. // aren't called after tests.
  1326. module_list(TRUE);
  1327. module_implements_reset();
  1328. // Reset the Field API.
  1329. field_cache_clear();
  1330. // Rebuild caches.
  1331. $this->refreshVariables();
  1332. // Reset language.
  1333. $language = $this->originalLanguage;
  1334. if ($this->originalLanguageDefault) {
  1335. $GLOBALS['conf']['language_default'] = $this->originalLanguageDefault;
  1336. }
  1337. // Close the CURL handler.
  1338. $this->curlClose();
  1339. }
  1340. /**
  1341. * Initializes the cURL connection.
  1342. *
  1343. * If the simpletest_httpa…

Large files files are truncated, but you can click here to view the full file