run-tests.sh

This script runs Drupal tests from command line.

File

drupal/core/scripts/run-tests.sh
View source
  1. /**
  2. * @file
  3. * This script runs Drupal tests from command line.
  4. */
  5. const SIMPLETEST_SCRIPT_COLOR_PASS = 32; // Green.
  6. const SIMPLETEST_SCRIPT_COLOR_FAIL = 31; // Red.
  7. const SIMPLETEST_SCRIPT_COLOR_EXCEPTION = 33; // Brown.
  8. // Set defaults and get overrides.
  9. list($args, $count) = simpletest_script_parse_args();
  10. if ($args['help'] || $count == 0) {
  11. simpletest_script_help();
  12. exit;
  13. }
  14. if ($args['execute-test']) {
  15. // Masquerade as Apache for running tests.
  16. simpletest_script_init("Apache");
  17. simpletest_script_run_one_test($args['test-id'], $args['execute-test']);
  18. // Sub-process script execution ends here.
  19. }
  20. else {
  21. // Run administrative functions as CLI.
  22. simpletest_script_init(NULL);
  23. }
  24. // Bootstrap to perform initial validation or other operations.
  25. drupal_bootstrap(DRUPAL_BOOTSTRAP_CODE);
  26. if (!module_exists('simpletest')) {
  27. simpletest_script_print_error("The simpletest module must be enabled before this script can run.");
  28. exit;
  29. }
  30. if ($args['clean']) {
  31. // Clean up left-over times and directories.
  32. simpletest_clean_environment();
  33. echo "\nEnvironment cleaned.\n";
  34. // Get the status messages and print them.
  35. $messages = array_pop(drupal_get_messages('status'));
  36. foreach ($messages as $text) {
  37. echo " - " . $text . "\n";
  38. }
  39. exit;
  40. }
  41. if ($args['list']) {
  42. // Display all available tests.
  43. echo "\nAvailable test groups & classes\n";
  44. echo "-------------------------------\n\n";
  45. $groups = simpletest_test_get_all();
  46. foreach ($groups as $group => $tests) {
  47. echo $group . "\n";
  48. foreach ($tests as $class => $info) {
  49. echo " - " . $info['name'] . ' (' . $class . ')' . "\n";
  50. }
  51. }
  52. exit;
  53. }
  54. $test_list = simpletest_script_get_test_list();
  55. // Try to allocate unlimited time to run the tests.
  56. drupal_set_time_limit(0);
  57. simpletest_script_reporter_init();
  58. // Execute tests.
  59. simpletest_script_execute_batch(simpletest_script_get_test_list());
  60. // Stop the timer.
  61. simpletest_script_reporter_timer_stop();
  62. // Display results before database is cleared.
  63. simpletest_script_reporter_display_results();
  64. if ($args['xml']) {
  65. simpletest_script_reporter_write_xml_results();
  66. }
  67. // Clean up all test results.
  68. if (!$args['keep-results']) {
  69. simpletest_clean_results_table();
  70. }
  71. // Test complete, exit.
  72. exit;
  73. /**
  74. * Print help text.
  75. */
  76. function simpletest_script_help() {
  77. global $args;
  78. echo <<
  79. Run Drupal tests from the shell.
  80. Usage: {$args['script']} [OPTIONS]
  81. Example: {$args['script']} Profile
  82. All arguments are long options.
  83. --help Print this page.
  84. --list Display all available test groups.
  85. --clean Cleans up database tables or directories from previous, failed,
  86. tests and then exits (no tests are run).
  87. --url Immediately precedes a URL to set the host and path. You will
  88. need this parameter if Drupal is in a subdirectory on your
  89. localhost and you have not set \$base_url in settings.php. Tests
  90. can be run under SSL by including https:// in the URL.
  91. --php The absolute path to the PHP executable. Usually not needed.
  92. --concurrency [num]
  93. Run tests in parallel, up to [num] tests at a time.
  94. --all Run all available tests.
  95. --module Run all tests belonging to the specified module name.
  96. (e.g., 'node')
  97. --class Run tests identified by specific class names, instead of group names.
  98. --file Run tests identified by specific file names, instead of group names.
  99. Specify the path and the extension
  100. (i.e. 'core/modules/user/user.test').
  101. --xml
  102. If provided, test results will be written as xml files to this path.
  103. --color Output text format results with color highlighting.
  104. --verbose Output detailed assertion messages in addition to summary.
  105. --keep-results
  106. Keeps detailed assertion results (in the database) after tests
  107. have completed. By default, assertion results are cleared.
  108. [,[, ...]]
  109. One or more tests to be run. By default, these are interpreted
  110. as the names of test groups as shown at
  111. admin/config/development/testing.
  112. These group names typically correspond to module names like "User"
  113. or "Profile" or "System", but there is also a group "XML-RPC".
  114. If --class is specified then these are interpreted as the names of
  115. specific test classes whose test methods will be run. Tests must
  116. be separated by commas. Ignored if --all is specified.
  117. To run this script you will normally invoke it from the root directory of your
  118. Drupal installation as the webserver user (differs per configuration), or root:
  119. sudo -u [wwwrun|www-data|etc] php ./core/scripts/{$args['script']}
  120. --url http://example.com/ --all
  121. sudo -u [wwwrun|www-data|etc] php ./core/scripts/{$args['script']}
  122. --url http://example.com/ --class "Drupal\block\Tests\BlockTest"
  123. \n
  124. EOF;
  125. }
  126. /**
  127. * Parse execution argument and ensure that all are valid.
  128. *
  129. * @return The list of arguments.
  130. */
  131. function simpletest_script_parse_args() {
  132. // Set default values.
  133. $args = array(
  134. 'script' => '',
  135. 'help' => FALSE,
  136. 'list' => FALSE,
  137. 'clean' => FALSE,
  138. 'url' => '',
  139. 'php' => '',
  140. 'concurrency' => 1,
  141. 'all' => FALSE,
  142. 'module' => FALSE,
  143. 'class' => FALSE,
  144. 'file' => FALSE,
  145. 'color' => FALSE,
  146. 'verbose' => FALSE,
  147. 'keep-results' => FALSE,
  148. 'test_names' => array(),
  149. // Used internally.
  150. 'test-id' => 0,
  151. 'execute-test' => '',
  152. 'xml' => '',
  153. );
  154. // Override with set values.
  155. $args['script'] = basename(array_shift($_SERVER['argv']));
  156. $count = 0;
  157. while ($arg = array_shift($_SERVER['argv'])) {
  158. if (preg_match('/--(\S+)/', $arg, $matches)) {
  159. // Argument found.
  160. if (array_key_exists($matches[1], $args)) {
  161. // Argument found in list.
  162. $previous_arg = $matches[1];
  163. if (is_bool($args[$previous_arg])) {
  164. $args[$matches[1]] = TRUE;
  165. }
  166. else {
  167. $args[$matches[1]] = array_shift($_SERVER['argv']);
  168. }
  169. // Clear extraneous values.
  170. $args['test_names'] = array();
  171. $count++;
  172. }
  173. else {
  174. // Argument not found in list.
  175. simpletest_script_print_error("Unknown argument '$arg'.");
  176. exit;
  177. }
  178. }
  179. else {
  180. // Values found without an argument should be test names.
  181. $args['test_names'] += explode(',', $arg);
  182. $count++;
  183. }
  184. }
  185. // Validate the concurrency argument
  186. if (!is_numeric($args['concurrency']) || $args['concurrency'] <= 0) {
  187. simpletest_script_print_error("--concurrency must be a strictly positive integer.");
  188. exit;
  189. }
  190. return array($args, $count);
  191. }
  192. /**
  193. * Initialize script variables and perform general setup requirements.
  194. */
  195. function simpletest_script_init($server_software) {
  196. global $args, $php;
  197. $host = 'localhost';
  198. $path = '';
  199. // Determine location of php command automatically, unless a command line argument is supplied.
  200. if (!empty($args['php'])) {
  201. $php = $args['php'];
  202. }
  203. elseif ($php_env = getenv('_')) {
  204. // '_' is an environment variable set by the shell. It contains the command that was executed.
  205. $php = $php_env;
  206. }
  207. elseif ($sudo = getenv('SUDO_COMMAND')) {
  208. // 'SUDO_COMMAND' is an environment variable set by the sudo program.
  209. // Extract only the PHP interpreter, not the rest of the command.
  210. list($php, ) = explode(' ', $sudo, 2);
  211. }
  212. else {
  213. simpletest_script_print_error('Unable to automatically determine the path to the PHP interpreter. Supply the --php command line argument.');
  214. simpletest_script_help();
  215. exit();
  216. }
  217. // Get URL from arguments.
  218. if (!empty($args['url'])) {
  219. $parsed_url = parse_url($args['url']);
  220. $host = $parsed_url['host'] . (isset($parsed_url['port']) ? ':' . $parsed_url['port'] : '');
  221. $path = isset($parsed_url['path']) ? $parsed_url['path'] : '';
  222. // If the passed URL schema is 'https' then setup the $_SERVER variables
  223. // properly so that testing will run under HTTPS.
  224. if ($parsed_url['scheme'] == 'https') {
  225. $_SERVER['HTTPS'] = 'on';
  226. }
  227. }
  228. $_SERVER['HTTP_HOST'] = $host;
  229. $_SERVER['REMOTE_ADDR'] = '127.0.0.1';
  230. $_SERVER['SERVER_ADDR'] = '127.0.0.1';
  231. $_SERVER['SERVER_SOFTWARE'] = $server_software;
  232. $_SERVER['SERVER_NAME'] = 'localhost';
  233. $_SERVER['REQUEST_URI'] = $path .'/';
  234. $_SERVER['REQUEST_METHOD'] = 'GET';
  235. $_SERVER['SCRIPT_NAME'] = $path .'/index.php';
  236. $_SERVER['PHP_SELF'] = $path .'/index.php';
  237. $_SERVER['HTTP_USER_AGENT'] = 'Drupal command line';
  238. if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
  239. // Ensure that any and all environment variables are changed to https://.
  240. foreach ($_SERVER as $key => $value) {
  241. $_SERVER[$key] = str_replace('http://', 'https://', $_SERVER[$key]);
  242. }
  243. }
  244. chdir(realpath(__DIR__ . '/../..'));
  245. define('DRUPAL_ROOT', getcwd());
  246. require_once DRUPAL_ROOT . '/core/includes/bootstrap.inc';
  247. }
  248. /**
  249. * Execute a batch of tests.
  250. */
  251. function simpletest_script_execute_batch($test_classes) {
  252. global $args, $test_ids;
  253. // Multi-process execution.
  254. $children = array();
  255. while (!empty($test_classes) || !empty($children)) {
  256. while (count($children) < $args['concurrency']) {
  257. if (empty($test_classes)) {
  258. break;
  259. }
  260. // Fork a child process.
  261. $test_id = db_insert('simpletest_test_id')->useDefaults(array('test_id'))->execute();
  262. $test_ids[] = $test_id;
  263. $test_class = array_shift($test_classes);
  264. $command = simpletest_script_command($test_id, $test_class);
  265. $process = proc_open($command, array(), $pipes, NULL, NULL, array('bypass_shell' => TRUE));
  266. if (!is_resource($process)) {
  267. echo "Unable to fork test process. Aborting.\n";
  268. exit;
  269. }
  270. // Register our new child.
  271. $children[] = array(
  272. 'process' => $process,
  273. 'test_id' => $test_id,
  274. 'class' => $test_class,
  275. 'pipes' => $pipes,
  276. );
  277. }
  278. // Wait for children every 200ms.
  279. usleep(200000);
  280. // Check if some children finished.
  281. foreach ($children as $cid => $child) {
  282. $status = proc_get_status($child['process']);
  283. if (empty($status['running'])) {
  284. // The child exited, unregister it.
  285. proc_close($child['process']);
  286. if ($status['exitcode']) {
  287. echo 'FATAL ' . $child['class'] . ': test runner returned a non-zero error code (' . $status['exitcode'] . ').' . "\n";
  288. }
  289. // Free-up space by removing any potentially created resources.
  290. if (!$args['keep-results']) {
  291. simpletest_script_cleanup($child['test_id'], $child['class'], $status['exitcode']);
  292. }
  293. // Remove this child.
  294. unset($children[$cid]);
  295. }
  296. }
  297. }
  298. }
  299. /**
  300. * Bootstrap Drupal and run a single test.
  301. */
  302. function simpletest_script_run_one_test($test_id, $test_class) {
  303. global $args, $conf;
  304. try {
  305. // Bootstrap Drupal.
  306. drupal_bootstrap(DRUPAL_BOOTSTRAP_CODE);
  307. simpletest_classloader_register();
  308. // Override configuration according to command line parameters.
  309. $conf['simpletest.settings']['verbose'] = $args['verbose'];
  310. $conf['simpletest.settings']['clear_results'] = !$args['keep-results'];
  311. $test = new $test_class($test_id);
  312. $test->run();
  313. $info = $test->getInfo();
  314. $had_fails = (isset($test->results['#fail']) && $test->results['#fail'] > 0);
  315. $had_exceptions = (isset($test->results['#exception']) && $test->results['#exception'] > 0);
  316. $status = ($had_fails || $had_exceptions ? 'fail' : 'pass');
  317. simpletest_script_print($info['name'] . ' ' . _simpletest_format_summary_line($test->results) . "\n", simpletest_script_color_code($status));
  318. // Finished, kill this runner.
  319. exit(0);
  320. }
  321. // DrupalTestCase::run() catches exceptions already, so this is only reached
  322. // when an exception is thrown in the wrapping test runner environment.
  323. catch (Exception $e) {
  324. echo (string) $e;
  325. exit(1);
  326. }
  327. }
  328. /**
  329. * Return a command used to run a test in a separate process.
  330. *
  331. * @param $test_id
  332. * The current test ID.
  333. * @param $test_class
  334. * The name of the test class to run.
  335. */
  336. function simpletest_script_command($test_id, $test_class) {
  337. global $args, $php;
  338. $command = escapeshellarg($php) . ' ' . escapeshellarg('./core/scripts/' . $args['script']);
  339. $command .= ' --url ' . escapeshellarg($args['url']);
  340. $command .= ' --php ' . escapeshellarg($php);
  341. $command .= " --test-id $test_id";
  342. foreach (array('verbose', 'keep-results', 'color') as $arg) {
  343. if ($args[$arg]) {
  344. $command .= ' --' . $arg;
  345. }
  346. }
  347. // --execute-test and class name needs to come last.
  348. $command .= ' --execute-test ' . escapeshellarg($test_class);
  349. return $command;
  350. }
  351. /**
  352. * Removes all remnants of a test runner.
  353. *
  354. * In case a (e.g., fatal) error occurs after the test site has been fully setup
  355. * and the error happens in many tests, the environment that executes the tests
  356. * can easily run out of memory or disk space. This function ensures that all
  357. * created resources are properly cleaned up after every executed test.
  358. *
  359. * This clean-up only exists in this script, since SimpleTest module itself does
  360. * not use isolated sub-processes for each test being run, so a fatal error
  361. * halts not only the test, but also the test runner (i.e., the parent site).
  362. *
  363. * @param int $test_id
  364. * The test ID of the test run.
  365. * @param string $test_class
  366. * The class name of the test run.
  367. * @param int $exitcode
  368. * The exit code of the test runner.
  369. *
  370. * @see simpletest_script_run_one_test()
  371. */
  372. function simpletest_script_cleanup($test_id, $test_class, $exitcode) {
  373. // Retrieve the last database prefix used for testing.
  374. list($db_prefix, ) = simpletest_last_test_get($test_id);
  375. // If no database prefix was found, then the test was not set up correctly.
  376. if (empty($db_prefix)) {
  377. echo "\nFATAL $test_class: Found no database prefix for test ID $test_id. (Check whether setUp() is invoked correctly.)";
  378. return;
  379. }
  380. // Do not output verbose cleanup messages in case of a positive exitcode.
  381. $output = !empty($exitcode);
  382. $messages = array();
  383. $messages[] = "- Found database prefix '$db_prefix' for test ID $test_id.";
  384. // Read the log file in case any fatal errors caused the test to crash.
  385. simpletest_log_read($test_id, $db_prefix, $test_class);
  386. // Check whether a test file directory was setup already.
  387. // @see prepareEnvironment()
  388. $public_files = variable_get('file_public_path', conf_path() . '/files');
  389. $test_directory = $public_files . '/simpletest/' . substr($db_prefix, 10);
  390. if (is_dir($test_directory)) {
  391. // Output the error_log.
  392. if (is_file($test_directory . '/error.log')) {
  393. if ($errors = file_get_contents($test_directory . '/error.log')) {
  394. $output = TRUE;
  395. $messages[] = $errors;
  396. }
  397. }
  398. // Delete the test files directory.
  399. // simpletest_clean_temporary_directories() cannot be used here, since it
  400. // would also delete file directories of other tests that are potentially
  401. // running concurrently.
  402. file_unmanaged_delete_recursive($test_directory, array('Drupal\simpletest\TestBase', 'filePreDeleteCallback'));
  403. $messages[] = "- Removed test files directory.";
  404. }
  405. // Clear out all database tables from the test.
  406. $count = 0;
  407. foreach (db_find_tables($db_prefix . '%') as $table) {
  408. db_drop_table($table);
  409. $count++;
  410. }
  411. if ($count) {
  412. $messages[] = "- " . format_plural($count, 'Removed 1 leftover table.', 'Removed @count leftover tables.');
  413. }
  414. if ($output) {
  415. echo implode("\n", $messages);
  416. echo "\n";
  417. }
  418. }
  419. /**
  420. * Get list of tests based on arguments. If --all specified then
  421. * returns all available tests, otherwise reads list of tests.
  422. *
  423. * Will print error and exit if no valid tests were found.
  424. *
  425. * @return List of tests.
  426. */
  427. function simpletest_script_get_test_list() {
  428. global $args;
  429. $test_list = array();
  430. if ($args['all']) {
  431. $groups = simpletest_test_get_all();
  432. $all_tests = array();
  433. foreach ($groups as $group => $tests) {
  434. $all_tests = array_merge($all_tests, array_keys($tests));
  435. }
  436. $test_list = $all_tests;
  437. }
  438. else {
  439. if ($args['class']) {
  440. foreach ($args['test_names'] as $class_name) {
  441. $test_list[] = $class_name;
  442. }
  443. }
  444. elseif ($args['module']) {
  445. $modules = drupal_system_listing('/^' . DRUPAL_PHP_FUNCTION_PATTERN . '\.module$/', 'modules', 'name', 0);
  446. foreach ($args['test_names'] as $module) {
  447. // PSR-0 only.
  448. $dir = dirname($modules[$module]->uri) . "/lib/Drupal/$module/Tests";
  449. $files = file_scan_directory($dir, '@\.php$@', array(
  450. 'key' => 'name',
  451. 'recurse' => TRUE,
  452. ));
  453. $test_list = array_merge($test_list, array_keys($files));
  454. }
  455. }
  456. elseif ($args['file']) {
  457. // Extract test case class names from specified files.
  458. foreach ($args['test_names'] as $file) {
  459. if (!file_exists($file)) {
  460. simpletest_script_print_error('File not found: ' . $file);
  461. exit;
  462. }
  463. $content = file_get_contents($file);
  464. // Extract a potential namespace.
  465. $namespace = FALSE;
  466. if (preg_match('@^namespace ([^ ;]+)@m', $content, $matches)) {
  467. $namespace = $matches[1];
  468. }
  469. // Extract all class names.
  470. // Abstract classes are excluded on purpose.
  471. preg_match_all('@^class ([^ ]+)@m', $content, $matches);
  472. if (!$namespace) {
  473. $test_list = array_merge($test_list, $matches[1]);
  474. }
  475. else {
  476. foreach ($matches[1] as $class_name) {
  477. $test_list[] = $namespace . '\\' . $class_name;
  478. }
  479. }
  480. }
  481. }
  482. else {
  483. $groups = simpletest_test_get_all();
  484. foreach ($args['test_names'] as $group_name) {
  485. $test_list = array_merge($test_list, array_keys($groups[$group_name]));
  486. }
  487. }
  488. }
  489. if (empty($test_list)) {
  490. simpletest_script_print_error('No valid tests were specified.');
  491. exit;
  492. }
  493. return $test_list;
  494. }
  495. /**
  496. * Initialize the reporter.
  497. */
  498. function simpletest_script_reporter_init() {
  499. global $args, $test_list, $results_map;
  500. $results_map = array(
  501. 'pass' => 'Pass',
  502. 'fail' => 'Fail',
  503. 'exception' => 'Exception'
  504. );
  505. echo "\n";
  506. echo "Drupal test run\n";
  507. echo "---------------\n";
  508. echo "\n";
  509. // Tell the user about what tests are to be run.
  510. if ($args['all']) {
  511. echo "All tests will run.\n\n";
  512. }
  513. else {
  514. echo "Tests to be run:\n";
  515. foreach ($test_list as $class_name) {
  516. $info = call_user_func(array($class_name, 'getInfo'));
  517. echo " - " . $info['name'] . ' (' . $class_name . ')' . "\n";
  518. }
  519. echo "\n";
  520. }
  521. echo "Test run started:\n";
  522. echo " " . format_date($_SERVER['REQUEST_TIME'], 'long') . "\n";
  523. timer_start('run-tests');
  524. echo "\n";
  525. echo "Test summary\n";
  526. echo "------------\n";
  527. echo "\n";
  528. }
  529. /**
  530. * Display jUnit XML test results.
  531. */
  532. function simpletest_script_reporter_write_xml_results() {
  533. global $args, $test_ids, $results_map;
  534. $results = db_query("SELECT * FROM {simpletest} WHERE test_id IN (:test_ids) ORDER BY test_class, message_id", array(':test_ids' => $test_ids));
  535. $test_class = '';
  536. $xml_files = array();
  537. foreach ($results as $result) {
  538. if (isset($results_map[$result->status])) {
  539. if ($result->test_class != $test_class) {
  540. // We've moved onto a new class, so write the last classes results to a file:
  541. if (isset($xml_files[$test_class])) {
  542. file_put_contents($args['xml'] . '/' . $test_class . '.xml', $xml_files[$test_class]['doc']->saveXML());
  543. unset($xml_files[$test_class]);
  544. }
  545. $test_class = $result->test_class;
  546. if (!isset($xml_files[$test_class])) {
  547. $doc = new DomDocument('1.0');
  548. $root = $doc->createElement('testsuite');
  549. $root = $doc->appendChild($root);
  550. $xml_files[$test_class] = array('doc' => $doc, 'suite' => $root);
  551. }
  552. }
  553. // For convenience:
  554. $dom_document = &$xml_files[$test_class]['doc'];
  555. // Create the XML element for this test case:
  556. $case = $dom_document->createElement('testcase');
  557. $case->setAttribute('classname', $test_class);
  558. list($class, $name) = explode('->', $result->function, 2);
  559. $case->setAttribute('name', $name);
  560. // Passes get no further attention, but failures and exceptions get to add more detail:
  561. if ($result->status == 'fail') {
  562. $fail = $dom_document->createElement('failure');
  563. $fail->setAttribute('type', 'failure');
  564. $fail->setAttribute('message', $result->message_group);
  565. $text = $dom_document->createTextNode($result->message);
  566. $fail->appendChild($text);
  567. $case->appendChild($fail);
  568. }
  569. elseif ($result->status == 'exception') {
  570. // In the case of an exception the $result->function may not be a class
  571. // method so we record the full function name:
  572. $case->setAttribute('name', $result->function);
  573. $fail = $dom_document->createElement('error');
  574. $fail->setAttribute('type', 'exception');
  575. $fail->setAttribute('message', $result->message_group);
  576. $full_message = $result->message . "\n\nline: " . $result->line . "\nfile: " . $result->file;
  577. $text = $dom_document->createTextNode($full_message);
  578. $fail->appendChild($text);
  579. $case->appendChild($fail);
  580. }
  581. // Append the test case XML to the test suite:
  582. $xml_files[$test_class]['suite']->appendChild($case);
  583. }
  584. }
  585. // The last test case hasn't been saved to a file yet, so do that now:
  586. if (isset($xml_files[$test_class])) {
  587. file_put_contents($args['xml'] . '/' . $test_class . '.xml', $xml_files[$test_class]['doc']->saveXML());
  588. unset($xml_files[$test_class]);
  589. }
  590. }
  591. /**
  592. * Stop the test timer.
  593. */
  594. function simpletest_script_reporter_timer_stop() {
  595. echo "\n";
  596. $end = timer_stop('run-tests');
  597. echo "Test run duration: " . format_interval($end['time'] / 1000);
  598. echo "\n\n";
  599. }
  600. /**
  601. * Display test results.
  602. */
  603. function simpletest_script_reporter_display_results() {
  604. global $args, $test_ids, $results_map;
  605. if ($args['verbose']) {
  606. // Report results.
  607. echo "Detailed test results\n";
  608. echo "---------------------\n";
  609. $results = db_query("SELECT * FROM {simpletest} WHERE test_id IN (:test_ids) ORDER BY test_class, message_id", array(':test_ids' => $test_ids));
  610. $test_class = '';
  611. foreach ($results as $result) {
  612. if (isset($results_map[$result->status])) {
  613. if ($result->test_class != $test_class) {
  614. // Display test class every time results are for new test class.
  615. echo "\n\n---- $result->test_class ----\n\n\n";
  616. $test_class = $result->test_class;
  617. // Print table header.
  618. echo "Status Group Filename Line Function \n";
  619. echo "--------------------------------------------------------------------------------\n";
  620. }
  621. simpletest_script_format_result($result);
  622. }
  623. }
  624. }
  625. }
  626. /**
  627. * Format the result so that it fits within the default 80 character
  628. * terminal size.
  629. *
  630. * @param $result The result object to format.
  631. */
  632. function simpletest_script_format_result($result) {
  633. global $results_map, $color;
  634. $summary = sprintf("%-9.9s %-10.10s %-17.17s %4.4s %-35.35s\n",
  635. $results_map[$result->status], $result->message_group, basename($result->file), $result->line, $result->function);
  636. simpletest_script_print($summary, simpletest_script_color_code($result->status));
  637. $lines = explode("\n", wordwrap(trim(strip_tags($result->message)), 76));
  638. foreach ($lines as $line) {
  639. echo " $line\n";
  640. }
  641. }
  642. /**
  643. * Print error message prefixed with " ERROR: " and displayed in fail color
  644. * if color output is enabled.
  645. *
  646. * @param $message The message to print.
  647. */
  648. function simpletest_script_print_error($message) {
  649. simpletest_script_print(" ERROR: $message\n", SIMPLETEST_SCRIPT_COLOR_FAIL);
  650. }
  651. /**
  652. * Print a message to the console, if color is enabled then the specified
  653. * color code will be used.
  654. *
  655. * @param $message The message to print.
  656. * @param $color_code The color code to use for coloring.
  657. */
  658. function simpletest_script_print($message, $color_code) {
  659. global $args;
  660. if ($args['color']) {
  661. echo "\033[" . $color_code . "m" . $message . "\033[0m";
  662. }
  663. else {
  664. echo $message;
  665. }
  666. }
  667. /**
  668. * Get the color code associated with the specified status.
  669. *
  670. * @param $status The status string to get code for.
  671. * @return Color code.
  672. */
  673. function simpletest_script_color_code($status) {
  674. switch ($status) {
  675. case 'pass':
  676. return SIMPLETEST_SCRIPT_COLOR_PASS;
  677. case 'fail':
  678. return SIMPLETEST_SCRIPT_COLOR_FAIL;
  679. case 'exception':
  680. return SIMPLETEST_SCRIPT_COLOR_EXCEPTION;
  681. }
  682. return 0; // Default formatting.
  683. }