5 * Provides testing functionality.
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;
21 * Implements hook_help().
23 function simpletest_help($route_name, RouteMatchInterface $route_match) {
24 switch ($route_name) {
25 case 'help.page.simpletest':
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>';
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>';
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>.');
44 * Implements hook_theme().
46 function simpletest_theme() {
48 'simpletest_result_summary' => [
49 'variables' => ['label' => NULL, 'items' => [], 'pass' => 0, 'fail' => 0, 'exception' => 0, 'debug' => 0],
55 * Implements hook_js_alter().
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;
67 * Prepares variables for simpletest result summary templates.
69 * Default template: simpletest-result-summary.html.twig.
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.
80 function template_preprocess_simpletest_result_summary(&$variables) {
81 $variables['items'] = _simpletest_build_summary_line($variables);
85 * Formats each test result type pluralized summary.
87 * @param array $summary
88 * A summary of the test results.
91 * The pluralized test summary items.
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');
105 * Formats test result summaries into a comma separated string for run-tests.sh.
107 * @param array $summary
108 * A summary of the test results.
111 * A concatenated string of the formatted test results.
113 function _simpletest_format_summary_line($summary) {
114 $parts = _simpletest_build_summary_line($summary);
115 return implode(', ', $parts);
122 * List of tests to run.
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']);
136 if (isset($test_list['phpunit'])) {
137 $test_list = array_merge($test_list, $test_list['phpunit']);
138 unset($test_list['phpunit']);
141 $test_id = db_insert('simpletest_test_id')
142 ->useDefaults(['test_id'])
145 // Clear out the previous verbose files.
146 file_unmanaged_delete_recursive('public://simpletest/verbose');
148 // Get the info for the first test being run.
149 $first_test = reset($test_list);
150 $info = TestDiscovery::getTestInfo($first_test);
153 'title' => t('Running tests'),
155 ['_simpletest_batch_operation', [$test_list, $test_id]],
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)]),
164 \Drupal::moduleHandler()->invokeAll('test_group_started');
170 * Executes PHPUnit tests and returns the results of the run.
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.
178 * (optional) The exit status code of the PHPUnit process will be assigned to
182 * The parsed results of PHPUnit's JUnit XML output, in the format of
183 * {simpletest}'s schema.
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);
190 if ($status == TestStatus::PASS) {
191 $rows = simpletest_phpunit_xml_to_rows($test_id, $phpunit_file);
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),
202 'file' => $phpunit_file,
209 * Inserts the parsed PHPUnit results into {simpletest}.
211 * @param array[] $phpunit_results
212 * An array of test results returned from simpletest_phpunit_xml_to_rows().
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);
229 * Maps phpunit results to a data structure for batch messages and run-tests.sh.
231 * @param array $results
232 * The output from simpletest_run_phpunit_tests().
235 * The test result summary. A row per test class.
237 function simpletest_summarize_phpunit_result($results) {
239 foreach ($results as $result) {
240 if (!isset($summaries[$result['test_class']])) {
241 $summaries[$result['test_class']] = [
249 switch ($result['status']) {
251 $summaries[$result['test_class']]['#pass']++;
255 $summaries[$result['test_class']]['#fail']++;
259 $summaries[$result['test_class']]['#exception']++;
263 $summaries[$result['test_class']]['#debug']++;
271 * Returns the path to use for PHPUnit's --log-junit option.
274 * The current test ID.
277 * Path to the PHPUnit XML file to use for the current $test_id.
279 function simpletest_phpunit_xml_filepath($test_id) {
280 return \Drupal::service('file_system')->realpath('public://simpletest') . '/phpunit-' . $test_id . '.xml';
284 * Returns the path to core's phpunit.xml.dist configuration file.
287 * The path to core's phpunit.xml.dist configuration file.
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.
293 * @see simpletest_phpunit_run_command()
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';
301 * Executes the PHPUnit command.
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.
309 * (optional) The exit status code of the PHPUnit process will be assigned to
311 * @param string $output
312 * (optional) The output by running the phpunit command.
315 * The results as returned by exec().
317 function simpletest_phpunit_run_command(array $unescaped_test_classnames, $phpunit_file, &$status = NULL, &$output = NULL) {
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());
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
328 putenv('SIMPLETEST_BASE_URL=' . $base_url);
329 putenv('BROWSERTEST_OUTPUT_DIRECTORY=' . \Drupal::service('file_system')->realpath('public://simpletest'));
331 $phpunit_bin = simpletest_phpunit_command();
336 escapeshellarg($phpunit_file),
338 escapeshellarg(SimpletestUiPrinter::class),
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());
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);
352 $filter_string = implode("|", $escaped_test_classnames);
353 $command = array_merge($command, [
355 escapeshellarg($filter_string),
359 // Need to change directories before running the command so that we can use
360 // relative paths in the configuration file's exclusions.
362 chdir(\Drupal::root() . "/core");
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);
369 putenv('SIMPLETEST_DB=');
371 putenv('SIMPLETEST_BASE_URL=');
372 putenv('BROWSERTEST_OUTPUT_DIRECTORY=');
378 * Returns the command to run PHPUnit.
381 * The command that can be run through exec().
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()));
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 . ' --';
403 * Implements callback_batch_operation().
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];
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'];
419 $max = $context['sandbox']['max'];
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];
429 $test = new $test_class($test_id);
431 \Drupal::moduleHandler()->invokeAll('test_finished', [$test->results]);
432 $test_results[$test_class] = $test->results;
434 $size = count($test_list);
435 $info = TestDiscovery::getTestInfo($test_class);
437 // Gather results and compose the report.
438 foreach ($test_results[$test_class] as $key => $value) {
439 $test_results[$key] += $value;
441 $test_results[$test_class]['#name'] = $info['name'];
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'] . ':'),
448 array_unshift($items, \Drupal::service('renderer')->render($class_test_result));
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:'),
455 $context['message'] .= \Drupal::service('renderer')->render($overall_results);
458 '#theme' => 'item_list',
461 $context['message'] .= \Drupal::service('renderer')->render($item_list);
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;
469 // Multistep processing: report progress.
470 $context['finished'] = 1 - $size / $max;
474 * Implements callback_batch_finished().
476 function _simpletest_batch_finished($success, $results, $operations, $elapsed) {
478 \Drupal::messenger()->addStatus(t('The test run finished in @elapsed.', ['@elapsed' => $elapsed]));
481 // Use the test_id passed as a parameter to _simpletest_batch_operation().
482 $test_id = $operations[0][1][1];
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);
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.'));
493 \Drupal::moduleHandler()->invokeAll('test_group_finished');
497 * Get information about the last test that ran given a test ID.
500 * The test ID to get the last test from.
502 * Array containing the last database prefix used and the last test class
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,
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,
516 return [$last_prefix, $last_test_class];
520 * Reads the error log and reports any errors as assertion failures.
522 * The errors in the log should only be fatal errors since any other errors
523 * will have been recorded by the error handler.
526 * The test ID to which the log relates.
527 * @param $database_prefix
528 * The database prefix to which the log relates.
530 * The test class to which the log relates.
533 * Whether any fatal errors were found.
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';
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
548 TestBase::insertAssert($test_id, $test_class, FALSE, $match[2], $match[1], $caller);
551 // Unknown format, place the entire message in the log.
552 TestBase::insertAssert($test_id, $test_class, FALSE, $line, 'Fatal error');
561 * Gets a list of all of the tests provided by the system.
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.
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.
573 * An array of tests keyed with the groups, and then keyed by test classes.
576 * $groups['Block'] => array(
577 * 'BlockTestCase' => array(
578 * 'name' => 'Block functionality',
579 * 'description' => 'Add, edit and delete custom block.',
580 * 'group' => 'Block',
585 * @deprecated in Drupal 8.3.x, for removal before 9.0.0 release. Use
586 * \Drupal::service('test_discovery')->getTestClasses($extension, $types)
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);
595 * Registers test namespaces of all extensions and core test classes.
597 * @deprecated in Drupal 8.3.x for removal before 9.0.0 release. Use
598 * \Drupal::service('test_discovery')->registerTestNamespaces() instead.
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();
606 * Generates a test file.
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
613 * The number of characters on one line.
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'
625 * The name of the file, including the path.
627 function simpletest_generate_file($filename, $width, $lines, $type = 'binary-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++) {
634 $text .= chr(rand(32, 126));
637 $text .= chr(rand(0, 31));
649 file_put_contents('public://' . $filename . '.txt', $text);
654 * Removes all temporary database tables and directories.
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.'));
664 \Drupal::messenger()->addWarning(t('Clear results is disabled and the test results table will not be cleared.'), 'warning');
669 * Removes prefixed tables from the database from crashed tests.
671 function simpletest_clean_database() {
672 $schema = Database::getConnection()->schema();
673 $tables = db_find_tables('test%');
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]);
685 \Drupal::messenger()->addStatus(\Drupal::translation()->formatPlural($count, 'Removed 1 leftover table.', 'Removed @count leftover tables.'));
688 \Drupal::messenger()->addStatus(t('No leftover tables to remove.'));
693 * Finds all leftover temporary directories and removes them.
695 function simpletest_clean_temporary_directories() {
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);
711 \Drupal::messenger()->addStatus(\Drupal::translation()->formatPlural($count, 'Removed 1 temporary directory.', 'Removed @count temporary directories.'));
714 \Drupal::messenger()->addStatus(t('No temporary directories to remove.'));
719 * Clears the test result tables.
722 * Test ID to remove results for, or NULL to remove all results.
725 * The number of results that were removed.
727 function simpletest_clean_results_table($test_id = NULL) {
728 if (\Drupal::config('simpletest.settings')->get('clear_results')) {
729 $connection = TestDatabase::getConnection();
731 $count = $connection->query('SELECT COUNT(test_id) FROM {simpletest_test_id} WHERE test_id = :test_id', [':test_id' => $test_id])->fetchField();
733 $connection->delete('simpletest')
734 ->condition('test_id', $test_id)
736 $connection->delete('simpletest_test_id')
737 ->condition('test_id', $test_id)
741 $count = $connection->query('SELECT COUNT(test_id) FROM {simpletest_test_id}')->fetchField();
743 // Clear test results.
744 $connection->delete('simpletest')->execute();
745 $connection->delete('simpletest_test_id')->execute();
754 * Implements hook_mail_alter().
756 * Aborts sending of messages with ID 'simpletest_cancel_test'.
758 * @see MailTestCase::testCancelMessage()
760 function simpletest_mail_alter(&$message) {
761 if ($message['id'] == 'simpletest_cancel_test') {
762 $message['send'] = FALSE;
767 * Converts PHPUnit's JUnit XML output to an array.
770 * The current test ID.
771 * @param $phpunit_xml_file
772 * Path to the PHPUnit XML file.
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.
779 function simpletest_phpunit_xml_to_rows($test_id, $phpunit_xml_file) {
780 $contents = @file_get_contents($phpunit_xml_file);
785 $testcases = simpletest_phpunit_find_testcases(new SimpleXMLElement($contents));
786 foreach ($testcases as $testcase) {
787 $records[] = simpletest_phpunit_testcase_to_row($test_id, $testcase);
793 * Finds all test cases recursively from a test suite list.
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.
801 * A list of all test cases.
803 function simpletest_phpunit_find_testcases(\SimpleXMLElement $element, \SimpleXMLElement $parent = NULL) {
806 if (!isset($parent)) {
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]);
818 $testcases[] = $element;
821 foreach ($element as $child) {
822 $file = (string) $parent->attributes()->file;
823 if ($file && !$child->attributes()->file) {
824 $child->addAttribute('file', $file);
826 $testcases = array_merge($testcases, simpletest_phpunit_find_testcases($child, $element));
833 * Converts a PHPUnit test case result to a {simpletest} result row.
835 * @param int $test_id
836 * The current test ID.
837 * @param \SimpleXMLElement $testcase
838 * The PHPUnit test case represented as XML element.
841 * An array containing the {simpletest} result row.
843 function simpletest_phpunit_testcase_to_row($test_id, \SimpleXMLElement $testcase) {
846 if ($testcase->failure) {
847 $lines = explode("\n", $testcase->failure);
848 $message = $lines[2];
851 if ($testcase->error) {
852 $message = $testcase->error;
856 $attributes = $testcase->attributes();
859 'test_id' => $test_id,
860 'test_class' => (string) $attributes->class,
861 'status' => $pass ? 'pass' : 'fail',
862 'message' => $message,
863 // @todo: Check on the proper values for this.
864 'message_group' => 'Other',
865 'function' => $attributes->class . '->' . $attributes->name . '()',
866 'line' => $attributes->line ?: 0,
867 'file' => $attributes->file,