run-tests.sh 53 KB

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