Chris@0: ' . t('About') . ''; Chris@0: $output .= '

' . 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 online documentation for the Testing module.', [':simpletest' => 'https://www.drupal.org/documentation/modules/simpletest']) . '

'; Chris@0: $output .= '

' . t('Uses') . '

'; Chris@0: $output .= '
'; Chris@0: $output .= '
' . t('Running tests') . '
'; Chris@18: $output .= '

' . t('Visit the Testing page to display a list of available tests. For comprehensive testing, select all tests, or individually select tests for more targeted testing. Note that it might take several minutes for all tests to complete.', [':admin-simpletest' => Url::fromRoute('simpletest.test_form')->toString()]) . '

'; Chris@0: $output .= '

' . 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.') . '

'; Chris@0: $output .= '
'; Chris@0: return $output; Chris@0: Chris@0: case 'simpletest.test_form': Chris@0: $output = t('Select the test(s) or test group(s) you would like to run, and click Run tests.'); Chris@0: return $output; Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Implements hook_theme(). Chris@0: */ Chris@0: function simpletest_theme() { Chris@0: return [ Chris@0: 'simpletest_result_summary' => [ Chris@0: 'variables' => ['label' => NULL, 'items' => [], 'pass' => 0, 'fail' => 0, 'exception' => 0, 'debug' => 0], Chris@0: ], Chris@0: ]; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Implements hook_js_alter(). Chris@0: */ Chris@0: function simpletest_js_alter(&$javascript, AttachedAssetsInterface $assets) { Chris@0: // Since SimpleTest is a special use case for the table select, stick the Chris@0: // SimpleTest JavaScript above the table select. Chris@0: $simpletest = drupal_get_path('module', 'simpletest') . '/simpletest.js'; Chris@0: if (array_key_exists($simpletest, $javascript) && array_key_exists('core/misc/tableselect.js', $javascript)) { Chris@0: $javascript[$simpletest]['weight'] = $javascript['core/misc/tableselect.js']['weight'] - 1; Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Prepares variables for simpletest result summary templates. Chris@0: * Chris@0: * Default template: simpletest-result-summary.html.twig. Chris@0: * Chris@0: * @param array $variables Chris@0: * An associative array containing: Chris@0: * - label: An optional label to be rendered before the results. Chris@0: * - ok: The overall group result pass or fail. Chris@0: * - pass: The number of passes. Chris@0: * - fail: The number of fails. Chris@0: * - exception: The number of exceptions. Chris@0: * - debug: The number of debug messages. Chris@0: */ Chris@0: function template_preprocess_simpletest_result_summary(&$variables) { Chris@0: $variables['items'] = _simpletest_build_summary_line($variables); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Formats each test result type pluralized summary. Chris@0: * Chris@0: * @param array $summary Chris@0: * A summary of the test results. Chris@0: * Chris@0: * @return array Chris@0: * The pluralized test summary items. Chris@0: */ Chris@0: function _simpletest_build_summary_line($summary) { Chris@0: $translation = \Drupal::translation(); Chris@0: $items['pass'] = $translation->formatPlural($summary['pass'], '1 pass', '@count passes'); Chris@0: $items['fail'] = $translation->formatPlural($summary['fail'], '1 fail', '@count fails'); Chris@0: $items['exception'] = $translation->formatPlural($summary['exception'], '1 exception', '@count exceptions'); Chris@0: if ($summary['debug']) { Chris@0: $items['debug'] = $translation->formatPlural($summary['debug'], '1 debug message', '@count debug messages'); Chris@0: } Chris@0: return $items; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Formats test result summaries into a comma separated string for run-tests.sh. Chris@0: * Chris@0: * @param array $summary Chris@0: * A summary of the test results. Chris@0: * Chris@0: * @return string Chris@0: * A concatenated string of the formatted test results. Chris@0: */ Chris@0: function _simpletest_format_summary_line($summary) { Chris@0: $parts = _simpletest_build_summary_line($summary); Chris@0: return implode(', ', $parts); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Runs tests. Chris@0: * Chris@0: * @param $test_list Chris@0: * List of tests to run. Chris@0: * Chris@0: * @return string Chris@0: * The test ID. Chris@0: */ Chris@0: function simpletest_run_tests($test_list) { Chris@0: // We used to separate PHPUnit and Simpletest tests for a performance Chris@0: // optimization. In order to support backwards compatibility check if these Chris@0: // keys are set and create a single test list. Chris@0: // @todo https://www.drupal.org/node/2748967 Remove BC support in Drupal 9. Chris@0: if (isset($test_list['simpletest'])) { Chris@0: $test_list = array_merge($test_list, $test_list['simpletest']); Chris@0: unset($test_list['simpletest']); Chris@0: } Chris@0: if (isset($test_list['phpunit'])) { Chris@0: $test_list = array_merge($test_list, $test_list['phpunit']); Chris@0: unset($test_list['phpunit']); Chris@0: } Chris@0: Chris@18: $test_id = \Drupal::database()->insert('simpletest_test_id') Chris@0: ->useDefaults(['test_id']) Chris@0: ->execute(); Chris@0: Chris@0: // Clear out the previous verbose files. Chris@18: try { Chris@18: \Drupal::service('file_system')->deleteRecursive('public://simpletest/verbose'); Chris@18: } Chris@18: catch (FileException $e) { Chris@18: // Ignore failed deletes. Chris@18: } Chris@0: Chris@0: // Get the info for the first test being run. Chris@0: $first_test = reset($test_list); Chris@0: $info = TestDiscovery::getTestInfo($first_test); Chris@0: Chris@0: $batch = [ Chris@0: 'title' => t('Running tests'), Chris@0: 'operations' => [ Chris@0: ['_simpletest_batch_operation', [$test_list, $test_id]], Chris@0: ], Chris@0: 'finished' => '_simpletest_batch_finished', Chris@0: 'progress_message' => '', Chris@0: 'library' => ['simpletest/drupal.simpletest'], Chris@0: 'init_message' => t('Processing test @num of @max - %test.', ['%test' => $info['name'], '@num' => '1', '@max' => count($test_list)]), Chris@0: ]; Chris@0: batch_set($batch); Chris@0: Chris@0: \Drupal::moduleHandler()->invokeAll('test_group_started'); Chris@0: Chris@0: return $test_id; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Executes PHPUnit tests and returns the results of the run. Chris@0: * Chris@0: * @param $test_id Chris@0: * The current test ID. Chris@0: * @param $unescaped_test_classnames Chris@0: * An array of test class names, including full namespaces, to be passed as Chris@0: * a regular expression to PHPUnit's --filter option. Chris@0: * @param int $status Chris@0: * (optional) The exit status code of the PHPUnit process will be assigned to Chris@0: * this variable. Chris@0: * Chris@0: * @return array Chris@0: * The parsed results of PHPUnit's JUnit XML output, in the format of Chris@0: * {simpletest}'s schema. Chris@0: */ Chris@0: function simpletest_run_phpunit_tests($test_id, array $unescaped_test_classnames, &$status = NULL) { Chris@0: $phpunit_file = simpletest_phpunit_xml_filepath($test_id); Chris@0: simpletest_phpunit_run_command($unescaped_test_classnames, $phpunit_file, $status, $output); Chris@0: Chris@0: $rows = []; Chris@0: if ($status == TestStatus::PASS) { Chris@0: $rows = simpletest_phpunit_xml_to_rows($test_id, $phpunit_file); Chris@0: } Chris@0: else { Chris@0: $rows[] = [ Chris@0: 'test_id' => $test_id, Chris@0: 'test_class' => implode(",", $unescaped_test_classnames), Chris@0: 'status' => TestStatus::label($status), Chris@0: 'message' => 'PHPunit Test failed to complete; Error: ' . implode("\n", $output), Chris@0: 'message_group' => 'Other', Chris@0: 'function' => implode(",", $unescaped_test_classnames), Chris@0: 'line' => '0', Chris@0: 'file' => $phpunit_file, Chris@0: ]; Chris@0: } Chris@0: return $rows; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Inserts the parsed PHPUnit results into {simpletest}. Chris@0: * Chris@0: * @param array[] $phpunit_results Chris@0: * An array of test results returned from simpletest_phpunit_xml_to_rows(). Chris@0: */ Chris@0: function simpletest_process_phpunit_results($phpunit_results) { Chris@0: // Insert the results of the PHPUnit test run into the database so the results Chris@0: // are displayed along with Simpletest's results. Chris@0: if (!empty($phpunit_results)) { Chris@0: $query = TestDatabase::getConnection() Chris@0: ->insert('simpletest') Chris@0: ->fields(array_keys($phpunit_results[0])); Chris@0: foreach ($phpunit_results as $result) { Chris@0: $query->values($result); Chris@0: } Chris@0: $query->execute(); Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Maps phpunit results to a data structure for batch messages and run-tests.sh. Chris@0: * Chris@0: * @param array $results Chris@0: * The output from simpletest_run_phpunit_tests(). Chris@0: * Chris@0: * @return array Chris@0: * The test result summary. A row per test class. Chris@0: */ Chris@0: function simpletest_summarize_phpunit_result($results) { Chris@0: $summaries = []; Chris@0: foreach ($results as $result) { Chris@0: if (!isset($summaries[$result['test_class']])) { Chris@0: $summaries[$result['test_class']] = [ Chris@0: '#pass' => 0, Chris@0: '#fail' => 0, Chris@0: '#exception' => 0, Chris@0: '#debug' => 0, Chris@0: ]; Chris@0: } Chris@0: Chris@0: switch ($result['status']) { Chris@0: case 'pass': Chris@0: $summaries[$result['test_class']]['#pass']++; Chris@0: break; Chris@0: Chris@0: case 'fail': Chris@0: $summaries[$result['test_class']]['#fail']++; Chris@0: break; Chris@0: Chris@0: case 'exception': Chris@0: $summaries[$result['test_class']]['#exception']++; Chris@0: break; Chris@0: Chris@0: case 'debug': Chris@0: $summaries[$result['test_class']]['#debug']++; Chris@0: break; Chris@0: } Chris@0: } Chris@0: return $summaries; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns the path to use for PHPUnit's --log-junit option. Chris@0: * Chris@0: * @param $test_id Chris@0: * The current test ID. Chris@0: * Chris@0: * @return string Chris@0: * Path to the PHPUnit XML file to use for the current $test_id. Chris@0: */ Chris@0: function simpletest_phpunit_xml_filepath($test_id) { Chris@0: return \Drupal::service('file_system')->realpath('public://simpletest') . '/phpunit-' . $test_id . '.xml'; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns the path to core's phpunit.xml.dist configuration file. Chris@0: * Chris@0: * @return string Chris@0: * The path to core's phpunit.xml.dist configuration file. Chris@0: * Chris@0: * @deprecated in Drupal 8.4.x for removal before Drupal 9.0.0. PHPUnit test Chris@0: * runners should change directory into core/ and then run the phpunit tool. Chris@0: * See simpletest_phpunit_run_command() for an example. Chris@0: * Chris@0: * @see simpletest_phpunit_run_command() Chris@0: */ Chris@0: function simpletest_phpunit_configuration_filepath() { Chris@0: @trigger_error('The ' . __FUNCTION__ . ' function is deprecated since version 8.4.x and will be removed in 9.0.0.', E_USER_DEPRECATED); Chris@0: return \Drupal::root() . '/core/phpunit.xml.dist'; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Executes the PHPUnit command. Chris@0: * Chris@0: * @param array $unescaped_test_classnames Chris@0: * An array of test class names, including full namespaces, to be passed as Chris@0: * a regular expression to PHPUnit's --filter option. Chris@0: * @param string $phpunit_file Chris@0: * A filepath to use for PHPUnit's --log-junit option. Chris@0: * @param int $status Chris@0: * (optional) The exit status code of the PHPUnit process will be assigned to Chris@0: * this variable. Chris@0: * @param string $output Chris@0: * (optional) The output by running the phpunit command. Chris@0: * Chris@0: * @return string Chris@0: * The results as returned by exec(). Chris@0: */ Chris@0: function simpletest_phpunit_run_command(array $unescaped_test_classnames, $phpunit_file, &$status = NULL, &$output = NULL) { Chris@0: global $base_url; Chris@0: // Setup an environment variable containing the database connection so that Chris@0: // functional tests can connect to the database. Chris@0: putenv('SIMPLETEST_DB=' . Database::getConnectionInfoAsUrl()); Chris@0: Chris@0: // Setup an environment variable containing the base URL, if it is available. Chris@0: // This allows functional tests to browse the site under test. When running Chris@0: // tests via CLI, core/phpunit.xml.dist or core/scripts/run-tests.sh can set Chris@0: // this variable. Chris@0: if ($base_url) { Chris@0: putenv('SIMPLETEST_BASE_URL=' . $base_url); Chris@0: putenv('BROWSERTEST_OUTPUT_DIRECTORY=' . \Drupal::service('file_system')->realpath('public://simpletest')); Chris@0: } Chris@0: $phpunit_bin = simpletest_phpunit_command(); Chris@0: Chris@0: $command = [ Chris@0: $phpunit_bin, Chris@0: '--log-junit', Chris@0: escapeshellarg($phpunit_file), Chris@0: '--printer', Chris@0: escapeshellarg(SimpletestUiPrinter::class), Chris@0: ]; Chris@0: Chris@0: // Optimized for running a single test. Chris@0: if (count($unescaped_test_classnames) == 1) { Chris@0: $class = new \ReflectionClass($unescaped_test_classnames[0]); Chris@0: $command[] = escapeshellarg($class->getFileName()); Chris@0: } Chris@0: else { Chris@0: // Double escape namespaces so they'll work in a regexp. Chris@0: $escaped_test_classnames = array_map(function ($class) { Chris@0: return addslashes($class); Chris@0: }, $unescaped_test_classnames); Chris@0: Chris@0: $filter_string = implode("|", $escaped_test_classnames); Chris@0: $command = array_merge($command, [ Chris@0: '--filter', Chris@0: escapeshellarg($filter_string), Chris@0: ]); Chris@0: } Chris@0: Chris@0: // Need to change directories before running the command so that we can use Chris@0: // relative paths in the configuration file's exclusions. Chris@0: $old_cwd = getcwd(); Chris@0: chdir(\Drupal::root() . "/core"); Chris@0: Chris@0: // exec in a subshell so that the environment is isolated when running tests Chris@0: // via the simpletest UI. Chris@0: $ret = exec(implode(" ", $command), $output, $status); Chris@0: Chris@0: chdir($old_cwd); Chris@0: putenv('SIMPLETEST_DB='); Chris@0: if ($base_url) { Chris@0: putenv('SIMPLETEST_BASE_URL='); Chris@0: putenv('BROWSERTEST_OUTPUT_DIRECTORY='); Chris@0: } Chris@0: return $ret; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns the command to run PHPUnit. Chris@0: * Chris@0: * @return string Chris@0: * The command that can be run through exec(). Chris@0: */ Chris@0: function simpletest_phpunit_command() { Chris@0: // Load the actual autoloader being used and determine its filename using Chris@0: // reflection. We can determine the vendor directory based on that filename. Chris@0: $autoloader = require \Drupal::root() . '/autoload.php'; Chris@0: $reflector = new ReflectionClass($autoloader); Chris@0: $vendor_dir = dirname(dirname($reflector->getFileName())); Chris@0: Chris@0: // The file in Composer's bin dir is a *nix link, which does not work when Chris@0: // extracted from a tarball and generally not on Windows. Chris@16: $command = escapeshellarg($vendor_dir . '/phpunit/phpunit/phpunit'); Chris@0: if (substr(PHP_OS, 0, 3) == 'WIN') { Chris@0: // On Windows it is necessary to run the script using the PHP executable. Chris@0: $php_executable_finder = new PhpExecutableFinder(); Chris@0: $php = $php_executable_finder->find(); Chris@16: $command = $php . ' -f ' . $command . ' --'; Chris@0: } Chris@0: return $command; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Implements callback_batch_operation(). Chris@0: */ Chris@0: function _simpletest_batch_operation($test_list_init, $test_id, &$context) { Chris@17: \Drupal::service('test_discovery')->registerTestNamespaces(); Chris@0: // Get working values. Chris@0: if (!isset($context['sandbox']['max'])) { Chris@0: // First iteration: initialize working values. Chris@0: $test_list = $test_list_init; Chris@0: $context['sandbox']['max'] = count($test_list); Chris@0: $test_results = ['#pass' => 0, '#fail' => 0, '#exception' => 0, '#debug' => 0]; Chris@0: } Chris@0: else { Chris@0: // Nth iteration: get the current values where we last stored them. Chris@0: $test_list = $context['sandbox']['tests']; Chris@0: $test_results = $context['sandbox']['test_results']; Chris@0: } Chris@0: $max = $context['sandbox']['max']; Chris@0: Chris@0: // Perform the next test. Chris@0: $test_class = array_shift($test_list); Chris@0: if (is_subclass_of($test_class, TestCase::class)) { Chris@0: $phpunit_results = simpletest_run_phpunit_tests($test_id, [$test_class]); Chris@0: simpletest_process_phpunit_results($phpunit_results); Chris@0: $test_results[$test_class] = simpletest_summarize_phpunit_result($phpunit_results)[$test_class]; Chris@0: } Chris@0: else { Chris@0: $test = new $test_class($test_id); Chris@0: $test->run(); Chris@0: \Drupal::moduleHandler()->invokeAll('test_finished', [$test->results]); Chris@0: $test_results[$test_class] = $test->results; Chris@0: } Chris@0: $size = count($test_list); Chris@0: $info = TestDiscovery::getTestInfo($test_class); Chris@0: Chris@0: // Gather results and compose the report. Chris@0: foreach ($test_results[$test_class] as $key => $value) { Chris@0: $test_results[$key] += $value; Chris@0: } Chris@0: $test_results[$test_class]['#name'] = $info['name']; Chris@0: $items = []; Chris@0: foreach (Element::children($test_results) as $class) { Chris@0: $class_test_result = $test_results[$class] + [ Chris@0: '#theme' => 'simpletest_result_summary', Chris@0: '#label' => t($test_results[$class]['#name'] . ':'), Chris@0: ]; Chris@0: array_unshift($items, \Drupal::service('renderer')->render($class_test_result)); Chris@0: } Chris@0: $context['message'] = t('Processed test @num of @max - %test.', ['%test' => $info['name'], '@num' => $max - $size, '@max' => $max]); Chris@0: $overall_results = $test_results + [ Chris@0: '#theme' => 'simpletest_result_summary', Chris@0: '#label' => t('Overall results:'), Chris@0: ]; Chris@0: $context['message'] .= \Drupal::service('renderer')->render($overall_results); Chris@0: Chris@0: $item_list = [ Chris@0: '#theme' => 'item_list', Chris@0: '#items' => $items, Chris@0: ]; Chris@0: $context['message'] .= \Drupal::service('renderer')->render($item_list); Chris@0: Chris@0: // Save working values for the next iteration. Chris@0: $context['sandbox']['tests'] = $test_list; Chris@0: $context['sandbox']['test_results'] = $test_results; Chris@0: // The test_id is the only thing we need to save for the report page. Chris@0: $context['results']['test_id'] = $test_id; Chris@0: Chris@0: // Multistep processing: report progress. Chris@0: $context['finished'] = 1 - $size / $max; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Implements callback_batch_finished(). Chris@0: */ Chris@0: function _simpletest_batch_finished($success, $results, $operations, $elapsed) { Chris@0: if ($success) { Chris@17: \Drupal::messenger()->addStatus(t('The test run finished in @elapsed.', ['@elapsed' => $elapsed])); Chris@0: } Chris@0: else { Chris@0: // Use the test_id passed as a parameter to _simpletest_batch_operation(). Chris@0: $test_id = $operations[0][1][1]; Chris@0: Chris@0: // Retrieve the last database prefix used for testing and the last test Chris@0: // class that was run from. Use the information to read the lgo file Chris@0: // in case any fatal errors caused the test to crash. Chris@0: list($last_prefix, $last_test_class) = simpletest_last_test_get($test_id); Chris@0: simpletest_log_read($test_id, $last_prefix, $last_test_class); Chris@0: Chris@17: \Drupal::messenger()->addError(t('The test run did not successfully finish.')); Chris@17: \Drupal::messenger()->addWarning(t('Use the Clean environment button to clean-up temporary files and tables.')); Chris@0: } Chris@0: \Drupal::moduleHandler()->invokeAll('test_group_finished'); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Get information about the last test that ran given a test ID. Chris@0: * Chris@0: * @param $test_id Chris@0: * The test ID to get the last test from. Chris@0: * @return array Chris@0: * Array containing the last database prefix used and the last test class Chris@0: * that ran. Chris@0: */ Chris@0: function simpletest_last_test_get($test_id) { Chris@0: $last_prefix = TestDatabase::getConnection() Chris@0: ->queryRange('SELECT last_prefix FROM {simpletest_test_id} WHERE test_id = :test_id', 0, 1, [ Chris@0: ':test_id' => $test_id, Chris@0: ]) Chris@0: ->fetchField(); Chris@0: $last_test_class = TestDatabase::getConnection() Chris@0: ->queryRange('SELECT test_class FROM {simpletest} WHERE test_id = :test_id ORDER BY message_id DESC', 0, 1, [ Chris@0: ':test_id' => $test_id, Chris@0: ]) Chris@0: ->fetchField(); Chris@0: return [$last_prefix, $last_test_class]; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Reads the error log and reports any errors as assertion failures. Chris@0: * Chris@0: * The errors in the log should only be fatal errors since any other errors Chris@0: * will have been recorded by the error handler. Chris@0: * Chris@0: * @param $test_id Chris@0: * The test ID to which the log relates. Chris@0: * @param $database_prefix Chris@0: * The database prefix to which the log relates. Chris@0: * @param $test_class Chris@0: * The test class to which the log relates. Chris@0: * Chris@0: * @return bool Chris@0: * Whether any fatal errors were found. Chris@0: */ Chris@0: function simpletest_log_read($test_id, $database_prefix, $test_class) { Chris@0: $test_db = new TestDatabase($database_prefix); Chris@0: $log = DRUPAL_ROOT . '/' . $test_db->getTestSitePath() . '/error.log'; Chris@0: $found = FALSE; Chris@0: if (file_exists($log)) { Chris@0: foreach (file($log) as $line) { Chris@0: if (preg_match('/\[.*?\] (.*?): (.*?) in (.*) on line (\d+)/', $line, $match)) { Chris@0: // Parse PHP fatal errors for example: PHP Fatal error: Call to Chris@0: // undefined function break_me() in /path/to/file.php on line 17 Chris@0: $caller = [ Chris@0: 'line' => $match[4], Chris@0: 'file' => $match[3], Chris@0: ]; Chris@0: TestBase::insertAssert($test_id, $test_class, FALSE, $match[2], $match[1], $caller); Chris@0: } Chris@0: else { Chris@0: // Unknown format, place the entire message in the log. Chris@0: TestBase::insertAssert($test_id, $test_class, FALSE, $line, 'Fatal error'); Chris@0: } Chris@0: $found = TRUE; Chris@0: } Chris@0: } Chris@0: return $found; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets a list of all of the tests provided by the system. Chris@0: * Chris@0: * The list of test classes is loaded by searching the designated directory for Chris@0: * each module for files matching the PSR-0 standard. Once loaded the test list Chris@0: * is cached and stored in a static variable. Chris@0: * Chris@0: * @param string $extension Chris@0: * (optional) The name of an extension to limit discovery to; e.g., 'node'. Chris@0: * @param string[] $types Chris@0: * An array of included test types. Chris@0: * Chris@0: * @return array[] Chris@0: * An array of tests keyed with the groups, and then keyed by test classes. Chris@0: * For example: Chris@0: * @code Chris@0: * $groups['Block'] => array( Chris@0: * 'BlockTestCase' => array( Chris@0: * 'name' => 'Block functionality', Chris@0: * 'description' => 'Add, edit and delete custom block.', Chris@0: * 'group' => 'Block', Chris@0: * ), Chris@0: * ); Chris@0: * @endcode Chris@0: * Chris@0: * @deprecated in Drupal 8.3.x, for removal before 9.0.0 release. Use Chris@0: * \Drupal::service('test_discovery')->getTestClasses($extension, $types) Chris@0: * instead. Chris@0: */ Chris@0: function simpletest_test_get_all($extension = NULL, array $types = []) { Chris@17: @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); Chris@0: return \Drupal::service('test_discovery')->getTestClasses($extension, $types); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Registers test namespaces of all extensions and core test classes. Chris@0: * Chris@0: * @deprecated in Drupal 8.3.x for removal before 9.0.0 release. Use Chris@0: * \Drupal::service('test_discovery')->registerTestNamespaces() instead. Chris@0: */ Chris@0: function simpletest_classloader_register() { Chris@17: @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); Chris@0: \Drupal::service('test_discovery')->registerTestNamespaces(); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Generates a test file. Chris@0: * Chris@0: * @param string $filename Chris@0: * The name of the file, including the path. The suffix '.txt' is appended to Chris@0: * the supplied file name and the file is put into the public:// files Chris@0: * directory. Chris@0: * @param int $width Chris@0: * The number of characters on one line. Chris@0: * @param int $lines Chris@0: * The number of lines in the file. Chris@0: * @param string $type Chris@0: * (optional) The type, one of: Chris@0: * - text: The generated file contains random ASCII characters. Chris@0: * - binary: The generated file contains random characters whose codes are in Chris@0: * the range of 0 to 31. Chris@0: * - binary-text: The generated file contains random sequence of '0' and '1' Chris@0: * values. Chris@0: * Chris@0: * @return string Chris@0: * The name of the file, including the path. Chris@0: */ Chris@0: function simpletest_generate_file($filename, $width, $lines, $type = 'binary-text') { Chris@0: $text = ''; Chris@0: for ($i = 0; $i < $lines; $i++) { Chris@0: // Generate $width - 1 characters to leave space for the "\n" character. Chris@0: for ($j = 0; $j < $width - 1; $j++) { Chris@0: switch ($type) { Chris@0: case 'text': Chris@0: $text .= chr(rand(32, 126)); Chris@0: break; Chris@0: case 'binary': Chris@0: $text .= chr(rand(0, 31)); Chris@0: break; Chris@0: case 'binary-text': Chris@0: default: Chris@0: $text .= rand(0, 1); Chris@0: break; Chris@0: } Chris@0: } Chris@0: $text .= "\n"; Chris@0: } Chris@0: Chris@0: // Create filename. Chris@0: file_put_contents('public://' . $filename . '.txt', $text); Chris@0: return $filename; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Removes all temporary database tables and directories. Chris@0: */ Chris@0: function simpletest_clean_environment() { Chris@0: simpletest_clean_database(); Chris@0: simpletest_clean_temporary_directories(); Chris@0: if (\Drupal::config('simpletest.settings')->get('clear_results')) { Chris@0: $count = simpletest_clean_results_table(); Chris@17: \Drupal::messenger()->addStatus(\Drupal::translation()->formatPlural($count, 'Removed 1 test result.', 'Removed @count test results.')); Chris@0: } Chris@0: else { Chris@17: \Drupal::messenger()->addWarning(t('Clear results is disabled and the test results table will not be cleared.'), 'warning'); Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Removes prefixed tables from the database from crashed tests. Chris@0: */ Chris@0: function simpletest_clean_database() { Chris@17: $schema = Database::getConnection()->schema(); Chris@18: $tables = $schema->findTables('test%'); Chris@0: $count = 0; Chris@0: foreach ($tables as $table) { Chris@0: // Only drop tables which begin wih 'test' followed by digits, for example, Chris@0: // {test12345678node__body}. Chris@0: if (preg_match('/^test\d+.*/', $table, $matches)) { Chris@17: $schema->dropTable($matches[0]); Chris@0: $count++; Chris@0: } Chris@0: } Chris@0: Chris@0: if ($count > 0) { Chris@17: \Drupal::messenger()->addStatus(\Drupal::translation()->formatPlural($count, 'Removed 1 leftover table.', 'Removed @count leftover tables.')); Chris@0: } Chris@0: else { Chris@17: \Drupal::messenger()->addStatus(t('No leftover tables to remove.')); Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Finds all leftover temporary directories and removes them. Chris@0: */ Chris@0: function simpletest_clean_temporary_directories() { Chris@0: $count = 0; Chris@0: if (is_dir(DRUPAL_ROOT . '/sites/simpletest')) { Chris@0: $files = scandir(DRUPAL_ROOT . '/sites/simpletest'); Chris@0: foreach ($files as $file) { Chris@0: if ($file[0] != '.') { Chris@0: $path = DRUPAL_ROOT . '/sites/simpletest/' . $file; Chris@18: try { Chris@18: \Drupal::service('file_system')->deleteRecursive($path, function ($any_path) { Chris@18: @chmod($any_path, 0700); Chris@18: }); Chris@18: } Chris@18: catch (FileException $e) { Chris@18: // Ignore failed deletes. Chris@18: } Chris@0: $count++; Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: if ($count > 0) { Chris@17: \Drupal::messenger()->addStatus(\Drupal::translation()->formatPlural($count, 'Removed 1 temporary directory.', 'Removed @count temporary directories.')); Chris@0: } Chris@0: else { Chris@17: \Drupal::messenger()->addStatus(t('No temporary directories to remove.')); Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Clears the test result tables. Chris@0: * Chris@0: * @param $test_id Chris@0: * Test ID to remove results for, or NULL to remove all results. Chris@0: * Chris@0: * @return int Chris@0: * The number of results that were removed. Chris@0: */ Chris@0: function simpletest_clean_results_table($test_id = NULL) { Chris@0: if (\Drupal::config('simpletest.settings')->get('clear_results')) { Chris@0: $connection = TestDatabase::getConnection(); Chris@0: if ($test_id) { Chris@0: $count = $connection->query('SELECT COUNT(test_id) FROM {simpletest_test_id} WHERE test_id = :test_id', [':test_id' => $test_id])->fetchField(); Chris@0: Chris@0: $connection->delete('simpletest') Chris@0: ->condition('test_id', $test_id) Chris@0: ->execute(); Chris@0: $connection->delete('simpletest_test_id') Chris@0: ->condition('test_id', $test_id) Chris@0: ->execute(); Chris@0: } Chris@0: else { Chris@0: $count = $connection->query('SELECT COUNT(test_id) FROM {simpletest_test_id}')->fetchField(); Chris@0: Chris@0: // Clear test results. Chris@0: $connection->delete('simpletest')->execute(); Chris@0: $connection->delete('simpletest_test_id')->execute(); Chris@0: } Chris@0: Chris@0: return $count; Chris@0: } Chris@0: return 0; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Implements hook_mail_alter(). Chris@0: * Chris@0: * Aborts sending of messages with ID 'simpletest_cancel_test'. Chris@0: * Chris@0: * @see MailTestCase::testCancelMessage() Chris@0: */ Chris@0: function simpletest_mail_alter(&$message) { Chris@0: if ($message['id'] == 'simpletest_cancel_test') { Chris@0: $message['send'] = FALSE; Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Converts PHPUnit's JUnit XML output to an array. Chris@0: * Chris@0: * @param $test_id Chris@0: * The current test ID. Chris@0: * @param $phpunit_xml_file Chris@0: * Path to the PHPUnit XML file. Chris@0: * Chris@0: * @return array[]|null Chris@0: * The results as array of rows in a format that can be inserted into Chris@0: * {simpletest}. If the phpunit_xml_file does not have any contents then the Chris@0: * function will return NULL. Chris@0: */ Chris@0: function simpletest_phpunit_xml_to_rows($test_id, $phpunit_xml_file) { Chris@0: $contents = @file_get_contents($phpunit_xml_file); Chris@0: if (!$contents) { Chris@0: return; Chris@0: } Chris@0: $records = []; Chris@0: $testcases = simpletest_phpunit_find_testcases(new SimpleXMLElement($contents)); Chris@0: foreach ($testcases as $testcase) { Chris@0: $records[] = simpletest_phpunit_testcase_to_row($test_id, $testcase); Chris@0: } Chris@0: return $records; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Finds all test cases recursively from a test suite list. Chris@0: * Chris@0: * @param \SimpleXMLElement $element Chris@0: * The PHPUnit xml to search for test cases. Chris@0: * @param \SimpleXMLElement $parent Chris@0: * (Optional) The parent of the current element. Defaults to NULL. Chris@0: * Chris@0: * @return array Chris@0: * A list of all test cases. Chris@0: */ Chris@0: function simpletest_phpunit_find_testcases(\SimpleXMLElement $element, \SimpleXMLElement $parent = NULL) { Chris@0: $testcases = []; Chris@0: Chris@0: if (!isset($parent)) { Chris@0: $parent = $element; Chris@0: } Chris@0: Chris@0: if ($element->getName() === 'testcase' && (int) $parent->attributes()->tests > 0) { Chris@0: // Add the class attribute if the testcase does not have one. This is the Chris@0: // case for tests using a data provider. The name of the parent testsuite Chris@0: // will be in the format class::method. Chris@0: if (!$element->attributes()->class) { Chris@0: $name = explode('::', $parent->attributes()->name, 2); Chris@0: $element->addAttribute('class', $name[0]); Chris@0: } Chris@0: $testcases[] = $element; Chris@0: } Chris@0: else { Chris@0: foreach ($element as $child) { Chris@0: $file = (string) $parent->attributes()->file; Chris@0: if ($file && !$child->attributes()->file) { Chris@0: $child->addAttribute('file', $file); Chris@0: } Chris@0: $testcases = array_merge($testcases, simpletest_phpunit_find_testcases($child, $element)); Chris@0: } Chris@0: } Chris@0: return $testcases; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Converts a PHPUnit test case result to a {simpletest} result row. Chris@0: * Chris@0: * @param int $test_id Chris@0: * The current test ID. Chris@0: * @param \SimpleXMLElement $testcase Chris@0: * The PHPUnit test case represented as XML element. Chris@0: * Chris@0: * @return array Chris@0: * An array containing the {simpletest} result row. Chris@0: */ Chris@0: function simpletest_phpunit_testcase_to_row($test_id, \SimpleXMLElement $testcase) { Chris@0: $message = ''; Chris@0: $pass = TRUE; Chris@0: if ($testcase->failure) { Chris@0: $lines = explode("\n", $testcase->failure); Chris@0: $message = $lines[2]; Chris@0: $pass = FALSE; Chris@0: } Chris@0: if ($testcase->error) { Chris@0: $message = $testcase->error; Chris@0: $pass = FALSE; Chris@0: } Chris@0: Chris@0: $attributes = $testcase->attributes(); Chris@0: Chris@17: $function = $attributes->class . '->' . $attributes->name . '()'; Chris@0: $record = [ Chris@0: 'test_id' => $test_id, Chris@0: 'test_class' => (string) $attributes->class, Chris@0: 'status' => $pass ? 'pass' : 'fail', Chris@0: 'message' => $message, Chris@0: // @todo: Check on the proper values for this. Chris@0: 'message_group' => 'Other', Chris@17: 'function' => $function, Chris@0: 'line' => $attributes->line ?: 0, Chris@17: // There are situations when the file will not be present because a PHPUnit Chris@17: // @requires has caused a test to be skipped. Chris@17: 'file' => $attributes->file ?: $function, Chris@0: ]; Chris@0: return $record; Chris@0: }