run-tests.sh 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674
  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. // Set defaults and get overrides.
  10. list($args, $count) = simpletest_script_parse_args();
  11. if ($args['help'] || $count == 0) {
  12. simpletest_script_help();
  13. exit;
  14. }
  15. if ($args['execute-test']) {
  16. // Masquerade as Apache for running tests.
  17. simpletest_script_init("Apache");
  18. simpletest_script_run_one_test($args['test-id'], $args['execute-test']);
  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_FULL);
  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. // Load SimpleTest files.
  42. $groups = simpletest_test_get_all();
  43. $all_tests = array();
  44. foreach ($groups as $group => $tests) {
  45. $all_tests = array_merge($all_tests, array_keys($tests));
  46. }
  47. $test_list = array();
  48. if ($args['list']) {
  49. // Display all available tests.
  50. echo "\nAvailable test groups & classes\n";
  51. echo "-------------------------------\n\n";
  52. foreach ($groups as $group => $tests) {
  53. echo $group . "\n";
  54. foreach ($tests as $class => $info) {
  55. echo " - " . $info['name'] . ' (' . $class . ')' . "\n";
  56. }
  57. }
  58. exit;
  59. }
  60. $test_list = simpletest_script_get_test_list();
  61. // Try to allocate unlimited time to run the tests.
  62. drupal_set_time_limit(0);
  63. simpletest_script_reporter_init();
  64. // Setup database for test results.
  65. $test_id = db_insert('simpletest_test_id')->useDefaults(array('test_id'))->execute();
  66. // Execute tests.
  67. simpletest_script_execute_batch($test_id, simpletest_script_get_test_list());
  68. // Retrieve the last database prefix used for testing and the last test class
  69. // that was run from. Use the information to read the lgo file in case any
  70. // fatal errors caused the test to crash.
  71. list($last_prefix, $last_test_class) = simpletest_last_test_get($test_id);
  72. simpletest_log_read($test_id, $last_prefix, $last_test_class);
  73. // Stop the timer.
  74. simpletest_script_reporter_timer_stop();
  75. // Display results before database is cleared.
  76. simpletest_script_reporter_display_results();
  77. if ($args['xml']) {
  78. simpletest_script_reporter_write_xml_results();
  79. }
  80. // Cleanup our test results.
  81. simpletest_clean_results_table($test_id);
  82. // Test complete, exit.
  83. exit;
  84. /**
  85. * Print help text.
  86. */
  87. function simpletest_script_help() {
  88. global $args;
  89. echo <<<EOF
  90. Run Drupal tests from the shell.
  91. Usage: {$args['script']} [OPTIONS] <tests>
  92. Example: {$args['script']} Profile
  93. All arguments are long options.
  94. --help Print this page.
  95. --list Display all available test groups.
  96. --clean Cleans up database tables or directories from previous, failed,
  97. tests and then exits (no tests are run).
  98. --url Immediately precedes a URL to set the host and path. You will
  99. need this parameter if Drupal is in a subdirectory on your
  100. localhost and you have not set \$base_url in settings.php. Tests
  101. can be run under SSL by including https:// in the URL.
  102. --php The absolute path to the PHP executable. Usually not needed.
  103. --concurrency [num]
  104. Run tests in parallel, up to [num] tests at a time.
  105. --all Run all available tests.
  106. --class Run tests identified by specific class names, instead of group names.
  107. --file Run tests identified by specific file names, instead of group names.
  108. Specify the path and the extension (i.e. 'modules/user/user.test').
  109. --xml <path>
  110. If provided, test results will be written as xml files to this path.
  111. --color Output text format results with color highlighting.
  112. --verbose Output detailed assertion messages in addition to summary.
  113. <test1>[,<test2>[,<test3> ...]]
  114. One or more tests to be run. By default, these are interpreted
  115. as the names of test groups as shown at
  116. ?q=admin/config/development/testing.
  117. These group names typically correspond to module names like "User"
  118. or "Profile" or "System", but there is also a group "XML-RPC".
  119. If --class is specified then these are interpreted as the names of
  120. specific test classes whose test methods will be run. Tests must
  121. be separated by commas. Ignored if --all is specified.
  122. To run this script you will normally invoke it from the root directory of your
  123. Drupal installation as the webserver user (differs per configuration), or root:
  124. sudo -u [wwwrun|www-data|etc] php ./scripts/{$args['script']}
  125. --url http://example.com/ --all
  126. sudo -u [wwwrun|www-data|etc] php ./scripts/{$args['script']}
  127. --url http://example.com/ --class BlockTestCase
  128. \n
  129. EOF;
  130. }
  131. /**
  132. * Parse execution argument and ensure that all are valid.
  133. *
  134. * @return The list of arguments.
  135. */
  136. function simpletest_script_parse_args() {
  137. // Set default values.
  138. $args = array(
  139. 'script' => '',
  140. 'help' => FALSE,
  141. 'list' => FALSE,
  142. 'clean' => FALSE,
  143. 'url' => '',
  144. 'php' => '',
  145. 'concurrency' => 1,
  146. 'all' => FALSE,
  147. 'class' => FALSE,
  148. 'file' => FALSE,
  149. 'color' => FALSE,
  150. 'verbose' => FALSE,
  151. 'test_names' => array(),
  152. // Used internally.
  153. 'test-id' => 0,
  154. 'execute-test' => '',
  155. 'xml' => '',
  156. );
  157. // Override with set values.
  158. $args['script'] = basename(array_shift($_SERVER['argv']));
  159. $count = 0;
  160. while ($arg = array_shift($_SERVER['argv'])) {
  161. if (preg_match('/--(\S+)/', $arg, $matches)) {
  162. // Argument found.
  163. if (array_key_exists($matches[1], $args)) {
  164. // Argument found in list.
  165. $previous_arg = $matches[1];
  166. if (is_bool($args[$previous_arg])) {
  167. $args[$matches[1]] = TRUE;
  168. }
  169. else {
  170. $args[$matches[1]] = array_shift($_SERVER['argv']);
  171. }
  172. // Clear extraneous values.
  173. $args['test_names'] = array();
  174. $count++;
  175. }
  176. else {
  177. // Argument not found in list.
  178. simpletest_script_print_error("Unknown argument '$arg'.");
  179. exit;
  180. }
  181. }
  182. else {
  183. // Values found without an argument should be test names.
  184. $args['test_names'] += explode(',', $arg);
  185. $count++;
  186. }
  187. }
  188. // Validate the concurrency argument
  189. if (!is_numeric($args['concurrency']) || $args['concurrency'] <= 0) {
  190. simpletest_script_print_error("--concurrency must be a strictly positive integer.");
  191. exit;
  192. }
  193. return array($args, $count);
  194. }
  195. /**
  196. * Initialize script variables and perform general setup requirements.
  197. */
  198. function simpletest_script_init($server_software) {
  199. global $args, $php;
  200. $host = 'localhost';
  201. $path = '';
  202. // Determine location of php command automatically, unless a command line argument is supplied.
  203. if (!empty($args['php'])) {
  204. $php = $args['php'];
  205. }
  206. elseif ($php_env = getenv('_')) {
  207. // '_' is an environment variable set by the shell. It contains the command that was executed.
  208. $php = $php_env;
  209. }
  210. elseif ($sudo = getenv('SUDO_COMMAND')) {
  211. // 'SUDO_COMMAND' is an environment variable set by the sudo program.
  212. // Extract only the PHP interpreter, not the rest of the command.
  213. list($php, ) = explode(' ', $sudo, 2);
  214. }
  215. else {
  216. simpletest_script_print_error('Unable to automatically determine the path to the PHP interpreter. Supply the --php command line argument.');
  217. simpletest_script_help();
  218. exit();
  219. }
  220. // Get URL from arguments.
  221. if (!empty($args['url'])) {
  222. $parsed_url = parse_url($args['url']);
  223. $host = $parsed_url['host'] . (isset($parsed_url['port']) ? ':' . $parsed_url['port'] : '');
  224. $path = isset($parsed_url['path']) ? $parsed_url['path'] : '';
  225. // If the passed URL schema is 'https' then setup the $_SERVER variables
  226. // properly so that testing will run under HTTPS.
  227. if ($parsed_url['scheme'] == 'https') {
  228. $_SERVER['HTTPS'] = 'on';
  229. }
  230. }
  231. $_SERVER['HTTP_HOST'] = $host;
  232. $_SERVER['REMOTE_ADDR'] = '127.0.0.1';
  233. $_SERVER['SERVER_ADDR'] = '127.0.0.1';
  234. $_SERVER['SERVER_SOFTWARE'] = $server_software;
  235. $_SERVER['SERVER_NAME'] = 'localhost';
  236. $_SERVER['REQUEST_URI'] = $path .'/';
  237. $_SERVER['REQUEST_METHOD'] = 'GET';
  238. $_SERVER['SCRIPT_NAME'] = $path .'/index.php';
  239. $_SERVER['PHP_SELF'] = $path .'/index.php';
  240. $_SERVER['HTTP_USER_AGENT'] = 'Drupal command line';
  241. if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
  242. // Ensure that any and all environment variables are changed to https://.
  243. foreach ($_SERVER as $key => $value) {
  244. $_SERVER[$key] = str_replace('http://', 'https://', $_SERVER[$key]);
  245. }
  246. }
  247. chdir(realpath(dirname(__FILE__) . '/..'));
  248. define('DRUPAL_ROOT', getcwd());
  249. require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
  250. }
  251. /**
  252. * Execute a batch of tests.
  253. */
  254. function simpletest_script_execute_batch($test_id, $test_classes) {
  255. global $args;
  256. // Multi-process execution.
  257. $children = array();
  258. while (!empty($test_classes) || !empty($children)) {
  259. while (count($children) < $args['concurrency']) {
  260. if (empty($test_classes)) {
  261. break;
  262. }
  263. // Fork a child process.
  264. $test_class = array_shift($test_classes);
  265. $command = simpletest_script_command($test_id, $test_class);
  266. $process = proc_open($command, array(), $pipes, NULL, NULL, array('bypass_shell' => TRUE));
  267. if (!is_resource($process)) {
  268. echo "Unable to fork test process. Aborting.\n";
  269. exit;
  270. }
  271. // Register our new child.
  272. $children[] = array(
  273. 'process' => $process,
  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 ' . $test_class . ': test runner returned a non-zero error code (' . $status['exitcode'] . ').' . "\n";
  288. }
  289. unset($children[$cid]);
  290. }
  291. }
  292. }
  293. }
  294. /**
  295. * Bootstrap Drupal and run a single test.
  296. */
  297. function simpletest_script_run_one_test($test_id, $test_class) {
  298. try {
  299. // Bootstrap Drupal.
  300. drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
  301. $test = new $test_class($test_id);
  302. $test->run();
  303. $info = $test->getInfo();
  304. $had_fails = (isset($test->results['#fail']) && $test->results['#fail'] > 0);
  305. $had_exceptions = (isset($test->results['#exception']) && $test->results['#exception'] > 0);
  306. $status = ($had_fails || $had_exceptions ? 'fail' : 'pass');
  307. simpletest_script_print($info['name'] . ' ' . _simpletest_format_summary_line($test->results) . "\n", simpletest_script_color_code($status));
  308. // Finished, kill this runner.
  309. exit(0);
  310. }
  311. catch (Exception $e) {
  312. echo (string) $e;
  313. exit(1);
  314. }
  315. }
  316. /**
  317. * Return a command used to run a test in a separate process.
  318. *
  319. * @param $test_id
  320. * The current test ID.
  321. * @param $test_class
  322. * The name of the test class to run.
  323. */
  324. function simpletest_script_command($test_id, $test_class) {
  325. global $args, $php;
  326. $command = escapeshellarg($php) . ' ' . escapeshellarg('./scripts/' . $args['script']) . ' --url ' . escapeshellarg($args['url']);
  327. if ($args['color']) {
  328. $command .= ' --color';
  329. }
  330. $command .= " --php " . escapeshellarg($php) . " --test-id $test_id --execute-test $test_class";
  331. return $command;
  332. }
  333. /**
  334. * Get list of tests based on arguments. If --all specified then
  335. * returns all available tests, otherwise reads list of tests.
  336. *
  337. * Will print error and exit if no valid tests were found.
  338. *
  339. * @return List of tests.
  340. */
  341. function simpletest_script_get_test_list() {
  342. global $args, $all_tests, $groups;
  343. $test_list = array();
  344. if ($args['all']) {
  345. $test_list = $all_tests;
  346. }
  347. else {
  348. if ($args['class']) {
  349. // Check for valid class names.
  350. foreach ($args['test_names'] as $class_name) {
  351. if (in_array($class_name, $all_tests)) {
  352. $test_list[] = $class_name;
  353. }
  354. }
  355. }
  356. elseif ($args['file']) {
  357. $files = array();
  358. foreach ($args['test_names'] as $file) {
  359. $files[drupal_realpath($file)] = 1;
  360. }
  361. // Check for valid class names.
  362. foreach ($all_tests as $class_name) {
  363. $refclass = new ReflectionClass($class_name);
  364. $file = $refclass->getFileName();
  365. if (isset($files[$file])) {
  366. $test_list[] = $class_name;
  367. }
  368. }
  369. }
  370. else {
  371. // Check for valid group names and get all valid classes in group.
  372. foreach ($args['test_names'] as $group_name) {
  373. if (isset($groups[$group_name])) {
  374. foreach ($groups[$group_name] as $class_name => $info) {
  375. $test_list[] = $class_name;
  376. }
  377. }
  378. }
  379. }
  380. }
  381. if (empty($test_list)) {
  382. simpletest_script_print_error('No valid tests were specified.');
  383. exit;
  384. }
  385. return $test_list;
  386. }
  387. /**
  388. * Initialize the reporter.
  389. */
  390. function simpletest_script_reporter_init() {
  391. global $args, $all_tests, $test_list, $results_map;
  392. $results_map = array(
  393. 'pass' => 'Pass',
  394. 'fail' => 'Fail',
  395. 'exception' => 'Exception'
  396. );
  397. echo "\n";
  398. echo "Drupal test run\n";
  399. echo "---------------\n";
  400. echo "\n";
  401. // Tell the user about what tests are to be run.
  402. if ($args['all']) {
  403. echo "All tests will run.\n\n";
  404. }
  405. else {
  406. echo "Tests to be run:\n";
  407. foreach ($test_list as $class_name) {
  408. $info = call_user_func(array($class_name, 'getInfo'));
  409. echo " - " . $info['name'] . ' (' . $class_name . ')' . "\n";
  410. }
  411. echo "\n";
  412. }
  413. echo "Test run started:\n";
  414. echo " " . format_date($_SERVER['REQUEST_TIME'], 'long') . "\n";
  415. timer_start('run-tests');
  416. echo "\n";
  417. echo "Test summary\n";
  418. echo "------------\n";
  419. echo "\n";
  420. }
  421. /**
  422. * Display jUnit XML test results.
  423. */
  424. function simpletest_script_reporter_write_xml_results() {
  425. global $args, $test_id, $results_map;
  426. $results = db_query("SELECT * FROM {simpletest} WHERE test_id = :test_id ORDER BY test_class, message_id", array(':test_id' => $test_id));
  427. $test_class = '';
  428. $xml_files = array();
  429. foreach ($results as $result) {
  430. if (isset($results_map[$result->status])) {
  431. if ($result->test_class != $test_class) {
  432. // We've moved onto a new class, so write the last classes results to a file:
  433. if (isset($xml_files[$test_class])) {
  434. file_put_contents($args['xml'] . '/' . $test_class . '.xml', $xml_files[$test_class]['doc']->saveXML());
  435. unset($xml_files[$test_class]);
  436. }
  437. $test_class = $result->test_class;
  438. if (!isset($xml_files[$test_class])) {
  439. $doc = new DomDocument('1.0');
  440. $root = $doc->createElement('testsuite');
  441. $root = $doc->appendChild($root);
  442. $xml_files[$test_class] = array('doc' => $doc, 'suite' => $root);
  443. }
  444. }
  445. // For convenience:
  446. $dom_document = &$xml_files[$test_class]['doc'];
  447. // Create the XML element for this test case:
  448. $case = $dom_document->createElement('testcase');
  449. $case->setAttribute('classname', $test_class);
  450. list($class, $name) = explode('->', $result->function, 2);
  451. $case->setAttribute('name', $name);
  452. // Passes get no further attention, but failures and exceptions get to add more detail:
  453. if ($result->status == 'fail') {
  454. $fail = $dom_document->createElement('failure');
  455. $fail->setAttribute('type', 'failure');
  456. $fail->setAttribute('message', $result->message_group);
  457. $text = $dom_document->createTextNode($result->message);
  458. $fail->appendChild($text);
  459. $case->appendChild($fail);
  460. }
  461. elseif ($result->status == 'exception') {
  462. // In the case of an exception the $result->function may not be a class
  463. // method so we record the full function name:
  464. $case->setAttribute('name', $result->function);
  465. $fail = $dom_document->createElement('error');
  466. $fail->setAttribute('type', 'exception');
  467. $fail->setAttribute('message', $result->message_group);
  468. $full_message = $result->message . "\n\nline: " . $result->line . "\nfile: " . $result->file;
  469. $text = $dom_document->createTextNode($full_message);
  470. $fail->appendChild($text);
  471. $case->appendChild($fail);
  472. }
  473. // Append the test case XML to the test suite:
  474. $xml_files[$test_class]['suite']->appendChild($case);
  475. }
  476. }
  477. // The last test case hasn't been saved to a file yet, so do that now:
  478. if (isset($xml_files[$test_class])) {
  479. file_put_contents($args['xml'] . '/' . $test_class . '.xml', $xml_files[$test_class]['doc']->saveXML());
  480. unset($xml_files[$test_class]);
  481. }
  482. }
  483. /**
  484. * Stop the test timer.
  485. */
  486. function simpletest_script_reporter_timer_stop() {
  487. echo "\n";
  488. $end = timer_stop('run-tests');
  489. echo "Test run duration: " . format_interval($end['time'] / 1000);
  490. echo "\n\n";
  491. }
  492. /**
  493. * Display test results.
  494. */
  495. function simpletest_script_reporter_display_results() {
  496. global $args, $test_id, $results_map;
  497. if ($args['verbose']) {
  498. // Report results.
  499. echo "Detailed test results\n";
  500. echo "---------------------\n";
  501. $results = db_query("SELECT * FROM {simpletest} WHERE test_id = :test_id ORDER BY test_class, message_id", array(':test_id' => $test_id));
  502. $test_class = '';
  503. foreach ($results as $result) {
  504. if (isset($results_map[$result->status])) {
  505. if ($result->test_class != $test_class) {
  506. // Display test class every time results are for new test class.
  507. echo "\n\n---- $result->test_class ----\n\n\n";
  508. $test_class = $result->test_class;
  509. // Print table header.
  510. echo "Status Group Filename Line Function \n";
  511. echo "--------------------------------------------------------------------------------\n";
  512. }
  513. simpletest_script_format_result($result);
  514. }
  515. }
  516. }
  517. }
  518. /**
  519. * Format the result so that it fits within the default 80 character
  520. * terminal size.
  521. *
  522. * @param $result The result object to format.
  523. */
  524. function simpletest_script_format_result($result) {
  525. global $results_map, $color;
  526. $summary = sprintf("%-9.9s %-10.10s %-17.17s %4.4s %-35.35s\n",
  527. $results_map[$result->status], $result->message_group, basename($result->file), $result->line, $result->function);
  528. simpletest_script_print($summary, simpletest_script_color_code($result->status));
  529. $lines = explode("\n", wordwrap(trim(strip_tags($result->message)), 76));
  530. foreach ($lines as $line) {
  531. echo " $line\n";
  532. }
  533. }
  534. /**
  535. * Print error message prefixed with " ERROR: " and displayed in fail color
  536. * if color output is enabled.
  537. *
  538. * @param $message The message to print.
  539. */
  540. function simpletest_script_print_error($message) {
  541. simpletest_script_print(" ERROR: $message\n", SIMPLETEST_SCRIPT_COLOR_FAIL);
  542. }
  543. /**
  544. * Print a message to the console, if color is enabled then the specified
  545. * color code will be used.
  546. *
  547. * @param $message The message to print.
  548. * @param $color_code The color code to use for coloring.
  549. */
  550. function simpletest_script_print($message, $color_code) {
  551. global $args;
  552. if ($args['color']) {
  553. echo "\033[" . $color_code . "m" . $message . "\033[0m";
  554. }
  555. else {
  556. echo $message;
  557. }
  558. }
  559. /**
  560. * Get the color code associated with the specified status.
  561. *
  562. * @param $status The status string to get code for.
  563. * @return Color code.
  564. */
  565. function simpletest_script_color_code($status) {
  566. switch ($status) {
  567. case 'pass':
  568. return SIMPLETEST_SCRIPT_COLOR_PASS;
  569. case 'fail':
  570. return SIMPLETEST_SCRIPT_COLOR_FAIL;
  571. case 'exception':
  572. return SIMPLETEST_SCRIPT_COLOR_EXCEPTION;
  573. }
  574. return 0; // Default formatting.
  575. }