run-tests.sh

Same filename and directory in other branches
  1. 7.x scripts/run-tests.sh
  2. 9 core/scripts/run-tests.sh
  3. 8.9.x core/scripts/run-tests.sh
  4. 10 core/scripts/run-tests.sh

Script for running tests on DrupalCI.

This script is intended for use only by drupal.org's testing. In general, tests should be run directly with phpunit.

@internal

File

core/scripts/run-tests.sh

View source
  1. <?php
  2. /**
  3. * @file
  4. * Script for running tests on DrupalCI.
  5. *
  6. * This script is intended for use only by drupal.org's testing. In general,
  7. * tests should be run directly with phpunit.
  8. *
  9. * @internal
  10. */
  11. use Drupal\Component\FileSystem\FileSystem;
  12. use Drupal\Component\Utility\Environment;
  13. use Drupal\Component\Utility\Html;
  14. use Drupal\Component\Utility\Timer;
  15. use Drupal\Core\Composer\Composer;
  16. use Drupal\Core\Database\Database;
  17. use Drupal\Core\Test\EnvironmentCleaner;
  18. use Drupal\Core\Test\PhpUnitTestDiscovery;
  19. use Drupal\Core\Test\PhpUnitTestRunner;
  20. use Drupal\Core\Test\SimpletestTestRunResultsStorage;
  21. use Drupal\Core\Test\TestDatabase;
  22. use Drupal\Core\Test\TestRun;
  23. use Drupal\Core\Test\TestRunnerKernel;
  24. use Drupal\Core\Test\TestRunResultsStorageInterface;
  25. use Drupal\BuildTests\Framework\BuildTestBase;
  26. use Drupal\FunctionalJavascriptTests\WebDriverTestBase;
  27. use Drupal\KernelTests\KernelTestBase;
  28. use Drupal\Tests\BrowserTestBase;
  29. use PHPUnit\Framework\TestCase;
  30. use PHPUnit\Runner\Version;
  31. use Symfony\Component\Console\Output\ConsoleOutput;
  32. use Symfony\Component\HttpFoundation\Request;
  33. use Symfony\Component\Process\Process;
  34. // cspell:ignore exitcode testbots wwwrun
  35. // Define some colors for display.
  36. // A nice calming green.
  37. const SIMPLETEST_SCRIPT_COLOR_PASS = 32;
  38. // An alerting Red.
  39. const SIMPLETEST_SCRIPT_COLOR_FAIL = 31;
  40. // An annoying brown.
  41. const SIMPLETEST_SCRIPT_COLOR_EXCEPTION = 33;
  42. // An appeasing yellow.
  43. const SIMPLETEST_SCRIPT_COLOR_YELLOW = 33;
  44. // A refreshing cyan.
  45. const SIMPLETEST_SCRIPT_COLOR_CYAN = 36;
  46. // A fainting gray.
  47. const SIMPLETEST_SCRIPT_COLOR_GRAY = 90;
  48. // A notable white.
  49. const SIMPLETEST_SCRIPT_COLOR_BRIGHT_WHITE = "1;97";
  50. // Restricting the chunk of queries prevents memory exhaustion.
  51. const SIMPLETEST_SCRIPT_SQLITE_VARIABLE_LIMIT = 350;
  52. const SIMPLETEST_SCRIPT_EXIT_SUCCESS = 0;
  53. const SIMPLETEST_SCRIPT_EXIT_FAILURE = 1;
  54. const SIMPLETEST_SCRIPT_EXIT_ERROR = 2;
  55. const SIMPLETEST_SCRIPT_EXIT_EXCEPTION = 3;
  56. // Set defaults and get overrides.
  57. [$args, $count] = simpletest_script_parse_args();
  58. if ($args['help'] || $count == 0) {
  59. simpletest_script_help();
  60. exit(($count == 0) ? SIMPLETEST_SCRIPT_EXIT_FAILURE : SIMPLETEST_SCRIPT_EXIT_SUCCESS);
  61. }
  62. simpletest_script_init();
  63. if (!class_exists(TestCase::class)) {
  64. echo "\nrun-tests.sh requires the PHPUnit testing framework. Use 'composer install' to ensure that it is present.\n\n";
  65. exit(SIMPLETEST_SCRIPT_EXIT_FAILURE);
  66. }
  67. if ($args['execute-test']) {
  68. simpletest_script_setup_database();
  69. $test_run_results_storage = simpletest_script_setup_test_run_results_storage();
  70. $test_run = TestRun::get($test_run_results_storage, $args['test-id']);
  71. simpletest_script_run_one_test($test_run, $args['execute-test']);
  72. // Sub-process exited already; this is just for clarity.
  73. exit(SIMPLETEST_SCRIPT_EXIT_SUCCESS);
  74. }
  75. if ($args['list']) {
  76. // Display all available tests organized by one @group annotation.
  77. echo "\nAvailable test groups & classes\n";
  78. echo "-------------------------------\n\n";
  79. $test_discovery = PhpUnitTestDiscovery::instance()->setConfigurationFilePath(\Drupal::root() . \DIRECTORY_SEPARATOR . 'core');
  80. try {
  81. $groups = $test_discovery->getTestClasses($args['module']);
  82. foreach ($test_discovery->getWarnings() as $warning) {
  83. simpletest_script_print($warning . "\n", SIMPLETEST_SCRIPT_COLOR_EXCEPTION);
  84. }
  85. }
  86. catch (Exception $e) {
  87. error_log((string) $e);
  88. echo (string) $e;
  89. exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
  90. }
  91. // A given class can appear in multiple groups. For historical reasons, we
  92. // need to present each test only once. The test is shown in the group that is
  93. // printed first.
  94. $printed_tests = [];
  95. foreach ($groups as $group => $tests) {
  96. echo $group . "\n";
  97. $tests = array_diff(array_keys($tests), $printed_tests);
  98. foreach ($tests as $test) {
  99. echo " - $test\n";
  100. }
  101. $printed_tests = array_merge($printed_tests, $tests);
  102. }
  103. exit(SIMPLETEST_SCRIPT_EXIT_SUCCESS);
  104. }
  105. // List-files and list-files-json provide a way for external tools such as the
  106. // testbot to prioritize running changed tests.
  107. // @see https://www.drupal.org/node/2569585
  108. if ($args['list-files'] || $args['list-files-json']) {
  109. // List all files which could be run as tests.
  110. $test_discovery = PhpUnitTestDiscovery::instance()->setConfigurationFilePath(\Drupal::root() . \DIRECTORY_SEPARATOR . 'core');
  111. // PhpUnitTestDiscovery::findAllClassFiles() gives us a classmap similar to a
  112. // Composer 'classmap' array.
  113. $test_classes = $test_discovery->findAllClassFiles();
  114. // JSON output is the easiest.
  115. if ($args['list-files-json']) {
  116. echo json_encode($test_classes);
  117. exit(SIMPLETEST_SCRIPT_EXIT_SUCCESS);
  118. }
  119. // Output the list of files.
  120. else {
  121. foreach (array_values($test_classes) as $test_class) {
  122. echo $test_class . "\n";
  123. }
  124. }
  125. exit(SIMPLETEST_SCRIPT_EXIT_SUCCESS);
  126. }
  127. simpletest_script_setup_database(TRUE);
  128. // Setup the test run results storage environment. Currently, this coincides
  129. // with the simpletest database schema.
  130. $test_run_results_storage = simpletest_script_setup_test_run_results_storage(TRUE);
  131. if ($args['clean']) {
  132. // Clean up left-over tables and directories.
  133. $cleaner = new EnvironmentCleaner(
  134. DRUPAL_ROOT,
  135. Database::getConnection(),
  136. $test_run_results_storage,
  137. new ConsoleOutput(),
  138. \Drupal::service('file_system')
  139. );
  140. try {
  141. $cleaner->cleanEnvironment();
  142. }
  143. catch (Exception $e) {
  144. echo (string) $e;
  145. exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
  146. }
  147. echo "\nEnvironment cleaned.\n";
  148. // Get the status messages and print them.
  149. $messages = \Drupal::messenger()->messagesByType('status');
  150. foreach ($messages as $text) {
  151. echo " - " . $text . "\n";
  152. }
  153. exit(SIMPLETEST_SCRIPT_EXIT_SUCCESS);
  154. }
  155. if (!Composer::upgradePHPUnitCheck(Version::id())) {
  156. simpletest_script_print_error("PHPUnit testing framework version 11 or greater is required when running on PHP 8.4 or greater. Run the command 'composer run-script drupal-phpunit-upgrade' in order to fix this.");
  157. exit(SIMPLETEST_SCRIPT_EXIT_FAILURE);
  158. }
  159. echo "\n";
  160. echo "Drupal test run\n\n";
  161. echo sprintf("Drupal Version: %s\n", \Drupal::VERSION);
  162. echo sprintf("PHP Version: %s\n", \PHP_VERSION);
  163. echo sprintf("PHP Binary: %s\n", $php ?? getenv('_'));
  164. echo sprintf("PHPUnit Version: %s\n", Version::id());
  165. echo "-------------------------------\n";
  166. echo "\n";
  167. $test_list = simpletest_script_get_test_list();
  168. // Try to allocate unlimited time to run the tests.
  169. Environment::setTimeLimit(0);
  170. simpletest_script_reporter_init();
  171. $tests_to_run = [];
  172. for ($i = 0; $i < $args['repeat']; $i++) {
  173. $tests_to_run = array_merge($tests_to_run, $test_list);
  174. }
  175. // Execute tests.
  176. $status = simpletest_script_execute_batch($test_run_results_storage, $tests_to_run);
  177. // Stop the timer.
  178. simpletest_script_reporter_timer_stop();
  179. // Ensure all test locks are released once finished. If tests are run with a
  180. // concurrency of 1 the each test will clean up its own lock. Test locks are
  181. // not released if using a higher concurrency to ensure each test has unique
  182. // fixtures.
  183. TestDatabase::releaseAllTestLocks();
  184. // Display results before database is cleared.
  185. simpletest_script_reporter_display_results($test_run_results_storage);
  186. if ($args['xml']) {
  187. simpletest_script_reporter_write_xml_results($test_run_results_storage);
  188. }
  189. // Clean up all test results.
  190. if (!$args['keep-results']) {
  191. try {
  192. $cleaner = new EnvironmentCleaner(
  193. DRUPAL_ROOT,
  194. Database::getConnection(),
  195. $test_run_results_storage,
  196. new ConsoleOutput(),
  197. \Drupal::service('file_system')
  198. );
  199. $cleaner->cleanResults();
  200. }
  201. catch (Exception $e) {
  202. echo (string) $e;
  203. exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
  204. }
  205. }
  206. // Test complete, exit.
  207. exit($status);
  208. /**
  209. * Print help text.
  210. */
  211. function simpletest_script_help(): void {
  212. global $args;
  213. echo <<
  214. Run Drupal tests from the shell.
  215. Usage: {$args['script']} [OPTIONS]
  216. Example: {$args['script']} Profile
  217. All arguments are long options.
  218. --help Print this page.
  219. --list Display all available test groups.
  220. --list-files
  221. Display all discoverable test file paths.
  222. --list-files-json
  223. Display all discoverable test files as JSON. The array key will be
  224. the test class name, and the value will be the file path of the
  225. test.
  226. --clean Cleans up database tables or directories from previous, failed,
  227. tests and then exits (no tests are run).
  228. --url The base URL of the root directory of this Drupal checkout; e.g.:
  229. http://drupal.test/
  230. Required unless the Drupal root directory maps exactly to:
  231. http://localhost:80/
  232. Use a https:// URL to force all tests to be run under SSL.
  233. --sqlite A pathname to use for the SQLite database of the test runner.
  234. Required unless this script is executed with a working Drupal
  235. installation.
  236. A relative pathname is interpreted relative to the Drupal root
  237. directory.
  238. Note that ':memory:' cannot be used, because this script spawns
  239. sub-processes. However, you may use e.g. '/tmpfs/test.sqlite'
  240. --keep-results-table
  241. Boolean flag to indicate to not cleanup the simpletest result
  242. table. For testbots or repeated execution of a single test it can
  243. be helpful to not cleanup the simpletest result table.
  244. --dburl A URI denoting the database driver, credentials, server hostname,
  245. and database name to use in tests.
  246. Required when running tests without a Drupal installation that
  247. contains default database connection info in settings.php.
  248. Examples:
  249. mysql://username:password@localhost/database_name#table_prefix
  250. sqlite://localhost/relative/path/db.sqlite
  251. sqlite://localhost//absolute/path/db.sqlite
  252. --php The absolute path to the PHP executable. Usually not needed.
  253. --concurrency [num]
  254. Run tests in parallel, up to [num] tests at a time.
  255. --all Run all available tests.
  256. --module Run all tests belonging to the specified module name.
  257. (e.g., 'node')
  258. --class Run tests identified by specific class names, instead of group names.
  259. --file Run tests identified by specific file names, instead of group names.
  260. Specify the path and the extension
  261. (i.e. 'core/modules/user/tests/src/Functional/UserCreateTest.php').
  262. This argument must be last on the command line.
  263. --types
  264. Runs just tests from the specified test type, for example
  265. run-tests.sh
  266. (i.e. --types "PHPUnit-Unit,PHPUnit-Kernel")
  267. --directory Run all tests found within the specified file directory.
  268. --xml
  269. If provided, test results will be written as xml files to this path.
  270. --color Output text format results with color highlighting.
  271. --verbose Output detailed assertion messages in addition to summary.
  272. --keep-results
  273. Keeps detailed assertion results (in the database) after tests
  274. have completed. By default, assertion results are cleared.
  275. --repeat Number of times to repeat the test.
  276. --die-on-fail
  277. Exit test execution immediately upon any failed assertion. This
  278. allows to access the test site by changing settings.php to use the
  279. test database and configuration directories. Use in combination
  280. with --repeat for debugging random test failures.
  281. --non-html Removes escaping from output. Useful for reading results on the
  282. CLI.
  283. --suppress-deprecations
  284. Stops tests from failing if deprecation errors are triggered. If
  285. this is not set the value specified in the
  286. SYMFONY_DEPRECATIONS_HELPER environment variable, or the value
  287. specified in core/phpunit.xml (if it exists), or the default value
  288. will be used. The default is that any unexpected silenced
  289. deprecation error will fail tests.
  290. --ci-parallel-node-total
  291. The total number of instances of this job running in parallel.
  292. --ci-parallel-node-index
  293. The index of the job in the job set.
  294. --debug-discovery
  295. If provided, dumps detailed information on the tests selected
  296. for execution, before the execution starts.
  297. [,[, ...]]
  298. One or more tests to be run. By default, these are interpreted
  299. as the names of test groups which are derived from test class
  300. @group annotations.
  301. These group names typically correspond to module names like "User"
  302. or "Profile" or "System", but there is also a group "Database".
  303. If --class is specified then these are interpreted as the names of
  304. specific test classes whose test methods will be run. Tests must
  305. be separated by commas. Ignored if --all is specified.
  306. To run this script you will normally invoke it from the root directory of your
  307. Drupal installation as the webserver user (differs per configuration), or root:
  308. sudo -u [wwwrun|www-data|etc] php ./core/scripts/{$args['script']}
  309. --url http://example.com/ --all
  310. sudo -u [wwwrun|www-data|etc] php ./core/scripts/{$args['script']}
  311. --url http://example.com/ --class Drupal\Tests\block\Functional\BlockTest
  312. Without a preinstalled Drupal site, specify a SQLite database pathname to create
  313. (for the test runner) and the default database connection info (for Drupal) to
  314. use in tests:
  315. sudo -u [wwwrun|www-data|etc] php ./core/scripts/{$args['script']}
  316. --sqlite /tmpfs/drupal/test.sqlite
  317. --dburl mysql://username:password@localhost/database
  318. --url http://example.com/ --all
  319. EOF;
  320. }
  321. /**
  322. * Parse execution argument and ensure that all are valid.
  323. *
  324. * @return array
  325. * The list of arguments.
  326. */
  327. function simpletest_script_parse_args() {
  328. // Set default values.
  329. $args = [
  330. 'script' => '',
  331. 'help' => FALSE,
  332. 'list' => FALSE,
  333. 'list-files' => FALSE,
  334. 'list-files-json' => FALSE,
  335. 'clean' => FALSE,
  336. 'url' => '',
  337. 'sqlite' => NULL,
  338. 'dburl' => NULL,
  339. 'php' => '',
  340. 'concurrency' => 1,
  341. 'all' => FALSE,
  342. 'module' => NULL,
  343. 'class' => FALSE,
  344. 'file' => FALSE,
  345. 'types' => [],
  346. 'directory' => NULL,
  347. 'color' => FALSE,
  348. 'verbose' => FALSE,
  349. 'keep-results' => FALSE,
  350. 'keep-results-table' => FALSE,
  351. 'test_names' => [],
  352. 'repeat' => 1,
  353. 'die-on-fail' => FALSE,
  354. 'suppress-deprecations' => FALSE,
  355. // Used internally.
  356. 'test-id' => 0,
  357. 'execute-test' => '',
  358. 'xml' => '',
  359. 'non-html' => FALSE,
  360. 'ci-parallel-node-index' => 1,
  361. 'ci-parallel-node-total' => 1,
  362. 'debug-discovery' => FALSE,
  363. ];
  364. // Override with set values.
  365. $args['script'] = basename(array_shift($_SERVER['argv']));
  366. $count = 0;
  367. while ($arg = array_shift($_SERVER['argv'])) {
  368. if (preg_match('/--(\S+)/', $arg, $matches)) {
  369. // Argument found.
  370. if (array_key_exists($matches[1], $args)) {
  371. // Argument found in list.
  372. $previous_arg = $matches[1];
  373. if (is_bool($args[$previous_arg])) {
  374. $args[$matches[1]] = TRUE;
  375. }
  376. elseif (is_array($args[$previous_arg])) {
  377. $value = array_shift($_SERVER['argv']);
  378. $args[$matches[1]] = array_map('trim', explode(',', $value));
  379. }
  380. else {
  381. $args[$matches[1]] = array_shift($_SERVER['argv']);
  382. }
  383. // Clear extraneous values.
  384. $args['test_names'] = [];
  385. $count++;
  386. }
  387. else {
  388. // Argument not found in list.
  389. simpletest_script_print_error("Unknown argument '$arg'.");
  390. exit(SIMPLETEST_SCRIPT_EXIT_FAILURE);
  391. }
  392. }
  393. else {
  394. // Values found without an argument should be test names.
  395. $args['test_names'] += explode(',', $arg);
  396. $count++;
  397. }
  398. }
  399. // Validate the concurrency argument.
  400. if (!is_numeric($args['concurrency']) || $args['concurrency'] <= 0) {
  401. simpletest_script_print_error("--concurrency must be a strictly positive integer.");
  402. exit(SIMPLETEST_SCRIPT_EXIT_FAILURE);
  403. }
  404. return [$args, $count];
  405. }
  406. /**
  407. * Initialize script variables and perform general setup requirements.
  408. */
  409. function simpletest_script_init(): void {
  410. global $args, $php;
  411. $host = 'localhost';
  412. $path = '';
  413. $port = '80';
  414. $php = "";
  415. // Determine location of php command automatically, unless a command line
  416. // argument is supplied.
  417. if ($php_env = getenv('_')) {
  418. // '_' is an environment variable set by the shell. It contains the command
  419. // that was executed.
  420. $php = $php_env;
  421. }
  422. if ($sudo = getenv('SUDO_COMMAND')) {
  423. // 'SUDO_COMMAND' is an environment variable set by the sudo program.
  424. // This will be set if the script is run directly by sudo or if the
  425. // script is run under a shell started by sudo.
  426. if (str_contains($sudo, basename(__FILE__))) {
  427. // This script may have been directly run by sudo. $php may have the
  428. // path to sudo from getenv('_') if run with the -E option.
  429. // Extract what may be the PHP interpreter.
  430. [$php] = explode(' ', $sudo, 2);
  431. }
  432. }
  433. if (!empty($args['php'])) {
  434. // Caller has specified path to php. Override auto-detection.
  435. $php = $args['php'];
  436. }
  437. if ($php == "") {
  438. simpletest_script_print_error('Unable to automatically determine the path to the PHP interpreter. Supply the --php command line argument.');
  439. simpletest_script_help();
  440. exit(SIMPLETEST_SCRIPT_EXIT_FAILURE);
  441. }
  442. // Detect if we're in the top-level process using the private 'execute-test'
  443. // argument. Determine if being run on drupal.org's testing infrastructure
  444. // using the presence of 'drupalci' in the sqlite argument.
  445. // @todo https://www.drupal.org/project/drupalci_testbot/issues/2860941 Use
  446. // better environment variable to detect DrupalCI.
  447. if (!$args['execute-test'] && preg_match('/drupalci/', $args['sqlite'] ?? '')) {
  448. // Update PHPUnit if needed and possible. There is a later check once the
  449. // autoloader is in place to ensure we're on the correct version. We need to
  450. // do this before the autoloader is in place to ensure that it is correct.
  451. $composer = ($composer = rtrim('\\' === DIRECTORY_SEPARATOR ? preg_replace('/[\r\n].*/', '', `where.exe composer.phar`) : `which composer.phar`))
  452. ? $php . ' ' . escapeshellarg($composer)
  453. : 'composer';
  454. passthru("$composer run-script drupal-phpunit-upgrade-check");
  455. }
  456. $autoloader = require_once __DIR__ . '/../../autoload.php';
  457. // The PHPUnit compatibility layer needs to be available to autoload tests.
  458. $autoloader->add('Drupal\\TestTools', __DIR__ . '/../tests');
  459. // Get URL from arguments.
  460. if (!empty($args['url'])) {
  461. $parsed_url = parse_url($args['url']);
  462. $host = $parsed_url['host'] . (isset($parsed_url['port']) ? ':' . $parsed_url['port'] : '');
  463. $path = isset($parsed_url['path']) ? rtrim(rtrim($parsed_url['path']), '/') : '';
  464. $port = $parsed_url['port'] ?? $port;
  465. if ($path == '/') {
  466. $path = '';
  467. }
  468. // If the passed URL schema is 'https' then setup the $_SERVER variables
  469. // properly so that testing will run under HTTPS.
  470. if ($parsed_url['scheme'] == 'https') {
  471. $_SERVER['HTTPS'] = 'on';
  472. }
  473. }
  474. if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') {
  475. $base_url = 'https://';
  476. }
  477. else {
  478. $base_url = 'http://';
  479. }
  480. $base_url .= $host;
  481. if ($path !== '') {
  482. $base_url .= $path;
  483. }
  484. putenv('SIMPLETEST_BASE_URL=' . $base_url);
  485. $_SERVER['HTTP_HOST'] = $host;
  486. $_SERVER['REMOTE_ADDR'] = '127.0.0.1';
  487. $_SERVER['SERVER_ADDR'] = '127.0.0.1';
  488. $_SERVER['SERVER_PORT'] = $port;
  489. $_SERVER['SERVER_SOFTWARE'] = NULL;
  490. $_SERVER['SERVER_NAME'] = 'localhost';
  491. $_SERVER['REQUEST_URI'] = $path . '/';
  492. $_SERVER['REQUEST_METHOD'] = 'GET';
  493. $_SERVER['SCRIPT_NAME'] = $path . '/index.php';
  494. $_SERVER['SCRIPT_FILENAME'] = $path . '/index.php';
  495. $_SERVER['PHP_SELF'] = $path . '/index.php';
  496. $_SERVER['HTTP_USER_AGENT'] = 'Drupal command line';
  497. if ($args['concurrency'] > 1) {
  498. $directory = FileSystem::getOsTemporaryDirectory();
  499. $test_symlink = @symlink(__FILE__, $directory . '/test_symlink');
  500. if (!$test_symlink) {
  501. throw new \RuntimeException('In order to use a concurrency higher than 1 the test system needs to be able to create symlinks in ' . $directory);
  502. }
  503. unlink($directory . '/test_symlink');
  504. putenv('RUN_TESTS_CONCURRENCY=' . $args['concurrency']);
  505. }
  506. if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
  507. // Ensure that any and all environment variables are changed to https://.
  508. foreach ($_SERVER as $key => $value) {
  509. // Some values are NULL. Non-NULL values which are falsy will not contain
  510. // text to replace.
  511. if ($value) {
  512. $_SERVER[$key] = str_replace('http://', 'https://', $value);
  513. }
  514. }
  515. }
  516. chdir(realpath(__DIR__ . '/../..'));
  517. // Prepare the kernel.
  518. try {
  519. $request = Request::createFromGlobals();
  520. $kernel = TestRunnerKernel::createFromRequest($request, $autoloader);
  521. $kernel->boot();
  522. $kernel->preHandle($request);
  523. }
  524. catch (Exception $e) {
  525. echo (string) $e;
  526. exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
  527. }
  528. }
  529. /**
  530. * Sets up database connection info for running tests.
  531. *
  532. * If this script is executed from within a real Drupal installation, then this
  533. * function essentially performs nothing (unless the --sqlite or --dburl
  534. * parameters were passed).
  535. *
  536. * Otherwise, there are three database connections of concern:
  537. * - --sqlite: The test runner connection, providing access to database tables
  538. * for recording test IDs and assertion results.
  539. * - --dburl: A database connection that is used as base connection info for all
  540. * tests; i.e., every test will spawn from this connection. In case this
  541. * connection uses e.g. SQLite, then all tests will run against SQLite. This
  542. * is exposed as $databases['default']['default'] to Drupal.
  543. * - The actual database connection used within a test. This is the same as
  544. * --dburl, but uses an additional database table prefix. This is
  545. * $databases['default']['default'] within a test environment. The original
  546. * connection is retained in
  547. * $databases['simpletest_original_default']['default'] and restored after
  548. * each test.
  549. *
  550. * @param bool $new
  551. * Whether this process is a run-tests.sh master process. If TRUE, the SQLite
  552. * database file specified by --sqlite (if any) is set up. Otherwise, database
  553. * connections are prepared only.
  554. */
  555. function simpletest_script_setup_database($new = FALSE): void {
  556. global $args;
  557. // If there is an existing Drupal installation that contains a database
  558. // connection info in settings.php, then $databases['default']['default'] will
  559. // hold the default database connection already. This connection is assumed to
  560. // be valid, and this connection will be used in tests, so that they run
  561. // against e.g. MySQL instead of SQLite.
  562. // However, in case no Drupal installation exists, this default database
  563. // connection can be set and/or overridden with the --dburl parameter.
  564. if (!empty($args['dburl'])) {
  565. // Remove a possibly existing default connection (from settings.php).
  566. Database::removeConnection('default');
  567. try {
  568. $databases['default']['default'] = Database::convertDbUrlToConnectionInfo($args['dburl'], TRUE);
  569. }
  570. catch (\InvalidArgumentException $e) {
  571. simpletest_script_print_error('Invalid --dburl. Reason: ' . $e->getMessage());
  572. exit(SIMPLETEST_SCRIPT_EXIT_FAILURE);
  573. }
  574. }
  575. // Otherwise, use the default database connection from settings.php.
  576. else {
  577. $databases['default'] = Database::getConnectionInfo('default');
  578. }
  579. if (isset($databases['default']['default'])) {
  580. Database::addConnectionInfo('default', 'default', $databases['default']['default']);
  581. }
  582. }
  583. /**
  584. * Sets up the test runs results storage.
  585. */
  586. function simpletest_script_setup_test_run_results_storage($new = FALSE) {
  587. global $args;
  588. $databases['default'] = Database::getConnectionInfo('default');
  589. // If no --sqlite parameter has been passed, then the test runner database
  590. // connection is the default database connection.
  591. if (empty($args['sqlite'])) {
  592. $sqlite = FALSE;
  593. $databases['test-runner']['default'] = $databases['default']['default'];
  594. }
  595. // Otherwise, set up a SQLite connection for the test runner.
  596. else {
  597. if ($args['sqlite'][0] === '/') {
  598. $sqlite = $args['sqlite'];
  599. }
  600. else {
  601. $sqlite = DRUPAL_ROOT . '/' . $args['sqlite'];
  602. }
  603. $databases['test-runner']['default'] = [
  604. 'driver' => 'sqlite',
  605. 'database' => $sqlite,
  606. 'prefix' => '',
  607. ];
  608. // Create the test runner SQLite database, unless it exists already.
  609. if ($new && !file_exists($sqlite)) {
  610. if (!is_dir(dirname($sqlite))) {
  611. mkdir(dirname($sqlite));
  612. }
  613. touch($sqlite);
  614. }
  615. }
  616. // Add the test runner database connection.
  617. Database::addConnectionInfo('test-runner', 'default', $databases['test-runner']['default']);
  618. // Create the test result schema.
  619. try {
  620. $test_run_results_storage = new SimpletestTestRunResultsStorage(Database::getConnection('default', 'test-runner'));
  621. }
  622. catch (\PDOException $e) {
  623. simpletest_script_print_error($databases['test-runner']['default']['driver'] . ': ' . $e->getMessage());
  624. exit(SIMPLETEST_SCRIPT_EXIT_FAILURE);
  625. }
  626. if ($new && $sqlite) {
  627. try {
  628. $test_run_results_storage->buildTestingResultsEnvironment(!empty($args['keep-results-table']));
  629. }
  630. catch (Exception $e) {
  631. echo (string) $e;
  632. exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
  633. }
  634. }
  635. // Verify that the test result database schema exists by checking one table.
  636. try {
  637. if (!$test_run_results_storage->validateTestingResultsEnvironment()) {
  638. simpletest_script_print_error('Missing test result database schema. Use the --sqlite parameter.');
  639. exit(SIMPLETEST_SCRIPT_EXIT_FAILURE);
  640. }
  641. }
  642. catch (Exception $e) {
  643. echo (string) $e;
  644. exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
  645. }
  646. return $test_run_results_storage;
  647. }
  648. /**
  649. * Execute a batch of tests.
  650. */
  651. function simpletest_script_execute_batch(TestRunResultsStorageInterface $test_run_results_storage, $test_classes) {
  652. global $args, $test_ids;
  653. $total_status = SIMPLETEST_SCRIPT_EXIT_SUCCESS;
  654. // Multi-process execution.
  655. $children = [];
  656. while (!empty($test_classes) || !empty($children)) {
  657. while (count($children) < $args['concurrency']) {
  658. if (empty($test_classes)) {
  659. break;
  660. }
  661. try {
  662. $test_run = TestRun::createNew($test_run_results_storage);
  663. }
  664. catch (Exception $e) {
  665. echo (string) $e;
  666. exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
  667. }
  668. $test_ids[] = $test_run->id();
  669. $test_class = array_shift($test_classes);
  670. // Fork a child process.
  671. $command = simpletest_script_command($test_run, $test_class);
  672. try {
  673. $process = new Process($command);
  674. $process->start();
  675. }
  676. catch (\Exception $e) {
  677. echo get_class($e) . ": " . $e->getMessage() . "\n";
  678. echo "Unable to fork test process. Aborting.\n";
  679. exit(SIMPLETEST_SCRIPT_EXIT_SUCCESS);
  680. }
  681. // Register our new child.
  682. $children[] = [
  683. 'process' => $process,
  684. 'test_run' => $test_run,
  685. 'class' => $test_class,
  686. ];
  687. }
  688. // Wait for children every 2ms.
  689. usleep(2000);
  690. // Check if some children finished.
  691. foreach ($children as $cid => $child) {
  692. if ($child['process']->isTerminated()) {
  693. // The child exited.
  694. echo $child['process']->getOutput();
  695. $errorOutput = $child['process']->getErrorOutput();
  696. if ($errorOutput) {
  697. echo 'ERROR: ' . $errorOutput;
  698. }
  699. if (in_array($child['process']->getExitCode(), [SIMPLETEST_SCRIPT_EXIT_FAILURE, SIMPLETEST_SCRIPT_EXIT_ERROR])) {
  700. $total_status = max($child['process']->getExitCode(), $total_status);
  701. }
  702. elseif ($child['process']->getExitCode()) {
  703. $message = 'FATAL ' . $child['class'] . ': test runner returned an unexpected error code (' . $child['process']->getExitCode() . ').';
  704. echo $message . "\n";
  705. $total_status = max(SIMPLETEST_SCRIPT_EXIT_EXCEPTION, $total_status);
  706. if ($args['die-on-fail']) {
  707. $test_db = new TestDatabase($child['test_run']->getDatabasePrefix());
  708. $test_directory = $test_db->getTestSitePath();
  709. echo 'Test database and files kept and test exited immediately on fail so should be reproducible if you change settings.php to use the database prefix ' . $child['test_run']->getDatabasePrefix() . ' and config directories in ' . $test_directory . "\n";
  710. $args['keep-results'] = TRUE;
  711. // Exit repeat loop immediately.
  712. $args['repeat'] = -1;
  713. }
  714. }
  715. // Remove this child.
  716. unset($children[$cid]);
  717. }
  718. }
  719. }
  720. return $total_status;
  721. }
  722. /**
  723. * Run a PHPUnit-based test.
  724. */
  725. function simpletest_script_run_phpunit(TestRun $test_run, $class) {
  726. global $args;
  727. $runner = PhpUnitTestRunner::create(\Drupal::getContainer());
  728. $start = microtime(TRUE);
  729. $results = $runner->execute($test_run, $class, $status, $args['color']);
  730. $time = microtime(TRUE) - $start;
  731. $runner->processPhpUnitResults($test_run, $results);
  732. $summaries = $runner->summarizeResults($results);
  733. foreach ($summaries as $class => $summary) {
  734. simpletest_script_reporter_display_summary($class, $summary, $time);
  735. }
  736. return $status;
  737. }
  738. /**
  739. * Run a single test, bootstrapping Drupal if needed.
  740. */
  741. function simpletest_script_run_one_test(TestRun $test_run, $test_class): void {
  742. global $args;
  743. try {
  744. if ($args['suppress-deprecations']) {
  745. putenv('SYMFONY_DEPRECATIONS_HELPER=disabled');
  746. }
  747. $status = simpletest_script_run_phpunit($test_run, $test_class);
  748. exit($status);
  749. }
  750. // DrupalTestCase::run() catches exceptions already, so this is only reached
  751. // when an exception is thrown in the wrapping test runner environment.
  752. catch (Exception $e) {
  753. echo (string) $e;
  754. exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
  755. }
  756. }
  757. /**
  758. * Return a command used to run a test in a separate process.
  759. *
  760. * @param int $test_id
  761. * The current test ID.
  762. * @param string $test_class
  763. * The name of the test class to run.
  764. *
  765. * @return list
  766. * The list of command-line elements.
  767. */
  768. function simpletest_script_command(TestRun $test_run, string $test_class): array {
  769. global $args, $php;
  770. $command = [];
  771. $command[] = $php;
  772. $command[] = './core/scripts/' . $args['script'];
  773. $command[] = '--url';
  774. $command[] = $args['url'];
  775. if (!empty($args['sqlite'])) {
  776. $command[] = '--sqlite';
  777. $command[] = $args['sqlite'];
  778. }
  779. if (!empty($args['dburl'])) {
  780. $command[] = '--dburl';
  781. $command[] = $args['dburl'];
  782. }
  783. $command[] = '--php';
  784. $command[] = $php;
  785. $command[] = '--test-id';
  786. $command[] = $test_run->id();
  787. foreach (['verbose', 'keep-results', 'color', 'die-on-fail', 'suppress-deprecations'] as $arg) {
  788. if ($args[$arg]) {
  789. $command[] = '--' . $arg;
  790. }
  791. }
  792. // --execute-test and class name needs to come last.
  793. $command[] = '--execute-test';
  794. $command[] = $test_class;
  795. return $command;
  796. }
  797. /**
  798. * Get list of tests based on arguments.
  799. *
  800. * If --all specified then return all available tests, otherwise reads list of
  801. * tests.
  802. *
  803. * @return array
  804. * List of tests.
  805. */
  806. function simpletest_script_get_test_list() {
  807. global $args;
  808. $test_discovery = PhpUnitTestDiscovery::instance()->setConfigurationFilePath(\Drupal::root() . \DIRECTORY_SEPARATOR . 'core');
  809. $test_list = [];
  810. $slow_tests = [];
  811. if ($args['all'] || $args['module'] || $args['directory']) {
  812. try {
  813. $groups = $test_discovery->getTestClasses($args['module'], $args['types'], $args['directory']);
  814. $warnings = $test_discovery->getWarnings();
  815. if (!empty($warnings)) {
  816. simpletest_script_print("Test discovery warnings\n", SIMPLETEST_SCRIPT_COLOR_BRIGHT_WHITE);
  817. simpletest_script_print("-----------------------\n", SIMPLETEST_SCRIPT_COLOR_BRIGHT_WHITE);
  818. foreach ($warnings as $warning) {
  819. simpletest_script_print('* ' . $warning . "\n\n", SIMPLETEST_SCRIPT_COLOR_EXCEPTION);
  820. }
  821. echo "\n";
  822. }
  823. }
  824. catch (Exception $e) {
  825. echo (string) $e;
  826. exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
  827. }
  828. // Ensure that tests marked explicitly as @group #slow are run at the
  829. // beginning of each job.
  830. if (key($groups) === '#slow') {
  831. $slow_tests = array_shift($groups);
  832. }
  833. $not_slow_tests = [];
  834. foreach ($groups as $group => $tests) {
  835. $not_slow_tests = array_merge($not_slow_tests, $tests);
  836. }
  837. // Filter slow tests out of the not slow tests and ensure a unique list
  838. // since tests may appear in more than one group.
  839. $not_slow_tests = array_diff_key($not_slow_tests, $slow_tests);
  840. // If the tests are not being run in parallel, then ensure slow tests run
  841. // all together first.
  842. if ((int) $args['ci-parallel-node-total'] <= 1 ) {
  843. sort_tests_by_type_and_methods($slow_tests);
  844. sort_tests_by_type_and_methods($not_slow_tests);
  845. $all_tests_list = array_merge($slow_tests, $not_slow_tests);
  846. assign_tests_sequence($all_tests_list);
  847. dump_tests_sequence($all_tests_list, $args);
  848. $test_list = array_keys($all_tests_list);
  849. }
  850. else {
  851. // Sort all tests by the number of test cases on the test class.
  852. // This is used in combination with @group #slow to start the slowest
  853. // tests first and distribute tests between test runners.
  854. sort_tests_by_public_method_count($slow_tests);
  855. sort_tests_by_public_method_count($not_slow_tests);
  856. $all_tests_list = array_merge($slow_tests, $not_slow_tests);
  857. assign_tests_sequence($all_tests_list);
  858. // Now set up a bin per test runner.
  859. $bin_count = (int) $args['ci-parallel-node-total'];
  860. // Now loop over the slow tests and add them to a bin one by one, this
  861. // distributes the tests evenly across the bins.
  862. $binned_slow_tests = place_tests_into_bins($slow_tests, $bin_count);
  863. $slow_tests_for_job = $binned_slow_tests[$args['ci-parallel-node-index'] - 1];
  864. // And the same for the rest of the tests.
  865. $binned_other_tests = place_tests_into_bins($not_slow_tests, $bin_count);
  866. $other_tests_for_job = $binned_other_tests[$args['ci-parallel-node-index'] - 1];
  867. $test_list = array_merge($slow_tests_for_job, $other_tests_for_job);
  868. dump_bin_tests_sequence($args['ci-parallel-node-index'], $all_tests_list, $test_list, $args);
  869. $test_list = array_keys($test_list);
  870. }
  871. }
  872. else {
  873. if ($args['class']) {
  874. $test_list = [];
  875. foreach ($args['test_names'] as $test_class) {
  876. [$class_name] = explode('::', $test_class, 2);
  877. if (class_exists($class_name)) {
  878. $test_list[] = $test_class;
  879. }
  880. else {
  881. try {
  882. $groups = $test_discovery->getTestClasses(NULL, $args['types']);
  883. foreach ($test_discovery->getWarnings() as $warning) {
  884. simpletest_script_print($warning . "\n", SIMPLETEST_SCRIPT_COLOR_EXCEPTION);
  885. }
  886. }
  887. catch (Exception $e) {
  888. echo (string) $e;
  889. exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
  890. }
  891. $all_classes = [];
  892. foreach ($groups as $group) {
  893. $all_classes = array_merge($all_classes, array_keys($group));
  894. }
  895. simpletest_script_print_error('Test class not found: ' . $class_name);
  896. simpletest_script_print_alternatives($class_name, $all_classes, 6);
  897. exit(SIMPLETEST_SCRIPT_EXIT_FAILURE);
  898. }
  899. }
  900. }
  901. elseif ($args['file']) {
  902. // Extract test case class names from specified files.
  903. foreach ($args['test_names'] as $file) {
  904. if (!file_exists($file) || is_dir($file)) {
  905. simpletest_script_print_error('File not found: ' . $file);
  906. exit(SIMPLETEST_SCRIPT_EXIT_FAILURE);
  907. }
  908. $fileTests = current($test_discovery->getTestClasses(NULL, [], $file));
  909. $test_list = array_merge($test_list, $fileTests);
  910. }
  911. assign_tests_sequence($test_list);
  912. dump_tests_sequence($test_list, $args);
  913. $test_list = array_keys($test_list);
  914. }
  915. else {
  916. try {
  917. $groups = $test_discovery->getTestClasses(NULL, $args['types']);
  918. foreach ($test_discovery->getWarnings() as $warning) {
  919. simpletest_script_print($warning . "\n", SIMPLETEST_SCRIPT_COLOR_EXCEPTION);
  920. }
  921. }
  922. catch (Exception $e) {
  923. echo (string) $e;
  924. exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
  925. }
  926. // Store all the groups so we can suggest alternatives if we need to.
  927. $all_groups = array_keys($groups);
  928. // Verify that the groups exist.
  929. if (!empty($unknown_groups = array_diff($args['test_names'], $all_groups))) {
  930. $first_group = reset($unknown_groups);
  931. simpletest_script_print_error('Test group not found: ' . $first_group);
  932. simpletest_script_print_alternatives($first_group, $all_groups);
  933. exit(SIMPLETEST_SCRIPT_EXIT_FAILURE);
  934. }
  935. // Merge the tests from the groups together.
  936. foreach ($args['test_names'] as $group_name) {
  937. $test_list = array_merge($test_list, $groups[$group_name]);
  938. }
  939. assign_tests_sequence($test_list);
  940. dump_tests_sequence($test_list, $args);
  941. // Ensure our list of tests contains only one entry for each test.
  942. $test_list = array_keys($test_list);
  943. }
  944. }
  945. if (empty($test_list)) {
  946. simpletest_script_print_error('No valid tests were specified.');
  947. exit(SIMPLETEST_SCRIPT_EXIT_FAILURE);
  948. }
  949. return $test_list;
  950. }
  951. /**
  952. * Sort tests by test type and number of public methods.
  953. */
  954. function sort_tests_by_type_and_methods(array &$tests): void {
  955. uasort($tests, function ($a, $b) {
  956. if (get_test_type_weight($a['name']) === get_test_type_weight($b['name'])) {
  957. return $b['tests_count'] <=> $a['tests_count'];
  958. }
  959. return get_test_type_weight($b['name']) <=> get_test_type_weight($a['name']);
  960. });
  961. }
  962. /**
  963. * Sort tests by the number of public methods in the test class.
  964. *
  965. * Tests with several methods take longer to run than tests with a single
  966. * method all else being equal, so this allows tests runs to be sorted by
  967. * approximately the slowest to fastest tests. Tests that are exceptionally
  968. * slow can be added to the '#slow' group so they are placed first in each
  969. * test run regardless of the number of methods.
  970. *
  971. * @param string[] $tests
  972. * An array of test class names.
  973. */
  974. function sort_tests_by_public_method_count(array &$tests): void {
  975. uasort($tests, function ($a, $b) {
  976. return $b['tests_count'] <=> $a['tests_count'];
  977. });
  978. }
  979. /**
  980. * Weights a test class based on which test base class it extends.
  981. *
  982. * @param string $class
  983. * The test class name.
  984. */
  985. function get_test_type_weight(string $class): int {
  986. return match(TRUE) {
  987. is_subclass_of($class, WebDriverTestBase::class) => 3,
  988. is_subclass_of($class, BrowserTestBase::class) => 2,
  989. is_subclass_of($class, BuildTestBase::class) => 2,
  990. is_subclass_of($class, KernelTestBase::class) => 1,
  991. default => 0,
  992. };
  993. }
  994. /**
  995. * Assigns the test sequence.
  996. *
  997. * @param array $tests
  998. * The array of test class info.
  999. */
  1000. function assign_tests_sequence(array &$tests): void {
  1001. $i = 0;
  1002. foreach ($tests as &$testInfo) {
  1003. $testInfo['sequence'] = ++$i;
  1004. }
  1005. }
  1006. /**
  1007. * Dumps the list of tests in order of execution after sorting.
  1008. *
  1009. * @param array $tests
  1010. * The array of test class info.
  1011. * @param array $args
  1012. * The command line arguments.
  1013. */
  1014. function dump_tests_sequence(array $tests, array $args): void {
  1015. if ($args['debug-discovery'] === FALSE) {
  1016. return;
  1017. }
  1018. echo "Test execution sequence\n";
  1019. echo "-----------------------\n\n";
  1020. echo " Seq Slow? Group Cnt Class\n";
  1021. echo "-----------------------------------------\n";
  1022. $i = 0;
  1023. foreach ($tests as $testInfo) {
  1024. echo sprintf(
  1025. "%4d %5s %15s %4d %s\n",
  1026. $testInfo['sequence'],
  1027. in_array('#slow', $testInfo['groups']) ? '#slow' : '',
  1028. trim_with_ellipsis($testInfo['group'], 15, \STR_PAD_RIGHT),
  1029. $testInfo['tests_count'],
  1030. trim_with_ellipsis($testInfo['name'], 60, \STR_PAD_LEFT),
  1031. );
  1032. }
  1033. echo "-----------------------------------------\n\n";
  1034. }
  1035. /**
  1036. * Distribute tests into bins.
  1037. *
  1038. * The given array of tests is split into the available bins. The distribution
  1039. * starts with the first test, placing the first test in the first bin, the
  1040. * second test in the second bin and so on. This results each bin having a
  1041. * similar number of test methods to run in total.
  1042. *
  1043. * @param string[] $tests
  1044. * An array of test class names.
  1045. * @param int $bin_count
  1046. * The number of bins available.
  1047. *
  1048. * @return array
  1049. * An associative array of bins and the test class names in each bin.
  1050. */
  1051. function place_tests_into_bins(array $tests, int $bin_count) {
  1052. // Create a bin corresponding to each parallel test job.
  1053. $bins = array_fill(0, $bin_count, []);
  1054. // Go through each test and add them to one bin at a time.
  1055. $i = 0;
  1056. foreach ($tests as $key => $test) {
  1057. $bins[($i++ % $bin_count)][$key] = $test;
  1058. }
  1059. return $bins;
  1060. }
  1061. /**
  1062. * Dumps the list of tests in order of execution for a bin.
  1063. *
  1064. * @param int $bin
  1065. * The bin.
  1066. * @param array $allTests
  1067. * The list of all test classes discovered.
  1068. * @param array $tests
  1069. * The list of test class to run for this bin.
  1070. * @param array $args
  1071. * The command line arguments.
  1072. */
  1073. function dump_bin_tests_sequence(int $bin, array $allTests, array $tests, array $args): void {
  1074. if ($args['debug-discovery'] === FALSE) {
  1075. return;
  1076. }
  1077. echo "Test execution sequence. ";
  1078. echo "Tests marked *** will be executed in this PARALLEL BIN #{$bin}.\n";
  1079. echo "-------------------------------------------------------------------------------------\n\n";
  1080. echo "Bin Seq Slow? Group Cnt Class\n";
  1081. echo "--------------------------------------------\n";
  1082. foreach ($allTests as $testInfo) {
  1083. $inBin = isset($tests[$testInfo['name']]);
  1084. $message = sprintf(
  1085. "%s %4d %5s %15s %4d %s\n",
  1086. $inBin ? "***" : " ",
  1087. $testInfo['sequence'],
  1088. in_array('#slow', $testInfo['groups']) ? '#slow' : '',
  1089. trim_with_ellipsis($testInfo['group'], 15, \STR_PAD_RIGHT),
  1090. $testInfo['tests_count'],
  1091. trim_with_ellipsis($testInfo['name'], 60, \STR_PAD_LEFT),
  1092. );
  1093. simpletest_script_print($message, $inBin ? SIMPLETEST_SCRIPT_COLOR_BRIGHT_WHITE : SIMPLETEST_SCRIPT_COLOR_GRAY);
  1094. }
  1095. echo "-------------------------------------------------\n\n";
  1096. }
  1097. /**
  1098. * Initialize the reporter.
  1099. */
  1100. function simpletest_script_reporter_init(): void {
  1101. global $args, $test_list, $results_map, $php;
  1102. $results_map = [
  1103. 'pass' => 'Pass',
  1104. 'fail' => 'Fail',
  1105. 'error' => 'Error',
  1106. 'skipped' => 'Skipped',
  1107. 'exception' => 'Exception',
  1108. 'debug' => 'Log',
  1109. ];
  1110. // Tell the user about what tests are to be run.
  1111. if ($args['all']) {
  1112. echo "All tests will run.\n\n";
  1113. }
  1114. else {
  1115. echo "Tests to be run:\n";
  1116. foreach ($test_list as $class_name) {
  1117. echo " - $class_name\n";
  1118. }
  1119. echo "\n";
  1120. }
  1121. echo "Test run started:\n";
  1122. echo " " . date('l, F j, Y - H:i', $_SERVER['REQUEST_TIME']) . "\n";
  1123. Timer::start('run-tests');
  1124. echo "\n";
  1125. echo "Test summary\n";
  1126. echo "------------\n";
  1127. echo "\n";
  1128. }
  1129. /**
  1130. * Displays the assertion result summary for a single test class.
  1131. *
  1132. * @param string $class
  1133. * The test class name that was run.
  1134. * @param array $results
  1135. * The assertion results using #pass, #fail, #exception, #debug array keys.
  1136. * @param float|null $duration
  1137. * The time taken for the test to complete.
  1138. */
  1139. function simpletest_script_reporter_display_summary($class, $results, $duration = NULL): void {
  1140. // Output all test results vertically aligned.
  1141. $summary = [str_pad($results['#pass'], 4, " ", STR_PAD_LEFT) . ' passed'];
  1142. if ($results['#fail']) {
  1143. $summary[] = $results['#fail'] . ' failed';
  1144. }
  1145. if ($results['#error']) {
  1146. $summary[] = $results['#error'] . ' errored';
  1147. }
  1148. if ($results['#skipped']) {
  1149. $summary[] = $results['#skipped'] . ' skipped';
  1150. }
  1151. if ($results['#exception']) {
  1152. $summary[] = $results['#exception'] . ' exception(s)';
  1153. }
  1154. if ($results['#debug']) {
  1155. $summary[] = $results['#debug'] . ' log(s)';
  1156. }
  1157. if ($results['#time']) {
  1158. $time = sprintf('%8.3fs', $results['#time']);
  1159. }
  1160. else {
  1161. $time = sprintf('%8.3fs', $duration);
  1162. }
  1163. $output = vsprintf('%s %s %s', [$time, trim_with_ellipsis($class, 70, STR_PAD_LEFT), implode(', ', $summary)]);
  1164. $status = ($results['#fail'] || $results['#exception'] || $results['#error'] ? 'fail' : 'pass');
  1165. simpletest_script_print($output . "\n", simpletest_script_color_code($status));
  1166. }
  1167. /**
  1168. * Display jUnit XML test results.
  1169. */
  1170. function simpletest_script_reporter_write_xml_results(TestRunResultsStorageInterface $test_run_results_storage): void {
  1171. global $args, $test_ids, $results_map;
  1172. try {
  1173. $results = simpletest_script_load_messages_by_test_id($test_run_results_storage, $test_ids);
  1174. }
  1175. catch (Exception $e) {
  1176. echo (string) $e;
  1177. exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
  1178. }
  1179. $test_class = '';
  1180. $xml_files = [];
  1181. foreach ($results as $result) {
  1182. if (isset($results_map[$result->status])) {
  1183. if ($result->test_class != $test_class) {
  1184. // We've moved onto a new class, so write the last classes results to a
  1185. // file:
  1186. if (isset($xml_files[$test_class])) {
  1187. file_put_contents($args['xml'] . '/' . str_replace('\\', '_', $test_class) . '.xml', $xml_files[$test_class]['doc']->saveXML());
  1188. unset($xml_files[$test_class]);
  1189. }
  1190. $test_class = $result->test_class;
  1191. if (!isset($xml_files[$test_class])) {
  1192. $doc = new DOMDocument('1.0', 'utf-8');
  1193. $root = $doc->createElement('testsuite');
  1194. $root = $doc->appendChild($root);
  1195. $xml_files[$test_class] = ['doc' => $doc, 'suite' => $root];
  1196. }
  1197. }
  1198. // For convenience:
  1199. $dom_document = &$xml_files[$test_class]['doc'];
  1200. // Create the XML element for this test case:
  1201. $case = $dom_document->createElement('testcase');
  1202. $case->setAttribute('classname', $test_class);
  1203. if (str_contains($result->function, '->')) {
  1204. [$class, $name] = explode('->', $result->function, 2);
  1205. }
  1206. else {
  1207. $name = $result->function;
  1208. }
  1209. $case->setAttribute('name', $name);
  1210. // Passes get no further attention, but failures and exceptions get to add
  1211. // more detail:
  1212. if ($result->status == 'fail') {
  1213. $fail = $dom_document->createElement('failure');
  1214. $fail->setAttribute('type', 'failure');
  1215. $fail->setAttribute('message', $result->message_group);
  1216. $text = $dom_document->createTextNode($result->message);
  1217. $fail->appendChild($text);
  1218. $case->appendChild($fail);
  1219. }
  1220. elseif ($result->status == 'exception') {
  1221. // In the case of an exception the $result->function may not be a class
  1222. // method so we record the full function name:
  1223. $case->setAttribute('name', $result->function);
  1224. $fail = $dom_document->createElement('error');
  1225. $fail->setAttribute('type', 'exception');
  1226. $fail->setAttribute('message', $result->message_group);
  1227. $full_message = $result->message . "\n\nline: " . $result->line . "\nfile: " . $result->file;
  1228. $text = $dom_document->createTextNode($full_message);
  1229. $fail->appendChild($text);
  1230. $case->appendChild($fail);
  1231. }
  1232. // Append the test case XML to the test suite:
  1233. $xml_files[$test_class]['suite']->appendChild($case);
  1234. }
  1235. }
  1236. // The last test case hasn't been saved to a file yet, so do that now:
  1237. if (isset($xml_files[$test_class])) {
  1238. file_put_contents($args['xml'] . '/' . str_replace('\\', '_', $test_class) . '.xml', $xml_files[$test_class]['doc']->saveXML());
  1239. unset($xml_files[$test_class]);
  1240. }
  1241. }
  1242. /**
  1243. * Stop the test timer.
  1244. */
  1245. function simpletest_script_reporter_timer_stop(): void {
  1246. echo "\n";
  1247. $end = Timer::stop('run-tests');
  1248. echo "Test run duration: " . \Drupal::service('date.formatter')->formatInterval((int) ($end['time'] / 1000));
  1249. echo "\n\n";
  1250. }
  1251. /**
  1252. * Display test results.
  1253. */
  1254. function simpletest_script_reporter_display_results(TestRunResultsStorageInterface $test_run_results_storage): void {
  1255. global $args, $test_ids, $results_map;
  1256. if ($args['verbose']) {
  1257. // Report results.
  1258. echo "Detailed test results\n";
  1259. echo "---------------------\n";
  1260. try {
  1261. $results = simpletest_script_load_messages_by_test_id($test_run_results_storage, $test_ids);
  1262. }
  1263. catch (Exception $e) {
  1264. echo (string) $e;
  1265. exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
  1266. }
  1267. $test_class = '';
  1268. foreach ($results as $result) {
  1269. if (isset($results_map[$result->status])) {
  1270. if ($result->test_class != $test_class) {
  1271. // Display test class every time results are for new test class.
  1272. echo "\n\n---- $result->test_class ----\n\n\n";
  1273. $test_class = $result->test_class;
  1274. // Print table header.
  1275. echo "Status Duration Info \n";
  1276. echo "--------------------------------------------------------------------------------------------------------\n";
  1277. }
  1278. simpletest_script_format_result($result);
  1279. }
  1280. }
  1281. }
  1282. }
  1283. /**
  1284. * Format the result so that it fits within 80 characters.
  1285. *
  1286. * @param object $result
  1287. * The result object to format.
  1288. */
  1289. function simpletest_script_format_result($result): void {
  1290. global $args, $results_map, $color;
  1291. $summary = sprintf("%-9.9s %9.3fs %s\n", $results_map[$result->status], $result->time, trim_with_ellipsis($result->function, 80, STR_PAD_LEFT));
  1292. simpletest_script_print($summary, simpletest_script_color_code($result->status));
  1293. if ($result->message === '' || in_array($result->status, ['pass', 'fail', 'error'])) {
  1294. return;
  1295. }
  1296. $message = trim(strip_tags($result->message));
  1297. if ($args['non-html']) {
  1298. $message = Html::decodeEntities($message);
  1299. }
  1300. $lines = explode("\n", $message);
  1301. foreach ($lines as $line) {
  1302. echo " $line\n";
  1303. }
  1304. }
  1305. /**
  1306. * Print error messages so the user will notice them.
  1307. *
  1308. * Print error message prefixed with " ERROR: " and displayed in fail color if
  1309. * color output is enabled.
  1310. *
  1311. * @param string $message
  1312. * The message to print.
  1313. */
  1314. function simpletest_script_print_error($message): void {
  1315. simpletest_script_print(" ERROR: $message\n", SIMPLETEST_SCRIPT_COLOR_FAIL);
  1316. }
  1317. /**
  1318. * Print a message to the console, using a color.
  1319. *
  1320. * @param string $message
  1321. * The message to print.
  1322. * @param int $color_code
  1323. * The color code to use for coloring.
  1324. */
  1325. function simpletest_script_print($message, $color_code): void {
  1326. global $args;
  1327. if ($args['color']) {
  1328. echo "\033[" . $color_code . "m" . $message . "\033[0m";
  1329. }
  1330. else {
  1331. echo $message;
  1332. }
  1333. }
  1334. /**
  1335. * Get the color code associated with the specified status.
  1336. *
  1337. * @param string $status
  1338. * The status string to get code for. Special cases are: 'pass', 'fail', or
  1339. * 'exception'.
  1340. *
  1341. * @return int
  1342. * Color code. Returns 0 for default case.
  1343. */
  1344. function simpletest_script_color_code($status) {
  1345. return match ($status) {
  1346. 'pass' => SIMPLETEST_SCRIPT_COLOR_PASS,
  1347. 'fail', 'error', 'exception' => SIMPLETEST_SCRIPT_COLOR_FAIL,
  1348. 'skipped' => SIMPLETEST_SCRIPT_COLOR_YELLOW,
  1349. 'debug' => SIMPLETEST_SCRIPT_COLOR_CYAN,
  1350. default => 0,
  1351. };
  1352. }
  1353. /**
  1354. * Prints alternative test names.
  1355. *
  1356. * Searches the provided array of string values for close matches based on the
  1357. * Levenshtein algorithm.
  1358. *
  1359. * @param string $string
  1360. * A string to test.
  1361. * @param array $array
  1362. * A list of strings to search.
  1363. * @param int $degree
  1364. * The matching strictness. Higher values return fewer matches. A value of
  1365. * 4 means that the function will return strings from $array if the candidate
  1366. * string in $array would be identical to $string by changing 1/4 or fewer of
  1367. * its characters.
  1368. *
  1369. * @see http://php.net/manual/function.levenshtein.php
  1370. */
  1371. function simpletest_script_print_alternatives($string, $array, $degree = 4): void {
  1372. $alternatives = [];
  1373. foreach ($array as $item) {
  1374. $lev = levenshtein($string, $item);
  1375. if ($lev <= strlen($item) / $degree || str_contains($string, $item)) {
  1376. $alternatives[] = $item;
  1377. }
  1378. }
  1379. if (!empty($alternatives)) {
  1380. simpletest_script_print(" Did you mean?\n", SIMPLETEST_SCRIPT_COLOR_FAIL);
  1381. foreach ($alternatives as $alternative) {
  1382. simpletest_script_print(" - $alternative\n", SIMPLETEST_SCRIPT_COLOR_FAIL);
  1383. }
  1384. }
  1385. }
  1386. /**
  1387. * Loads test result messages from the database.
  1388. *
  1389. * Messages are ordered by test class and message id.
  1390. *
  1391. * @param array $test_ids
  1392. * Array of test IDs of the messages to be loaded.
  1393. *
  1394. * @return array
  1395. * Array of test result messages from the database.
  1396. */
  1397. function simpletest_script_load_messages_by_test_id(TestRunResultsStorageInterface $test_run_results_storage, $test_ids) {
  1398. global $args;
  1399. $results = [];
  1400. // Sqlite has a maximum number of variables per query. If required, the
  1401. // database query is split into chunks.
  1402. if (count($test_ids) > SIMPLETEST_SCRIPT_SQLITE_VARIABLE_LIMIT && !empty($args['sqlite'])) {
  1403. $test_id_chunks = array_chunk($test_ids, SIMPLETEST_SCRIPT_SQLITE_VARIABLE_LIMIT);
  1404. }
  1405. else {
  1406. $test_id_chunks = [$test_ids];
  1407. }
  1408. foreach ($test_id_chunks as $test_id_chunk) {
  1409. try {
  1410. $result_chunk = [];
  1411. foreach ($test_id_chunk as $test_id) {
  1412. $test_run = TestRun::get($test_run_results_storage, $test_id);
  1413. $result_chunk = array_merge($result_chunk, $test_run->getLogEntriesByTestClass());
  1414. }
  1415. }
  1416. catch (Exception $e) {
  1417. echo (string) $e;
  1418. exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
  1419. }
  1420. if ($result_chunk) {
  1421. $results = array_merge($results, $result_chunk);
  1422. }
  1423. }
  1424. return $results;
  1425. }
  1426. /**
  1427. * Trims a string adding a leading or trailing ellipsis.
  1428. *
  1429. * @param string $input
  1430. * The input string.
  1431. * @param int $length
  1432. * The exact trimmed string length.
  1433. * @param int $side
  1434. * Leading or trailing ellipsis.
  1435. *
  1436. * @return string
  1437. * The trimmed string.
  1438. */
  1439. function trim_with_ellipsis(string $input, int $length, int $side): string {
  1440. if (strlen($input) < $length) {
  1441. return str_pad($input, $length, ' ', \STR_PAD_RIGHT);
  1442. }
  1443. elseif (strlen($input) > $length) {
  1444. return match($side) {
  1445. \STR_PAD_RIGHT => substr($input, 0, $length - 1) . '…',
  1446. default => '…' . substr($input, -$length + 1),
  1447. };
  1448. }
  1449. return $input;
  1450. }

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.