You are here

run-tests.sh in Drupal 9

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