run-tests.sh 52 KB

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