PageRenderTime 54ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/drupal-7.14/modules/simpletest/drupal_web_test_case.php

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

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