simpletest.module 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871
  1. <?php
  2. /**
  3. * @file
  4. * Provides testing functionality.
  5. */
  6. use Drupal\Core\Asset\AttachedAssetsInterface;
  7. use Drupal\Core\Database\Database;
  8. use Drupal\Core\Render\Element;
  9. use Drupal\Core\Routing\RouteMatchInterface;
  10. use Drupal\simpletest\TestBase;
  11. use Drupal\Core\Test\TestDatabase;
  12. use Drupal\simpletest\TestDiscovery;
  13. use Drupal\Tests\Listeners\SimpletestUiPrinter;
  14. use PHPUnit\Framework\TestCase;
  15. use Symfony\Component\Process\PhpExecutableFinder;
  16. use Drupal\Core\Test\TestStatus;
  17. /**
  18. * Implements hook_help().
  19. */
  20. function simpletest_help($route_name, RouteMatchInterface $route_match) {
  21. switch ($route_name) {
  22. case 'help.page.simpletest':
  23. $output = '';
  24. $output .= '<h3>' . t('About') . '</h3>';
  25. $output .= '<p>' . t('The Testing module provides a framework for running automated tests. It can be used to verify a working state of Drupal before and after any code changes, or as a means for developers to write and execute tests for their modules. For more information, see the <a href=":simpletest">online documentation for the Testing module</a>.', [':simpletest' => 'https://www.drupal.org/documentation/modules/simpletest']) . '</p>';
  26. $output .= '<h3>' . t('Uses') . '</h3>';
  27. $output .= '<dl>';
  28. $output .= '<dt>' . t('Running tests') . '</dt>';
  29. $output .= '<dd><p>' . t('Visit the <a href=":admin-simpletest">Testing page</a> to display a list of available tests. For comprehensive testing, select <em>all</em> tests, or individually select tests for more targeted testing. Note that it might take several minutes for all tests to complete.', [':admin-simpletest' => \Drupal::url('simpletest.test_form')]) . '</p>';
  30. $output .= '<p>' . t('After the tests run, a message will be displayed next to each test group indicating whether tests within it passed, failed, or had exceptions. A pass means that the test returned the expected results, while fail means that it did not. An exception normally indicates an error outside of the test, such as a PHP warning or notice. If there were failures or exceptions, the results will be expanded to show details, and the tests that had failures or exceptions will be indicated in red or pink rows. You can then use these results to refine your code and tests, until all tests pass.') . '</p></dd>';
  31. $output .= '</dl>';
  32. return $output;
  33. case 'simpletest.test_form':
  34. $output = t('Select the test(s) or test group(s) you would like to run, and click <em>Run tests</em>.');
  35. return $output;
  36. }
  37. }
  38. /**
  39. * Implements hook_theme().
  40. */
  41. function simpletest_theme() {
  42. return [
  43. 'simpletest_result_summary' => [
  44. 'variables' => ['label' => NULL, 'items' => [], 'pass' => 0, 'fail' => 0, 'exception' => 0, 'debug' => 0],
  45. ],
  46. ];
  47. }
  48. /**
  49. * Implements hook_js_alter().
  50. */
  51. function simpletest_js_alter(&$javascript, AttachedAssetsInterface $assets) {
  52. // Since SimpleTest is a special use case for the table select, stick the
  53. // SimpleTest JavaScript above the table select.
  54. $simpletest = drupal_get_path('module', 'simpletest') . '/simpletest.js';
  55. if (array_key_exists($simpletest, $javascript) && array_key_exists('core/misc/tableselect.js', $javascript)) {
  56. $javascript[$simpletest]['weight'] = $javascript['core/misc/tableselect.js']['weight'] - 1;
  57. }
  58. }
  59. /**
  60. * Prepares variables for simpletest result summary templates.
  61. *
  62. * Default template: simpletest-result-summary.html.twig.
  63. *
  64. * @param array $variables
  65. * An associative array containing:
  66. * - label: An optional label to be rendered before the results.
  67. * - ok: The overall group result pass or fail.
  68. * - pass: The number of passes.
  69. * - fail: The number of fails.
  70. * - exception: The number of exceptions.
  71. * - debug: The number of debug messages.
  72. */
  73. function template_preprocess_simpletest_result_summary(&$variables) {
  74. $variables['items'] = _simpletest_build_summary_line($variables);
  75. }
  76. /**
  77. * Formats each test result type pluralized summary.
  78. *
  79. * @param array $summary
  80. * A summary of the test results.
  81. *
  82. * @return array
  83. * The pluralized test summary items.
  84. */
  85. function _simpletest_build_summary_line($summary) {
  86. $translation = \Drupal::translation();
  87. $items['pass'] = $translation->formatPlural($summary['pass'], '1 pass', '@count passes');
  88. $items['fail'] = $translation->formatPlural($summary['fail'], '1 fail', '@count fails');
  89. $items['exception'] = $translation->formatPlural($summary['exception'], '1 exception', '@count exceptions');
  90. if ($summary['debug']) {
  91. $items['debug'] = $translation->formatPlural($summary['debug'], '1 debug message', '@count debug messages');
  92. }
  93. return $items;
  94. }
  95. /**
  96. * Formats test result summaries into a comma separated string for run-tests.sh.
  97. *
  98. * @param array $summary
  99. * A summary of the test results.
  100. *
  101. * @return string
  102. * A concatenated string of the formatted test results.
  103. */
  104. function _simpletest_format_summary_line($summary) {
  105. $parts = _simpletest_build_summary_line($summary);
  106. return implode(', ', $parts);
  107. }
  108. /**
  109. * Runs tests.
  110. *
  111. * @param $test_list
  112. * List of tests to run.
  113. *
  114. * @return string
  115. * The test ID.
  116. */
  117. function simpletest_run_tests($test_list) {
  118. // We used to separate PHPUnit and Simpletest tests for a performance
  119. // optimization. In order to support backwards compatibility check if these
  120. // keys are set and create a single test list.
  121. // @todo https://www.drupal.org/node/2748967 Remove BC support in Drupal 9.
  122. if (isset($test_list['simpletest'])) {
  123. $test_list = array_merge($test_list, $test_list['simpletest']);
  124. unset($test_list['simpletest']);
  125. }
  126. if (isset($test_list['phpunit'])) {
  127. $test_list = array_merge($test_list, $test_list['phpunit']);
  128. unset($test_list['phpunit']);
  129. }
  130. $test_id = db_insert('simpletest_test_id')
  131. ->useDefaults(['test_id'])
  132. ->execute();
  133. // Clear out the previous verbose files.
  134. file_unmanaged_delete_recursive('public://simpletest/verbose');
  135. // Get the info for the first test being run.
  136. $first_test = reset($test_list);
  137. $info = TestDiscovery::getTestInfo($first_test);
  138. $batch = [
  139. 'title' => t('Running tests'),
  140. 'operations' => [
  141. ['_simpletest_batch_operation', [$test_list, $test_id]],
  142. ],
  143. 'finished' => '_simpletest_batch_finished',
  144. 'progress_message' => '',
  145. 'library' => ['simpletest/drupal.simpletest'],
  146. 'init_message' => t('Processing test @num of @max - %test.', ['%test' => $info['name'], '@num' => '1', '@max' => count($test_list)]),
  147. ];
  148. batch_set($batch);
  149. \Drupal::moduleHandler()->invokeAll('test_group_started');
  150. return $test_id;
  151. }
  152. /**
  153. * Executes PHPUnit tests and returns the results of the run.
  154. *
  155. * @param $test_id
  156. * The current test ID.
  157. * @param $unescaped_test_classnames
  158. * An array of test class names, including full namespaces, to be passed as
  159. * a regular expression to PHPUnit's --filter option.
  160. * @param int $status
  161. * (optional) The exit status code of the PHPUnit process will be assigned to
  162. * this variable.
  163. *
  164. * @return array
  165. * The parsed results of PHPUnit's JUnit XML output, in the format of
  166. * {simpletest}'s schema.
  167. */
  168. function simpletest_run_phpunit_tests($test_id, array $unescaped_test_classnames, &$status = NULL) {
  169. $phpunit_file = simpletest_phpunit_xml_filepath($test_id);
  170. simpletest_phpunit_run_command($unescaped_test_classnames, $phpunit_file, $status, $output);
  171. $rows = [];
  172. if ($status == TestStatus::PASS) {
  173. $rows = simpletest_phpunit_xml_to_rows($test_id, $phpunit_file);
  174. }
  175. else {
  176. $rows[] = [
  177. 'test_id' => $test_id,
  178. 'test_class' => implode(",", $unescaped_test_classnames),
  179. 'status' => TestStatus::label($status),
  180. 'message' => 'PHPunit Test failed to complete; Error: ' . implode("\n", $output),
  181. 'message_group' => 'Other',
  182. 'function' => implode(",", $unescaped_test_classnames),
  183. 'line' => '0',
  184. 'file' => $phpunit_file,
  185. ];
  186. }
  187. return $rows;
  188. }
  189. /**
  190. * Inserts the parsed PHPUnit results into {simpletest}.
  191. *
  192. * @param array[] $phpunit_results
  193. * An array of test results returned from simpletest_phpunit_xml_to_rows().
  194. */
  195. function simpletest_process_phpunit_results($phpunit_results) {
  196. // Insert the results of the PHPUnit test run into the database so the results
  197. // are displayed along with Simpletest's results.
  198. if (!empty($phpunit_results)) {
  199. $query = TestDatabase::getConnection()
  200. ->insert('simpletest')
  201. ->fields(array_keys($phpunit_results[0]));
  202. foreach ($phpunit_results as $result) {
  203. $query->values($result);
  204. }
  205. $query->execute();
  206. }
  207. }
  208. /**
  209. * Maps phpunit results to a data structure for batch messages and run-tests.sh.
  210. *
  211. * @param array $results
  212. * The output from simpletest_run_phpunit_tests().
  213. *
  214. * @return array
  215. * The test result summary. A row per test class.
  216. */
  217. function simpletest_summarize_phpunit_result($results) {
  218. $summaries = [];
  219. foreach ($results as $result) {
  220. if (!isset($summaries[$result['test_class']])) {
  221. $summaries[$result['test_class']] = [
  222. '#pass' => 0,
  223. '#fail' => 0,
  224. '#exception' => 0,
  225. '#debug' => 0,
  226. ];
  227. }
  228. switch ($result['status']) {
  229. case 'pass':
  230. $summaries[$result['test_class']]['#pass']++;
  231. break;
  232. case 'fail':
  233. $summaries[$result['test_class']]['#fail']++;
  234. break;
  235. case 'exception':
  236. $summaries[$result['test_class']]['#exception']++;
  237. break;
  238. case 'debug':
  239. $summaries[$result['test_class']]['#debug']++;
  240. break;
  241. }
  242. }
  243. return $summaries;
  244. }
  245. /**
  246. * Returns the path to use for PHPUnit's --log-junit option.
  247. *
  248. * @param $test_id
  249. * The current test ID.
  250. *
  251. * @return string
  252. * Path to the PHPUnit XML file to use for the current $test_id.
  253. */
  254. function simpletest_phpunit_xml_filepath($test_id) {
  255. return \Drupal::service('file_system')->realpath('public://simpletest') . '/phpunit-' . $test_id . '.xml';
  256. }
  257. /**
  258. * Returns the path to core's phpunit.xml.dist configuration file.
  259. *
  260. * @return string
  261. * The path to core's phpunit.xml.dist configuration file.
  262. *
  263. * @deprecated in Drupal 8.4.x for removal before Drupal 9.0.0. PHPUnit test
  264. * runners should change directory into core/ and then run the phpunit tool.
  265. * See simpletest_phpunit_run_command() for an example.
  266. *
  267. * @see simpletest_phpunit_run_command()
  268. */
  269. function simpletest_phpunit_configuration_filepath() {
  270. @trigger_error('The ' . __FUNCTION__ . ' function is deprecated since version 8.4.x and will be removed in 9.0.0.', E_USER_DEPRECATED);
  271. return \Drupal::root() . '/core/phpunit.xml.dist';
  272. }
  273. /**
  274. * Executes the PHPUnit command.
  275. *
  276. * @param array $unescaped_test_classnames
  277. * An array of test class names, including full namespaces, to be passed as
  278. * a regular expression to PHPUnit's --filter option.
  279. * @param string $phpunit_file
  280. * A filepath to use for PHPUnit's --log-junit option.
  281. * @param int $status
  282. * (optional) The exit status code of the PHPUnit process will be assigned to
  283. * this variable.
  284. * @param string $output
  285. * (optional) The output by running the phpunit command.
  286. *
  287. * @return string
  288. * The results as returned by exec().
  289. */
  290. function simpletest_phpunit_run_command(array $unescaped_test_classnames, $phpunit_file, &$status = NULL, &$output = NULL) {
  291. global $base_url;
  292. // Setup an environment variable containing the database connection so that
  293. // functional tests can connect to the database.
  294. putenv('SIMPLETEST_DB=' . Database::getConnectionInfoAsUrl());
  295. // Setup an environment variable containing the base URL, if it is available.
  296. // This allows functional tests to browse the site under test. When running
  297. // tests via CLI, core/phpunit.xml.dist or core/scripts/run-tests.sh can set
  298. // this variable.
  299. if ($base_url) {
  300. putenv('SIMPLETEST_BASE_URL=' . $base_url);
  301. putenv('BROWSERTEST_OUTPUT_DIRECTORY=' . \Drupal::service('file_system')->realpath('public://simpletest'));
  302. }
  303. $phpunit_bin = simpletest_phpunit_command();
  304. $command = [
  305. $phpunit_bin,
  306. '--log-junit',
  307. escapeshellarg($phpunit_file),
  308. '--printer',
  309. escapeshellarg(SimpletestUiPrinter::class),
  310. ];
  311. // Optimized for running a single test.
  312. if (count($unescaped_test_classnames) == 1) {
  313. $class = new \ReflectionClass($unescaped_test_classnames[0]);
  314. $command[] = escapeshellarg($class->getFileName());
  315. }
  316. else {
  317. // Double escape namespaces so they'll work in a regexp.
  318. $escaped_test_classnames = array_map(function ($class) {
  319. return addslashes($class);
  320. }, $unescaped_test_classnames);
  321. $filter_string = implode("|", $escaped_test_classnames);
  322. $command = array_merge($command, [
  323. '--filter',
  324. escapeshellarg($filter_string),
  325. ]);
  326. }
  327. // Need to change directories before running the command so that we can use
  328. // relative paths in the configuration file's exclusions.
  329. $old_cwd = getcwd();
  330. chdir(\Drupal::root() . "/core");
  331. // exec in a subshell so that the environment is isolated when running tests
  332. // via the simpletest UI.
  333. $ret = exec(implode(" ", $command), $output, $status);
  334. chdir($old_cwd);
  335. putenv('SIMPLETEST_DB=');
  336. if ($base_url) {
  337. putenv('SIMPLETEST_BASE_URL=');
  338. putenv('BROWSERTEST_OUTPUT_DIRECTORY=');
  339. }
  340. return $ret;
  341. }
  342. /**
  343. * Returns the command to run PHPUnit.
  344. *
  345. * @return string
  346. * The command that can be run through exec().
  347. */
  348. function simpletest_phpunit_command() {
  349. // Load the actual autoloader being used and determine its filename using
  350. // reflection. We can determine the vendor directory based on that filename.
  351. $autoloader = require \Drupal::root() . '/autoload.php';
  352. $reflector = new ReflectionClass($autoloader);
  353. $vendor_dir = dirname(dirname($reflector->getFileName()));
  354. // The file in Composer's bin dir is a *nix link, which does not work when
  355. // extracted from a tarball and generally not on Windows.
  356. $command = $vendor_dir . '/phpunit/phpunit/phpunit';
  357. if (substr(PHP_OS, 0, 3) == 'WIN') {
  358. // On Windows it is necessary to run the script using the PHP executable.
  359. $php_executable_finder = new PhpExecutableFinder();
  360. $php = $php_executable_finder->find();
  361. $command = $php . ' -f ' . escapeshellarg($command) . ' --';
  362. }
  363. return $command;
  364. }
  365. /**
  366. * Implements callback_batch_operation().
  367. */
  368. function _simpletest_batch_operation($test_list_init, $test_id, &$context) {
  369. simpletest_classloader_register();
  370. // Get working values.
  371. if (!isset($context['sandbox']['max'])) {
  372. // First iteration: initialize working values.
  373. $test_list = $test_list_init;
  374. $context['sandbox']['max'] = count($test_list);
  375. $test_results = ['#pass' => 0, '#fail' => 0, '#exception' => 0, '#debug' => 0];
  376. }
  377. else {
  378. // Nth iteration: get the current values where we last stored them.
  379. $test_list = $context['sandbox']['tests'];
  380. $test_results = $context['sandbox']['test_results'];
  381. }
  382. $max = $context['sandbox']['max'];
  383. // Perform the next test.
  384. $test_class = array_shift($test_list);
  385. if (is_subclass_of($test_class, TestCase::class)) {
  386. $phpunit_results = simpletest_run_phpunit_tests($test_id, [$test_class]);
  387. simpletest_process_phpunit_results($phpunit_results);
  388. $test_results[$test_class] = simpletest_summarize_phpunit_result($phpunit_results)[$test_class];
  389. }
  390. else {
  391. $test = new $test_class($test_id);
  392. $test->run();
  393. \Drupal::moduleHandler()->invokeAll('test_finished', [$test->results]);
  394. $test_results[$test_class] = $test->results;
  395. }
  396. $size = count($test_list);
  397. $info = TestDiscovery::getTestInfo($test_class);
  398. // Gather results and compose the report.
  399. foreach ($test_results[$test_class] as $key => $value) {
  400. $test_results[$key] += $value;
  401. }
  402. $test_results[$test_class]['#name'] = $info['name'];
  403. $items = [];
  404. foreach (Element::children($test_results) as $class) {
  405. $class_test_result = $test_results[$class] + [
  406. '#theme' => 'simpletest_result_summary',
  407. '#label' => t($test_results[$class]['#name'] . ':'),
  408. ];
  409. array_unshift($items, \Drupal::service('renderer')->render($class_test_result));
  410. }
  411. $context['message'] = t('Processed test @num of @max - %test.', ['%test' => $info['name'], '@num' => $max - $size, '@max' => $max]);
  412. $overall_results = $test_results + [
  413. '#theme' => 'simpletest_result_summary',
  414. '#label' => t('Overall results:'),
  415. ];
  416. $context['message'] .= \Drupal::service('renderer')->render($overall_results);
  417. $item_list = [
  418. '#theme' => 'item_list',
  419. '#items' => $items,
  420. ];
  421. $context['message'] .= \Drupal::service('renderer')->render($item_list);
  422. // Save working values for the next iteration.
  423. $context['sandbox']['tests'] = $test_list;
  424. $context['sandbox']['test_results'] = $test_results;
  425. // The test_id is the only thing we need to save for the report page.
  426. $context['results']['test_id'] = $test_id;
  427. // Multistep processing: report progress.
  428. $context['finished'] = 1 - $size / $max;
  429. }
  430. /**
  431. * Implements callback_batch_finished().
  432. */
  433. function _simpletest_batch_finished($success, $results, $operations, $elapsed) {
  434. if ($success) {
  435. drupal_set_message(t('The test run finished in @elapsed.', ['@elapsed' => $elapsed]));
  436. }
  437. else {
  438. // Use the test_id passed as a parameter to _simpletest_batch_operation().
  439. $test_id = $operations[0][1][1];
  440. // Retrieve the last database prefix used for testing and the last test
  441. // class that was run from. Use the information to read the lgo file
  442. // in case any fatal errors caused the test to crash.
  443. list($last_prefix, $last_test_class) = simpletest_last_test_get($test_id);
  444. simpletest_log_read($test_id, $last_prefix, $last_test_class);
  445. drupal_set_message(t('The test run did not successfully finish.'), 'error');
  446. drupal_set_message(t('Use the <em>Clean environment</em> button to clean-up temporary files and tables.'), 'warning');
  447. }
  448. \Drupal::moduleHandler()->invokeAll('test_group_finished');
  449. }
  450. /**
  451. * Get information about the last test that ran given a test ID.
  452. *
  453. * @param $test_id
  454. * The test ID to get the last test from.
  455. * @return array
  456. * Array containing the last database prefix used and the last test class
  457. * that ran.
  458. */
  459. function simpletest_last_test_get($test_id) {
  460. $last_prefix = TestDatabase::getConnection()
  461. ->queryRange('SELECT last_prefix FROM {simpletest_test_id} WHERE test_id = :test_id', 0, 1, [
  462. ':test_id' => $test_id,
  463. ])
  464. ->fetchField();
  465. $last_test_class = TestDatabase::getConnection()
  466. ->queryRange('SELECT test_class FROM {simpletest} WHERE test_id = :test_id ORDER BY message_id DESC', 0, 1, [
  467. ':test_id' => $test_id,
  468. ])
  469. ->fetchField();
  470. return [$last_prefix, $last_test_class];
  471. }
  472. /**
  473. * Reads the error log and reports any errors as assertion failures.
  474. *
  475. * The errors in the log should only be fatal errors since any other errors
  476. * will have been recorded by the error handler.
  477. *
  478. * @param $test_id
  479. * The test ID to which the log relates.
  480. * @param $database_prefix
  481. * The database prefix to which the log relates.
  482. * @param $test_class
  483. * The test class to which the log relates.
  484. *
  485. * @return bool
  486. * Whether any fatal errors were found.
  487. */
  488. function simpletest_log_read($test_id, $database_prefix, $test_class) {
  489. $test_db = new TestDatabase($database_prefix);
  490. $log = DRUPAL_ROOT . '/' . $test_db->getTestSitePath() . '/error.log';
  491. $found = FALSE;
  492. if (file_exists($log)) {
  493. foreach (file($log) as $line) {
  494. if (preg_match('/\[.*?\] (.*?): (.*?) in (.*) on line (\d+)/', $line, $match)) {
  495. // Parse PHP fatal errors for example: PHP Fatal error: Call to
  496. // undefined function break_me() in /path/to/file.php on line 17
  497. $caller = [
  498. 'line' => $match[4],
  499. 'file' => $match[3],
  500. ];
  501. TestBase::insertAssert($test_id, $test_class, FALSE, $match[2], $match[1], $caller);
  502. }
  503. else {
  504. // Unknown format, place the entire message in the log.
  505. TestBase::insertAssert($test_id, $test_class, FALSE, $line, 'Fatal error');
  506. }
  507. $found = TRUE;
  508. }
  509. }
  510. return $found;
  511. }
  512. /**
  513. * Gets a list of all of the tests provided by the system.
  514. *
  515. * The list of test classes is loaded by searching the designated directory for
  516. * each module for files matching the PSR-0 standard. Once loaded the test list
  517. * is cached and stored in a static variable.
  518. *
  519. * @param string $extension
  520. * (optional) The name of an extension to limit discovery to; e.g., 'node'.
  521. * @param string[] $types
  522. * An array of included test types.
  523. *
  524. * @return array[]
  525. * An array of tests keyed with the groups, and then keyed by test classes.
  526. * For example:
  527. * @code
  528. * $groups['Block'] => array(
  529. * 'BlockTestCase' => array(
  530. * 'name' => 'Block functionality',
  531. * 'description' => 'Add, edit and delete custom block.',
  532. * 'group' => 'Block',
  533. * ),
  534. * );
  535. * @endcode
  536. *
  537. * @deprecated in Drupal 8.3.x, for removal before 9.0.0 release. Use
  538. * \Drupal::service('test_discovery')->getTestClasses($extension, $types)
  539. * instead.
  540. */
  541. function simpletest_test_get_all($extension = NULL, array $types = []) {
  542. return \Drupal::service('test_discovery')->getTestClasses($extension, $types);
  543. }
  544. /**
  545. * Registers test namespaces of all extensions and core test classes.
  546. *
  547. * @deprecated in Drupal 8.3.x for removal before 9.0.0 release. Use
  548. * \Drupal::service('test_discovery')->registerTestNamespaces() instead.
  549. */
  550. function simpletest_classloader_register() {
  551. \Drupal::service('test_discovery')->registerTestNamespaces();
  552. }
  553. /**
  554. * Generates a test file.
  555. *
  556. * @param string $filename
  557. * The name of the file, including the path. The suffix '.txt' is appended to
  558. * the supplied file name and the file is put into the public:// files
  559. * directory.
  560. * @param int $width
  561. * The number of characters on one line.
  562. * @param int $lines
  563. * The number of lines in the file.
  564. * @param string $type
  565. * (optional) The type, one of:
  566. * - text: The generated file contains random ASCII characters.
  567. * - binary: The generated file contains random characters whose codes are in
  568. * the range of 0 to 31.
  569. * - binary-text: The generated file contains random sequence of '0' and '1'
  570. * values.
  571. *
  572. * @return string
  573. * The name of the file, including the path.
  574. */
  575. function simpletest_generate_file($filename, $width, $lines, $type = 'binary-text') {
  576. $text = '';
  577. for ($i = 0; $i < $lines; $i++) {
  578. // Generate $width - 1 characters to leave space for the "\n" character.
  579. for ($j = 0; $j < $width - 1; $j++) {
  580. switch ($type) {
  581. case 'text':
  582. $text .= chr(rand(32, 126));
  583. break;
  584. case 'binary':
  585. $text .= chr(rand(0, 31));
  586. break;
  587. case 'binary-text':
  588. default:
  589. $text .= rand(0, 1);
  590. break;
  591. }
  592. }
  593. $text .= "\n";
  594. }
  595. // Create filename.
  596. file_put_contents('public://' . $filename . '.txt', $text);
  597. return $filename;
  598. }
  599. /**
  600. * Removes all temporary database tables and directories.
  601. */
  602. function simpletest_clean_environment() {
  603. simpletest_clean_database();
  604. simpletest_clean_temporary_directories();
  605. if (\Drupal::config('simpletest.settings')->get('clear_results')) {
  606. $count = simpletest_clean_results_table();
  607. drupal_set_message(\Drupal::translation()->formatPlural($count, 'Removed 1 test result.', 'Removed @count test results.'));
  608. }
  609. else {
  610. drupal_set_message(t('Clear results is disabled and the test results table will not be cleared.'), 'warning');
  611. }
  612. // Detect test classes that have been added, renamed or deleted.
  613. \Drupal::cache()->delete('simpletest');
  614. \Drupal::cache()->delete('simpletest_phpunit');
  615. }
  616. /**
  617. * Removes prefixed tables from the database from crashed tests.
  618. */
  619. function simpletest_clean_database() {
  620. $tables = db_find_tables('test%');
  621. $count = 0;
  622. foreach ($tables as $table) {
  623. // Only drop tables which begin wih 'test' followed by digits, for example,
  624. // {test12345678node__body}.
  625. if (preg_match('/^test\d+.*/', $table, $matches)) {
  626. db_drop_table($matches[0]);
  627. $count++;
  628. }
  629. }
  630. if ($count > 0) {
  631. drupal_set_message(\Drupal::translation()->formatPlural($count, 'Removed 1 leftover table.', 'Removed @count leftover tables.'));
  632. }
  633. else {
  634. drupal_set_message(t('No leftover tables to remove.'));
  635. }
  636. }
  637. /**
  638. * Finds all leftover temporary directories and removes them.
  639. */
  640. function simpletest_clean_temporary_directories() {
  641. $count = 0;
  642. if (is_dir(DRUPAL_ROOT . '/sites/simpletest')) {
  643. $files = scandir(DRUPAL_ROOT . '/sites/simpletest');
  644. foreach ($files as $file) {
  645. if ($file[0] != '.') {
  646. $path = DRUPAL_ROOT . '/sites/simpletest/' . $file;
  647. file_unmanaged_delete_recursive($path, function ($any_path) {
  648. @chmod($any_path, 0700);
  649. });
  650. $count++;
  651. }
  652. }
  653. }
  654. if ($count > 0) {
  655. drupal_set_message(\Drupal::translation()->formatPlural($count, 'Removed 1 temporary directory.', 'Removed @count temporary directories.'));
  656. }
  657. else {
  658. drupal_set_message(t('No temporary directories to remove.'));
  659. }
  660. }
  661. /**
  662. * Clears the test result tables.
  663. *
  664. * @param $test_id
  665. * Test ID to remove results for, or NULL to remove all results.
  666. *
  667. * @return int
  668. * The number of results that were removed.
  669. */
  670. function simpletest_clean_results_table($test_id = NULL) {
  671. if (\Drupal::config('simpletest.settings')->get('clear_results')) {
  672. $connection = TestDatabase::getConnection();
  673. if ($test_id) {
  674. $count = $connection->query('SELECT COUNT(test_id) FROM {simpletest_test_id} WHERE test_id = :test_id', [':test_id' => $test_id])->fetchField();
  675. $connection->delete('simpletest')
  676. ->condition('test_id', $test_id)
  677. ->execute();
  678. $connection->delete('simpletest_test_id')
  679. ->condition('test_id', $test_id)
  680. ->execute();
  681. }
  682. else {
  683. $count = $connection->query('SELECT COUNT(test_id) FROM {simpletest_test_id}')->fetchField();
  684. // Clear test results.
  685. $connection->delete('simpletest')->execute();
  686. $connection->delete('simpletest_test_id')->execute();
  687. }
  688. return $count;
  689. }
  690. return 0;
  691. }
  692. /**
  693. * Implements hook_mail_alter().
  694. *
  695. * Aborts sending of messages with ID 'simpletest_cancel_test'.
  696. *
  697. * @see MailTestCase::testCancelMessage()
  698. */
  699. function simpletest_mail_alter(&$message) {
  700. if ($message['id'] == 'simpletest_cancel_test') {
  701. $message['send'] = FALSE;
  702. }
  703. }
  704. /**
  705. * Converts PHPUnit's JUnit XML output to an array.
  706. *
  707. * @param $test_id
  708. * The current test ID.
  709. * @param $phpunit_xml_file
  710. * Path to the PHPUnit XML file.
  711. *
  712. * @return array[]|null
  713. * The results as array of rows in a format that can be inserted into
  714. * {simpletest}. If the phpunit_xml_file does not have any contents then the
  715. * function will return NULL.
  716. */
  717. function simpletest_phpunit_xml_to_rows($test_id, $phpunit_xml_file) {
  718. $contents = @file_get_contents($phpunit_xml_file);
  719. if (!$contents) {
  720. return;
  721. }
  722. $records = [];
  723. $testcases = simpletest_phpunit_find_testcases(new SimpleXMLElement($contents));
  724. foreach ($testcases as $testcase) {
  725. $records[] = simpletest_phpunit_testcase_to_row($test_id, $testcase);
  726. }
  727. return $records;
  728. }
  729. /**
  730. * Finds all test cases recursively from a test suite list.
  731. *
  732. * @param \SimpleXMLElement $element
  733. * The PHPUnit xml to search for test cases.
  734. * @param \SimpleXMLElement $parent
  735. * (Optional) The parent of the current element. Defaults to NULL.
  736. *
  737. * @return array
  738. * A list of all test cases.
  739. */
  740. function simpletest_phpunit_find_testcases(\SimpleXMLElement $element, \SimpleXMLElement $parent = NULL) {
  741. $testcases = [];
  742. if (!isset($parent)) {
  743. $parent = $element;
  744. }
  745. if ($element->getName() === 'testcase' && (int) $parent->attributes()->tests > 0) {
  746. // Add the class attribute if the testcase does not have one. This is the
  747. // case for tests using a data provider. The name of the parent testsuite
  748. // will be in the format class::method.
  749. if (!$element->attributes()->class) {
  750. $name = explode('::', $parent->attributes()->name, 2);
  751. $element->addAttribute('class', $name[0]);
  752. }
  753. $testcases[] = $element;
  754. }
  755. else {
  756. foreach ($element as $child) {
  757. $file = (string) $parent->attributes()->file;
  758. if ($file && !$child->attributes()->file) {
  759. $child->addAttribute('file', $file);
  760. }
  761. $testcases = array_merge($testcases, simpletest_phpunit_find_testcases($child, $element));
  762. }
  763. }
  764. return $testcases;
  765. }
  766. /**
  767. * Converts a PHPUnit test case result to a {simpletest} result row.
  768. *
  769. * @param int $test_id
  770. * The current test ID.
  771. * @param \SimpleXMLElement $testcase
  772. * The PHPUnit test case represented as XML element.
  773. *
  774. * @return array
  775. * An array containing the {simpletest} result row.
  776. */
  777. function simpletest_phpunit_testcase_to_row($test_id, \SimpleXMLElement $testcase) {
  778. $message = '';
  779. $pass = TRUE;
  780. if ($testcase->failure) {
  781. $lines = explode("\n", $testcase->failure);
  782. $message = $lines[2];
  783. $pass = FALSE;
  784. }
  785. if ($testcase->error) {
  786. $message = $testcase->error;
  787. $pass = FALSE;
  788. }
  789. $attributes = $testcase->attributes();
  790. $record = [
  791. 'test_id' => $test_id,
  792. 'test_class' => (string) $attributes->class,
  793. 'status' => $pass ? 'pass' : 'fail',
  794. 'message' => $message,
  795. // @todo: Check on the proper values for this.
  796. 'message_group' => 'Other',
  797. 'function' => $attributes->class . '->' . $attributes->name . '()',
  798. 'line' => $attributes->line ?: 0,
  799. 'file' => $attributes->file,
  800. ];
  801. return $record;
  802. }