Drupal investigation

simpletest.module 28KB

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