annotate core/scripts/run-tests.sh @ 19:fa3358dc1485 tip

Add ndrum files
author Chris Cannam
date Wed, 28 Aug 2019 13:14:47 +0100
parents af1871eacc83
children
rev   line source
Chris@0 1 <?php
Chris@0 2
Chris@0 3 /**
Chris@0 4 * @file
Chris@0 5 * This script runs Drupal tests from command line.
Chris@0 6 */
Chris@0 7
Chris@0 8 use Drupal\Component\FileSystem\FileSystem;
Chris@0 9 use Drupal\Component\Utility\Html;
Chris@0 10 use Drupal\Component\Utility\Timer;
Chris@0 11 use Drupal\Component\Uuid\Php;
Chris@14 12 use Drupal\Core\Composer\Composer;
Chris@14 13 use Drupal\Core\Asset\AttachedAssets;
Chris@0 14 use Drupal\Core\Database\Database;
Chris@18 15 use Drupal\Core\File\Exception\FileException;
Chris@18 16 use Drupal\Core\File\FileSystemInterface;
Chris@0 17 use Drupal\Core\StreamWrapper\PublicStream;
Chris@0 18 use Drupal\Core\Test\TestDatabase;
Chris@0 19 use Drupal\Core\Test\TestRunnerKernel;
Chris@0 20 use Drupal\simpletest\Form\SimpletestResultsForm;
Chris@0 21 use Drupal\simpletest\TestBase;
Chris@0 22 use Drupal\simpletest\TestDiscovery;
Chris@0 23 use PHPUnit\Framework\TestCase;
Chris@14 24 use PHPUnit\Runner\Version;
Chris@0 25 use Symfony\Component\HttpFoundation\Request;
Chris@0 26
Chris@0 27 // Define some colors for display.
Chris@0 28 // A nice calming green.
Chris@0 29 const SIMPLETEST_SCRIPT_COLOR_PASS = 32;
Chris@0 30 // An alerting Red.
Chris@0 31 const SIMPLETEST_SCRIPT_COLOR_FAIL = 31;
Chris@0 32 // An annoying brown.
Chris@0 33 const SIMPLETEST_SCRIPT_COLOR_EXCEPTION = 33;
Chris@0 34
Chris@0 35 // Restricting the chunk of queries prevents memory exhaustion.
Chris@0 36 const SIMPLETEST_SCRIPT_SQLITE_VARIABLE_LIMIT = 350;
Chris@0 37
Chris@0 38 const SIMPLETEST_SCRIPT_EXIT_SUCCESS = 0;
Chris@0 39 const SIMPLETEST_SCRIPT_EXIT_FAILURE = 1;
Chris@0 40 const SIMPLETEST_SCRIPT_EXIT_EXCEPTION = 2;
Chris@0 41
Chris@0 42 // Set defaults and get overrides.
Chris@0 43 list($args, $count) = simpletest_script_parse_args();
Chris@0 44
Chris@0 45 if ($args['help'] || $count == 0) {
Chris@0 46 simpletest_script_help();
Chris@0 47 exit(($count == 0) ? SIMPLETEST_SCRIPT_EXIT_FAILURE : SIMPLETEST_SCRIPT_EXIT_SUCCESS);
Chris@0 48 }
Chris@0 49
Chris@0 50 simpletest_script_init();
Chris@0 51
Chris@14 52 if (!class_exists(TestCase::class)) {
Chris@16 53 echo "\nrun-tests.sh requires the PHPUnit testing framework. Please use 'composer install' to ensure that it is present.\n\n";
Chris@14 54 exit(SIMPLETEST_SCRIPT_EXIT_FAILURE);
Chris@0 55 }
Chris@0 56
Chris@0 57 if ($args['execute-test']) {
Chris@0 58 simpletest_script_setup_database();
Chris@0 59 simpletest_script_run_one_test($args['test-id'], $args['execute-test']);
Chris@0 60 // Sub-process exited already; this is just for clarity.
Chris@0 61 exit(SIMPLETEST_SCRIPT_EXIT_SUCCESS);
Chris@0 62 }
Chris@0 63
Chris@0 64 if ($args['list']) {
Chris@18 65 // Display all available tests organized by one @group annotation.
Chris@0 66 echo "\nAvailable test groups & classes\n";
Chris@0 67 echo "-------------------------------\n\n";
Chris@0 68 try {
Chris@17 69 $groups = \Drupal::service('test_discovery')->getTestClasses($args['module']);
Chris@0 70 }
Chris@0 71 catch (Exception $e) {
Chris@0 72 error_log((string) $e);
Chris@0 73 echo (string) $e;
Chris@0 74 exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
Chris@0 75 }
Chris@18 76
Chris@18 77 // A given class can appear in multiple groups. For historical reasons, we
Chris@18 78 // need to present each test only once. The test is shown in the group that is
Chris@18 79 // printed first.
Chris@18 80 $printed_tests = [];
Chris@0 81 foreach ($groups as $group => $tests) {
Chris@0 82 echo $group . "\n";
Chris@18 83 $tests = array_diff(array_keys($tests), $printed_tests);
Chris@18 84 foreach ($tests as $test) {
Chris@18 85 echo " - $test\n";
Chris@0 86 }
Chris@18 87 $printed_tests = array_merge($printed_tests, $tests);
Chris@0 88 }
Chris@0 89 exit(SIMPLETEST_SCRIPT_EXIT_SUCCESS);
Chris@0 90 }
Chris@0 91
Chris@0 92 // List-files and list-files-json provide a way for external tools such as the
Chris@0 93 // testbot to prioritize running changed tests.
Chris@0 94 // @see https://www.drupal.org/node/2569585
Chris@0 95 if ($args['list-files'] || $args['list-files-json']) {
Chris@0 96 // List all files which could be run as tests.
Chris@0 97 $test_discovery = NULL;
Chris@0 98 try {
Chris@0 99 $test_discovery = \Drupal::service('test_discovery');
Chris@14 100 }
Chris@14 101 catch (Exception $e) {
Chris@0 102 error_log((string) $e);
Chris@14 103 echo (string) $e;
Chris@0 104 exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
Chris@0 105 }
Chris@0 106 // TestDiscovery::findAllClassFiles() gives us a classmap similar to a
Chris@0 107 // Composer 'classmap' array.
Chris@0 108 $test_classes = $test_discovery->findAllClassFiles();
Chris@0 109 // JSON output is the easiest.
Chris@0 110 if ($args['list-files-json']) {
Chris@0 111 echo json_encode($test_classes);
Chris@0 112 exit(SIMPLETEST_SCRIPT_EXIT_SUCCESS);
Chris@0 113 }
Chris@0 114 // Output the list of files.
Chris@0 115 else {
Chris@14 116 foreach (array_values($test_classes) as $test_class) {
Chris@0 117 echo $test_class . "\n";
Chris@0 118 }
Chris@0 119 }
Chris@0 120 exit(SIMPLETEST_SCRIPT_EXIT_SUCCESS);
Chris@0 121 }
Chris@0 122
Chris@0 123 simpletest_script_setup_database(TRUE);
Chris@0 124
Chris@0 125 if ($args['clean']) {
Chris@0 126 // Clean up left-over tables and directories.
Chris@0 127 try {
Chris@0 128 simpletest_clean_environment();
Chris@0 129 }
Chris@0 130 catch (Exception $e) {
Chris@0 131 echo (string) $e;
Chris@0 132 exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
Chris@0 133 }
Chris@0 134 echo "\nEnvironment cleaned.\n";
Chris@0 135
Chris@0 136 // Get the status messages and print them.
Chris@17 137 $messages = \Drupal::messenger()->messagesByType('status');
Chris@17 138 foreach ($messages as $text) {
Chris@0 139 echo " - " . $text . "\n";
Chris@0 140 }
Chris@0 141 exit(SIMPLETEST_SCRIPT_EXIT_SUCCESS);
Chris@0 142 }
Chris@0 143
Chris@14 144 // Ensure we have the correct PHPUnit version for the version of PHP.
Chris@14 145 if (class_exists('\PHPUnit_Runner_Version')) {
Chris@14 146 $phpunit_version = \PHPUnit_Runner_Version::id();
Chris@14 147 }
Chris@14 148 else {
Chris@14 149 $phpunit_version = Version::id();
Chris@14 150 }
Chris@14 151 if (!Composer::upgradePHPUnitCheck($phpunit_version)) {
Chris@17 152 simpletest_script_print_error("PHPUnit testing framework version 6 or greater is required when running on PHP 7.0 or greater. Run the command 'composer run-script drupal-phpunit-upgrade' in order to fix this.");
Chris@14 153 exit(SIMPLETEST_SCRIPT_EXIT_FAILURE);
Chris@14 154 }
Chris@14 155
Chris@0 156 $test_list = simpletest_script_get_test_list();
Chris@0 157
Chris@0 158 // Try to allocate unlimited time to run the tests.
Chris@0 159 drupal_set_time_limit(0);
Chris@0 160 simpletest_script_reporter_init();
Chris@0 161
Chris@14 162 $tests_to_run = [];
Chris@0 163 for ($i = 0; $i < $args['repeat']; $i++) {
Chris@0 164 $tests_to_run = array_merge($tests_to_run, $test_list);
Chris@0 165 }
Chris@0 166
Chris@0 167 // Execute tests.
Chris@0 168 $status = simpletest_script_execute_batch($tests_to_run);
Chris@0 169
Chris@0 170 // Stop the timer.
Chris@0 171 simpletest_script_reporter_timer_stop();
Chris@0 172
Chris@0 173 // Ensure all test locks are released once finished. If tests are run with a
Chris@0 174 // concurrency of 1 the each test will clean up its own lock. Test locks are
Chris@0 175 // not released if using a higher concurrency to ensure each test method has
Chris@0 176 // unique fixtures.
Chris@0 177 TestDatabase::releaseAllTestLocks();
Chris@0 178
Chris@0 179 // Display results before database is cleared.
Chris@0 180 if ($args['browser']) {
Chris@0 181 simpletest_script_open_browser();
Chris@0 182 }
Chris@0 183 else {
Chris@0 184 simpletest_script_reporter_display_results();
Chris@0 185 }
Chris@0 186
Chris@0 187 if ($args['xml']) {
Chris@0 188 simpletest_script_reporter_write_xml_results();
Chris@0 189 }
Chris@0 190
Chris@0 191 // Clean up all test results.
Chris@0 192 if (!$args['keep-results']) {
Chris@0 193 try {
Chris@0 194 simpletest_clean_results_table();
Chris@0 195 }
Chris@0 196 catch (Exception $e) {
Chris@0 197 echo (string) $e;
Chris@0 198 exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
Chris@0 199 }
Chris@0 200 }
Chris@0 201
Chris@0 202 // Test complete, exit.
Chris@0 203 exit($status);
Chris@0 204
Chris@0 205 /**
Chris@0 206 * Print help text.
Chris@0 207 */
Chris@0 208 function simpletest_script_help() {
Chris@0 209 global $args;
Chris@0 210
Chris@0 211 echo <<<EOF
Chris@0 212
Chris@0 213 Run Drupal tests from the shell.
Chris@0 214
Chris@0 215 Usage: {$args['script']} [OPTIONS] <tests>
Chris@0 216 Example: {$args['script']} Profile
Chris@0 217
Chris@0 218 All arguments are long options.
Chris@0 219
Chris@0 220 --help Print this page.
Chris@0 221
Chris@0 222 --list Display all available test groups.
Chris@0 223
Chris@0 224 --list-files
Chris@0 225 Display all discoverable test file paths.
Chris@0 226
Chris@0 227 --list-files-json
Chris@0 228 Display all discoverable test files as JSON. The array key will be
Chris@0 229 the test class name, and the value will be the file path of the
Chris@0 230 test.
Chris@0 231
Chris@0 232 --clean Cleans up database tables or directories from previous, failed,
Chris@0 233 tests and then exits (no tests are run).
Chris@0 234
Chris@0 235 --url The base URL of the root directory of this Drupal checkout; e.g.:
Chris@0 236 http://drupal.test/
Chris@0 237 Required unless the Drupal root directory maps exactly to:
Chris@0 238 http://localhost:80/
Chris@0 239 Use a https:// URL to force all tests to be run under SSL.
Chris@0 240
Chris@0 241 --sqlite A pathname to use for the SQLite database of the test runner.
Chris@0 242 Required unless this script is executed with a working Drupal
Chris@0 243 installation that has Simpletest module installed.
Chris@0 244 A relative pathname is interpreted relative to the Drupal root
Chris@0 245 directory.
Chris@0 246 Note that ':memory:' cannot be used, because this script spawns
Chris@0 247 sub-processes. However, you may use e.g. '/tmpfs/test.sqlite'
Chris@0 248
Chris@0 249 --keep-results-table
Chris@0 250
Chris@0 251 Boolean flag to indicate to not cleanup the simpletest result
Chris@0 252 table. For testbots or repeated execution of a single test it can
Chris@0 253 be helpful to not cleanup the simpletest result table.
Chris@0 254
Chris@0 255 --dburl A URI denoting the database driver, credentials, server hostname,
Chris@0 256 and database name to use in tests.
Chris@0 257 Required when running tests without a Drupal installation that
Chris@0 258 contains default database connection info in settings.php.
Chris@0 259 Examples:
Chris@0 260 mysql://username:password@localhost/databasename#table_prefix
Chris@0 261 sqlite://localhost/relative/path/db.sqlite
Chris@0 262 sqlite://localhost//absolute/path/db.sqlite
Chris@0 263
Chris@0 264 --php The absolute path to the PHP executable. Usually not needed.
Chris@0 265
Chris@0 266 --concurrency [num]
Chris@0 267
Chris@0 268 Run tests in parallel, up to [num] tests at a time.
Chris@0 269
Chris@0 270 --all Run all available tests.
Chris@0 271
Chris@0 272 --module Run all tests belonging to the specified module name.
Chris@0 273 (e.g., 'node')
Chris@0 274
Chris@0 275 --class Run tests identified by specific class names, instead of group names.
Chris@0 276 A specific test method can be added, for example,
Chris@0 277 'Drupal\book\Tests\BookTest::testBookExport'.
Chris@0 278
Chris@0 279 --file Run tests identified by specific file names, instead of group names.
Chris@0 280 Specify the path and the extension
Chris@0 281 (i.e. 'core/modules/user/user.test').
Chris@0 282
Chris@0 283 --types
Chris@0 284
Chris@0 285 Runs just tests from the specified test type, for example
Chris@0 286 run-tests.sh
Chris@0 287 (i.e. --types "Simpletest,PHPUnit-Functional")
Chris@0 288
Chris@0 289 --directory Run all tests found within the specified file directory.
Chris@0 290
Chris@0 291 --xml <path>
Chris@0 292
Chris@0 293 If provided, test results will be written as xml files to this path.
Chris@0 294
Chris@0 295 --color Output text format results with color highlighting.
Chris@0 296
Chris@0 297 --verbose Output detailed assertion messages in addition to summary.
Chris@0 298
Chris@0 299 --keep-results
Chris@0 300
Chris@0 301 Keeps detailed assertion results (in the database) after tests
Chris@0 302 have completed. By default, assertion results are cleared.
Chris@0 303
Chris@0 304 --repeat Number of times to repeat the test.
Chris@0 305
Chris@0 306 --die-on-fail
Chris@0 307
Chris@0 308 Exit test execution immediately upon any failed assertion. This
Chris@0 309 allows to access the test site by changing settings.php to use the
Chris@0 310 test database and configuration directories. Use in combination
Chris@0 311 with --repeat for debugging random test failures.
Chris@0 312
Chris@0 313 --browser Opens the results in the browser. This enforces --keep-results and
Chris@0 314 if you want to also view any pages rendered in the simpletest
Chris@0 315 browser you need to add --verbose to the command line.
Chris@0 316
Chris@0 317 --non-html Removes escaping from output. Useful for reading results on the
Chris@0 318 CLI.
Chris@0 319
Chris@12 320 --suppress-deprecations
Chris@12 321
Chris@17 322 Stops tests from failing if deprecation errors are triggered. If
Chris@17 323 this is not set the value specified in the
Chris@17 324 SYMFONY_DEPRECATIONS_HELPER environment variable, or the value
Chris@17 325 specified in core/phpunit.xml (if it exists), or the default value
Chris@17 326 will be used. The default is that any unexpected silenced
Chris@17 327 deprecation error will fail tests.
Chris@12 328
Chris@0 329 <test1>[,<test2>[,<test3> ...]]
Chris@0 330
Chris@0 331 One or more tests to be run. By default, these are interpreted
Chris@0 332 as the names of test groups as shown at
Chris@0 333 admin/config/development/testing.
Chris@0 334 These group names typically correspond to module names like "User"
Chris@0 335 or "Profile" or "System", but there is also a group "Database".
Chris@0 336 If --class is specified then these are interpreted as the names of
Chris@0 337 specific test classes whose test methods will be run. Tests must
Chris@0 338 be separated by commas. Ignored if --all is specified.
Chris@0 339
Chris@0 340 To run this script you will normally invoke it from the root directory of your
Chris@0 341 Drupal installation as the webserver user (differs per configuration), or root:
Chris@0 342
Chris@0 343 sudo -u [wwwrun|www-data|etc] php ./core/scripts/{$args['script']}
Chris@0 344 --url http://example.com/ --all
Chris@0 345 sudo -u [wwwrun|www-data|etc] php ./core/scripts/{$args['script']}
Chris@0 346 --url http://example.com/ --class "Drupal\block\Tests\BlockTest"
Chris@0 347
Chris@0 348 Without a preinstalled Drupal site and enabled Simpletest module, specify a
Chris@0 349 SQLite database pathname to create and the default database connection info to
Chris@0 350 use in tests:
Chris@0 351
Chris@0 352 sudo -u [wwwrun|www-data|etc] php ./core/scripts/{$args['script']}
Chris@0 353 --sqlite /tmpfs/drupal/test.sqlite
Chris@0 354 --dburl mysql://username:password@localhost/database
Chris@0 355 --url http://example.com/ --all
Chris@0 356
Chris@0 357 EOF;
Chris@0 358 }
Chris@0 359
Chris@0 360 /**
Chris@0 361 * Parse execution argument and ensure that all are valid.
Chris@0 362 *
Chris@0 363 * @return array
Chris@0 364 * The list of arguments.
Chris@0 365 */
Chris@0 366 function simpletest_script_parse_args() {
Chris@0 367 // Set default values.
Chris@14 368 $args = [
Chris@0 369 'script' => '',
Chris@0 370 'help' => FALSE,
Chris@0 371 'list' => FALSE,
Chris@0 372 'list-files' => FALSE,
Chris@0 373 'list-files-json' => FALSE,
Chris@0 374 'clean' => FALSE,
Chris@0 375 'url' => '',
Chris@0 376 'sqlite' => NULL,
Chris@0 377 'dburl' => NULL,
Chris@0 378 'php' => '',
Chris@0 379 'concurrency' => 1,
Chris@0 380 'all' => FALSE,
Chris@0 381 'module' => NULL,
Chris@0 382 'class' => FALSE,
Chris@0 383 'file' => FALSE,
Chris@0 384 'types' => [],
Chris@0 385 'directory' => NULL,
Chris@0 386 'color' => FALSE,
Chris@0 387 'verbose' => FALSE,
Chris@0 388 'keep-results' => FALSE,
Chris@0 389 'keep-results-table' => FALSE,
Chris@14 390 'test_names' => [],
Chris@0 391 'repeat' => 1,
Chris@0 392 'die-on-fail' => FALSE,
Chris@12 393 'suppress-deprecations' => FALSE,
Chris@0 394 'browser' => FALSE,
Chris@0 395 // Used internally.
Chris@0 396 'test-id' => 0,
Chris@0 397 'execute-test' => '',
Chris@0 398 'xml' => '',
Chris@0 399 'non-html' => FALSE,
Chris@14 400 ];
Chris@0 401
Chris@0 402 // Override with set values.
Chris@0 403 $args['script'] = basename(array_shift($_SERVER['argv']));
Chris@0 404
Chris@0 405 $count = 0;
Chris@0 406 while ($arg = array_shift($_SERVER['argv'])) {
Chris@0 407 if (preg_match('/--(\S+)/', $arg, $matches)) {
Chris@0 408 // Argument found.
Chris@0 409 if (array_key_exists($matches[1], $args)) {
Chris@0 410 // Argument found in list.
Chris@0 411 $previous_arg = $matches[1];
Chris@0 412 if (is_bool($args[$previous_arg])) {
Chris@0 413 $args[$matches[1]] = TRUE;
Chris@0 414 }
Chris@0 415 elseif (is_array($args[$previous_arg])) {
Chris@0 416 $value = array_shift($_SERVER['argv']);
Chris@0 417 $args[$matches[1]] = array_map('trim', explode(',', $value));
Chris@0 418 }
Chris@0 419 else {
Chris@0 420 $args[$matches[1]] = array_shift($_SERVER['argv']);
Chris@0 421 }
Chris@0 422 // Clear extraneous values.
Chris@14 423 $args['test_names'] = [];
Chris@0 424 $count++;
Chris@0 425 }
Chris@0 426 else {
Chris@0 427 // Argument not found in list.
Chris@0 428 simpletest_script_print_error("Unknown argument '$arg'.");
Chris@0 429 exit(SIMPLETEST_SCRIPT_EXIT_FAILURE);
Chris@0 430 }
Chris@0 431 }
Chris@0 432 else {
Chris@0 433 // Values found without an argument should be test names.
Chris@0 434 $args['test_names'] += explode(',', $arg);
Chris@0 435 $count++;
Chris@0 436 }
Chris@0 437 }
Chris@0 438
Chris@0 439 // Validate the concurrency argument.
Chris@0 440 if (!is_numeric($args['concurrency']) || $args['concurrency'] <= 0) {
Chris@0 441 simpletest_script_print_error("--concurrency must be a strictly positive integer.");
Chris@0 442 exit(SIMPLETEST_SCRIPT_EXIT_FAILURE);
Chris@0 443 }
Chris@0 444
Chris@0 445 if ($args['browser']) {
Chris@0 446 $args['keep-results'] = TRUE;
Chris@0 447 }
Chris@14 448 return [$args, $count];
Chris@0 449 }
Chris@0 450
Chris@0 451 /**
Chris@0 452 * Initialize script variables and perform general setup requirements.
Chris@0 453 */
Chris@0 454 function simpletest_script_init() {
Chris@0 455 global $args, $php;
Chris@0 456
Chris@0 457 $host = 'localhost';
Chris@0 458 $path = '';
Chris@0 459 $port = '80';
Chris@0 460
Chris@0 461 // Determine location of php command automatically, unless a command line
Chris@0 462 // argument is supplied.
Chris@0 463 if (!empty($args['php'])) {
Chris@0 464 $php = $args['php'];
Chris@0 465 }
Chris@0 466 elseif ($php_env = getenv('_')) {
Chris@0 467 // '_' is an environment variable set by the shell. It contains the command
Chris@0 468 // that was executed.
Chris@0 469 $php = $php_env;
Chris@0 470 }
Chris@0 471 elseif ($sudo = getenv('SUDO_COMMAND')) {
Chris@0 472 // 'SUDO_COMMAND' is an environment variable set by the sudo program.
Chris@0 473 // Extract only the PHP interpreter, not the rest of the command.
Chris@0 474 list($php) = explode(' ', $sudo, 2);
Chris@0 475 }
Chris@0 476 else {
Chris@0 477 simpletest_script_print_error('Unable to automatically determine the path to the PHP interpreter. Supply the --php command line argument.');
Chris@0 478 simpletest_script_help();
Chris@0 479 exit(SIMPLETEST_SCRIPT_EXIT_FAILURE);
Chris@0 480 }
Chris@0 481
Chris@14 482 // Detect if we're in the top-level process using the private 'execute-test'
Chris@14 483 // argument. Determine if being run on drupal.org's testing infrastructure
Chris@14 484 // using the presence of 'drupaltestbot' in the database url.
Chris@14 485 // @todo https://www.drupal.org/project/drupalci_testbot/issues/2860941 Use
Chris@14 486 // better environment variable to detect DrupalCI.
Chris@14 487 // @todo https://www.drupal.org/project/drupal/issues/2942473 Remove when
Chris@14 488 // dropping PHPUnit 4 and PHP 5 support.
Chris@14 489 if (!$args['execute-test'] && preg_match('/drupalci/', $args['sqlite'])) {
Chris@14 490 // Update PHPUnit if needed and possible. There is a later check once the
Chris@14 491 // autoloader is in place to ensure we're on the correct version. We need to
Chris@14 492 // do this before the autoloader is in place to ensure that it is correct.
Chris@14 493 $composer = ($composer = rtrim('\\' === DIRECTORY_SEPARATOR ? preg_replace('/[\r\n].*/', '', `where.exe composer.phar`) : `which composer.phar`))
Chris@14 494 ? $php . ' ' . escapeshellarg($composer)
Chris@14 495 : 'composer';
Chris@14 496 passthru("$composer run-script drupal-phpunit-upgrade-check");
Chris@14 497 }
Chris@14 498
Chris@14 499 $autoloader = require_once __DIR__ . '/../../autoload.php';
Chris@14 500
Chris@0 501 // Get URL from arguments.
Chris@0 502 if (!empty($args['url'])) {
Chris@0 503 $parsed_url = parse_url($args['url']);
Chris@0 504 $host = $parsed_url['host'] . (isset($parsed_url['port']) ? ':' . $parsed_url['port'] : '');
Chris@0 505 $path = isset($parsed_url['path']) ? rtrim(rtrim($parsed_url['path']), '/') : '';
Chris@0 506 $port = (isset($parsed_url['port']) ? $parsed_url['port'] : $port);
Chris@0 507 if ($path == '/') {
Chris@0 508 $path = '';
Chris@0 509 }
Chris@0 510 // If the passed URL schema is 'https' then setup the $_SERVER variables
Chris@0 511 // properly so that testing will run under HTTPS.
Chris@0 512 if ($parsed_url['scheme'] == 'https') {
Chris@0 513 $_SERVER['HTTPS'] = 'on';
Chris@0 514 }
Chris@0 515 }
Chris@0 516
Chris@0 517 if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') {
Chris@0 518 $base_url = 'https://';
Chris@0 519 }
Chris@0 520 else {
Chris@0 521 $base_url = 'http://';
Chris@0 522 }
Chris@0 523 $base_url .= $host;
Chris@0 524 if ($path !== '') {
Chris@0 525 $base_url .= $path;
Chris@0 526 }
Chris@0 527 putenv('SIMPLETEST_BASE_URL=' . $base_url);
Chris@0 528 $_SERVER['HTTP_HOST'] = $host;
Chris@0 529 $_SERVER['REMOTE_ADDR'] = '127.0.0.1';
Chris@0 530 $_SERVER['SERVER_ADDR'] = '127.0.0.1';
Chris@0 531 $_SERVER['SERVER_PORT'] = $port;
Chris@0 532 $_SERVER['SERVER_SOFTWARE'] = NULL;
Chris@0 533 $_SERVER['SERVER_NAME'] = 'localhost';
Chris@0 534 $_SERVER['REQUEST_URI'] = $path . '/';
Chris@0 535 $_SERVER['REQUEST_METHOD'] = 'GET';
Chris@0 536 $_SERVER['SCRIPT_NAME'] = $path . '/index.php';
Chris@0 537 $_SERVER['SCRIPT_FILENAME'] = $path . '/index.php';
Chris@0 538 $_SERVER['PHP_SELF'] = $path . '/index.php';
Chris@0 539 $_SERVER['HTTP_USER_AGENT'] = 'Drupal command line';
Chris@0 540
Chris@0 541 if ($args['concurrency'] > 1) {
Chris@0 542 $directory = FileSystem::getOsTemporaryDirectory();
Chris@0 543 $test_symlink = @symlink(__FILE__, $directory . '/test_symlink');
Chris@0 544 if (!$test_symlink) {
Chris@0 545 throw new \RuntimeException('In order to use a concurrency higher than 1 the test system needs to be able to create symlinks in ' . $directory);
Chris@0 546 }
Chris@0 547 unlink($directory . '/test_symlink');
Chris@0 548 putenv('RUN_TESTS_CONCURRENCY=' . $args['concurrency']);
Chris@0 549 }
Chris@0 550
Chris@0 551 if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
Chris@0 552 // Ensure that any and all environment variables are changed to https://.
Chris@0 553 foreach ($_SERVER as $key => $value) {
Chris@0 554 $_SERVER[$key] = str_replace('http://', 'https://', $_SERVER[$key]);
Chris@0 555 }
Chris@0 556 }
Chris@0 557
Chris@0 558 chdir(realpath(__DIR__ . '/../..'));
Chris@14 559
Chris@14 560 // Prepare the kernel.
Chris@14 561 try {
Chris@14 562 $request = Request::createFromGlobals();
Chris@14 563 $kernel = TestRunnerKernel::createFromRequest($request, $autoloader);
Chris@14 564 $kernel->prepareLegacyRequest($request);
Chris@14 565 }
Chris@14 566 catch (Exception $e) {
Chris@14 567 echo (string) $e;
Chris@14 568 exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
Chris@14 569 }
Chris@0 570 }
Chris@0 571
Chris@0 572 /**
Chris@0 573 * Sets up database connection info for running tests.
Chris@0 574 *
Chris@0 575 * If this script is executed from within a real Drupal installation, then this
Chris@0 576 * function essentially performs nothing (unless the --sqlite or --dburl
Chris@0 577 * parameters were passed).
Chris@0 578 *
Chris@0 579 * Otherwise, there are three database connections of concern:
Chris@0 580 * - --sqlite: The test runner connection, providing access to Simpletest
Chris@0 581 * database tables for recording test IDs and assertion results.
Chris@0 582 * - --dburl: A database connection that is used as base connection info for all
Chris@0 583 * tests; i.e., every test will spawn from this connection. In case this
Chris@0 584 * connection uses e.g. SQLite, then all tests will run against SQLite. This
Chris@0 585 * is exposed as $databases['default']['default'] to Drupal.
Chris@0 586 * - The actual database connection used within a test. This is the same as
Chris@0 587 * --dburl, but uses an additional database table prefix. This is
Chris@0 588 * $databases['default']['default'] within a test environment. The original
Chris@0 589 * connection is retained in
Chris@0 590 * $databases['simpletest_original_default']['default'] and restored after
Chris@0 591 * each test.
Chris@0 592 *
Chris@0 593 * @param bool $new
Chris@0 594 * Whether this process is a run-tests.sh master process. If TRUE, the SQLite
Chris@0 595 * database file specified by --sqlite (if any) is set up. Otherwise, database
Chris@0 596 * connections are prepared only.
Chris@0 597 */
Chris@0 598 function simpletest_script_setup_database($new = FALSE) {
Chris@0 599 global $args;
Chris@0 600
Chris@0 601 // If there is an existing Drupal installation that contains a database
Chris@0 602 // connection info in settings.php, then $databases['default']['default'] will
Chris@0 603 // hold the default database connection already. This connection is assumed to
Chris@0 604 // be valid, and this connection will be used in tests, so that they run
Chris@0 605 // against e.g. MySQL instead of SQLite.
Chris@0 606 // However, in case no Drupal installation exists, this default database
Chris@0 607 // connection can be set and/or overridden with the --dburl parameter.
Chris@0 608 if (!empty($args['dburl'])) {
Chris@0 609 // Remove a possibly existing default connection (from settings.php).
Chris@0 610 Database::removeConnection('default');
Chris@0 611 try {
Chris@0 612 $databases['default']['default'] = Database::convertDbUrlToConnectionInfo($args['dburl'], DRUPAL_ROOT);
Chris@0 613 }
Chris@0 614 catch (\InvalidArgumentException $e) {
Chris@0 615 simpletest_script_print_error('Invalid --dburl. Reason: ' . $e->getMessage());
Chris@0 616 exit(SIMPLETEST_SCRIPT_EXIT_FAILURE);
Chris@0 617 }
Chris@0 618 }
Chris@0 619 // Otherwise, use the default database connection from settings.php.
Chris@0 620 else {
Chris@0 621 $databases['default'] = Database::getConnectionInfo('default');
Chris@0 622 }
Chris@0 623
Chris@0 624 // If there is no default database connection for tests, we cannot continue.
Chris@0 625 if (!isset($databases['default']['default'])) {
Chris@0 626 simpletest_script_print_error('Missing default database connection for tests. Use --dburl to specify one.');
Chris@0 627 exit(SIMPLETEST_SCRIPT_EXIT_FAILURE);
Chris@0 628 }
Chris@0 629 Database::addConnectionInfo('default', 'default', $databases['default']['default']);
Chris@0 630
Chris@0 631 // If no --sqlite parameter has been passed, then Simpletest module is assumed
Chris@0 632 // to be installed, so the test runner database connection is the default
Chris@0 633 // database connection.
Chris@0 634 if (empty($args['sqlite'])) {
Chris@0 635 $sqlite = FALSE;
Chris@0 636 $databases['test-runner']['default'] = $databases['default']['default'];
Chris@0 637 }
Chris@0 638 // Otherwise, set up a SQLite connection for the test runner.
Chris@0 639 else {
Chris@0 640 if ($args['sqlite'][0] === '/') {
Chris@0 641 $sqlite = $args['sqlite'];
Chris@0 642 }
Chris@0 643 else {
Chris@0 644 $sqlite = DRUPAL_ROOT . '/' . $args['sqlite'];
Chris@0 645 }
Chris@14 646 $databases['test-runner']['default'] = [
Chris@0 647 'driver' => 'sqlite',
Chris@0 648 'database' => $sqlite,
Chris@14 649 'prefix' => [
Chris@0 650 'default' => '',
Chris@14 651 ],
Chris@14 652 ];
Chris@0 653 // Create the test runner SQLite database, unless it exists already.
Chris@0 654 if ($new && !file_exists($sqlite)) {
Chris@0 655 if (!is_dir(dirname($sqlite))) {
Chris@0 656 mkdir(dirname($sqlite));
Chris@0 657 }
Chris@0 658 touch($sqlite);
Chris@0 659 }
Chris@0 660 }
Chris@0 661
Chris@0 662 // Add the test runner database connection.
Chris@0 663 Database::addConnectionInfo('test-runner', 'default', $databases['test-runner']['default']);
Chris@0 664
Chris@0 665 // Create the Simpletest schema.
Chris@0 666 try {
Chris@0 667 $connection = Database::getConnection('default', 'test-runner');
Chris@0 668 $schema = $connection->schema();
Chris@0 669 }
Chris@0 670 catch (\PDOException $e) {
Chris@0 671 simpletest_script_print_error($databases['test-runner']['default']['driver'] . ': ' . $e->getMessage());
Chris@0 672 exit(SIMPLETEST_SCRIPT_EXIT_FAILURE);
Chris@0 673 }
Chris@0 674 if ($new && $sqlite) {
Chris@0 675 require_once DRUPAL_ROOT . '/' . drupal_get_path('module', 'simpletest') . '/simpletest.install';
Chris@0 676 foreach (simpletest_schema() as $name => $table_spec) {
Chris@0 677 try {
Chris@0 678 $table_exists = $schema->tableExists($name);
Chris@0 679 if (empty($args['keep-results-table']) && $table_exists) {
Chris@0 680 $connection->truncate($name)->execute();
Chris@0 681 }
Chris@0 682 if (!$table_exists) {
Chris@0 683 $schema->createTable($name, $table_spec);
Chris@0 684 }
Chris@0 685 }
Chris@0 686 catch (Exception $e) {
Chris@0 687 echo (string) $e;
Chris@0 688 exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
Chris@0 689 }
Chris@0 690 }
Chris@0 691 }
Chris@0 692 // Verify that the Simpletest database schema exists by checking one table.
Chris@0 693 try {
Chris@0 694 if (!$schema->tableExists('simpletest')) {
Chris@0 695 simpletest_script_print_error('Missing Simpletest database schema. Either install Simpletest module or use the --sqlite parameter.');
Chris@0 696 exit(SIMPLETEST_SCRIPT_EXIT_FAILURE);
Chris@0 697 }
Chris@0 698 }
Chris@0 699 catch (Exception $e) {
Chris@0 700 echo (string) $e;
Chris@0 701 exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
Chris@0 702 }
Chris@0 703 }
Chris@0 704
Chris@0 705 /**
Chris@0 706 * Execute a batch of tests.
Chris@0 707 */
Chris@0 708 function simpletest_script_execute_batch($test_classes) {
Chris@0 709 global $args, $test_ids;
Chris@0 710
Chris@0 711 $total_status = SIMPLETEST_SCRIPT_EXIT_SUCCESS;
Chris@0 712
Chris@0 713 // Multi-process execution.
Chris@14 714 $children = [];
Chris@0 715 while (!empty($test_classes) || !empty($children)) {
Chris@0 716 while (count($children) < $args['concurrency']) {
Chris@0 717 if (empty($test_classes)) {
Chris@0 718 break;
Chris@0 719 }
Chris@0 720
Chris@0 721 try {
Chris@0 722 $test_id = Database::getConnection('default', 'test-runner')
Chris@0 723 ->insert('simpletest_test_id')
Chris@14 724 ->useDefaults(['test_id'])
Chris@0 725 ->execute();
Chris@0 726 }
Chris@0 727 catch (Exception $e) {
Chris@0 728 echo (string) $e;
Chris@0 729 exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
Chris@0 730 }
Chris@0 731 $test_ids[] = $test_id;
Chris@0 732
Chris@0 733 $test_class = array_shift($test_classes);
Chris@0 734 // Fork a child process.
Chris@0 735 $command = simpletest_script_command($test_id, $test_class);
Chris@14 736 $process = proc_open($command, [], $pipes, NULL, NULL, ['bypass_shell' => TRUE]);
Chris@0 737
Chris@0 738 if (!is_resource($process)) {
Chris@0 739 echo "Unable to fork test process. Aborting.\n";
Chris@0 740 exit(SIMPLETEST_SCRIPT_EXIT_SUCCESS);
Chris@0 741 }
Chris@0 742
Chris@0 743 // Register our new child.
Chris@14 744 $children[] = [
Chris@0 745 'process' => $process,
Chris@0 746 'test_id' => $test_id,
Chris@0 747 'class' => $test_class,
Chris@0 748 'pipes' => $pipes,
Chris@14 749 ];
Chris@0 750 }
Chris@0 751
Chris@0 752 // Wait for children every 200ms.
Chris@0 753 usleep(200000);
Chris@0 754
Chris@0 755 // Check if some children finished.
Chris@0 756 foreach ($children as $cid => $child) {
Chris@0 757 $status = proc_get_status($child['process']);
Chris@0 758 if (empty($status['running'])) {
Chris@0 759 // The child exited, unregister it.
Chris@0 760 proc_close($child['process']);
Chris@0 761 if ($status['exitcode'] === SIMPLETEST_SCRIPT_EXIT_FAILURE) {
Chris@0 762 $total_status = max($status['exitcode'], $total_status);
Chris@0 763 }
Chris@0 764 elseif ($status['exitcode']) {
Chris@0 765 $message = 'FATAL ' . $child['class'] . ': test runner returned a non-zero error code (' . $status['exitcode'] . ').';
Chris@0 766 echo $message . "\n";
Chris@0 767 // @todo Return SIMPLETEST_SCRIPT_EXIT_EXCEPTION instead, when
Chris@0 768 // DrupalCI supports this.
Chris@0 769 // @see https://www.drupal.org/node/2780087
Chris@0 770 $total_status = max(SIMPLETEST_SCRIPT_EXIT_FAILURE, $total_status);
Chris@0 771 // Insert a fail for xml results.
Chris@0 772 TestBase::insertAssert($child['test_id'], $child['class'], FALSE, $message, 'run-tests.sh check');
Chris@0 773 // Ensure that an error line is displayed for the class.
Chris@0 774 simpletest_script_reporter_display_summary(
Chris@0 775 $child['class'],
Chris@0 776 ['#pass' => 0, '#fail' => 1, '#exception' => 0, '#debug' => 0]
Chris@0 777 );
Chris@0 778 if ($args['die-on-fail']) {
Chris@0 779 list($db_prefix) = simpletest_last_test_get($child['test_id']);
Chris@0 780 $test_db = new TestDatabase($db_prefix);
Chris@0 781 $test_directory = $test_db->getTestSitePath();
Chris@0 782 echo 'Simpletest database and files kept and test exited immediately on fail so should be reproducible if you change settings.php to use the database prefix ' . $db_prefix . ' and config directories in ' . $test_directory . "\n";
Chris@0 783 $args['keep-results'] = TRUE;
Chris@0 784 // Exit repeat loop immediately.
Chris@0 785 $args['repeat'] = -1;
Chris@0 786 }
Chris@0 787 }
Chris@0 788 // Free-up space by removing any potentially created resources.
Chris@0 789 if (!$args['keep-results']) {
Chris@0 790 simpletest_script_cleanup($child['test_id'], $child['class'], $status['exitcode']);
Chris@0 791 }
Chris@0 792
Chris@0 793 // Remove this child.
Chris@0 794 unset($children[$cid]);
Chris@0 795 }
Chris@0 796 }
Chris@0 797 }
Chris@0 798 return $total_status;
Chris@0 799 }
Chris@0 800
Chris@0 801 /**
Chris@0 802 * Run a PHPUnit-based test.
Chris@0 803 */
Chris@0 804 function simpletest_script_run_phpunit($test_id, $class) {
Chris@0 805 $reflection = new \ReflectionClass($class);
Chris@0 806 if ($reflection->hasProperty('runLimit')) {
Chris@0 807 set_time_limit($reflection->getStaticPropertyValue('runLimit'));
Chris@0 808 }
Chris@0 809
Chris@14 810 $results = simpletest_run_phpunit_tests($test_id, [$class], $status);
Chris@0 811 simpletest_process_phpunit_results($results);
Chris@0 812
Chris@0 813 // Map phpunit results to a data structure we can pass to
Chris@0 814 // _simpletest_format_summary_line.
Chris@0 815 $summaries = simpletest_summarize_phpunit_result($results);
Chris@0 816 foreach ($summaries as $class => $summary) {
Chris@0 817 simpletest_script_reporter_display_summary($class, $summary);
Chris@0 818 }
Chris@0 819 return $status;
Chris@0 820 }
Chris@0 821
Chris@0 822 /**
Chris@0 823 * Run a single test, bootstrapping Drupal if needed.
Chris@0 824 */
Chris@0 825 function simpletest_script_run_one_test($test_id, $test_class) {
Chris@0 826 global $args;
Chris@0 827
Chris@0 828 try {
Chris@0 829 if (strpos($test_class, '::') > 0) {
Chris@0 830 list($class_name, $method) = explode('::', $test_class, 2);
Chris@0 831 $methods = [$method];
Chris@0 832 }
Chris@0 833 else {
Chris@0 834 $class_name = $test_class;
Chris@0 835 // Use empty array to run all the test methods.
Chris@14 836 $methods = [];
Chris@0 837 }
Chris@0 838 $test = new $class_name($test_id);
Chris@12 839 if ($args['suppress-deprecations']) {
Chris@12 840 putenv('SYMFONY_DEPRECATIONS_HELPER=disabled');
Chris@12 841 }
Chris@0 842 if (is_subclass_of($test_class, TestCase::class)) {
Chris@0 843 $status = simpletest_script_run_phpunit($test_id, $test_class);
Chris@0 844 }
Chris@0 845 else {
Chris@0 846 $test->dieOnFail = (bool) $args['die-on-fail'];
Chris@0 847 $test->verbose = (bool) $args['verbose'];
Chris@0 848 $test->run($methods);
Chris@0 849 simpletest_script_reporter_display_summary($test_class, $test->results);
Chris@0 850
Chris@0 851 $status = SIMPLETEST_SCRIPT_EXIT_SUCCESS;
Chris@0 852 // Finished, kill this runner.
Chris@0 853 if ($test->results['#fail'] || $test->results['#exception']) {
Chris@0 854 $status = SIMPLETEST_SCRIPT_EXIT_FAILURE;
Chris@0 855 }
Chris@0 856 }
Chris@0 857
Chris@0 858 exit($status);
Chris@0 859 }
Chris@0 860 // DrupalTestCase::run() catches exceptions already, so this is only reached
Chris@0 861 // when an exception is thrown in the wrapping test runner environment.
Chris@0 862 catch (Exception $e) {
Chris@0 863 echo (string) $e;
Chris@0 864 exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
Chris@0 865 }
Chris@0 866 }
Chris@0 867
Chris@0 868 /**
Chris@0 869 * Return a command used to run a test in a separate process.
Chris@0 870 *
Chris@0 871 * @param int $test_id
Chris@0 872 * The current test ID.
Chris@0 873 * @param string $test_class
Chris@0 874 * The name of the test class to run.
Chris@0 875 *
Chris@0 876 * @return string
Chris@0 877 * The assembled command string.
Chris@0 878 */
Chris@0 879 function simpletest_script_command($test_id, $test_class) {
Chris@0 880 global $args, $php;
Chris@0 881
Chris@0 882 $command = escapeshellarg($php) . ' ' . escapeshellarg('./core/scripts/' . $args['script']);
Chris@0 883 $command .= ' --url ' . escapeshellarg($args['url']);
Chris@0 884 if (!empty($args['sqlite'])) {
Chris@0 885 $command .= ' --sqlite ' . escapeshellarg($args['sqlite']);
Chris@0 886 }
Chris@0 887 if (!empty($args['dburl'])) {
Chris@0 888 $command .= ' --dburl ' . escapeshellarg($args['dburl']);
Chris@0 889 }
Chris@0 890 $command .= ' --php ' . escapeshellarg($php);
Chris@0 891 $command .= " --test-id $test_id";
Chris@14 892 foreach (['verbose', 'keep-results', 'color', 'die-on-fail', 'suppress-deprecations'] as $arg) {
Chris@0 893 if ($args[$arg]) {
Chris@0 894 $command .= ' --' . $arg;
Chris@0 895 }
Chris@0 896 }
Chris@0 897 // --execute-test and class name needs to come last.
Chris@0 898 $command .= ' --execute-test ' . escapeshellarg($test_class);
Chris@0 899 return $command;
Chris@0 900 }
Chris@0 901
Chris@0 902 /**
Chris@0 903 * Removes all remnants of a test runner.
Chris@0 904 *
Chris@0 905 * In case a (e.g., fatal) error occurs after the test site has been fully setup
Chris@0 906 * and the error happens in many tests, the environment that executes the tests
Chris@0 907 * can easily run out of memory or disk space. This function ensures that all
Chris@0 908 * created resources are properly cleaned up after every executed test.
Chris@0 909 *
Chris@0 910 * This clean-up only exists in this script, since SimpleTest module itself does
Chris@0 911 * not use isolated sub-processes for each test being run, so a fatal error
Chris@0 912 * halts not only the test, but also the test runner (i.e., the parent site).
Chris@0 913 *
Chris@0 914 * @param int $test_id
Chris@0 915 * The test ID of the test run.
Chris@0 916 * @param string $test_class
Chris@0 917 * The class name of the test run.
Chris@0 918 * @param int $exitcode
Chris@0 919 * The exit code of the test runner.
Chris@0 920 *
Chris@0 921 * @see simpletest_script_run_one_test()
Chris@0 922 */
Chris@0 923 function simpletest_script_cleanup($test_id, $test_class, $exitcode) {
Chris@0 924 if (is_subclass_of($test_class, TestCase::class)) {
Chris@0 925 // PHPUnit test, move on.
Chris@0 926 return;
Chris@0 927 }
Chris@0 928 // Retrieve the last database prefix used for testing.
Chris@0 929 try {
Chris@0 930 list($db_prefix) = simpletest_last_test_get($test_id);
Chris@0 931 }
Chris@0 932 catch (Exception $e) {
Chris@0 933 echo (string) $e;
Chris@0 934 exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
Chris@0 935 }
Chris@0 936
Chris@0 937 // If no database prefix was found, then the test was not set up correctly.
Chris@0 938 if (empty($db_prefix)) {
Chris@0 939 echo "\nFATAL $test_class: Found no database prefix for test ID $test_id. (Check whether setUp() is invoked correctly.)";
Chris@0 940 return;
Chris@0 941 }
Chris@0 942
Chris@0 943 // Do not output verbose cleanup messages in case of a positive exitcode.
Chris@0 944 $output = !empty($exitcode);
Chris@14 945 $messages = [];
Chris@0 946
Chris@0 947 $messages[] = "- Found database prefix '$db_prefix' for test ID $test_id.";
Chris@0 948
Chris@0 949 // Read the log file in case any fatal errors caused the test to crash.
Chris@0 950 try {
Chris@0 951 simpletest_log_read($test_id, $db_prefix, $test_class);
Chris@0 952 }
Chris@0 953 catch (Exception $e) {
Chris@0 954 echo (string) $e;
Chris@0 955 exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
Chris@0 956 }
Chris@0 957
Chris@0 958 // Check whether a test site directory was setup already.
Chris@0 959 // @see \Drupal\simpletest\TestBase::prepareEnvironment()
Chris@0 960 $test_db = new TestDatabase($db_prefix);
Chris@0 961 $test_directory = DRUPAL_ROOT . '/' . $test_db->getTestSitePath();
Chris@0 962 if (is_dir($test_directory)) {
Chris@0 963 // Output the error_log.
Chris@0 964 if (is_file($test_directory . '/error.log')) {
Chris@0 965 if ($errors = file_get_contents($test_directory . '/error.log')) {
Chris@0 966 $output = TRUE;
Chris@0 967 $messages[] = $errors;
Chris@0 968 }
Chris@0 969 }
Chris@0 970 // Delete the test site directory.
Chris@0 971 // simpletest_clean_temporary_directories() cannot be used here, since it
Chris@0 972 // would also delete file directories of other tests that are potentially
Chris@0 973 // running concurrently.
Chris@18 974 try {
Chris@18 975 \Drupal::service('file_system')->deleteRecursive($test_directory, ['Drupal\simpletest\TestBase', 'filePreDeleteCallback']);
Chris@18 976 $messages[] = "- Removed test site directory.";
Chris@18 977 }
Chris@18 978 catch (FileException $e) {
Chris@18 979 // Ignore failed deletes.
Chris@18 980 }
Chris@0 981 }
Chris@0 982
Chris@0 983 // Clear out all database tables from the test.
Chris@0 984 try {
Chris@0 985 $schema = Database::getConnection('default', 'default')->schema();
Chris@0 986 $count = 0;
Chris@0 987 foreach ($schema->findTables($db_prefix . '%') as $table) {
Chris@0 988 $schema->dropTable($table);
Chris@0 989 $count++;
Chris@0 990 }
Chris@0 991 }
Chris@0 992 catch (Exception $e) {
Chris@0 993 echo (string) $e;
Chris@0 994 exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
Chris@0 995 }
Chris@0 996
Chris@0 997 if ($count) {
Chris@0 998 $messages[] = "- Removed $count leftover tables.";
Chris@0 999 }
Chris@0 1000
Chris@0 1001 if ($output) {
Chris@0 1002 echo implode("\n", $messages);
Chris@0 1003 echo "\n";
Chris@0 1004 }
Chris@0 1005 }
Chris@0 1006
Chris@0 1007 /**
Chris@0 1008 * Get list of tests based on arguments.
Chris@0 1009 *
Chris@0 1010 * If --all specified then return all available tests, otherwise reads list of
Chris@0 1011 * tests.
Chris@0 1012 *
Chris@0 1013 * @return array
Chris@0 1014 * List of tests.
Chris@0 1015 */
Chris@0 1016 function simpletest_script_get_test_list() {
Chris@0 1017 global $args;
Chris@0 1018
Chris@17 1019 /** $test_discovery \Drupal\simpletest\TestDiscovery */
Chris@17 1020 $test_discovery = \Drupal::service('test_discovery');
Chris@0 1021 $types_processed = empty($args['types']);
Chris@14 1022 $test_list = [];
Chris@0 1023 if ($args['all'] || $args['module']) {
Chris@0 1024 try {
Chris@17 1025 $groups = $test_discovery->getTestClasses($args['module'], $args['types']);
Chris@0 1026 $types_processed = TRUE;
Chris@0 1027 }
Chris@0 1028 catch (Exception $e) {
Chris@0 1029 echo (string) $e;
Chris@0 1030 exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
Chris@0 1031 }
Chris@14 1032 $all_tests = [];
Chris@0 1033 foreach ($groups as $group => $tests) {
Chris@0 1034 $all_tests = array_merge($all_tests, array_keys($tests));
Chris@0 1035 }
Chris@18 1036 $test_list = array_unique($all_tests);
Chris@0 1037 }
Chris@0 1038 else {
Chris@0 1039 if ($args['class']) {
Chris@14 1040 $test_list = [];
Chris@0 1041 foreach ($args['test_names'] as $test_class) {
Chris@0 1042 list($class_name) = explode('::', $test_class, 2);
Chris@0 1043 if (class_exists($class_name)) {
Chris@0 1044 $test_list[] = $test_class;
Chris@0 1045 }
Chris@0 1046 else {
Chris@0 1047 try {
Chris@17 1048 $groups = $test_discovery->getTestClasses(NULL, $args['types']);
Chris@0 1049 }
Chris@0 1050 catch (Exception $e) {
Chris@0 1051 echo (string) $e;
Chris@0 1052 exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
Chris@0 1053 }
Chris@14 1054 $all_classes = [];
Chris@0 1055 foreach ($groups as $group) {
Chris@0 1056 $all_classes = array_merge($all_classes, array_keys($group));
Chris@0 1057 }
Chris@0 1058 simpletest_script_print_error('Test class not found: ' . $class_name);
Chris@0 1059 simpletest_script_print_alternatives($class_name, $all_classes, 6);
Chris@0 1060 exit(SIMPLETEST_SCRIPT_EXIT_FAILURE);
Chris@0 1061 }
Chris@0 1062 }
Chris@0 1063 }
Chris@0 1064 elseif ($args['file']) {
Chris@0 1065 // Extract test case class names from specified files.
Chris@0 1066 foreach ($args['test_names'] as $file) {
Chris@0 1067 if (!file_exists($file)) {
Chris@0 1068 simpletest_script_print_error('File not found: ' . $file);
Chris@0 1069 exit(SIMPLETEST_SCRIPT_EXIT_FAILURE);
Chris@0 1070 }
Chris@0 1071 $content = file_get_contents($file);
Chris@0 1072 // Extract a potential namespace.
Chris@0 1073 $namespace = FALSE;
Chris@0 1074 if (preg_match('@^namespace ([^ ;]+)@m', $content, $matches)) {
Chris@0 1075 $namespace = $matches[1];
Chris@0 1076 }
Chris@0 1077 // Extract all class names.
Chris@0 1078 // Abstract classes are excluded on purpose.
Chris@0 1079 preg_match_all('@^class ([^ ]+)@m', $content, $matches);
Chris@0 1080 if (!$namespace) {
Chris@0 1081 $test_list = array_merge($test_list, $matches[1]);
Chris@0 1082 }
Chris@0 1083 else {
Chris@0 1084 foreach ($matches[1] as $class_name) {
Chris@0 1085 $namespace_class = $namespace . '\\' . $class_name;
Chris@0 1086 if (is_subclass_of($namespace_class, '\Drupal\simpletest\TestBase') || is_subclass_of($namespace_class, TestCase::class)) {
Chris@0 1087 $test_list[] = $namespace_class;
Chris@0 1088 }
Chris@0 1089 }
Chris@0 1090 }
Chris@0 1091 }
Chris@0 1092 }
Chris@0 1093 elseif ($args['directory']) {
Chris@0 1094 // Extract test case class names from specified directory.
Chris@0 1095 // Find all tests in the PSR-X structure; Drupal\$extension\Tests\*.php
Chris@0 1096 // Since we do not want to hard-code too many structural file/directory
Chris@0 1097 // assumptions about PSR-0/4 files and directories, we check for the
Chris@0 1098 // minimal conditions only; i.e., a '*.php' file that has '/Tests/' in
Chris@0 1099 // its path.
Chris@0 1100 // Ignore anything from third party vendors.
Chris@14 1101 $ignore = ['.', '..', 'vendor'];
Chris@0 1102 $files = [];
Chris@0 1103 if ($args['directory'][0] === '/') {
Chris@0 1104 $directory = $args['directory'];
Chris@0 1105 }
Chris@0 1106 else {
Chris@0 1107 $directory = DRUPAL_ROOT . "/" . $args['directory'];
Chris@0 1108 }
Chris@0 1109 foreach (file_scan_directory($directory, '/\.php$/', $ignore) as $file) {
Chris@0 1110 // '/Tests/' can be contained anywhere in the file's path (there can be
Chris@0 1111 // sub-directories below /Tests), but must be contained literally.
Chris@0 1112 // Case-insensitive to match all Simpletest and PHPUnit tests:
Chris@0 1113 // ./lib/Drupal/foo/Tests/Bar/Baz.php
Chris@0 1114 // ./foo/src/Tests/Bar/Baz.php
Chris@0 1115 // ./foo/tests/Drupal/foo/Tests/FooTest.php
Chris@0 1116 // ./foo/tests/src/FooTest.php
Chris@0 1117 // $file->filename doesn't give us a directory, so we use $file->uri
Chris@0 1118 // Strip the drupal root directory and trailing slash off the URI.
Chris@0 1119 $filename = substr($file->uri, strlen(DRUPAL_ROOT) + 1);
Chris@0 1120 if (stripos($filename, '/Tests/')) {
Chris@0 1121 $files[$filename] = $filename;
Chris@0 1122 }
Chris@0 1123 }
Chris@0 1124 foreach ($files as $file) {
Chris@0 1125 $content = file_get_contents($file);
Chris@0 1126 // Extract a potential namespace.
Chris@0 1127 $namespace = FALSE;
Chris@0 1128 if (preg_match('@^\s*namespace ([^ ;]+)@m', $content, $matches)) {
Chris@0 1129 $namespace = $matches[1];
Chris@0 1130 }
Chris@0 1131 // Extract all class names.
Chris@0 1132 // Abstract classes are excluded on purpose.
Chris@0 1133 preg_match_all('@^\s*class ([^ ]+)@m', $content, $matches);
Chris@0 1134 if (!$namespace) {
Chris@0 1135 $test_list = array_merge($test_list, $matches[1]);
Chris@0 1136 }
Chris@0 1137 else {
Chris@0 1138 foreach ($matches[1] as $class_name) {
Chris@0 1139 $namespace_class = $namespace . '\\' . $class_name;
Chris@0 1140 if (is_subclass_of($namespace_class, '\Drupal\simpletest\TestBase') || is_subclass_of($namespace_class, TestCase::class)) {
Chris@0 1141 $test_list[] = $namespace_class;
Chris@0 1142 }
Chris@0 1143 }
Chris@0 1144 }
Chris@0 1145 }
Chris@0 1146 }
Chris@0 1147 else {
Chris@0 1148 try {
Chris@17 1149 $groups = $test_discovery->getTestClasses(NULL, $args['types']);
Chris@0 1150 $types_processed = TRUE;
Chris@0 1151 }
Chris@0 1152 catch (Exception $e) {
Chris@0 1153 echo (string) $e;
Chris@0 1154 exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
Chris@0 1155 }
Chris@18 1156 // Store all the groups so we can suggest alternatives if we need to.
Chris@18 1157 $all_groups = array_keys($groups);
Chris@18 1158 // Verify that the groups exist.
Chris@18 1159 if (!empty($unknown_groups = array_diff($args['test_names'], $all_groups))) {
Chris@18 1160 $first_group = reset($unknown_groups);
Chris@18 1161 simpletest_script_print_error('Test group not found: ' . $first_group);
Chris@18 1162 simpletest_script_print_alternatives($first_group, $all_groups);
Chris@18 1163 exit(SIMPLETEST_SCRIPT_EXIT_FAILURE);
Chris@18 1164 }
Chris@18 1165 // Ensure our list of tests contains only one entry for each test.
Chris@0 1166 foreach ($args['test_names'] as $group_name) {
Chris@18 1167 $test_list = array_merge($test_list, array_flip(array_keys($groups[$group_name])));
Chris@0 1168 }
Chris@18 1169 $test_list = array_flip($test_list);
Chris@0 1170 }
Chris@0 1171 }
Chris@0 1172
Chris@0 1173 // If the test list creation does not automatically limit by test type then
Chris@0 1174 // we need to do so here.
Chris@0 1175 if (!$types_processed) {
Chris@0 1176 $test_list = array_filter($test_list, function ($test_class) use ($args) {
Chris@0 1177 $test_info = TestDiscovery::getTestInfo($test_class);
Chris@0 1178 return in_array($test_info['type'], $args['types'], TRUE);
Chris@0 1179 });
Chris@0 1180 }
Chris@0 1181
Chris@0 1182 if (empty($test_list)) {
Chris@0 1183 simpletest_script_print_error('No valid tests were specified.');
Chris@0 1184 exit(SIMPLETEST_SCRIPT_EXIT_FAILURE);
Chris@0 1185 }
Chris@0 1186 return $test_list;
Chris@0 1187 }
Chris@0 1188
Chris@0 1189 /**
Chris@0 1190 * Initialize the reporter.
Chris@0 1191 */
Chris@0 1192 function simpletest_script_reporter_init() {
Chris@0 1193 global $args, $test_list, $results_map;
Chris@0 1194
Chris@14 1195 $results_map = [
Chris@0 1196 'pass' => 'Pass',
Chris@0 1197 'fail' => 'Fail',
Chris@0 1198 'exception' => 'Exception',
Chris@14 1199 ];
Chris@0 1200
Chris@0 1201 echo "\n";
Chris@0 1202 echo "Drupal test run\n";
Chris@0 1203 echo "---------------\n";
Chris@0 1204 echo "\n";
Chris@0 1205
Chris@0 1206 // Tell the user about what tests are to be run.
Chris@0 1207 if ($args['all']) {
Chris@0 1208 echo "All tests will run.\n\n";
Chris@0 1209 }
Chris@0 1210 else {
Chris@0 1211 echo "Tests to be run:\n";
Chris@0 1212 foreach ($test_list as $class_name) {
Chris@0 1213 echo " - $class_name\n";
Chris@0 1214 }
Chris@0 1215 echo "\n";
Chris@0 1216 }
Chris@0 1217
Chris@0 1218 echo "Test run started:\n";
Chris@0 1219 echo " " . date('l, F j, Y - H:i', $_SERVER['REQUEST_TIME']) . "\n";
Chris@0 1220 Timer::start('run-tests');
Chris@0 1221 echo "\n";
Chris@0 1222
Chris@0 1223 echo "Test summary\n";
Chris@0 1224 echo "------------\n";
Chris@0 1225 echo "\n";
Chris@0 1226 }
Chris@0 1227
Chris@0 1228 /**
Chris@0 1229 * Displays the assertion result summary for a single test class.
Chris@0 1230 *
Chris@0 1231 * @param string $class
Chris@0 1232 * The test class name that was run.
Chris@0 1233 * @param array $results
Chris@0 1234 * The assertion results using #pass, #fail, #exception, #debug array keys.
Chris@0 1235 */
Chris@0 1236 function simpletest_script_reporter_display_summary($class, $results) {
Chris@0 1237 // Output all test results vertically aligned.
Chris@0 1238 // Cut off the class name after 60 chars, and pad each group with 3 digits
Chris@0 1239 // by default (more than 999 assertions are rare).
Chris@14 1240 $output = vsprintf('%-60.60s %10s %9s %14s %12s', [
Chris@0 1241 $class,
Chris@0 1242 $results['#pass'] . ' passes',
Chris@0 1243 !$results['#fail'] ? '' : $results['#fail'] . ' fails',
Chris@0 1244 !$results['#exception'] ? '' : $results['#exception'] . ' exceptions',
Chris@0 1245 !$results['#debug'] ? '' : $results['#debug'] . ' messages',
Chris@14 1246 ]);
Chris@0 1247
Chris@0 1248 $status = ($results['#fail'] || $results['#exception'] ? 'fail' : 'pass');
Chris@0 1249 simpletest_script_print($output . "\n", simpletest_script_color_code($status));
Chris@0 1250 }
Chris@0 1251
Chris@0 1252 /**
Chris@0 1253 * Display jUnit XML test results.
Chris@0 1254 */
Chris@0 1255 function simpletest_script_reporter_write_xml_results() {
Chris@0 1256 global $args, $test_ids, $results_map;
Chris@0 1257
Chris@0 1258 try {
Chris@0 1259 $results = simpletest_script_load_messages_by_test_id($test_ids);
Chris@0 1260 }
Chris@0 1261 catch (Exception $e) {
Chris@0 1262 echo (string) $e;
Chris@0 1263 exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
Chris@0 1264 }
Chris@0 1265
Chris@0 1266 $test_class = '';
Chris@14 1267 $xml_files = [];
Chris@0 1268
Chris@0 1269 foreach ($results as $result) {
Chris@0 1270 if (isset($results_map[$result->status])) {
Chris@0 1271 if ($result->test_class != $test_class) {
Chris@0 1272 // We've moved onto a new class, so write the last classes results to a
Chris@0 1273 // file:
Chris@0 1274 if (isset($xml_files[$test_class])) {
Chris@0 1275 file_put_contents($args['xml'] . '/' . str_replace('\\', '_', $test_class) . '.xml', $xml_files[$test_class]['doc']->saveXML());
Chris@0 1276 unset($xml_files[$test_class]);
Chris@0 1277 }
Chris@0 1278 $test_class = $result->test_class;
Chris@0 1279 if (!isset($xml_files[$test_class])) {
Chris@0 1280 $doc = new DomDocument('1.0');
Chris@0 1281 $root = $doc->createElement('testsuite');
Chris@0 1282 $root = $doc->appendChild($root);
Chris@14 1283 $xml_files[$test_class] = ['doc' => $doc, 'suite' => $root];
Chris@0 1284 }
Chris@0 1285 }
Chris@0 1286
Chris@0 1287 // For convenience:
Chris@0 1288 $dom_document = &$xml_files[$test_class]['doc'];
Chris@0 1289
Chris@0 1290 // Create the XML element for this test case:
Chris@0 1291 $case = $dom_document->createElement('testcase');
Chris@0 1292 $case->setAttribute('classname', $test_class);
Chris@0 1293 if (strpos($result->function, '->') !== FALSE) {
Chris@0 1294 list($class, $name) = explode('->', $result->function, 2);
Chris@0 1295 }
Chris@0 1296 else {
Chris@0 1297 $name = $result->function;
Chris@0 1298 }
Chris@0 1299 $case->setAttribute('name', $name);
Chris@0 1300
Chris@0 1301 // Passes get no further attention, but failures and exceptions get to add
Chris@0 1302 // more detail:
Chris@0 1303 if ($result->status == 'fail') {
Chris@0 1304 $fail = $dom_document->createElement('failure');
Chris@0 1305 $fail->setAttribute('type', 'failure');
Chris@0 1306 $fail->setAttribute('message', $result->message_group);
Chris@0 1307 $text = $dom_document->createTextNode($result->message);
Chris@0 1308 $fail->appendChild($text);
Chris@0 1309 $case->appendChild($fail);
Chris@0 1310 }
Chris@0 1311 elseif ($result->status == 'exception') {
Chris@0 1312 // In the case of an exception the $result->function may not be a class
Chris@0 1313 // method so we record the full function name:
Chris@0 1314 $case->setAttribute('name', $result->function);
Chris@0 1315
Chris@0 1316 $fail = $dom_document->createElement('error');
Chris@0 1317 $fail->setAttribute('type', 'exception');
Chris@0 1318 $fail->setAttribute('message', $result->message_group);
Chris@0 1319 $full_message = $result->message . "\n\nline: " . $result->line . "\nfile: " . $result->file;
Chris@0 1320 $text = $dom_document->createTextNode($full_message);
Chris@0 1321 $fail->appendChild($text);
Chris@0 1322 $case->appendChild($fail);
Chris@0 1323 }
Chris@0 1324 // Append the test case XML to the test suite:
Chris@0 1325 $xml_files[$test_class]['suite']->appendChild($case);
Chris@0 1326 }
Chris@0 1327 }
Chris@0 1328 // The last test case hasn't been saved to a file yet, so do that now:
Chris@0 1329 if (isset($xml_files[$test_class])) {
Chris@0 1330 file_put_contents($args['xml'] . '/' . str_replace('\\', '_', $test_class) . '.xml', $xml_files[$test_class]['doc']->saveXML());
Chris@0 1331 unset($xml_files[$test_class]);
Chris@0 1332 }
Chris@0 1333 }
Chris@0 1334
Chris@0 1335 /**
Chris@0 1336 * Stop the test timer.
Chris@0 1337 */
Chris@0 1338 function simpletest_script_reporter_timer_stop() {
Chris@0 1339 echo "\n";
Chris@0 1340 $end = Timer::stop('run-tests');
Chris@0 1341 echo "Test run duration: " . \Drupal::service('date.formatter')->formatInterval($end['time'] / 1000);
Chris@0 1342 echo "\n\n";
Chris@0 1343 }
Chris@0 1344
Chris@0 1345 /**
Chris@0 1346 * Display test results.
Chris@0 1347 */
Chris@0 1348 function simpletest_script_reporter_display_results() {
Chris@0 1349 global $args, $test_ids, $results_map;
Chris@0 1350
Chris@0 1351 if ($args['verbose']) {
Chris@0 1352 // Report results.
Chris@0 1353 echo "Detailed test results\n";
Chris@0 1354 echo "---------------------\n";
Chris@0 1355
Chris@0 1356 try {
Chris@0 1357 $results = simpletest_script_load_messages_by_test_id($test_ids);
Chris@0 1358 }
Chris@0 1359 catch (Exception $e) {
Chris@0 1360 echo (string) $e;
Chris@0 1361 exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
Chris@0 1362 }
Chris@0 1363 $test_class = '';
Chris@0 1364 foreach ($results as $result) {
Chris@0 1365 if (isset($results_map[$result->status])) {
Chris@0 1366 if ($result->test_class != $test_class) {
Chris@0 1367 // Display test class every time results are for new test class.
Chris@0 1368 echo "\n\n---- $result->test_class ----\n\n\n";
Chris@0 1369 $test_class = $result->test_class;
Chris@0 1370
Chris@0 1371 // Print table header.
Chris@0 1372 echo "Status Group Filename Line Function \n";
Chris@0 1373 echo "--------------------------------------------------------------------------------\n";
Chris@0 1374 }
Chris@0 1375
Chris@0 1376 simpletest_script_format_result($result);
Chris@0 1377 }
Chris@0 1378 }
Chris@0 1379 }
Chris@0 1380 }
Chris@0 1381
Chris@0 1382 /**
Chris@0 1383 * Format the result so that it fits within 80 characters.
Chris@0 1384 *
Chris@0 1385 * @param object $result
Chris@0 1386 * The result object to format.
Chris@0 1387 */
Chris@0 1388 function simpletest_script_format_result($result) {
Chris@0 1389 global $args, $results_map, $color;
Chris@0 1390
Chris@0 1391 $summary = sprintf("%-9.9s %-10.10s %-17.17s %4.4s %-35.35s\n",
Chris@0 1392 $results_map[$result->status], $result->message_group, basename($result->file), $result->line, $result->function);
Chris@0 1393
Chris@0 1394 simpletest_script_print($summary, simpletest_script_color_code($result->status));
Chris@0 1395
Chris@0 1396 $message = trim(strip_tags($result->message));
Chris@0 1397 if ($args['non-html']) {
Chris@0 1398 $message = Html::decodeEntities($message, ENT_QUOTES, 'UTF-8');
Chris@0 1399 }
Chris@0 1400 $lines = explode("\n", wordwrap($message), 76);
Chris@0 1401 foreach ($lines as $line) {
Chris@0 1402 echo " $line\n";
Chris@0 1403 }
Chris@0 1404 }
Chris@0 1405
Chris@0 1406 /**
Chris@0 1407 * Print error messages so the user will notice them.
Chris@0 1408 *
Chris@0 1409 * Print error message prefixed with " ERROR: " and displayed in fail color if
Chris@0 1410 * color output is enabled.
Chris@0 1411 *
Chris@0 1412 * @param string $message
Chris@0 1413 * The message to print.
Chris@0 1414 */
Chris@0 1415 function simpletest_script_print_error($message) {
Chris@0 1416 simpletest_script_print(" ERROR: $message\n", SIMPLETEST_SCRIPT_COLOR_FAIL);
Chris@0 1417 }
Chris@0 1418
Chris@0 1419 /**
Chris@0 1420 * Print a message to the console, using a color.
Chris@0 1421 *
Chris@0 1422 * @param string $message
Chris@0 1423 * The message to print.
Chris@0 1424 * @param int $color_code
Chris@0 1425 * The color code to use for coloring.
Chris@0 1426 */
Chris@0 1427 function simpletest_script_print($message, $color_code) {
Chris@0 1428 global $args;
Chris@0 1429 if ($args['color']) {
Chris@0 1430 echo "\033[" . $color_code . "m" . $message . "\033[0m";
Chris@0 1431 }
Chris@0 1432 else {
Chris@0 1433 echo $message;
Chris@0 1434 }
Chris@0 1435 }
Chris@0 1436
Chris@0 1437 /**
Chris@0 1438 * Get the color code associated with the specified status.
Chris@0 1439 *
Chris@0 1440 * @param string $status
Chris@0 1441 * The status string to get code for. Special cases are: 'pass', 'fail', or
Chris@0 1442 * 'exception'.
Chris@0 1443 *
Chris@0 1444 * @return int
Chris@0 1445 * Color code. Returns 0 for default case.
Chris@0 1446 */
Chris@0 1447 function simpletest_script_color_code($status) {
Chris@0 1448 switch ($status) {
Chris@0 1449 case 'pass':
Chris@0 1450 return SIMPLETEST_SCRIPT_COLOR_PASS;
Chris@0 1451
Chris@0 1452 case 'fail':
Chris@0 1453 return SIMPLETEST_SCRIPT_COLOR_FAIL;
Chris@0 1454
Chris@0 1455 case 'exception':
Chris@0 1456 return SIMPLETEST_SCRIPT_COLOR_EXCEPTION;
Chris@0 1457 }
Chris@0 1458 // Default formatting.
Chris@0 1459 return 0;
Chris@0 1460 }
Chris@0 1461
Chris@0 1462 /**
Chris@0 1463 * Prints alternative test names.
Chris@0 1464 *
Chris@0 1465 * Searches the provided array of string values for close matches based on the
Chris@0 1466 * Levenshtein algorithm.
Chris@0 1467 *
Chris@0 1468 * @param string $string
Chris@0 1469 * A string to test.
Chris@0 1470 * @param array $array
Chris@0 1471 * A list of strings to search.
Chris@0 1472 * @param int $degree
Chris@0 1473 * The matching strictness. Higher values return fewer matches. A value of
Chris@0 1474 * 4 means that the function will return strings from $array if the candidate
Chris@0 1475 * string in $array would be identical to $string by changing 1/4 or fewer of
Chris@0 1476 * its characters.
Chris@0 1477 *
Chris@14 1478 * @see http://php.net/manual/function.levenshtein.php
Chris@0 1479 */
Chris@0 1480 function simpletest_script_print_alternatives($string, $array, $degree = 4) {
Chris@14 1481 $alternatives = [];
Chris@0 1482 foreach ($array as $item) {
Chris@0 1483 $lev = levenshtein($string, $item);
Chris@0 1484 if ($lev <= strlen($item) / $degree || FALSE !== strpos($string, $item)) {
Chris@0 1485 $alternatives[] = $item;
Chris@0 1486 }
Chris@0 1487 }
Chris@0 1488 if (!empty($alternatives)) {
Chris@0 1489 simpletest_script_print(" Did you mean?\n", SIMPLETEST_SCRIPT_COLOR_FAIL);
Chris@0 1490 foreach ($alternatives as $alternative) {
Chris@0 1491 simpletest_script_print(" - $alternative\n", SIMPLETEST_SCRIPT_COLOR_FAIL);
Chris@0 1492 }
Chris@0 1493 }
Chris@0 1494 }
Chris@0 1495
Chris@0 1496 /**
Chris@0 1497 * Loads the simpletest messages from the database.
Chris@0 1498 *
Chris@0 1499 * Messages are ordered by test class and message id.
Chris@0 1500 *
Chris@0 1501 * @param array $test_ids
Chris@0 1502 * Array of test IDs of the messages to be loaded.
Chris@0 1503 *
Chris@0 1504 * @return array
Chris@0 1505 * Array of simpletest messages from the database.
Chris@0 1506 */
Chris@0 1507 function simpletest_script_load_messages_by_test_id($test_ids) {
Chris@0 1508 global $args;
Chris@14 1509 $results = [];
Chris@0 1510
Chris@0 1511 // Sqlite has a maximum number of variables per query. If required, the
Chris@0 1512 // database query is split into chunks.
Chris@0 1513 if (count($test_ids) > SIMPLETEST_SCRIPT_SQLITE_VARIABLE_LIMIT && !empty($args['sqlite'])) {
Chris@0 1514 $test_id_chunks = array_chunk($test_ids, SIMPLETEST_SCRIPT_SQLITE_VARIABLE_LIMIT);
Chris@0 1515 }
Chris@0 1516 else {
Chris@14 1517 $test_id_chunks = [$test_ids];
Chris@0 1518 }
Chris@0 1519
Chris@0 1520 foreach ($test_id_chunks as $test_id_chunk) {
Chris@0 1521 try {
Chris@0 1522 $result_chunk = Database::getConnection('default', 'test-runner')
Chris@14 1523 ->query("SELECT * FROM {simpletest} WHERE test_id IN ( :test_ids[] ) ORDER BY test_class, message_id", [
Chris@0 1524 ':test_ids[]' => $test_id_chunk,
Chris@14 1525 ])->fetchAll();
Chris@0 1526 }
Chris@0 1527 catch (Exception $e) {
Chris@0 1528 echo (string) $e;
Chris@0 1529 exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
Chris@0 1530 }
Chris@0 1531 if ($result_chunk) {
Chris@0 1532 $results = array_merge($results, $result_chunk);
Chris@0 1533 }
Chris@0 1534 }
Chris@0 1535
Chris@0 1536 return $results;
Chris@0 1537 }
Chris@0 1538
Chris@0 1539 /**
Chris@0 1540 * Display test results.
Chris@0 1541 */
Chris@0 1542 function simpletest_script_open_browser() {
Chris@0 1543 global $test_ids;
Chris@0 1544
Chris@0 1545 try {
Chris@0 1546 $connection = Database::getConnection('default', 'test-runner');
Chris@0 1547 $results = $connection->select('simpletest')
Chris@0 1548 ->fields('simpletest')
Chris@0 1549 ->condition('test_id', $test_ids, 'IN')
Chris@0 1550 ->orderBy('test_class')
Chris@0 1551 ->orderBy('message_id')
Chris@0 1552 ->execute()
Chris@0 1553 ->fetchAll();
Chris@0 1554 }
Chris@0 1555 catch (Exception $e) {
Chris@0 1556 echo (string) $e;
Chris@0 1557 exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
Chris@0 1558 }
Chris@0 1559
Chris@0 1560 // Get the results form.
Chris@14 1561 $form = [];
Chris@0 1562 SimpletestResultsForm::addResultForm($form, $results);
Chris@0 1563
Chris@0 1564 // Get the assets to make the details element collapsible and theme the result
Chris@0 1565 // form.
Chris@14 1566 $assets = new AttachedAssets();
Chris@0 1567 $assets->setLibraries([
Chris@0 1568 'core/drupal.collapse',
Chris@0 1569 'system/admin',
Chris@0 1570 'simpletest/drupal.simpletest',
Chris@0 1571 ]);
Chris@0 1572 $resolver = \Drupal::service('asset.resolver');
Chris@0 1573 list($js_assets_header, $js_assets_footer) = $resolver->getJsAssets($assets, FALSE);
Chris@0 1574 $js_collection_renderer = \Drupal::service('asset.js.collection_renderer');
Chris@0 1575 $js_assets_header = $js_collection_renderer->render($js_assets_header);
Chris@0 1576 $js_assets_footer = $js_collection_renderer->render($js_assets_footer);
Chris@0 1577 $css_assets = \Drupal::service('asset.css.collection_renderer')->render($resolver->getCssAssets($assets, FALSE));
Chris@0 1578
Chris@0 1579 // Make the html page to write to disk.
Chris@0 1580 $render_service = \Drupal::service('renderer');
Chris@0 1581 $html = '<head>' . $render_service->renderPlain($js_assets_header) . $render_service->renderPlain($css_assets) . '</head><body>' . $render_service->renderPlain($form) . $render_service->renderPlain($js_assets_footer) . '</body>';
Chris@0 1582
Chris@0 1583 // Ensure we have assets verbose directory - tests with no verbose output will
Chris@0 1584 // not have created one.
Chris@0 1585 $directory = PublicStream::basePath() . '/simpletest/verbose';
Chris@18 1586 \Drupal::service('file_system')->prepareDirectory($directory, FileSystemInterface::CREATE_DIRECTORY | FileSystemInterface::MODIFY_PERMISSIONS);
Chris@0 1587 $php = new Php();
Chris@0 1588 $uuid = $php->generate();
Chris@0 1589 $filename = $directory . '/results-' . $uuid . '.html';
Chris@0 1590 $base_url = getenv('SIMPLETEST_BASE_URL');
Chris@0 1591 if (empty($base_url)) {
Chris@0 1592 simpletest_script_print_error("--browser needs argument --url.");
Chris@0 1593 }
Chris@0 1594 $url = $base_url . '/' . PublicStream::basePath() . '/simpletest/verbose/results-' . $uuid . '.html';
Chris@0 1595 file_put_contents($filename, $html);
Chris@0 1596
Chris@0 1597 // See if we can find an OS helper to open URLs in default browser.
Chris@0 1598 $browser = FALSE;
Chris@0 1599 if (shell_exec('which xdg-open')) {
Chris@0 1600 $browser = 'xdg-open';
Chris@0 1601 }
Chris@0 1602 elseif (shell_exec('which open')) {
Chris@0 1603 $browser = 'open';
Chris@0 1604 }
Chris@0 1605 elseif (substr(PHP_OS, 0, 3) == 'WIN') {
Chris@0 1606 $browser = 'start';
Chris@0 1607 }
Chris@0 1608
Chris@0 1609 if ($browser) {
Chris@0 1610 shell_exec($browser . ' ' . escapeshellarg($url));
Chris@0 1611 }
Chris@0 1612 else {
Chris@0 1613 // Can't find assets valid browser.
Chris@0 1614 print 'Open file://' . realpath($filename) . ' in your browser to see the verbose output.';
Chris@0 1615 }
Chris@0 1616 }