You are here

run-tests.sh in Drupal 7

This script runs Drupal tests from command line.

File

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