annotate core/modules/simpletest/simpletest.module @ 0:c75dbcec494b

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