run-tests.sh

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

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