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

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