You are here

run-tests.sh in Drupal 10

Same filename and directory in other branches
  1. 8 core/scripts/run-tests.sh
  2. 9 core/scripts/run-tests.sh

This script runs Drupal tests from command line.

File

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