You are here

run-tests.sh in SimpleTest 6.2

This script runs Drupal tests from command line.

File

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