PageRenderTime 63ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

/modules/simpletest/drupal_web_test_case.php

https://bitbucket.org/micahw156/sites_chacadwa
PHP | 4027 lines | 1765 code | 325 blank | 1937 comment | 273 complexity | 8fa058be46264e4d470c66d2e6fa1f71 MD5 | raw file
Possible License(s): MIT, JSON, GPL-2.0, LGPL-2.1

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

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