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 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 testing. In general,
  7. * tests should be run directly with phpunit.
  8. *
  9. * @internal
  10. */
  11. use Composer\Autoload\ClassLoader;
  12. use Drupal\Component\FileSystem\FileSystem;
  13. use Drupal\Component\Utility\Environment;
  14. use Drupal\Component\Utility\Html;
  15. use Drupal\Component\Utility\Timer;
  16. use Drupal\Core\Composer\Composer;
  17. use Drupal\Core\Database\Database;
  18. use Drupal\Core\Test\EnvironmentCleaner;
  19. use Drupal\Core\Test\PhpUnitTestDiscovery;
  20. use Drupal\Core\Test\PhpUnitTestRunner;
  21. use Drupal\Core\Test\SimpletestTestRunResultsStorage;
  22. use Drupal\Core\Test\TestDatabase;
  23. use Drupal\Core\Test\TestRun;
  24. use Drupal\Core\Test\TestRunnerKernel;
  25. use Drupal\Core\Test\TestRunResultsStorageInterface;
  26. use Drupal\TestTools\TestRunner\Configuration as Config;
  27. use Drupal\TestTools\TestRunner\MemoryTestRunResultsStorage;
  28. use Drupal\TestTools\TestRunner\WorkAllocator;
  29. use PHPUnit\Framework\TestCase;
  30. use PHPUnit\Runner\Version;
  31. use Symfony\Component\Console\Helper\DescriptorHelper;
  32. use Symfony\Component\Console\Input\InputDefinition;
  33. use Symfony\Component\Console\Output\ConsoleOutput;
  34. use Symfony\Component\HttpFoundation\Request;
  35. use Symfony\Component\Process\PhpExecutableFinder;
  36. // cspell:ignore exitcode testbots wwwrun
  37. // Define some colors for display.
  38. // A nice calming green.
  39. const SIMPLETEST_SCRIPT_COLOR_PASS = 32;
  40. // An alerting Red.
  41. const SIMPLETEST_SCRIPT_COLOR_FAIL = 31;
  42. // An annoying brown.
  43. const SIMPLETEST_SCRIPT_COLOR_EXCEPTION = 33;
  44. // An appeasing yellow.
  45. const SIMPLETEST_SCRIPT_COLOR_YELLOW = 33;
  46. // A refreshing cyan.
  47. const SIMPLETEST_SCRIPT_COLOR_CYAN = 36;
  48. // A fainting gray.
  49. const SIMPLETEST_SCRIPT_COLOR_GRAY = 90;
  50. // A notable white.
  51. const SIMPLETEST_SCRIPT_COLOR_BRIGHT_WHITE = "1;97";
  52. // Restricting the chunk of queries prevents memory exhaustion.
  53. const SIMPLETEST_SCRIPT_SQLITE_VARIABLE_LIMIT = 350;
  54. const SIMPLETEST_SCRIPT_EXIT_SUCCESS = 0;
  55. const SIMPLETEST_SCRIPT_EXIT_FAILURE = 1;
  56. const SIMPLETEST_SCRIPT_EXIT_ERROR = 2;
  57. const SIMPLETEST_SCRIPT_EXIT_EXCEPTION = 3;
  58. // Setup class autoloading.
  59. $autoloader = require_once __DIR__ . '/../../autoload.php';
  60. $autoloader->addPsr4('Drupal\\TestTools\\', __DIR__ . '/../tests/Drupal/TestTools');
  61. // Setup console output.
  62. $console_output = new ConsoleOutput();
  63. // Get the configuration from the command line.
  64. $script_basename = basename($_SERVER['argv'][0]);
  65. try {
  66. Config::createFromCommandLine($_SERVER['argv']);
  67. }
  68. catch (\RuntimeException $e) {
  69. simpletest_script_print_error($e->getMessage() . ' ' . "Use the --help option for the list and usage of the options available.\n");
  70. simpletest_script_print(Config::commandLineDefinition()->getSynopsis(), SIMPLETEST_SCRIPT_COLOR_PASS);
  71. exit(SIMPLETEST_SCRIPT_EXIT_FAILURE);
  72. }
  73. // If --help requested, show it and exit.
  74. if (Config::get('help')) {
  75. simpletest_script_help(Config::commandLineDefinition(), $script_basename, $console_output);
  76. exit(SIMPLETEST_SCRIPT_EXIT_SUCCESS);
  77. }
  78. // Initialize script variables and bootstrap Drupal kernel.
  79. simpletest_script_init($autoloader);
  80. if (!class_exists(TestCase::class)) {
  81. echo "\nrun-tests.sh requires the PHPUnit testing framework. Use 'composer install' to ensure that it is present.\n\n";
  82. exit(SIMPLETEST_SCRIPT_EXIT_FAILURE);
  83. }
  84. // Defaults the PHPUnit configuration file path.
  85. if (empty(Config::get('phpunit-configuration'))) {
  86. Config::set('phpunit-configuration', \Drupal::root() . \DIRECTORY_SEPARATOR . 'core');
  87. }
  88. if (!Composer::upgradePHPUnitCheck(Version::id())) {
  89. 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.");
  90. exit(SIMPLETEST_SCRIPT_EXIT_FAILURE);
  91. }
  92. if (Config::get('list')) {
  93. // Display all available tests organized by one #[Group()] attribute.
  94. echo "\nAvailable test groups & classes\n";
  95. echo "-------------------------------\n\n";
  96. $testDiscovery = PhpUnitTestDiscovery::instance()->setConfigurationFilePath(Config::get('phpunit-configuration'));
  97. try {
  98. $groupedTestClassInfoList = $testDiscovery->getTestClasses(Config::get('module'), Config::get('types'), Config::get('directory'), Config::getTests());
  99. dump_discovery_warnings();
  100. }
  101. catch (Exception $e) {
  102. error_log((string) $e);
  103. echo (string) $e;
  104. exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
  105. }
  106. // A given class can appear in multiple groups. For historical reasons, we
  107. // need to present each test only once. The test is shown in the group that is
  108. // printed first.
  109. $printed_tests = [];
  110. foreach ($groupedTestClassInfoList as $group => $tests) {
  111. echo $group . "\n";
  112. $tests = array_diff(array_keys($tests), $printed_tests);
  113. foreach ($tests as $test) {
  114. echo " - $test\n";
  115. }
  116. $printed_tests = array_merge($printed_tests, $tests);
  117. }
  118. exit(SIMPLETEST_SCRIPT_EXIT_SUCCESS);
  119. }
  120. // List-files and list-files-json provide a way for external tools such as the
  121. // testbot to prioritize running changed tests.
  122. // @see https://www.drupal.org/node/2569585
  123. if (Config::get('list-files') || Config::get('list-files-json')) {
  124. // List all files which could be run as tests.
  125. $testDiscovery = PhpUnitTestDiscovery::instance()->setConfigurationFilePath(Config::get('phpunit-configuration'));
  126. // PhpUnitTestDiscovery::findAllClassFiles() gives us a classmap similar to a
  127. // Composer 'classmap' array.
  128. $test_classes = $testDiscovery->findAllClassFiles(Config::get('module'), Config::get('types'), Config::get('directory'), Config::getTests());
  129. // JSON output is the easiest.
  130. if (Config::get('list-files-json')) {
  131. echo json_encode($test_classes);
  132. exit(SIMPLETEST_SCRIPT_EXIT_SUCCESS);
  133. }
  134. // Output the list of files.
  135. else {
  136. foreach (array_values($test_classes) as $test_class) {
  137. echo $test_class . "\n";
  138. }
  139. }
  140. exit(SIMPLETEST_SCRIPT_EXIT_SUCCESS);
  141. }
  142. simpletest_script_setup_database();
  143. // Setup the test run results storage environment. Currently, this coincides
  144. // with the simpletest database schema.
  145. $test_run_results_storage = simpletest_script_setup_test_run_results_storage();
  146. if (Config::get('clean')) {
  147. // Clean up left-over tables and directories.
  148. $cleaner = new EnvironmentCleaner(
  149. DRUPAL_ROOT,
  150. Database::getConnection(),
  151. $test_run_results_storage,
  152. $console_output,
  153. \Drupal::service('file_system')
  154. );
  155. try {
  156. $cleaner->cleanEnvironment();
  157. }
  158. catch (Exception $e) {
  159. echo (string) $e;
  160. exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
  161. }
  162. echo "\nEnvironment cleaned.\n";
  163. // Get the status messages and print them.
  164. $messages = \Drupal::messenger()->messagesByType('status');
  165. foreach ($messages as $text) {
  166. echo " - " . $text . "\n";
  167. }
  168. exit(SIMPLETEST_SCRIPT_EXIT_SUCCESS);
  169. }
  170. echo "\n";
  171. echo "Drupal test run\n\n";
  172. echo "--------------------------------------------------------------\n";
  173. echo sprintf("Drupal Version.......: %s\n", \Drupal::VERSION);
  174. echo sprintf("PHP Version..........: %s\n", \PHP_VERSION);
  175. echo sprintf("PHP Binary...........: %s\n", (new PhpExecutableFinder())->find());
  176. echo sprintf("PHPUnit Version......: %s\n", Version::id());
  177. echo sprintf("PHPUnit configuration: %s\n", Config::get('phpunit-configuration'));
  178. if (Config::get('dburl')) {
  179. $sut_connection_info = Database::getConnectionInfo();
  180. $sut_tasks_class = $sut_connection_info['default']['namespace'] . "\\Install\\Tasks";
  181. $sut_installer = new $sut_tasks_class();
  182. $sut_connection = Database::getConnection();
  183. echo sprintf("Database.............: %s\n", (string) $sut_installer->name());
  184. echo sprintf("Database Version.....: %s\n", $sut_connection->version());
  185. }
  186. echo sprintf("Working directory....: %s\n", getcwd());
  187. echo "--------------------------------------------------------------\n";
  188. $groupedTestClassInfoList = simpletest_script_get_test_list();
  189. $workAllocator = new WorkAllocator(
  190. $groupedTestClassInfoList,
  191. (int) Config::get('ci-parallel-node-total'),
  192. (int) Config::get('ci-parallel-node-index'),
  193. );
  194. $test_list = array_keys($workAllocator->getAllocatedList());
  195. if (Config::get('debug-discovery')) {
  196. if ((int) Config::get('ci-parallel-node-total') > 1) {
  197. dump_bin_tests_sequence((int) Config::get('ci-parallel-node-index'), $workAllocator->getSortedList(), $workAllocator->getAllocatedList());
  198. }
  199. else {
  200. dump_tests_sequence($workAllocator->getAllocatedList());
  201. }
  202. }
  203. // Try to allocate unlimited time to run the tests.
  204. Environment::setTimeLimit(0);
  205. simpletest_script_reporter_init();
  206. $tests_to_run = [];
  207. for ($i = 0; $i < Config::get('repeat'); $i++) {
  208. $tests_to_run = array_merge($tests_to_run, $test_list);
  209. }
  210. // Execute tests.
  211. $status = simpletest_script_execute_batch($test_run_results_storage, $tests_to_run);
  212. // Stop the timer.
  213. simpletest_script_reporter_timer_stop();
  214. // Ensure all test locks are released once finished. If tests are run with a
  215. // concurrency of 1 the each test will clean up its own lock. Test locks are
  216. // not released if using a higher concurrency to ensure each test has unique
  217. // fixtures.
  218. TestDatabase::releaseAllTestLocks();
  219. // Display results before database is cleared.
  220. simpletest_script_reporter_display_results($test_run_results_storage);
  221. if (Config::get('xml')) {
  222. simpletest_script_reporter_write_xml_results($test_run_results_storage);
  223. }
  224. // Clean up all test results.
  225. if (!Config::get('keep-results')) {
  226. try {
  227. $cleaner = new EnvironmentCleaner(
  228. DRUPAL_ROOT,
  229. Database::getConnection(),
  230. $test_run_results_storage,
  231. $console_output,
  232. \Drupal::service('file_system')
  233. );
  234. $cleaner->cleanResults();
  235. }
  236. catch (Exception $e) {
  237. echo (string) $e;
  238. exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
  239. }
  240. }
  241. // Test complete, exit.
  242. exit($status);
  243. /**
  244. * Print help text.
  245. */
  246. function simpletest_script_help(InputDefinition $input_definition, string $script_basename, ConsoleOutput $console_output): void {
  247. echo <<
  248. Run Drupal tests from the shell.
  249. Usage: {$script_basename} [OPTIONS]
  250. Example: {$script_basename} Profile
  251. EOF;
  252. $helper = new DescriptorHelper();
  253. $helper->describe($console_output, $input_definition);
  254. echo <<
  255. To run this script you will normally invoke it from the root directory of your
  256. Drupal installation as the webserver user (differs per configuration), or root:
  257. sudo -u [wwwrun|www-data|etc] php ./core/scripts/{$script_basename} --url http://example.com/ --all
  258. sudo -u [wwwrun|www-data|etc] php ./core/scripts/{$script_basename} --url http://example.com/ --class Drupal\\\\Tests\\\\block\\\\Functional\\\\BlockTest
  259. Without a preinstalled Drupal site, specify a SQLite database pathname to create
  260. (for the test runner) and the default database connection info (for Drupal) to
  261. use in tests:
  262. sudo -u [wwwrun|www-data|etc] php ./core/scripts/{$script_basename}
  263. --sqlite /tmpfs/drupal/test.sqlite
  264. --dburl mysql://username:password@localhost/database
  265. --url http://example.com/ --all
  266. EOF;
  267. }
  268. /**
  269. * Initialize script variables and perform general setup requirements.
  270. *
  271. * @param \Drupal\Core\Composer\Composer $autoloader
  272. * The Composer provided PHP class loader.
  273. */
  274. function simpletest_script_init(ClassLoader $autoloader): void {
  275. // Get URL from arguments.
  276. $parsed_url = parse_url(Config::get('url'));
  277. $host = $parsed_url['host'] . (isset($parsed_url['port']) ? ':' . $parsed_url['port'] : '');
  278. $path = isset($parsed_url['path']) ? rtrim(rtrim($parsed_url['path']), '/') : '';
  279. $port = $parsed_url['port'] ?? '80';
  280. // If the passed URL schema is 'https' then setup the $_SERVER variables
  281. // properly so that testing will run under HTTPS.
  282. if ($parsed_url['scheme'] == 'https') {
  283. $_SERVER['HTTPS'] = 'on';
  284. }
  285. $base_url = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://';
  286. $base_url .= $host;
  287. if ($path !== '') {
  288. $base_url .= $path;
  289. }
  290. putenv('SIMPLETEST_BASE_URL=' . $base_url);
  291. $_SERVER['HTTP_HOST'] = $host;
  292. $_SERVER['REMOTE_ADDR'] = '127.0.0.1';
  293. $_SERVER['SERVER_ADDR'] = '127.0.0.1';
  294. $_SERVER['SERVER_PORT'] = $port;
  295. $_SERVER['SERVER_SOFTWARE'] = NULL;
  296. $_SERVER['SERVER_NAME'] = 'localhost';
  297. $_SERVER['REQUEST_URI'] = $path . '/';
  298. $_SERVER['REQUEST_METHOD'] = 'GET';
  299. $_SERVER['SCRIPT_NAME'] = $path . '/index.php';
  300. $_SERVER['SCRIPT_FILENAME'] = $path . '/index.php';
  301. $_SERVER['PHP_SELF'] = $path . '/index.php';
  302. $_SERVER['HTTP_USER_AGENT'] = 'Drupal command line';
  303. if (Config::get('concurrency') > 1) {
  304. $directory = FileSystem::getOsTemporaryDirectory();
  305. $test_symlink = @symlink(__FILE__, $directory . '/test_symlink');
  306. if (!$test_symlink) {
  307. throw new \RuntimeException('In order to use a concurrency higher than 1 the test system needs to be able to create symlinks in ' . $directory);
  308. }
  309. unlink($directory . '/test_symlink');
  310. putenv('RUN_TESTS_CONCURRENCY=' . Config::get('concurrency'));
  311. }
  312. if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
  313. // Ensure that any and all environment variables are changed to https://.
  314. foreach ($_SERVER as $key => $value) {
  315. // Some values are NULL. Non-NULL values which are falsy will not contain
  316. // text to replace.
  317. if ($value) {
  318. $_SERVER[$key] = str_replace('http://', 'https://', $value);
  319. }
  320. }
  321. }
  322. chdir(realpath(__DIR__ . '/../..'));
  323. // Prepare the kernel.
  324. try {
  325. $request = Request::createFromGlobals();
  326. $kernel = TestRunnerKernel::createFromRequest($request, $autoloader);
  327. $kernel->boot();
  328. $kernel->preHandle($request);
  329. }
  330. catch (Exception $e) {
  331. echo (string) $e;
  332. exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
  333. }
  334. }
  335. /**
  336. * Sets up database connection info for running tests.
  337. *
  338. * If this script is executed from within a real Drupal installation, then this
  339. * function essentially performs nothing (unless the --sqlite or --dburl
  340. * parameters were passed).
  341. *
  342. * Otherwise, there are three database connections of concern:
  343. * - --sqlite: The test runner connection, providing access to database tables
  344. * for recording test IDs and assertion results.
  345. * - --dburl: A database connection that is used as base connection info for all
  346. * tests; i.e., every test will spawn from this connection. In case this
  347. * connection uses e.g. SQLite, then all tests will run against SQLite. This
  348. * is exposed as $databases['default']['default'] to Drupal.
  349. * - The actual database connection used within a test. This is the same as
  350. * --dburl, but uses an additional database table prefix. This is
  351. * $databases['default']['default'] within a test environment. The original
  352. * connection is retained in
  353. * $databases['simpletest_original_default']['default'] and restored after
  354. * each test.
  355. */
  356. function simpletest_script_setup_database(): void {
  357. // If there is an existing Drupal installation that contains a database
  358. // connection info in settings.php, then $databases['default']['default'] will
  359. // hold the default database connection already. This connection is assumed to
  360. // be valid, and this connection will be used in tests, so that they run
  361. // against e.g. MySQL instead of SQLite.
  362. // However, in case no Drupal installation exists, this default database
  363. // connection can be set and/or overridden with the --dburl parameter.
  364. if (Config::get('dburl')) {
  365. // Remove a possibly existing default connection (from settings.php).
  366. Database::removeConnection('default');
  367. try {
  368. $databases['default']['default'] = Database::convertDbUrlToConnectionInfo(Config::get('dburl'), TRUE);
  369. }
  370. catch (\InvalidArgumentException $e) {
  371. simpletest_script_print_error('Invalid --dburl. Reason: ' . $e->getMessage());
  372. exit(SIMPLETEST_SCRIPT_EXIT_FAILURE);
  373. }
  374. }
  375. // Otherwise, use the default database connection from settings.php.
  376. else {
  377. $databases['default'] = Database::getConnectionInfo('default');
  378. }
  379. if (isset($databases['default']['default'])) {
  380. Database::addConnectionInfo('default', 'default', $databases['default']['default']);
  381. }
  382. }
  383. /**
  384. * Sets up the test runs results storage.
  385. */
  386. function simpletest_script_setup_test_run_results_storage() {
  387. $sqlite = Config::get('sqlite');
  388. if ($sqlite === NULL) {
  389. // If no --sqlite parameter has been passed, then use the in-memory storage
  390. // for test results.
  391. $inMemory = TRUE;
  392. }
  393. else {
  394. $inMemory = FALSE;
  395. if ($sqlite !== ':memory:' && is_string($sqlite) && !str_starts_with($sqlite, '/')) {
  396. $sqlite = DRUPAL_ROOT . '/' . $sqlite;
  397. }
  398. $databases['test-runner']['default'] = [
  399. 'driver' => 'sqlite',
  400. 'database' => $sqlite,
  401. 'prefix' => '',
  402. ];
  403. // Create the test runner SQLite database, unless it exists already.
  404. if ($sqlite !== ':memory:' && !file_exists($sqlite)) {
  405. if (!is_dir(dirname($sqlite))) {
  406. mkdir(dirname($sqlite));
  407. }
  408. touch($sqlite);
  409. }
  410. // Add the test runner database connection.
  411. Database::addConnectionInfo('test-runner', 'default', $databases['test-runner']['default']);
  412. }
  413. try {
  414. $test_run_results_storage = $inMemory ?
  415. new MemoryTestRunResultsStorage() :
  416. new SimpletestTestRunResultsStorage(Database::getConnection('default', 'test-runner'));
  417. $test_run_results_storage->buildTestingResultsEnvironment(Config::get('keep-results-table'));
  418. if (!$test_run_results_storage->validateTestingResultsEnvironment()) {
  419. simpletest_script_print_error('The database is missing the test result tables required.');
  420. exit(SIMPLETEST_SCRIPT_EXIT_FAILURE);
  421. }
  422. }
  423. catch (\Exception $e) {
  424. echo (string) $e;
  425. exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
  426. }
  427. return $test_run_results_storage;
  428. }
  429. /**
  430. * Execute a batch of tests.
  431. */
  432. function simpletest_script_execute_batch(TestRunResultsStorageInterface $test_run_results_storage, $test_classes) {
  433. global $test_ids, $total_time;
  434. $total_status = SIMPLETEST_SCRIPT_EXIT_SUCCESS;
  435. $total_time = 0;
  436. $process_runner = PhpUnitTestRunner::create(\Drupal::getContainer())
  437. ->setConfigurationFilePath(Config::get('phpunit-configuration'));
  438. // Multi-process execution.
  439. $children = [];
  440. while (!empty($test_classes) || !empty($children)) {
  441. while (count($children) < Config::get('concurrency')) {
  442. if (empty($test_classes)) {
  443. break;
  444. }
  445. try {
  446. $test_run = TestRun::createNew($test_run_results_storage);
  447. }
  448. catch (Exception $e) {
  449. echo (string) $e;
  450. exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
  451. }
  452. $test_ids[] = $test_run->id();
  453. $test_class = array_shift($test_classes);
  454. // Fork a child process.
  455. try {
  456. $process = $process_runner->startPhpUnitOnSingleTestClass(
  457. $test_run,
  458. $test_class,
  459. Config::get('color'),
  460. Config::get('suppress-deprecations'),
  461. );
  462. }
  463. catch (\Throwable $e) {
  464. // PHPUnit catches exceptions already, so this is only reached when an
  465. // exception is thrown in the wrapped test runner environment.
  466. echo (string) $e;
  467. exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
  468. }
  469. // Register our new child.
  470. $children[] = [
  471. 'process' => $process,
  472. 'test_run' => $test_run,
  473. 'class' => $test_class,
  474. ];
  475. }
  476. // Wait for children every 2ms.
  477. usleep(2000);
  478. // Check if some children finished.
  479. foreach ($children as $cid => $child) {
  480. if ($child['process']->isTerminated()) {
  481. // The child exited.
  482. $child['test_run']->end(microtime(TRUE));
  483. $total_time += $child['test_run']->duration();
  484. $process_outcome = $process_runner->processPhpUnitOnSingleTestClassOutcome(
  485. $child['process'],
  486. $child['test_run'],
  487. $child['class'],
  488. );
  489. simpletest_script_reporter_display_summary(
  490. $child['class'],
  491. $process_outcome['summaries'][$child['class']],
  492. $child['test_run']->duration()
  493. );
  494. if ($process_outcome['error_output']) {
  495. echo 'ERROR: ' . implode("\n", $process_outcome['error_output']);
  496. }
  497. if (in_array($process_outcome['status'], [SIMPLETEST_SCRIPT_EXIT_FAILURE, SIMPLETEST_SCRIPT_EXIT_ERROR])) {
  498. $total_status = max($process_outcome['status'], $total_status);
  499. }
  500. elseif ($process_outcome['status']) {
  501. $message = 'FATAL ' . $child['class'] . ': test runner returned an unexpected error code (' . $process_outcome['status'] . ').';
  502. echo $message . "\n";
  503. $total_status = max(SIMPLETEST_SCRIPT_EXIT_EXCEPTION, $total_status);
  504. if (Config::get('die-on-fail')) {
  505. $test_db = new TestDatabase($child['test_run']->getDatabasePrefix());
  506. $test_directory = $test_db->getTestSitePath();
  507. 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";
  508. Config::set('keep-results', TRUE);
  509. // Exit repeat loop immediately.
  510. Config::set('repeat', -1);
  511. }
  512. }
  513. // Remove this child.
  514. unset($children[$cid]);
  515. }
  516. }
  517. }
  518. return $total_status;
  519. }
  520. /**
  521. * Get list of tests based on arguments.
  522. *
  523. * If --all specified then return all available tests, otherwise reads list of
  524. * tests.
  525. *
  526. * @return array
  527. * List of tests.
  528. */
  529. function simpletest_script_get_test_list() {
  530. $testDiscovery = PhpUnitTestDiscovery::instance()->setConfigurationFilePath(Config::get('phpunit-configuration'));
  531. echo "Test discovery\n";
  532. try {
  533. if (Config::get('all') || Config::get('module') || Config::get('directory')) {
  534. if (Config::get('types')) {
  535. echo sprintf("PHPUnit test suite(s): %s\n", implode(', ', Config::get('types')));
  536. }
  537. if (Config::get('module')) {
  538. echo sprintf("Drupal module........: %s\n", Config::get('module'));
  539. }
  540. if (Config::get('directory')) {
  541. echo sprintf("Directory............: %s\n", Config::get('directory'));
  542. }
  543. if (Config::getTests()) {
  544. echo sprintf("PHPUnit test group(s): %s\n", implode(', ', Config::getTests()));
  545. }
  546. echo "--------------------------------------------------------------\n";
  547. $groupedTestClassInfoList = $testDiscovery->getTestClasses(Config::get('module'), Config::get('types'), Config::get('directory'), Config::getTests());
  548. }
  549. elseif (Config::get('class')) {
  550. // When --class is specified, we have to find the file of each of the
  551. // classes indicated as argument and run test discovery for it, then
  552. // merge the results.
  553. $classesArg = Config::getTests();
  554. echo sprintf("Test class(es).......: %s\n", array_shift($classesArg));
  555. foreach ($classesArg as $arg) {
  556. echo sprintf(" : %s\n", $arg);
  557. }
  558. echo "--------------------------------------------------------------\n";
  559. $groupedTestClassInfoList = [];
  560. foreach (Config::getTests() as $test_class) {
  561. [$class_name] = explode('::', $test_class, 2);
  562. if (class_exists($class_name)) {
  563. $fileName = (new \ReflectionClass($class_name))->getFileName();
  564. $groupedClassInfo = $testDiscovery->getTestClasses(NULL, [], $fileName);
  565. foreach (array_keys($groupedClassInfo) as $classGroupKey) {
  566. if (array_key_exists($classGroupKey, $groupedTestClassInfoList)) {
  567. $groupedTestClassInfoList[$classGroupKey] = array_merge($groupedTestClassInfoList[$classGroupKey], $groupedClassInfo[$classGroupKey]);
  568. }
  569. else {
  570. $groupedTestClassInfoList[$classGroupKey] = $groupedClassInfo[$classGroupKey];
  571. }
  572. }
  573. }
  574. else {
  575. // The class does not exist: we discover all the test classes and
  576. // suggest a possible alternative.
  577. $groupedTestClassInfoList = $testDiscovery->getTestClasses(NULL, Config::get('types'));
  578. dump_discovery_warnings();
  579. $all_classes = [];
  580. foreach ($groupedTestClassInfoList as $group) {
  581. $all_classes = array_merge($all_classes, array_keys($group));
  582. }
  583. simpletest_script_print_error('Test class not found: ' . $class_name);
  584. simpletest_script_print_alternatives($class_name, $all_classes, 6);
  585. exit(SIMPLETEST_SCRIPT_EXIT_FAILURE);
  586. }
  587. }
  588. }
  589. elseif (Config::get('file')) {
  590. // When --file is specified, we have to run test discovery for each of
  591. // the files indicated, then merge the results.
  592. $filesArg = Config::getTests();
  593. echo sprintf("Test file(s).........: %s\n", array_shift($filesArg));
  594. foreach ($filesArg as $arg) {
  595. echo sprintf(" : %s\n", $arg);
  596. }
  597. echo "--------------------------------------------------------------\n";
  598. $groupedTestClassInfoList = [];
  599. foreach (Config::getTests() as $file) {
  600. if (!file_exists($file) || is_dir($file)) {
  601. simpletest_script_print_error('File not found: ' . $file);
  602. exit(SIMPLETEST_SCRIPT_EXIT_FAILURE);
  603. }
  604. $groupedClassInfo = $testDiscovery->getTestClasses(NULL, [], $file);
  605. foreach (array_keys($groupedClassInfo) as $classGroupKey) {
  606. if (array_key_exists($classGroupKey, $groupedTestClassInfoList)) {
  607. $groupedTestClassInfoList[$classGroupKey] = array_merge($groupedTestClassInfoList[$classGroupKey], $groupedClassInfo[$classGroupKey]);
  608. }
  609. else {
  610. $groupedTestClassInfoList[$classGroupKey] = $groupedClassInfo[$classGroupKey];
  611. }
  612. }
  613. }
  614. }
  615. else {
  616. // When no restriction options are specified, we consider the argument as
  617. // a list of groups of tests to be executed.
  618. if (Config::get('types')) {
  619. echo sprintf("PHPUnit test suite(s): %s\n", implode(', ', Config::get('types')));
  620. }
  621. if (Config::getTests()) {
  622. echo sprintf("PHPUnit test group(s): %s\n", implode(', ', Config::getTests()));
  623. }
  624. echo "--------------------------------------------------------------\n";
  625. $groupedTestClassInfoList = [];
  626. try {
  627. $groupedTestClassInfoFullSuiteList = $testDiscovery->getTestClasses(NULL, Config::get('types'));
  628. }
  629. catch (\Exception $e) {
  630. echo (string) $e;
  631. exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
  632. }
  633. // Store all the groups so we can suggest alternatives if we need to.
  634. $all_groups = array_keys($groupedTestClassInfoFullSuiteList);
  635. // Verify that the groups exist.
  636. if (!empty($unknown_groups = array_diff(Config::getTests(), $all_groups))) {
  637. $first_group = reset($unknown_groups);
  638. simpletest_script_print_error('Test group not found: ' . $first_group);
  639. simpletest_script_print_alternatives($first_group, $all_groups);
  640. exit(SIMPLETEST_SCRIPT_EXIT_FAILURE);
  641. }
  642. foreach (Config::getTests() as $group_name) {
  643. $groupedTestClassInfoList[$group_name] = $groupedTestClassInfoFullSuiteList[$group_name];
  644. }
  645. // The '#slow' group is a special case, because it may not be selected in
  646. // the argument, but it must be present if any test class indicates it in
  647. // metadata, for the work allocator to prioritize its execution.
  648. foreach ($groupedTestClassInfoList as $testClassInfoList) {
  649. foreach ($testClassInfoList as $testClass => $testClassInfo) {
  650. if (in_array('#slow', $testClassInfo['groups'])) {
  651. $groupedTestClassInfoList['#slow'][$testClass] = $testClassInfo;
  652. }
  653. }
  654. }
  655. }
  656. }
  657. catch (\Exception $e) {
  658. echo (string) $e;
  659. exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
  660. }
  661. echo "\n";
  662. dump_discovery_warnings();
  663. if (empty($groupedTestClassInfoList)) {
  664. simpletest_script_print_error('No valid tests were specified.');
  665. exit(SIMPLETEST_SCRIPT_EXIT_FAILURE);
  666. }
  667. return $groupedTestClassInfoList;
  668. }
  669. /**
  670. * Dumps the list of tests in order of execution after sorting.
  671. *
  672. * @param array $tests
  673. * The array of test class info.
  674. */
  675. function dump_tests_sequence(array $tests): void {
  676. if (!Config::get('debug-discovery')) {
  677. return;
  678. }
  679. echo "Test execution sequence\n";
  680. echo "-----------------------\n\n";
  681. echo " Seq Slow? Group Cnt Class\n";
  682. echo "-----------------------------------------\n";
  683. foreach ($tests as $testInfo) {
  684. echo sprintf(
  685. "%4d %5s %15s %4d %s\n",
  686. $testInfo['worker_sequence'],
  687. in_array('#slow', $testInfo['groups']) ? '#slow' : '',
  688. trim_with_ellipsis($testInfo['group'], 15, \STR_PAD_RIGHT),
  689. $testInfo['tests_count'],
  690. trim_with_ellipsis($testInfo['name'], 60, \STR_PAD_LEFT),
  691. );
  692. }
  693. echo "-----------------------------------------\n\n";
  694. }
  695. /**
  696. * Dumps the list of tests in order of execution for a bin.
  697. *
  698. * @param int $bin
  699. * The bin.
  700. * @param array $allTests
  701. * The list of all test classes discovered.
  702. * @param array $tests
  703. * The list of test class to run for this bin.
  704. */
  705. function dump_bin_tests_sequence(int $bin, array $allTests, array $tests): void {
  706. echo "Test execution sequence. ";
  707. echo "Tests marked *** will be executed in this PARALLEL BIN #{$bin}.\n";
  708. echo "-------------------------------------------------------------------------------------\n\n";
  709. echo " Sort Bin \n";
  710. echo "Bin Seq Seq Slow? Group Cnt Class\n";
  711. echo "-------------------------------------------------------------------------------------\n";
  712. foreach ($allTests as $testInfo) {
  713. $inBin = isset($tests[$testInfo['name']]);
  714. $message = sprintf(
  715. "%s %4d %s %5s %15s %4d %s\n",
  716. $inBin ? "***" : " ",
  717. $testInfo['sorted_sequence'],
  718. $inBin ? sprintf('%4d', $tests[$testInfo['name']]['worker_sequence']) : " ",
  719. in_array('#slow', $testInfo['groups']) ? '#slow' : '',
  720. trim_with_ellipsis($testInfo['group'], 15, \STR_PAD_RIGHT),
  721. $testInfo['tests_count'],
  722. trim_with_ellipsis($testInfo['name'], 60, \STR_PAD_LEFT),
  723. );
  724. simpletest_script_print($message, $inBin ? SIMPLETEST_SCRIPT_COLOR_BRIGHT_WHITE : SIMPLETEST_SCRIPT_COLOR_GRAY);
  725. }
  726. echo "-------------------------------------------------------------------------------------\n\n";
  727. }
  728. /**
  729. * Initialize the reporter.
  730. */
  731. function simpletest_script_reporter_init(): void {
  732. global $test_list, $results_map;
  733. $results_map = [
  734. 'pass' => 'Pass',
  735. 'fail' => 'Fail',
  736. 'error' => 'Error',
  737. 'skipped' => 'Skipped',
  738. 'cli_fail' => 'Failure',
  739. 'exception' => 'Exception',
  740. 'debug' => 'Log',
  741. ];
  742. // Tell the user about what tests are to be run.
  743. if (Config::get('all')) {
  744. echo "All tests will run.\n\n";
  745. }
  746. else {
  747. echo "Tests to be run:\n";
  748. foreach ($test_list as $class_name) {
  749. echo " - $class_name\n";
  750. }
  751. echo "\n";
  752. }
  753. echo "Test run started:\n";
  754. echo " " . date('l, F j, Y - H:i', $_SERVER['REQUEST_TIME']) . "\n";
  755. Timer::start('run-tests');
  756. echo "\n";
  757. echo "Test summary\n";
  758. echo "------------\n";
  759. echo "\n";
  760. }
  761. /**
  762. * Displays the assertion result summary for a single test class.
  763. *
  764. * @param string $class
  765. * The test class name that was run.
  766. * @param array $results
  767. * The assertion results using #pass, #fail, #exception, #debug array keys.
  768. * @param float|null $duration
  769. * The time taken for the test to complete.
  770. */
  771. function simpletest_script_reporter_display_summary($class, $results, $duration = NULL): void {
  772. // Output all test results vertically aligned.
  773. $summary = [str_pad($results['#pass'], 4, " ", STR_PAD_LEFT) . ' passed'];
  774. if ($results['#fail']) {
  775. $summary[] = $results['#fail'] . ' failed';
  776. }
  777. if ($results['#error']) {
  778. $summary[] = $results['#error'] . ' errored';
  779. }
  780. if ($results['#skipped']) {
  781. $summary[] = $results['#skipped'] . ' skipped';
  782. }
  783. if ($results['#exception']) {
  784. $summary[] = $results['#exception'] . ' exception(s)';
  785. }
  786. if ($results['#debug']) {
  787. $summary[] = $results['#debug'] . ' log(s)';
  788. }
  789. if ($results['#cli_fail']) {
  790. $summary[] = 'exit code ' . $results['#exit_code'];
  791. }
  792. // The key $results['#time'] holds the sum of the tests execution times,
  793. // without taking into account the process spawning time and the setup
  794. // times of the tests themselves. So for reporting to be consistent with
  795. // PHPUnit CLI reported execution time, we report here the overall time of
  796. // execution of the spawned process.
  797. $time = sprintf('%8.3fs', $duration);
  798. $output = vsprintf('%s %s %s', [$time, trim_with_ellipsis($class, 70, STR_PAD_LEFT), implode(', ', $summary)]);
  799. $status = ($results['#fail'] || $results['#cli_fail'] || $results['#exception'] || $results['#error'] ? 'fail' : 'pass');
  800. simpletest_script_print($output . "\n", simpletest_script_color_code($status));
  801. }
  802. /**
  803. * Display jUnit XML test results.
  804. */
  805. function simpletest_script_reporter_write_xml_results(TestRunResultsStorageInterface $test_run_results_storage): void {
  806. global $test_ids, $results_map;
  807. try {
  808. $results = simpletest_script_load_messages_by_test_id($test_run_results_storage, $test_ids);
  809. }
  810. catch (Exception $e) {
  811. echo (string) $e;
  812. exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
  813. }
  814. $test_class = '';
  815. $xml_files = [];
  816. foreach ($results as $result) {
  817. if (isset($results_map[$result->status])) {
  818. if ($result->test_class != $test_class) {
  819. // We've moved onto a new class, so write the last classes results to a
  820. // file:
  821. if (isset($xml_files[$test_class])) {
  822. file_put_contents(Config::get('xml') . '/' . str_replace('\\', '_', $test_class) . '.xml', $xml_files[$test_class]['doc']->saveXML());
  823. unset($xml_files[$test_class]);
  824. }
  825. $test_class = $result->test_class;
  826. if (!isset($xml_files[$test_class])) {
  827. $doc = new DOMDocument('1.0', 'utf-8');
  828. $root = $doc->createElement('testsuite');
  829. $root = $doc->appendChild($root);
  830. $xml_files[$test_class] = ['doc' => $doc, 'suite' => $root];
  831. }
  832. }
  833. // For convenience:
  834. $dom_document = &$xml_files[$test_class]['doc'];
  835. // Create the XML element for this test case:
  836. $case = $dom_document->createElement('testcase');
  837. $case->setAttribute('classname', $test_class);
  838. if (str_contains($result->function, '->')) {
  839. [, $name] = explode('->', $result->function, 2);
  840. }
  841. else {
  842. $name = $result->function;
  843. }
  844. $case->setAttribute('name', $name);
  845. // Passes get no further attention, but failures and exceptions get to add
  846. // more detail:
  847. if ($result->status == 'fail') {
  848. $fail = $dom_document->createElement('failure');
  849. $fail->setAttribute('type', 'failure');
  850. $fail->setAttribute('message', $result->message_group);
  851. $text = $dom_document->createTextNode($result->message);
  852. $fail->appendChild($text);
  853. $case->appendChild($fail);
  854. }
  855. elseif ($result->status == 'exception') {
  856. // In the case of an exception the $result->function may not be a class
  857. // method so we record the full function name:
  858. $case->setAttribute('name', $result->function);
  859. $fail = $dom_document->createElement('error');
  860. $fail->setAttribute('type', 'exception');
  861. $fail->setAttribute('message', $result->message_group);
  862. $full_message = $result->message . "\n\nline: " . $result->line . "\nfile: " . $result->file;
  863. $text = $dom_document->createTextNode($full_message);
  864. $fail->appendChild($text);
  865. $case->appendChild($fail);
  866. }
  867. // Append the test case XML to the test suite:
  868. $xml_files[$test_class]['suite']->appendChild($case);
  869. }
  870. }
  871. // The last test case hasn't been saved to a file yet, so do that now:
  872. if (isset($xml_files[$test_class])) {
  873. file_put_contents(Config::get('xml') . '/' . str_replace('\\', '_', $test_class) . '.xml', $xml_files[$test_class]['doc']->saveXML());
  874. unset($xml_files[$test_class]);
  875. }
  876. }
  877. /**
  878. * Stop the test timer.
  879. */
  880. function simpletest_script_reporter_timer_stop(): void {
  881. global $total_time;
  882. echo "\n";
  883. $end = Timer::stop('run-tests');
  884. $wall_seconds = $end['time'] / 1000;
  885. $formatter = \Drupal::service('date.formatter');
  886. echo "Wall time: " . $formatter->formatInterval((int) $wall_seconds) . "\n";
  887. echo "Total time: " . $formatter->formatInterval((int) $total_time) . "\n";
  888. if ($wall_seconds > 0) {
  889. echo sprintf("Speedup: %.2fx (concurrency %d)\n", $total_time / $wall_seconds, Config::get('concurrency'));
  890. }
  891. echo "\n";
  892. }
  893. /**
  894. * Display test results.
  895. */
  896. function simpletest_script_reporter_display_results(TestRunResultsStorageInterface $test_run_results_storage): void {
  897. global $test_ids, $results_map;
  898. if (Config::get('verbose')) {
  899. // Report results.
  900. echo "Detailed test results\n";
  901. echo "---------------------\n";
  902. try {
  903. $results = simpletest_script_load_messages_by_test_id($test_run_results_storage, $test_ids);
  904. }
  905. catch (Exception $e) {
  906. echo (string) $e;
  907. exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
  908. }
  909. $test_class = '';
  910. foreach ($results as $result) {
  911. if (isset($results_map[$result->status])) {
  912. if ($result->test_class != $test_class) {
  913. // Display test class every time results are for new test class.
  914. echo "\n\n---- $result->test_class ----\n\n\n";
  915. $test_class = $result->test_class;
  916. // Print table header.
  917. echo "Status Duration Info \n";
  918. echo "--------------------------------------------------------------------------------------------------------\n";
  919. }
  920. simpletest_script_format_result($result);
  921. }
  922. }
  923. }
  924. }
  925. /**
  926. * Format the result so that it fits within 80 characters.
  927. *
  928. * @param object $result
  929. * The result object to format.
  930. */
  931. function simpletest_script_format_result($result): void {
  932. global $results_map;
  933. if ($result->time == 0) {
  934. $duration = " ";
  935. }
  936. elseif ($result->time < 0.001) {
  937. $duration = " <1 ms";
  938. }
  939. else {
  940. $duration = sprintf("%9.3fs", $result->time);
  941. }
  942. $summary = sprintf("%-9.9s %s %s\n", $results_map[$result->status], $duration, trim_with_ellipsis($result->function, 80, STR_PAD_LEFT));
  943. simpletest_script_print($summary, simpletest_script_color_code($result->status));
  944. if ($result->message === '' || in_array($result->status, ['pass', 'fail', 'error'])) {
  945. return;
  946. }
  947. $message = trim(strip_tags($result->message));
  948. if (Config::get('non-html')) {
  949. $message = Html::decodeEntities($message);
  950. }
  951. $lines = explode("\n", $message);
  952. foreach ($lines as $line) {
  953. echo " $line\n";
  954. }
  955. }
  956. /**
  957. * Print error messages so the user will notice them.
  958. *
  959. * Print error message prefixed with " ERROR: " and displayed in fail color if
  960. * color output is enabled.
  961. *
  962. * @param string $message
  963. * The message to print.
  964. */
  965. function simpletest_script_print_error($message): void {
  966. simpletest_script_print(" ERROR: $message\n", SIMPLETEST_SCRIPT_COLOR_FAIL);
  967. }
  968. /**
  969. * Print a message to the console, using a color.
  970. *
  971. * @param string $message
  972. * The message to print.
  973. * @param int|string $color_code
  974. * The color code to use for coloring.
  975. */
  976. function simpletest_script_print($message, $color_code): void {
  977. try {
  978. if (Config::get('color')) {
  979. echo "\033[" . $color_code . "m" . $message . "\033[0m";
  980. }
  981. else {
  982. echo $message;
  983. }
  984. }
  985. catch (\RuntimeException) {
  986. echo $message;
  987. }
  988. }
  989. /**
  990. * Get the color code associated with the specified status.
  991. *
  992. * @param string $status
  993. * The status string to get code for. Special cases are: 'pass', 'fail', or
  994. * 'exception'.
  995. *
  996. * @return int
  997. * Color code. Returns 0 for default case.
  998. */
  999. function simpletest_script_color_code($status) {
  1000. return match ($status) {
  1001. 'pass' => SIMPLETEST_SCRIPT_COLOR_PASS,
  1002. 'fail', 'cli_fail', 'error', 'exception' => SIMPLETEST_SCRIPT_COLOR_FAIL,
  1003. 'skipped' => SIMPLETEST_SCRIPT_COLOR_YELLOW,
  1004. 'debug' => SIMPLETEST_SCRIPT_COLOR_CYAN,
  1005. default => 0,
  1006. };
  1007. }
  1008. /**
  1009. * Prints alternative test names.
  1010. *
  1011. * Searches the provided array of string values for close matches based on the
  1012. * Levenshtein algorithm.
  1013. *
  1014. * @param string $string
  1015. * A string to test.
  1016. * @param array $array
  1017. * A list of strings to search.
  1018. * @param int $degree
  1019. * The matching strictness. Higher values return fewer matches. A value of
  1020. * 4 means that the function will return strings from $array if the candidate
  1021. * string in $array would be identical to $string by changing 1/4 or fewer of
  1022. * its characters.
  1023. *
  1024. * @see http://php.net/manual/function.levenshtein.php
  1025. */
  1026. function simpletest_script_print_alternatives($string, $array, $degree = 4): void {
  1027. $alternatives = [];
  1028. foreach ($array as $item) {
  1029. $lev = levenshtein($string, $item);
  1030. if ($lev <= strlen($item) / $degree || str_contains($string, $item)) {
  1031. $alternatives[] = $item;
  1032. }
  1033. }
  1034. if (!empty($alternatives)) {
  1035. simpletest_script_print(" Did you mean?\n", SIMPLETEST_SCRIPT_COLOR_FAIL);
  1036. foreach ($alternatives as $alternative) {
  1037. simpletest_script_print(" - $alternative\n", SIMPLETEST_SCRIPT_COLOR_FAIL);
  1038. }
  1039. }
  1040. }
  1041. /**
  1042. * Loads test result messages from the database.
  1043. *
  1044. * Messages are ordered by test class and message id.
  1045. *
  1046. * @param array $test_ids
  1047. * Array of test IDs of the messages to be loaded.
  1048. *
  1049. * @return array
  1050. * Array of test result messages from the database.
  1051. */
  1052. function simpletest_script_load_messages_by_test_id(TestRunResultsStorageInterface $test_run_results_storage, $test_ids) {
  1053. $results = [];
  1054. // Sqlite has a maximum number of variables per query. If required, the
  1055. // database query is split into chunks.
  1056. if (count($test_ids) > SIMPLETEST_SCRIPT_SQLITE_VARIABLE_LIMIT && Config::get('sqlite')) {
  1057. $test_id_chunks = array_chunk($test_ids, SIMPLETEST_SCRIPT_SQLITE_VARIABLE_LIMIT);
  1058. }
  1059. else {
  1060. $test_id_chunks = [$test_ids];
  1061. }
  1062. foreach ($test_id_chunks as $test_id_chunk) {
  1063. try {
  1064. $result_chunk = [];
  1065. foreach ($test_id_chunk as $test_id) {
  1066. $test_run = TestRun::get($test_run_results_storage, $test_id);
  1067. $result_chunk = array_merge($result_chunk, $test_run->getLogEntriesByTestClass());
  1068. }
  1069. }
  1070. catch (Exception $e) {
  1071. echo (string) $e;
  1072. exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
  1073. }
  1074. if ($result_chunk) {
  1075. $results = array_merge($results, $result_chunk);
  1076. }
  1077. }
  1078. return $results;
  1079. }
  1080. /**
  1081. * Trims a string adding a leading or trailing ellipsis.
  1082. *
  1083. * @param string $input
  1084. * The input string.
  1085. * @param int $length
  1086. * The exact trimmed string length.
  1087. * @param int $side
  1088. * Leading or trailing ellipsis.
  1089. *
  1090. * @return string
  1091. * The trimmed string.
  1092. */
  1093. function trim_with_ellipsis(string $input, int $length, int $side): string {
  1094. if (strlen($input) < $length) {
  1095. return str_pad($input, $length, ' ', \STR_PAD_RIGHT);
  1096. }
  1097. elseif (strlen($input) > $length) {
  1098. return match($side) {
  1099. \STR_PAD_RIGHT => substr($input, 0, $length - 1) . '…',
  1100. default => '…' . substr($input, -$length + 1),
  1101. };
  1102. }
  1103. return $input;
  1104. }
  1105. /**
  1106. * Outputs the discovery warning messages.
  1107. */
  1108. function dump_discovery_warnings(): void {
  1109. $warnings = PhpUnitTestDiscovery::instance()->getWarnings();
  1110. if (!empty($warnings)) {
  1111. simpletest_script_print("Test discovery warnings\n", SIMPLETEST_SCRIPT_COLOR_BRIGHT_WHITE);
  1112. simpletest_script_print("-----------------------\n", SIMPLETEST_SCRIPT_COLOR_BRIGHT_WHITE);
  1113. foreach ($warnings as $warning) {
  1114. $tmp = explode("\n", $warning);
  1115. simpletest_script_print('* ' . array_shift($tmp) . "\n", SIMPLETEST_SCRIPT_COLOR_EXCEPTION);
  1116. foreach ($tmp as $sub) {
  1117. simpletest_script_print(' ' . $sub . "\n", SIMPLETEST_SCRIPT_COLOR_EXCEPTION);
  1118. }
  1119. echo "\n";
  1120. }
  1121. }
  1122. }

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