run-tests.sh

Same filename in other branches
  1. 7.x scripts/run-tests.sh
  2. 9 core/scripts/run-tests.sh
  3. 10 core/scripts/run-tests.sh
  4. 11.x core/scripts/run-tests.sh

This script runs Drupal tests from command line.

File

core/scripts/run-tests.sh

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

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