Drupal investigation

run-tests.sh 51KB

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