run-tests.sh 51 KB

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