run-tests.sh

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

Script for running tests on DrupalCI.

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

@internal

File

core/scripts/run-tests.sh

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

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