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 --dev' 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 = simpletest_test_get_all($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_get_messages('status');
  114. foreach ($messages['status'] 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.2 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.
  250. <test1>[,<test2>[,<test3> ...]]
  251. One or more tests to be run. By default, these are interpreted
  252. as the names of test groups as shown at
  253. admin/config/development/testing.
  254. These group names typically correspond to module names like "User"
  255. or "Profile" or "System", but there is also a group "Database".
  256. If --class is specified then these are interpreted as the names of
  257. specific test classes whose test methods will be run. Tests must
  258. be separated by commas. Ignored if --all is specified.
  259. To run this script you will normally invoke it from the root directory of your
  260. Drupal installation as the webserver user (differs per configuration), or root:
  261. sudo -u [wwwrun|www-data|etc] php ./core/scripts/{$args['script']}
  262. --url http://example.com/ --all
  263. sudo -u [wwwrun|www-data|etc] php ./core/scripts/{$args['script']}
  264. --url http://example.com/ --class "Drupal\block\Tests\BlockTest"
  265. Without a preinstalled Drupal site and enabled Simpletest module, specify a
  266. SQLite database pathname to create and the default database connection info to
  267. use in tests:
  268. sudo -u [wwwrun|www-data|etc] php ./core/scripts/{$args['script']}
  269. --sqlite /tmpfs/drupal/test.sqlite
  270. --dburl mysql://username:password@localhost/database
  271. --url http://example.com/ --all
  272. EOF;
  273. }
  274. /**
  275. * Parse execution argument and ensure that all are valid.
  276. *
  277. * @return array
  278. * The list of arguments.
  279. */
  280. function simpletest_script_parse_args() {
  281. // Set default values.
  282. $args = [
  283. 'script' => '',
  284. 'help' => FALSE,
  285. 'list' => FALSE,
  286. 'list-files' => FALSE,
  287. 'list-files-json' => FALSE,
  288. 'clean' => FALSE,
  289. 'url' => '',
  290. 'sqlite' => NULL,
  291. 'dburl' => NULL,
  292. 'php' => '',
  293. 'concurrency' => 1,
  294. 'all' => FALSE,
  295. 'module' => NULL,
  296. 'class' => FALSE,
  297. 'file' => FALSE,
  298. 'types' => [],
  299. 'directory' => NULL,
  300. 'color' => FALSE,
  301. 'verbose' => FALSE,
  302. 'keep-results' => FALSE,
  303. 'keep-results-table' => FALSE,
  304. 'test_names' => [],
  305. 'repeat' => 1,
  306. 'die-on-fail' => FALSE,
  307. 'suppress-deprecations' => FALSE,
  308. 'browser' => FALSE,
  309. // Used internally.
  310. 'test-id' => 0,
  311. 'execute-test' => '',
  312. 'xml' => '',
  313. 'non-html' => FALSE,
  314. ];
  315. // Override with set values.
  316. $args['script'] = basename(array_shift($_SERVER['argv']));
  317. $count = 0;
  318. while ($arg = array_shift($_SERVER['argv'])) {
  319. if (preg_match('/--(\S+)/', $arg, $matches)) {
  320. // Argument found.
  321. if (array_key_exists($matches[1], $args)) {
  322. // Argument found in list.
  323. $previous_arg = $matches[1];
  324. if (is_bool($args[$previous_arg])) {
  325. $args[$matches[1]] = TRUE;
  326. }
  327. elseif (is_array($args[$previous_arg])) {
  328. $value = array_shift($_SERVER['argv']);
  329. $args[$matches[1]] = array_map('trim', explode(',', $value));
  330. }
  331. else {
  332. $args[$matches[1]] = array_shift($_SERVER['argv']);
  333. }
  334. // Clear extraneous values.
  335. $args['test_names'] = [];
  336. $count++;
  337. }
  338. else {
  339. // Argument not found in list.
  340. simpletest_script_print_error("Unknown argument '$arg'.");
  341. exit(SIMPLETEST_SCRIPT_EXIT_FAILURE);
  342. }
  343. }
  344. else {
  345. // Values found without an argument should be test names.
  346. $args['test_names'] += explode(',', $arg);
  347. $count++;
  348. }
  349. }
  350. // Validate the concurrency argument.
  351. if (!is_numeric($args['concurrency']) || $args['concurrency'] <= 0) {
  352. simpletest_script_print_error("--concurrency must be a strictly positive integer.");
  353. exit(SIMPLETEST_SCRIPT_EXIT_FAILURE);
  354. }
  355. if ($args['browser']) {
  356. $args['keep-results'] = TRUE;
  357. }
  358. return [$args, $count];
  359. }
  360. /**
  361. * Initialize script variables and perform general setup requirements.
  362. */
  363. function simpletest_script_init() {
  364. global $args, $php;
  365. $host = 'localhost';
  366. $path = '';
  367. $port = '80';
  368. // Determine location of php command automatically, unless a command line
  369. // argument is supplied.
  370. if (!empty($args['php'])) {
  371. $php = $args['php'];
  372. }
  373. elseif ($php_env = getenv('_')) {
  374. // '_' is an environment variable set by the shell. It contains the command
  375. // that was executed.
  376. $php = $php_env;
  377. }
  378. elseif ($sudo = getenv('SUDO_COMMAND')) {
  379. // 'SUDO_COMMAND' is an environment variable set by the sudo program.
  380. // Extract only the PHP interpreter, not the rest of the command.
  381. list($php) = explode(' ', $sudo, 2);
  382. }
  383. else {
  384. simpletest_script_print_error('Unable to automatically determine the path to the PHP interpreter. Supply the --php command line argument.');
  385. simpletest_script_help();
  386. exit(SIMPLETEST_SCRIPT_EXIT_FAILURE);
  387. }
  388. // Detect if we're in the top-level process using the private 'execute-test'
  389. // argument. Determine if being run on drupal.org's testing infrastructure
  390. // using the presence of 'drupaltestbot' in the database url.
  391. // @todo https://www.drupal.org/project/drupalci_testbot/issues/2860941 Use
  392. // better environment variable to detect DrupalCI.
  393. // @todo https://www.drupal.org/project/drupal/issues/2942473 Remove when
  394. // dropping PHPUnit 4 and PHP 5 support.
  395. if (!$args['execute-test'] && preg_match('/drupalci/', $args['sqlite'])) {
  396. // Update PHPUnit if needed and possible. There is a later check once the
  397. // autoloader is in place to ensure we're on the correct version. We need to
  398. // do this before the autoloader is in place to ensure that it is correct.
  399. $composer = ($composer = rtrim('\\' === DIRECTORY_SEPARATOR ? preg_replace('/[\r\n].*/', '', `where.exe composer.phar`) : `which composer.phar`))
  400. ? $php . ' ' . escapeshellarg($composer)
  401. : 'composer';
  402. passthru("$composer run-script drupal-phpunit-upgrade-check");
  403. }
  404. $autoloader = require_once __DIR__ . '/../../autoload.php';
  405. // Get URL from arguments.
  406. if (!empty($args['url'])) {
  407. $parsed_url = parse_url($args['url']);
  408. $host = $parsed_url['host'] . (isset($parsed_url['port']) ? ':' . $parsed_url['port'] : '');
  409. $path = isset($parsed_url['path']) ? rtrim(rtrim($parsed_url['path']), '/') : '';
  410. $port = (isset($parsed_url['port']) ? $parsed_url['port'] : $port);
  411. if ($path == '/') {
  412. $path = '';
  413. }
  414. // If the passed URL schema is 'https' then setup the $_SERVER variables
  415. // properly so that testing will run under HTTPS.
  416. if ($parsed_url['scheme'] == 'https') {
  417. $_SERVER['HTTPS'] = 'on';
  418. }
  419. }
  420. if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') {
  421. $base_url = 'https://';
  422. }
  423. else {
  424. $base_url = 'http://';
  425. }
  426. $base_url .= $host;
  427. if ($path !== '') {
  428. $base_url .= $path;
  429. }
  430. putenv('SIMPLETEST_BASE_URL=' . $base_url);
  431. $_SERVER['HTTP_HOST'] = $host;
  432. $_SERVER['REMOTE_ADDR'] = '127.0.0.1';
  433. $_SERVER['SERVER_ADDR'] = '127.0.0.1';
  434. $_SERVER['SERVER_PORT'] = $port;
  435. $_SERVER['SERVER_SOFTWARE'] = NULL;
  436. $_SERVER['SERVER_NAME'] = 'localhost';
  437. $_SERVER['REQUEST_URI'] = $path . '/';
  438. $_SERVER['REQUEST_METHOD'] = 'GET';
  439. $_SERVER['SCRIPT_NAME'] = $path . '/index.php';
  440. $_SERVER['SCRIPT_FILENAME'] = $path . '/index.php';
  441. $_SERVER['PHP_SELF'] = $path . '/index.php';
  442. $_SERVER['HTTP_USER_AGENT'] = 'Drupal command line';
  443. if ($args['concurrency'] > 1) {
  444. $directory = FileSystem::getOsTemporaryDirectory();
  445. $test_symlink = @symlink(__FILE__, $directory . '/test_symlink');
  446. if (!$test_symlink) {
  447. throw new \RuntimeException('In order to use a concurrency higher than 1 the test system needs to be able to create symlinks in ' . $directory);
  448. }
  449. unlink($directory . '/test_symlink');
  450. putenv('RUN_TESTS_CONCURRENCY=' . $args['concurrency']);
  451. }
  452. if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
  453. // Ensure that any and all environment variables are changed to https://.
  454. foreach ($_SERVER as $key => $value) {
  455. $_SERVER[$key] = str_replace('http://', 'https://', $_SERVER[$key]);
  456. }
  457. }
  458. chdir(realpath(__DIR__ . '/../..'));
  459. // Prepare the kernel.
  460. try {
  461. $request = Request::createFromGlobals();
  462. $kernel = TestRunnerKernel::createFromRequest($request, $autoloader);
  463. $kernel->prepareLegacyRequest($request);
  464. }
  465. catch (Exception $e) {
  466. echo (string) $e;
  467. exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
  468. }
  469. }
  470. /**
  471. * Sets up database connection info for running tests.
  472. *
  473. * If this script is executed from within a real Drupal installation, then this
  474. * function essentially performs nothing (unless the --sqlite or --dburl
  475. * parameters were passed).
  476. *
  477. * Otherwise, there are three database connections of concern:
  478. * - --sqlite: The test runner connection, providing access to Simpletest
  479. * database tables for recording test IDs and assertion results.
  480. * - --dburl: A database connection that is used as base connection info for all
  481. * tests; i.e., every test will spawn from this connection. In case this
  482. * connection uses e.g. SQLite, then all tests will run against SQLite. This
  483. * is exposed as $databases['default']['default'] to Drupal.
  484. * - The actual database connection used within a test. This is the same as
  485. * --dburl, but uses an additional database table prefix. This is
  486. * $databases['default']['default'] within a test environment. The original
  487. * connection is retained in
  488. * $databases['simpletest_original_default']['default'] and restored after
  489. * each test.
  490. *
  491. * @param bool $new
  492. * Whether this process is a run-tests.sh master process. If TRUE, the SQLite
  493. * database file specified by --sqlite (if any) is set up. Otherwise, database
  494. * connections are prepared only.
  495. */
  496. function simpletest_script_setup_database($new = FALSE) {
  497. global $args;
  498. // If there is an existing Drupal installation that contains a database
  499. // connection info in settings.php, then $databases['default']['default'] will
  500. // hold the default database connection already. This connection is assumed to
  501. // be valid, and this connection will be used in tests, so that they run
  502. // against e.g. MySQL instead of SQLite.
  503. // However, in case no Drupal installation exists, this default database
  504. // connection can be set and/or overridden with the --dburl parameter.
  505. if (!empty($args['dburl'])) {
  506. // Remove a possibly existing default connection (from settings.php).
  507. Database::removeConnection('default');
  508. try {
  509. $databases['default']['default'] = Database::convertDbUrlToConnectionInfo($args['dburl'], DRUPAL_ROOT);
  510. }
  511. catch (\InvalidArgumentException $e) {
  512. simpletest_script_print_error('Invalid --dburl. Reason: ' . $e->getMessage());
  513. exit(SIMPLETEST_SCRIPT_EXIT_FAILURE);
  514. }
  515. }
  516. // Otherwise, use the default database connection from settings.php.
  517. else {
  518. $databases['default'] = Database::getConnectionInfo('default');
  519. }
  520. // If there is no default database connection for tests, we cannot continue.
  521. if (!isset($databases['default']['default'])) {
  522. simpletest_script_print_error('Missing default database connection for tests. Use --dburl to specify one.');
  523. exit(SIMPLETEST_SCRIPT_EXIT_FAILURE);
  524. }
  525. Database::addConnectionInfo('default', 'default', $databases['default']['default']);
  526. // If no --sqlite parameter has been passed, then Simpletest module is assumed
  527. // to be installed, so the test runner database connection is the default
  528. // database connection.
  529. if (empty($args['sqlite'])) {
  530. $sqlite = FALSE;
  531. $databases['test-runner']['default'] = $databases['default']['default'];
  532. }
  533. // Otherwise, set up a SQLite connection for the test runner.
  534. else {
  535. if ($args['sqlite'][0] === '/') {
  536. $sqlite = $args['sqlite'];
  537. }
  538. else {
  539. $sqlite = DRUPAL_ROOT . '/' . $args['sqlite'];
  540. }
  541. $databases['test-runner']['default'] = [
  542. 'driver' => 'sqlite',
  543. 'database' => $sqlite,
  544. 'prefix' => [
  545. 'default' => '',
  546. ],
  547. ];
  548. // Create the test runner SQLite database, unless it exists already.
  549. if ($new && !file_exists($sqlite)) {
  550. if (!is_dir(dirname($sqlite))) {
  551. mkdir(dirname($sqlite));
  552. }
  553. touch($sqlite);
  554. }
  555. }
  556. // Add the test runner database connection.
  557. Database::addConnectionInfo('test-runner', 'default', $databases['test-runner']['default']);
  558. // Create the Simpletest schema.
  559. try {
  560. $connection = Database::getConnection('default', 'test-runner');
  561. $schema = $connection->schema();
  562. }
  563. catch (\PDOException $e) {
  564. simpletest_script_print_error($databases['test-runner']['default']['driver'] . ': ' . $e->getMessage());
  565. exit(SIMPLETEST_SCRIPT_EXIT_FAILURE);
  566. }
  567. if ($new && $sqlite) {
  568. require_once DRUPAL_ROOT . '/' . drupal_get_path('module', 'simpletest') . '/simpletest.install';
  569. foreach (simpletest_schema() as $name => $table_spec) {
  570. try {
  571. $table_exists = $schema->tableExists($name);
  572. if (empty($args['keep-results-table']) && $table_exists) {
  573. $connection->truncate($name)->execute();
  574. }
  575. if (!$table_exists) {
  576. $schema->createTable($name, $table_spec);
  577. }
  578. }
  579. catch (Exception $e) {
  580. echo (string) $e;
  581. exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
  582. }
  583. }
  584. }
  585. // Verify that the Simpletest database schema exists by checking one table.
  586. try {
  587. if (!$schema->tableExists('simpletest')) {
  588. simpletest_script_print_error('Missing Simpletest database schema. Either install Simpletest module or use the --sqlite parameter.');
  589. exit(SIMPLETEST_SCRIPT_EXIT_FAILURE);
  590. }
  591. }
  592. catch (Exception $e) {
  593. echo (string) $e;
  594. exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
  595. }
  596. }
  597. /**
  598. * Execute a batch of tests.
  599. */
  600. function simpletest_script_execute_batch($test_classes) {
  601. global $args, $test_ids;
  602. $total_status = SIMPLETEST_SCRIPT_EXIT_SUCCESS;
  603. // Multi-process execution.
  604. $children = [];
  605. while (!empty($test_classes) || !empty($children)) {
  606. while (count($children) < $args['concurrency']) {
  607. if (empty($test_classes)) {
  608. break;
  609. }
  610. try {
  611. $test_id = Database::getConnection('default', 'test-runner')
  612. ->insert('simpletest_test_id')
  613. ->useDefaults(['test_id'])
  614. ->execute();
  615. }
  616. catch (Exception $e) {
  617. echo (string) $e;
  618. exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
  619. }
  620. $test_ids[] = $test_id;
  621. $test_class = array_shift($test_classes);
  622. // Fork a child process.
  623. $command = simpletest_script_command($test_id, $test_class);
  624. $process = proc_open($command, [], $pipes, NULL, NULL, ['bypass_shell' => TRUE]);
  625. if (!is_resource($process)) {
  626. echo "Unable to fork test process. Aborting.\n";
  627. exit(SIMPLETEST_SCRIPT_EXIT_SUCCESS);
  628. }
  629. // Register our new child.
  630. $children[] = [
  631. 'process' => $process,
  632. 'test_id' => $test_id,
  633. 'class' => $test_class,
  634. 'pipes' => $pipes,
  635. ];
  636. }
  637. // Wait for children every 200ms.
  638. usleep(200000);
  639. // Check if some children finished.
  640. foreach ($children as $cid => $child) {
  641. $status = proc_get_status($child['process']);
  642. if (empty($status['running'])) {
  643. // The child exited, unregister it.
  644. proc_close($child['process']);
  645. if ($status['exitcode'] === SIMPLETEST_SCRIPT_EXIT_FAILURE) {
  646. $total_status = max($status['exitcode'], $total_status);
  647. }
  648. elseif ($status['exitcode']) {
  649. $message = 'FATAL ' . $child['class'] . ': test runner returned a non-zero error code (' . $status['exitcode'] . ').';
  650. echo $message . "\n";
  651. // @todo Return SIMPLETEST_SCRIPT_EXIT_EXCEPTION instead, when
  652. // DrupalCI supports this.
  653. // @see https://www.drupal.org/node/2780087
  654. $total_status = max(SIMPLETEST_SCRIPT_EXIT_FAILURE, $total_status);
  655. // Insert a fail for xml results.
  656. TestBase::insertAssert($child['test_id'], $child['class'], FALSE, $message, 'run-tests.sh check');
  657. // Ensure that an error line is displayed for the class.
  658. simpletest_script_reporter_display_summary(
  659. $child['class'],
  660. ['#pass' => 0, '#fail' => 1, '#exception' => 0, '#debug' => 0]
  661. );
  662. if ($args['die-on-fail']) {
  663. list($db_prefix) = simpletest_last_test_get($child['test_id']);
  664. $test_db = new TestDatabase($db_prefix);
  665. $test_directory = $test_db->getTestSitePath();
  666. 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";
  667. $args['keep-results'] = TRUE;
  668. // Exit repeat loop immediately.
  669. $args['repeat'] = -1;
  670. }
  671. }
  672. // Free-up space by removing any potentially created resources.
  673. if (!$args['keep-results']) {
  674. simpletest_script_cleanup($child['test_id'], $child['class'], $status['exitcode']);
  675. }
  676. // Remove this child.
  677. unset($children[$cid]);
  678. }
  679. }
  680. }
  681. return $total_status;
  682. }
  683. /**
  684. * Run a PHPUnit-based test.
  685. */
  686. function simpletest_script_run_phpunit($test_id, $class) {
  687. $reflection = new \ReflectionClass($class);
  688. if ($reflection->hasProperty('runLimit')) {
  689. set_time_limit($reflection->getStaticPropertyValue('runLimit'));
  690. }
  691. $results = simpletest_run_phpunit_tests($test_id, [$class], $status);
  692. simpletest_process_phpunit_results($results);
  693. // Map phpunit results to a data structure we can pass to
  694. // _simpletest_format_summary_line.
  695. $summaries = simpletest_summarize_phpunit_result($results);
  696. foreach ($summaries as $class => $summary) {
  697. simpletest_script_reporter_display_summary($class, $summary);
  698. }
  699. return $status;
  700. }
  701. /**
  702. * Run a single test, bootstrapping Drupal if needed.
  703. */
  704. function simpletest_script_run_one_test($test_id, $test_class) {
  705. global $args;
  706. try {
  707. if (strpos($test_class, '::') > 0) {
  708. list($class_name, $method) = explode('::', $test_class, 2);
  709. $methods = [$method];
  710. }
  711. else {
  712. $class_name = $test_class;
  713. // Use empty array to run all the test methods.
  714. $methods = [];
  715. }
  716. $test = new $class_name($test_id);
  717. if ($args['suppress-deprecations']) {
  718. putenv('SYMFONY_DEPRECATIONS_HELPER=disabled');
  719. }
  720. else {
  721. // Prevent deprecations caused by vendor code calling deprecated code.
  722. // This also prevents mock objects in PHPUnit 6 triggering silenced
  723. // deprecations from breaking the test suite. We should consider changing
  724. // this to 'strict' once PHPUnit 4 is no longer used.
  725. putenv('SYMFONY_DEPRECATIONS_HELPER=weak_vendors');
  726. }
  727. if (is_subclass_of($test_class, TestCase::class)) {
  728. $status = simpletest_script_run_phpunit($test_id, $test_class);
  729. }
  730. else {
  731. $test->dieOnFail = (bool) $args['die-on-fail'];
  732. $test->verbose = (bool) $args['verbose'];
  733. $test->run($methods);
  734. simpletest_script_reporter_display_summary($test_class, $test->results);
  735. $status = SIMPLETEST_SCRIPT_EXIT_SUCCESS;
  736. // Finished, kill this runner.
  737. if ($test->results['#fail'] || $test->results['#exception']) {
  738. $status = SIMPLETEST_SCRIPT_EXIT_FAILURE;
  739. }
  740. }
  741. exit($status);
  742. }
  743. // DrupalTestCase::run() catches exceptions already, so this is only reached
  744. // when an exception is thrown in the wrapping test runner environment.
  745. catch (Exception $e) {
  746. echo (string) $e;
  747. exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
  748. }
  749. }
  750. /**
  751. * Return a command used to run a test in a separate process.
  752. *
  753. * @param int $test_id
  754. * The current test ID.
  755. * @param string $test_class
  756. * The name of the test class to run.
  757. *
  758. * @return string
  759. * The assembled command string.
  760. */
  761. function simpletest_script_command($test_id, $test_class) {
  762. global $args, $php;
  763. $command = escapeshellarg($php) . ' ' . escapeshellarg('./core/scripts/' . $args['script']);
  764. $command .= ' --url ' . escapeshellarg($args['url']);
  765. if (!empty($args['sqlite'])) {
  766. $command .= ' --sqlite ' . escapeshellarg($args['sqlite']);
  767. }
  768. if (!empty($args['dburl'])) {
  769. $command .= ' --dburl ' . escapeshellarg($args['dburl']);
  770. }
  771. $command .= ' --php ' . escapeshellarg($php);
  772. $command .= " --test-id $test_id";
  773. foreach (['verbose', 'keep-results', 'color', 'die-on-fail', 'suppress-deprecations'] as $arg) {
  774. if ($args[$arg]) {
  775. $command .= ' --' . $arg;
  776. }
  777. }
  778. // --execute-test and class name needs to come last.
  779. $command .= ' --execute-test ' . escapeshellarg($test_class);
  780. return $command;
  781. }
  782. /**
  783. * Removes all remnants of a test runner.
  784. *
  785. * In case a (e.g., fatal) error occurs after the test site has been fully setup
  786. * and the error happens in many tests, the environment that executes the tests
  787. * can easily run out of memory or disk space. This function ensures that all
  788. * created resources are properly cleaned up after every executed test.
  789. *
  790. * This clean-up only exists in this script, since SimpleTest module itself does
  791. * not use isolated sub-processes for each test being run, so a fatal error
  792. * halts not only the test, but also the test runner (i.e., the parent site).
  793. *
  794. * @param int $test_id
  795. * The test ID of the test run.
  796. * @param string $test_class
  797. * The class name of the test run.
  798. * @param int $exitcode
  799. * The exit code of the test runner.
  800. *
  801. * @see simpletest_script_run_one_test()
  802. */
  803. function simpletest_script_cleanup($test_id, $test_class, $exitcode) {
  804. if (is_subclass_of($test_class, TestCase::class)) {
  805. // PHPUnit test, move on.
  806. return;
  807. }
  808. // Retrieve the last database prefix used for testing.
  809. try {
  810. list($db_prefix) = simpletest_last_test_get($test_id);
  811. }
  812. catch (Exception $e) {
  813. echo (string) $e;
  814. exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
  815. }
  816. // If no database prefix was found, then the test was not set up correctly.
  817. if (empty($db_prefix)) {
  818. echo "\nFATAL $test_class: Found no database prefix for test ID $test_id. (Check whether setUp() is invoked correctly.)";
  819. return;
  820. }
  821. // Do not output verbose cleanup messages in case of a positive exitcode.
  822. $output = !empty($exitcode);
  823. $messages = [];
  824. $messages[] = "- Found database prefix '$db_prefix' for test ID $test_id.";
  825. // Read the log file in case any fatal errors caused the test to crash.
  826. try {
  827. simpletest_log_read($test_id, $db_prefix, $test_class);
  828. }
  829. catch (Exception $e) {
  830. echo (string) $e;
  831. exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
  832. }
  833. // Check whether a test site directory was setup already.
  834. // @see \Drupal\simpletest\TestBase::prepareEnvironment()
  835. $test_db = new TestDatabase($db_prefix);
  836. $test_directory = DRUPAL_ROOT . '/' . $test_db->getTestSitePath();
  837. if (is_dir($test_directory)) {
  838. // Output the error_log.
  839. if (is_file($test_directory . '/error.log')) {
  840. if ($errors = file_get_contents($test_directory . '/error.log')) {
  841. $output = TRUE;
  842. $messages[] = $errors;
  843. }
  844. }
  845. // Delete the test site directory.
  846. // simpletest_clean_temporary_directories() cannot be used here, since it
  847. // would also delete file directories of other tests that are potentially
  848. // running concurrently.
  849. file_unmanaged_delete_recursive($test_directory, ['Drupal\simpletest\TestBase', 'filePreDeleteCallback']);
  850. $messages[] = "- Removed test site directory.";
  851. }
  852. // Clear out all database tables from the test.
  853. try {
  854. $schema = Database::getConnection('default', 'default')->schema();
  855. $count = 0;
  856. foreach ($schema->findTables($db_prefix . '%') as $table) {
  857. $schema->dropTable($table);
  858. $count++;
  859. }
  860. }
  861. catch (Exception $e) {
  862. echo (string) $e;
  863. exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
  864. }
  865. if ($count) {
  866. $messages[] = "- Removed $count leftover tables.";
  867. }
  868. if ($output) {
  869. echo implode("\n", $messages);
  870. echo "\n";
  871. }
  872. }
  873. /**
  874. * Get list of tests based on arguments.
  875. *
  876. * If --all specified then return all available tests, otherwise reads list of
  877. * tests.
  878. *
  879. * @return array
  880. * List of tests.
  881. */
  882. function simpletest_script_get_test_list() {
  883. global $args;
  884. $types_processed = empty($args['types']);
  885. $test_list = [];
  886. if ($args['all'] || $args['module']) {
  887. try {
  888. $groups = simpletest_test_get_all($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 = simpletest_test_get_all(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 = simpletest_test_get_all(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. }