You are here

run-tests.sh in Drupal 8

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