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