PageRenderTime 64ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 1ms

/modules/simpletest/drupal_web_test_case.php

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

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