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. 11.x 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\TestTools\PhpUnitCompatibility\ClassWriter;
  27. use PHPUnit\Framework\TestCase;
  28. use PHPUnit\Runner\Version;
  29. use Symfony\Component\Console\Output\ConsoleOutput;
  30. use Symfony\Component\HttpFoundation\Request;
  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/tests/src/Functional/UserCreateTest.php').
  244. This argument must be last 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\Tests\block\Functional\BlockTest
  291. Without a preinstalled Drupal site, specify a SQLite database pathname to create
  292. and the default database connection info to use in tests:
  293. sudo -u [wwwrun|www-data|etc] php ./core/scripts/{$args['script']}
  294. --sqlite /tmpfs/drupal/test.sqlite
  295. --dburl mysql://username:password@localhost/database
  296. --url http://example.com/ --all
  297. EOF;
  298. }
  299. /**
  300. * Parse execution argument and ensure that all are valid.
  301. *
  302. * @return array
  303. * The list of arguments.
  304. */
  305. function simpletest_script_parse_args() {
  306. // Set default values.
  307. $args = [
  308. 'script' => '',
  309. 'help' => FALSE,
  310. 'list' => FALSE,
  311. 'list-files' => FALSE,
  312. 'list-files-json' => FALSE,
  313. 'clean' => FALSE,
  314. 'url' => '',
  315. 'sqlite' => NULL,
  316. 'dburl' => NULL,
  317. 'php' => '',
  318. 'concurrency' => 1,
  319. 'all' => FALSE,
  320. 'module' => NULL,
  321. 'class' => FALSE,
  322. 'file' => FALSE,
  323. 'types' => [],
  324. 'directory' => NULL,
  325. 'color' => FALSE,
  326. 'verbose' => FALSE,
  327. 'keep-results' => FALSE,
  328. 'keep-results-table' => FALSE,
  329. 'test_names' => [],
  330. 'repeat' => 1,
  331. 'die-on-fail' => FALSE,
  332. 'suppress-deprecations' => FALSE,
  333. // Used internally.
  334. 'test-id' => 0,
  335. 'execute-test' => '',
  336. 'xml' => '',
  337. 'non-html' => FALSE,
  338. 'ci-parallel-node-index' => 1,
  339. 'ci-parallel-node-total' => 1,
  340. ];
  341. // Override with set values.
  342. $args['script'] = basename(array_shift($_SERVER['argv']));
  343. $count = 0;
  344. while ($arg = array_shift($_SERVER['argv'])) {
  345. if (preg_match('/--(\S+)/', $arg, $matches)) {
  346. // Argument found.
  347. if (array_key_exists($matches[1], $args)) {
  348. // Argument found in list.
  349. $previous_arg = $matches[1];
  350. if (is_bool($args[$previous_arg])) {
  351. $args[$matches[1]] = TRUE;
  352. }
  353. elseif (is_array($args[$previous_arg])) {
  354. $value = array_shift($_SERVER['argv']);
  355. $args[$matches[1]] = array_map('trim', explode(',', $value));
  356. }
  357. else {
  358. $args[$matches[1]] = array_shift($_SERVER['argv']);
  359. }
  360. // Clear extraneous values.
  361. $args['test_names'] = [];
  362. $count++;
  363. }
  364. else {
  365. // Argument not found in list.
  366. simpletest_script_print_error("Unknown argument '$arg'.");
  367. exit(SIMPLETEST_SCRIPT_EXIT_FAILURE);
  368. }
  369. }
  370. else {
  371. // Values found without an argument should be test names.
  372. $args['test_names'] += explode(',', $arg);
  373. $count++;
  374. }
  375. }
  376. // Validate the concurrency argument.
  377. if (!is_numeric($args['concurrency']) || $args['concurrency'] <= 0) {
  378. simpletest_script_print_error("--concurrency must be a strictly positive integer.");
  379. exit(SIMPLETEST_SCRIPT_EXIT_FAILURE);
  380. }
  381. return [$args, $count];
  382. }
  383. /**
  384. * Initialize script variables and perform general setup requirements.
  385. */
  386. function simpletest_script_init() {
  387. global $args, $php;
  388. $host = 'localhost';
  389. $path = '';
  390. $port = '80';
  391. // Determine location of php command automatically, unless a command line
  392. // argument is supplied.
  393. if (!empty($args['php'])) {
  394. $php = $args['php'];
  395. }
  396. elseif ($php_env = getenv('_')) {
  397. // '_' is an environment variable set by the shell. It contains the command
  398. // that was executed.
  399. $php = $php_env;
  400. }
  401. elseif ($sudo = getenv('SUDO_COMMAND')) {
  402. // 'SUDO_COMMAND' is an environment variable set by the sudo program.
  403. // Extract only the PHP interpreter, not the rest of the command.
  404. [$php] = explode(' ', $sudo, 2);
  405. }
  406. else {
  407. simpletest_script_print_error('Unable to automatically determine the path to the PHP interpreter. Supply the --php command line argument.');
  408. simpletest_script_help();
  409. exit(SIMPLETEST_SCRIPT_EXIT_FAILURE);
  410. }
  411. // Detect if we're in the top-level process using the private 'execute-test'
  412. // argument. Determine if being run on drupal.org's testing infrastructure
  413. // using the presence of 'drupalci' in the sqlite argument.
  414. // @todo https://www.drupal.org/project/drupalci_testbot/issues/2860941 Use
  415. // better environment variable to detect DrupalCI.
  416. if (!$args['execute-test'] && preg_match('/drupalci/', $args['sqlite'] ?? '')) {
  417. // Update PHPUnit if needed and possible. There is a later check once the
  418. // autoloader is in place to ensure we're on the correct version. We need to
  419. // do this before the autoloader is in place to ensure that it is correct.
  420. $composer = ($composer = rtrim('\\' === DIRECTORY_SEPARATOR ? preg_replace('/[\r\n].*/', '', `where.exe composer.phar`) : `which composer.phar`))
  421. ? $php . ' ' . escapeshellarg($composer)
  422. : 'composer';
  423. passthru("$composer run-script drupal-phpunit-upgrade-check");
  424. }
  425. $autoloader = require_once __DIR__ . '/../../autoload.php';
  426. // The PHPUnit compatibility layer needs to be available to autoload tests.
  427. $autoloader->add('Drupal\\TestTools', __DIR__ . '/../tests');
  428. ClassWriter::mutateTestBase($autoloader);
  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. $reflection = new \ReflectionClass($class);
  709. if ($reflection->hasProperty('runLimit')) {
  710. set_time_limit($reflection->getStaticPropertyValue('runLimit'));
  711. }
  712. $runner = PhpUnitTestRunner::create(\Drupal::getContainer());
  713. $results = $runner->execute($test_run, [$class], $status);
  714. $runner->processPhpUnitResults($test_run, $results);
  715. $summaries = $runner->summarizeResults($results);
  716. foreach ($summaries as $class => $summary) {
  717. simpletest_script_reporter_display_summary($class, $summary);
  718. }
  719. return $status;
  720. }
  721. /**
  722. * Run a single test, bootstrapping Drupal if needed.
  723. */
  724. function simpletest_script_run_one_test(TestRun $test_run, $test_class) {
  725. global $args;
  726. try {
  727. if ($args['suppress-deprecations']) {
  728. putenv('SYMFONY_DEPRECATIONS_HELPER=disabled');
  729. }
  730. $status = simpletest_script_run_phpunit($test_run, $test_class);
  731. exit($status);
  732. }
  733. // DrupalTestCase::run() catches exceptions already, so this is only reached
  734. // when an exception is thrown in the wrapping test runner environment.
  735. catch (Exception $e) {
  736. echo (string) $e;
  737. exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
  738. }
  739. }
  740. /**
  741. * Return a command used to run a test in a separate process.
  742. *
  743. * @param int $test_id
  744. * The current test ID.
  745. * @param string $test_class
  746. * The name of the test class to run.
  747. *
  748. * @return string
  749. * The assembled command string.
  750. */
  751. function simpletest_script_command(TestRun $test_run, $test_class) {
  752. global $args, $php;
  753. $command = escapeshellarg($php) . ' ' . escapeshellarg('./core/scripts/' . $args['script']);
  754. $command .= ' --url ' . escapeshellarg($args['url']);
  755. if (!empty($args['sqlite'])) {
  756. $command .= ' --sqlite ' . escapeshellarg($args['sqlite']);
  757. }
  758. if (!empty($args['dburl'])) {
  759. $command .= ' --dburl ' . escapeshellarg($args['dburl']);
  760. }
  761. $command .= ' --php ' . escapeshellarg($php);
  762. $command .= " --test-id {$test_run->id()}";
  763. foreach (['verbose', 'keep-results', 'color', 'die-on-fail', 'suppress-deprecations'] as $arg) {
  764. if ($args[$arg]) {
  765. $command .= ' --' . $arg;
  766. }
  767. }
  768. // --execute-test and class name needs to come last.
  769. $command .= ' --execute-test ' . escapeshellarg($test_class);
  770. return $command;
  771. }
  772. /**
  773. * Get list of tests based on arguments.
  774. *
  775. * If --all specified then return all available tests, otherwise reads list of
  776. * tests.
  777. *
  778. * @return array
  779. * List of tests.
  780. */
  781. function simpletest_script_get_test_list() {
  782. global $args;
  783. $test_discovery = new TestDiscovery(
  784. \Drupal::root(),
  785. \Drupal::service('class_loader')
  786. );
  787. $types_processed = empty($args['types']);
  788. $test_list = [];
  789. $slow_tests = [];
  790. if ($args['all'] || $args['module'] || $args['directory']) {
  791. try {
  792. $groups = $test_discovery->getTestClasses($args['module'], $args['types'], $args['directory']);
  793. $types_processed = TRUE;
  794. }
  795. catch (Exception $e) {
  796. echo (string) $e;
  797. exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
  798. }
  799. // If the tests are run in parallel jobs, ensure that slow tests are
  800. // distributed between each job.
  801. if ((int) $args['ci-parallel-node-total'] > 1) {
  802. if (key($groups) === '#slow') {
  803. $slow_tests = array_keys(array_shift($groups));
  804. }
  805. }
  806. $all_tests = [];
  807. foreach ($groups as $group => $tests) {
  808. if ($group === '#slow') {
  809. $slow_group = $tests;
  810. }
  811. else {
  812. $all_tests = array_merge($all_tests, array_keys($tests));
  813. }
  814. }
  815. // If no type has been set, order the tests alphabetically by test namespace
  816. // so that unit tests run last. This takes advantage of the fact that Build,
  817. // Functional, Functional JavaScript, Kernel, Unit roughly corresponds to
  818. // test time.
  819. usort($all_tests, function ($a, $b) {
  820. $slice = function ($class) {
  821. $parts = explode('\\', $class);
  822. return implode('\\', array_slice($parts, 3));
  823. };
  824. return $slice($a) > $slice($b) ? 1 : -1;
  825. });
  826. // If the tests are not being run in parallel, then ensure slow tests run all
  827. // together first.
  828. if ((int) $args['ci-parallel-node-total'] <= 1 && !empty($slow_group)) {
  829. $all_tests = array_merge(array_keys($slow_group), $all_tests);
  830. }
  831. $test_list = array_unique($all_tests);
  832. $test_list = array_diff($test_list, $slow_tests);
  833. }
  834. else {
  835. if ($args['class']) {
  836. $test_list = [];
  837. foreach ($args['test_names'] as $test_class) {
  838. [$class_name] = explode('::', $test_class, 2);
  839. if (class_exists($class_name)) {
  840. $test_list[] = $test_class;
  841. }
  842. else {
  843. try {
  844. $groups = $test_discovery->getTestClasses(NULL, $args['types']);
  845. }
  846. catch (Exception $e) {
  847. echo (string) $e;
  848. exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
  849. }
  850. $all_classes = [];
  851. foreach ($groups as $group) {
  852. $all_classes = array_merge($all_classes, array_keys($group));
  853. }
  854. simpletest_script_print_error('Test class not found: ' . $class_name);
  855. simpletest_script_print_alternatives($class_name, $all_classes, 6);
  856. exit(SIMPLETEST_SCRIPT_EXIT_FAILURE);
  857. }
  858. }
  859. }
  860. elseif ($args['file']) {
  861. // Extract test case class names from specified files.
  862. $parser = new TestFileParser();
  863. foreach ($args['test_names'] as $file) {
  864. if (!file_exists($file)) {
  865. simpletest_script_print_error('File not found: ' . $file);
  866. exit(SIMPLETEST_SCRIPT_EXIT_FAILURE);
  867. }
  868. $test_list = array_merge($test_list, $parser->getTestListFromFile($file));
  869. }
  870. }
  871. else {
  872. try {
  873. $groups = $test_discovery->getTestClasses(NULL, $args['types']);
  874. $types_processed = TRUE;
  875. }
  876. catch (Exception $e) {
  877. echo (string) $e;
  878. exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
  879. }
  880. // Store all the groups so we can suggest alternatives if we need to.
  881. $all_groups = array_keys($groups);
  882. // Verify that the groups exist.
  883. if (!empty($unknown_groups = array_diff($args['test_names'], $all_groups))) {
  884. $first_group = reset($unknown_groups);
  885. simpletest_script_print_error('Test group not found: ' . $first_group);
  886. simpletest_script_print_alternatives($first_group, $all_groups);
  887. exit(SIMPLETEST_SCRIPT_EXIT_FAILURE);
  888. }
  889. // Merge the tests from the groups together.
  890. foreach ($args['test_names'] as $group_name) {
  891. $test_list = array_merge($test_list, array_keys($groups[$group_name]));
  892. }
  893. // Ensure our list of tests contains only one entry for each test.
  894. $test_list = array_unique($test_list);
  895. }
  896. }
  897. // If the test list creation does not automatically limit by test type then
  898. // we need to do so here.
  899. if (!$types_processed) {
  900. $test_list = array_filter($test_list, function ($test_class) use ($args) {
  901. $test_info = TestDiscovery::getTestInfo($test_class);
  902. return in_array($test_info['type'], $args['types'], TRUE);
  903. });
  904. }
  905. if (empty($test_list)) {
  906. simpletest_script_print_error('No valid tests were specified.');
  907. exit(SIMPLETEST_SCRIPT_EXIT_FAILURE);
  908. }
  909. if ((int) $args['ci-parallel-node-total'] > 1) {
  910. $slow_tests_per_job = (int) ceil(count($slow_tests) / $args['ci-parallel-node-total']);
  911. $tests_per_job = (int) ceil(count($test_list) / $args['ci-parallel-node-total']);
  912. $test_list = array_merge(array_slice($slow_tests, ($args['ci-parallel-node-index'] -1) * $slow_tests_per_job, $slow_tests_per_job), array_slice($test_list, ($args['ci-parallel-node-index'] - 1) * $tests_per_job, $tests_per_job));
  913. }
  914. return $test_list;
  915. }
  916. /**
  917. * Initialize the reporter.
  918. */
  919. function simpletest_script_reporter_init() {
  920. global $args, $test_list, $results_map;
  921. $results_map = [
  922. 'pass' => 'Pass',
  923. 'fail' => 'Fail',
  924. 'exception' => 'Exception',
  925. ];
  926. echo "\n";
  927. echo "Drupal test run\n";
  928. echo "---------------\n";
  929. echo "\n";
  930. // Tell the user about what tests are to be run.
  931. if ($args['all']) {
  932. echo "All tests will run.\n\n";
  933. }
  934. else {
  935. echo "Tests to be run:\n";
  936. foreach ($test_list as $class_name) {
  937. echo " - $class_name\n";
  938. }
  939. echo "\n";
  940. }
  941. echo "Test run started:\n";
  942. echo " " . date('l, F j, Y - H:i', $_SERVER['REQUEST_TIME']) . "\n";
  943. Timer::start('run-tests');
  944. echo "\n";
  945. echo "Test summary\n";
  946. echo "------------\n";
  947. echo "\n";
  948. }
  949. /**
  950. * Displays the assertion result summary for a single test class.
  951. *
  952. * @param string $class
  953. * The test class name that was run.
  954. * @param array $results
  955. * The assertion results using #pass, #fail, #exception, #debug array keys.
  956. */
  957. function simpletest_script_reporter_display_summary($class, $results) {
  958. // Output all test results vertically aligned.
  959. // Cut off the class name after 60 chars, and pad each group with 3 digits
  960. // by default (more than 999 assertions are rare).
  961. $output = vsprintf('%-60.60s %10s %9s %14s %12s', [
  962. $class,
  963. $results['#pass'] . ' passes',
  964. !$results['#fail'] ? '' : $results['#fail'] . ' fails',
  965. !$results['#exception'] ? '' : $results['#exception'] . ' exceptions',
  966. !$results['#debug'] ? '' : $results['#debug'] . ' messages',
  967. ]);
  968. $status = ($results['#fail'] || $results['#exception'] ? 'fail' : 'pass');
  969. simpletest_script_print($output . "\n", simpletest_script_color_code($status));
  970. }
  971. /**
  972. * Display jUnit XML test results.
  973. */
  974. function simpletest_script_reporter_write_xml_results(TestRunResultsStorageInterface $test_run_results_storage) {
  975. global $args, $test_ids, $results_map;
  976. try {
  977. $results = simpletest_script_load_messages_by_test_id($test_run_results_storage, $test_ids);
  978. }
  979. catch (Exception $e) {
  980. echo (string) $e;
  981. exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
  982. }
  983. $test_class = '';
  984. $xml_files = [];
  985. foreach ($results as $result) {
  986. if (isset($results_map[$result->status])) {
  987. if ($result->test_class != $test_class) {
  988. // We've moved onto a new class, so write the last classes results to a
  989. // file:
  990. if (isset($xml_files[$test_class])) {
  991. file_put_contents($args['xml'] . '/' . str_replace('\\', '_', $test_class) . '.xml', $xml_files[$test_class]['doc']->saveXML());
  992. unset($xml_files[$test_class]);
  993. }
  994. $test_class = $result->test_class;
  995. if (!isset($xml_files[$test_class])) {
  996. $doc = new DomDocument('1.0');
  997. $root = $doc->createElement('testsuite');
  998. $root = $doc->appendChild($root);
  999. $xml_files[$test_class] = ['doc' => $doc, 'suite' => $root];
  1000. }
  1001. }
  1002. // For convenience:
  1003. $dom_document = &$xml_files[$test_class]['doc'];
  1004. // Create the XML element for this test case:
  1005. $case = $dom_document->createElement('testcase');
  1006. $case->setAttribute('classname', $test_class);
  1007. if (str_contains($result->function, '->')) {
  1008. [$class, $name] = explode('->', $result->function, 2);
  1009. }
  1010. else {
  1011. $name = $result->function;
  1012. }
  1013. $case->setAttribute('name', $name);
  1014. // Passes get no further attention, but failures and exceptions get to add
  1015. // more detail:
  1016. if ($result->status == 'fail') {
  1017. $fail = $dom_document->createElement('failure');
  1018. $fail->setAttribute('type', 'failure');
  1019. $fail->setAttribute('message', $result->message_group);
  1020. $text = $dom_document->createTextNode($result->message);
  1021. $fail->appendChild($text);
  1022. $case->appendChild($fail);
  1023. }
  1024. elseif ($result->status == 'exception') {
  1025. // In the case of an exception the $result->function may not be a class
  1026. // method so we record the full function name:
  1027. $case->setAttribute('name', $result->function);
  1028. $fail = $dom_document->createElement('error');
  1029. $fail->setAttribute('type', 'exception');
  1030. $fail->setAttribute('message', $result->message_group);
  1031. $full_message = $result->message . "\n\nline: " . $result->line . "\nfile: " . $result->file;
  1032. $text = $dom_document->createTextNode($full_message);
  1033. $fail->appendChild($text);
  1034. $case->appendChild($fail);
  1035. }
  1036. // Append the test case XML to the test suite:
  1037. $xml_files[$test_class]['suite']->appendChild($case);
  1038. }
  1039. }
  1040. // The last test case hasn't been saved to a file yet, so do that now:
  1041. if (isset($xml_files[$test_class])) {
  1042. file_put_contents($args['xml'] . '/' . str_replace('\\', '_', $test_class) . '.xml', $xml_files[$test_class]['doc']->saveXML());
  1043. unset($xml_files[$test_class]);
  1044. }
  1045. }
  1046. /**
  1047. * Stop the test timer.
  1048. */
  1049. function simpletest_script_reporter_timer_stop() {
  1050. echo "\n";
  1051. $end = Timer::stop('run-tests');
  1052. echo "Test run duration: " . \Drupal::service('date.formatter')->formatInterval((int) ($end['time'] / 1000));
  1053. echo "\n\n";
  1054. }
  1055. /**
  1056. * Display test results.
  1057. */
  1058. function simpletest_script_reporter_display_results(TestRunResultsStorageInterface $test_run_results_storage) {
  1059. global $args, $test_ids, $results_map;
  1060. if ($args['verbose']) {
  1061. // Report results.
  1062. echo "Detailed test results\n";
  1063. echo "---------------------\n";
  1064. try {
  1065. $results = simpletest_script_load_messages_by_test_id($test_run_results_storage, $test_ids);
  1066. }
  1067. catch (Exception $e) {
  1068. echo (string) $e;
  1069. exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
  1070. }
  1071. $test_class = '';
  1072. foreach ($results as $result) {
  1073. if (isset($results_map[$result->status])) {
  1074. if ($result->test_class != $test_class) {
  1075. // Display test class every time results are for new test class.
  1076. echo "\n\n---- $result->test_class ----\n\n\n";
  1077. $test_class = $result->test_class;
  1078. // Print table header.
  1079. echo "Status Group Filename Line Function \n";
  1080. echo "--------------------------------------------------------------------------------\n";
  1081. }
  1082. simpletest_script_format_result($result);
  1083. }
  1084. }
  1085. }
  1086. }
  1087. /**
  1088. * Format the result so that it fits within 80 characters.
  1089. *
  1090. * @param object $result
  1091. * The result object to format.
  1092. */
  1093. function simpletest_script_format_result($result) {
  1094. global $args, $results_map, $color;
  1095. $summary = sprintf("%-9.9s %-10.10s %-17.17s %4.4s %-35.35s\n",
  1096. $results_map[$result->status], $result->message_group, basename($result->file), $result->line, $result->function);
  1097. simpletest_script_print($summary, simpletest_script_color_code($result->status));
  1098. $message = trim(strip_tags($result->message));
  1099. if ($args['non-html']) {
  1100. $message = Html::decodeEntities($message);
  1101. }
  1102. $lines = explode("\n", wordwrap($message), 76);
  1103. foreach ($lines as $line) {
  1104. echo " $line\n";
  1105. }
  1106. }
  1107. /**
  1108. * Print error messages so the user will notice them.
  1109. *
  1110. * Print error message prefixed with " ERROR: " and displayed in fail color if
  1111. * color output is enabled.
  1112. *
  1113. * @param string $message
  1114. * The message to print.
  1115. */
  1116. function simpletest_script_print_error($message) {
  1117. simpletest_script_print(" ERROR: $message\n", SIMPLETEST_SCRIPT_COLOR_FAIL);
  1118. }
  1119. /**
  1120. * Print a message to the console, using a color.
  1121. *
  1122. * @param string $message
  1123. * The message to print.
  1124. * @param int $color_code
  1125. * The color code to use for coloring.
  1126. */
  1127. function simpletest_script_print($message, $color_code) {
  1128. global $args;
  1129. if ($args['color']) {
  1130. echo "\033[" . $color_code . "m" . $message . "\033[0m";
  1131. }
  1132. else {
  1133. echo $message;
  1134. }
  1135. }
  1136. /**
  1137. * Get the color code associated with the specified status.
  1138. *
  1139. * @param string $status
  1140. * The status string to get code for. Special cases are: 'pass', 'fail', or
  1141. * 'exception'.
  1142. *
  1143. * @return int
  1144. * Color code. Returns 0 for default case.
  1145. */
  1146. function simpletest_script_color_code($status) {
  1147. switch ($status) {
  1148. case 'pass':
  1149. return SIMPLETEST_SCRIPT_COLOR_PASS;
  1150. case 'fail':
  1151. return SIMPLETEST_SCRIPT_COLOR_FAIL;
  1152. case 'exception':
  1153. return SIMPLETEST_SCRIPT_COLOR_EXCEPTION;
  1154. }
  1155. // Default formatting.
  1156. return 0;
  1157. }
  1158. /**
  1159. * Prints alternative test names.
  1160. *
  1161. * Searches the provided array of string values for close matches based on the
  1162. * Levenshtein algorithm.
  1163. *
  1164. * @param string $string
  1165. * A string to test.
  1166. * @param array $array
  1167. * A list of strings to search.
  1168. * @param int $degree
  1169. * The matching strictness. Higher values return fewer matches. A value of
  1170. * 4 means that the function will return strings from $array if the candidate
  1171. * string in $array would be identical to $string by changing 1/4 or fewer of
  1172. * its characters.
  1173. *
  1174. * @see http://php.net/manual/function.levenshtein.php
  1175. */
  1176. function simpletest_script_print_alternatives($string, $array, $degree = 4) {
  1177. $alternatives = [];
  1178. foreach ($array as $item) {
  1179. $lev = levenshtein($string, $item);
  1180. if ($lev <= strlen($item) / $degree || str_contains($string, $item)) {
  1181. $alternatives[] = $item;
  1182. }
  1183. }
  1184. if (!empty($alternatives)) {
  1185. simpletest_script_print(" Did you mean?\n", SIMPLETEST_SCRIPT_COLOR_FAIL);
  1186. foreach ($alternatives as $alternative) {
  1187. simpletest_script_print(" - $alternative\n", SIMPLETEST_SCRIPT_COLOR_FAIL);
  1188. }
  1189. }
  1190. }
  1191. /**
  1192. * Loads test result messages from the database.
  1193. *
  1194. * Messages are ordered by test class and message id.
  1195. *
  1196. * @param array $test_ids
  1197. * Array of test IDs of the messages to be loaded.
  1198. *
  1199. * @return array
  1200. * Array of test result messages from the database.
  1201. */
  1202. function simpletest_script_load_messages_by_test_id(TestRunResultsStorageInterface $test_run_results_storage, $test_ids) {
  1203. global $args;
  1204. $results = [];
  1205. // Sqlite has a maximum number of variables per query. If required, the
  1206. // database query is split into chunks.
  1207. if (count($test_ids) > SIMPLETEST_SCRIPT_SQLITE_VARIABLE_LIMIT && !empty($args['sqlite'])) {
  1208. $test_id_chunks = array_chunk($test_ids, SIMPLETEST_SCRIPT_SQLITE_VARIABLE_LIMIT);
  1209. }
  1210. else {
  1211. $test_id_chunks = [$test_ids];
  1212. }
  1213. foreach ($test_id_chunks as $test_id_chunk) {
  1214. try {
  1215. $result_chunk = [];
  1216. foreach ($test_id_chunk as $test_id) {
  1217. $test_run = TestRun::get($test_run_results_storage, $test_id);
  1218. $result_chunk = array_merge($result_chunk, $test_run->getLogEntriesByTestClass());
  1219. }
  1220. }
  1221. catch (Exception $e) {
  1222. echo (string) $e;
  1223. exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
  1224. }
  1225. if ($result_chunk) {
  1226. $results = array_merge($results, $result_chunk);
  1227. }
  1228. }
  1229. return $results;
  1230. }

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