run-tests.sh

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

Script for running tests on DrupalCI.

This script is intended for use only by drupal.org's testing. In general, tests should be run directly with phpunit.

@internal

File

core/scripts/run-tests.sh

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

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