0e0ea2afd4006d6c66b5906ccdbeb864284c27b9
[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 = $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 ' . escapeshellarg($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   simpletest_classloader_register();
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_set_message(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_set_message(t('The test run did not successfully finish.'), 'error');
491     drupal_set_message(t('Use the <em>Clean environment</em> button to clean-up temporary files and tables.'), 'warning');
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   return \Drupal::service('test_discovery')->getTestClasses($extension, $types);
591 }
592
593 /**
594  * Registers test namespaces of all extensions and core test classes.
595  *
596  * @deprecated in Drupal 8.3.x for removal before 9.0.0 release. Use
597  *   \Drupal::service('test_discovery')->registerTestNamespaces() instead.
598  */
599 function simpletest_classloader_register() {
600   \Drupal::service('test_discovery')->registerTestNamespaces();
601 }
602
603 /**
604  * Generates a test file.
605  *
606  * @param string $filename
607  *   The name of the file, including the path. The suffix '.txt' is appended to
608  *   the supplied file name and the file is put into the public:// files
609  *   directory.
610  * @param int $width
611  *   The number of characters on one line.
612  * @param int $lines
613  *   The number of lines in the file.
614  * @param string $type
615  *   (optional) The type, one of:
616  *   - text: The generated file contains random ASCII characters.
617  *   - binary: The generated file contains random characters whose codes are in
618  *     the range of 0 to 31.
619  *   - binary-text: The generated file contains random sequence of '0' and '1'
620  *     values.
621  *
622  * @return string
623  *   The name of the file, including the path.
624  */
625 function simpletest_generate_file($filename, $width, $lines, $type = 'binary-text') {
626   $text = '';
627   for ($i = 0; $i < $lines; $i++) {
628     // Generate $width - 1 characters to leave space for the "\n" character.
629     for ($j = 0; $j < $width - 1; $j++) {
630       switch ($type) {
631         case 'text':
632           $text .= chr(rand(32, 126));
633           break;
634         case 'binary':
635           $text .= chr(rand(0, 31));
636           break;
637         case 'binary-text':
638         default:
639           $text .= rand(0, 1);
640           break;
641       }
642     }
643     $text .= "\n";
644   }
645
646   // Create filename.
647   file_put_contents('public://' . $filename . '.txt', $text);
648   return $filename;
649 }
650
651 /**
652  * Removes all temporary database tables and directories.
653  */
654 function simpletest_clean_environment() {
655   simpletest_clean_database();
656   simpletest_clean_temporary_directories();
657   if (\Drupal::config('simpletest.settings')->get('clear_results')) {
658     $count = simpletest_clean_results_table();
659     drupal_set_message(\Drupal::translation()->formatPlural($count, 'Removed 1 test result.', 'Removed @count test results.'));
660   }
661   else {
662     drupal_set_message(t('Clear results is disabled and the test results table will not be cleared.'), 'warning');
663   }
664
665   // Detect test classes that have been added, renamed or deleted.
666   \Drupal::cache()->delete('simpletest');
667   \Drupal::cache()->delete('simpletest_phpunit');
668 }
669
670 /**
671  * Removes prefixed tables from the database from crashed tests.
672  */
673 function simpletest_clean_database() {
674   $tables = db_find_tables('test%');
675   $count = 0;
676   foreach ($tables as $table) {
677     // Only drop tables which begin wih 'test' followed by digits, for example,
678     // {test12345678node__body}.
679     if (preg_match('/^test\d+.*/', $table, $matches)) {
680       db_drop_table($matches[0]);
681       $count++;
682     }
683   }
684
685   if ($count > 0) {
686     drupal_set_message(\Drupal::translation()->formatPlural($count, 'Removed 1 leftover table.', 'Removed @count leftover tables.'));
687   }
688   else {
689     drupal_set_message(t('No leftover tables to remove.'));
690   }
691 }
692
693 /**
694  * Finds all leftover temporary directories and removes them.
695  */
696 function simpletest_clean_temporary_directories() {
697   $count = 0;
698   if (is_dir(DRUPAL_ROOT . '/sites/simpletest')) {
699     $files = scandir(DRUPAL_ROOT . '/sites/simpletest');
700     foreach ($files as $file) {
701       if ($file[0] != '.') {
702         $path = DRUPAL_ROOT . '/sites/simpletest/' . $file;
703         file_unmanaged_delete_recursive($path, function ($any_path) {
704           @chmod($any_path, 0700);
705         });
706         $count++;
707       }
708     }
709   }
710
711   if ($count > 0) {
712     drupal_set_message(\Drupal::translation()->formatPlural($count, 'Removed 1 temporary directory.', 'Removed @count temporary directories.'));
713   }
714   else {
715     drupal_set_message(t('No temporary directories to remove.'));
716   }
717 }
718
719 /**
720  * Clears the test result tables.
721  *
722  * @param $test_id
723  *   Test ID to remove results for, or NULL to remove all results.
724  *
725  * @return int
726  *   The number of results that were removed.
727  */
728 function simpletest_clean_results_table($test_id = NULL) {
729   if (\Drupal::config('simpletest.settings')->get('clear_results')) {
730     $connection = TestDatabase::getConnection();
731     if ($test_id) {
732       $count = $connection->query('SELECT COUNT(test_id) FROM {simpletest_test_id} WHERE test_id = :test_id', [':test_id' => $test_id])->fetchField();
733
734       $connection->delete('simpletest')
735         ->condition('test_id', $test_id)
736         ->execute();
737       $connection->delete('simpletest_test_id')
738         ->condition('test_id', $test_id)
739         ->execute();
740     }
741     else {
742       $count = $connection->query('SELECT COUNT(test_id) FROM {simpletest_test_id}')->fetchField();
743
744       // Clear test results.
745       $connection->delete('simpletest')->execute();
746       $connection->delete('simpletest_test_id')->execute();
747     }
748
749     return $count;
750   }
751   return 0;
752 }
753
754 /**
755  * Implements hook_mail_alter().
756  *
757  * Aborts sending of messages with ID 'simpletest_cancel_test'.
758  *
759  * @see MailTestCase::testCancelMessage()
760  */
761 function simpletest_mail_alter(&$message) {
762   if ($message['id'] == 'simpletest_cancel_test') {
763     $message['send'] = FALSE;
764   }
765 }
766
767 /**
768  * Converts PHPUnit's JUnit XML output to an array.
769  *
770  * @param $test_id
771  *   The current test ID.
772  * @param $phpunit_xml_file
773  *   Path to the PHPUnit XML file.
774  *
775  * @return array[]|null
776  *   The results as array of rows in a format that can be inserted into
777  *   {simpletest}. If the phpunit_xml_file does not have any contents then the
778  *   function will return NULL.
779  */
780 function simpletest_phpunit_xml_to_rows($test_id, $phpunit_xml_file) {
781   $contents = @file_get_contents($phpunit_xml_file);
782   if (!$contents) {
783     return;
784   }
785   $records = [];
786   $testcases = simpletest_phpunit_find_testcases(new SimpleXMLElement($contents));
787   foreach ($testcases as $testcase) {
788     $records[] = simpletest_phpunit_testcase_to_row($test_id, $testcase);
789   }
790   return $records;
791 }
792
793 /**
794  * Finds all test cases recursively from a test suite list.
795  *
796  * @param \SimpleXMLElement $element
797  *   The PHPUnit xml to search for test cases.
798  * @param \SimpleXMLElement $parent
799  *   (Optional) The parent of the current element. Defaults to NULL.
800  *
801  * @return array
802  *   A list of all test cases.
803  */
804 function simpletest_phpunit_find_testcases(\SimpleXMLElement $element, \SimpleXMLElement $parent = NULL) {
805   $testcases = [];
806
807   if (!isset($parent)) {
808     $parent = $element;
809   }
810
811   if ($element->getName() === 'testcase' && (int) $parent->attributes()->tests > 0) {
812     // Add the class attribute if the testcase does not have one. This is the
813     // case for tests using a data provider. The name of the parent testsuite
814     // will be in the format class::method.
815     if (!$element->attributes()->class) {
816       $name = explode('::', $parent->attributes()->name, 2);
817       $element->addAttribute('class', $name[0]);
818     }
819     $testcases[] = $element;
820   }
821   else {
822     foreach ($element as $child) {
823       $file = (string) $parent->attributes()->file;
824       if ($file && !$child->attributes()->file) {
825         $child->addAttribute('file', $file);
826       }
827       $testcases = array_merge($testcases, simpletest_phpunit_find_testcases($child, $element));
828     }
829   }
830   return $testcases;
831 }
832
833 /**
834  * Converts a PHPUnit test case result to a {simpletest} result row.
835  *
836  * @param int $test_id
837  *   The current test ID.
838  * @param \SimpleXMLElement $testcase
839  *   The PHPUnit test case represented as XML element.
840  *
841  * @return array
842  *   An array containing the {simpletest} result row.
843  */
844 function simpletest_phpunit_testcase_to_row($test_id, \SimpleXMLElement $testcase) {
845   $message = '';
846   $pass = TRUE;
847   if ($testcase->failure) {
848     $lines = explode("\n", $testcase->failure);
849     $message = $lines[2];
850     $pass = FALSE;
851   }
852   if ($testcase->error) {
853     $message = $testcase->error;
854     $pass = FALSE;
855   }
856
857   $attributes = $testcase->attributes();
858
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' => $attributes->class . '->' . $attributes->name . '()',
867     'line' => $attributes->line ?: 0,
868     'file' => $attributes->file,
869   ];
870   return $record;
871 }