run-tests.sh 25 KB

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