run-tests.sh 51 KB

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