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