You are here

run-tests.sh in Zircon Profile 8.0

This script runs Drupal tests from command line.

File

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