simpletest.module 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  1. <?php
  2. /**
  3. * @file
  4. * Provides testing functionality.
  5. */
  6. /**
  7. * Implements hook_help().
  8. */
  9. function simpletest_help($path, $arg) {
  10. switch ($path) {
  11. case 'admin/help#simpletest':
  12. $output = '';
  13. $output .= '<h3>' . t('About') . '</h3>';
  14. $output .= '<p>' . t('The Testing module provides a framework for running automated unit tests. It can be used to verify a working state of Drupal before and after any code changes, or as a means for developers to write and execute tests for their modules. For more information, see the online handbook entry for <a href="@simpletest">Testing module</a>.', array('@simpletest' => 'http://drupal.org/documentation/modules/simpletest', '@blocks' => url('admin/structure/block'))) . '</p>';
  15. $output .= '<h3>' . t('Uses') . '</h3>';
  16. $output .= '<dl>';
  17. $output .= '<dt>' . t('Running tests') . '</dt>';
  18. $output .= '<dd>' . t('Visit the <a href="@admin-simpletest">Testing page</a> to display a list of available tests. For comprehensive testing, select <em>all</em> tests, or individually select tests for more targeted testing. Note that it might take several minutes for all tests to complete. For more information on creating and modifying your own tests, see the <a href="@simpletest-api">Testing API Documentation</a> in the Drupal handbook.', array('@simpletest-api' => 'http://drupal.org/simpletest', '@admin-simpletest' => url('admin/config/development/testing'))) . '</dd>';
  19. $output .= '<dd>' . t('After the tests run, a message will be displayed next to each test group indicating whether tests within it passed, failed, or had exceptions. A pass means that the test returned the expected results, while fail means that it did not. An exception normally indicates an error outside of the test, such as a PHP warning or notice. If there were failures or exceptions, the results will be expanded to show details, and the tests that had failures or exceptions will be indicated in red or pink rows. You can then use these results to refine your code and tests, until all tests pass.') . '</dd>';
  20. $output .= '</dl>';
  21. return $output;
  22. }
  23. }
  24. /**
  25. * Implements hook_menu().
  26. */
  27. function simpletest_menu() {
  28. $items['admin/config/development/testing'] = array(
  29. 'title' => 'Testing',
  30. 'page callback' => 'drupal_get_form',
  31. 'page arguments' => array('simpletest_test_form'),
  32. 'description' => 'Run tests against Drupal core and your active modules. These tests help assure that your site code is working as designed.',
  33. 'access arguments' => array('administer unit tests'),
  34. 'file' => 'simpletest.pages.inc',
  35. 'weight' => -5,
  36. );
  37. $items['admin/config/development/testing/list'] = array(
  38. 'title' => 'List',
  39. 'type' => MENU_DEFAULT_LOCAL_TASK,
  40. );
  41. $items['admin/config/development/testing/settings'] = array(
  42. 'title' => 'Settings',
  43. 'page callback' => 'drupal_get_form',
  44. 'page arguments' => array('simpletest_settings_form'),
  45. 'access arguments' => array('administer unit tests'),
  46. 'type' => MENU_LOCAL_TASK,
  47. 'file' => 'simpletest.pages.inc',
  48. );
  49. $items['admin/config/development/testing/results/%'] = array(
  50. 'title' => 'Test result',
  51. 'page callback' => 'drupal_get_form',
  52. 'page arguments' => array('simpletest_result_form', 5),
  53. 'description' => 'View result of tests.',
  54. 'access arguments' => array('administer unit tests'),
  55. 'file' => 'simpletest.pages.inc',
  56. );
  57. return $items;
  58. }
  59. /**
  60. * Implements hook_permission().
  61. */
  62. function simpletest_permission() {
  63. return array(
  64. 'administer unit tests' => array(
  65. 'title' => t('Administer tests'),
  66. 'restrict access' => TRUE,
  67. ),
  68. );
  69. }
  70. /**
  71. * Implements hook_theme().
  72. */
  73. function simpletest_theme() {
  74. return array(
  75. 'simpletest_test_table' => array(
  76. 'render element' => 'table',
  77. 'file' => 'simpletest.pages.inc',
  78. ),
  79. 'simpletest_result_summary' => array(
  80. 'render element' => 'form',
  81. 'file' => 'simpletest.pages.inc',
  82. ),
  83. );
  84. }
  85. /**
  86. * Implements hook_js_alter().
  87. */
  88. function simpletest_js_alter(&$javascript) {
  89. // Since SimpleTest is a special use case for the table select, stick the
  90. // SimpleTest JavaScript above the table select.
  91. $simpletest = drupal_get_path('module', 'simpletest') . '/simpletest.js';
  92. if (array_key_exists($simpletest, $javascript) && array_key_exists('misc/tableselect.js', $javascript)) {
  93. $javascript[$simpletest]['weight'] = $javascript['misc/tableselect.js']['weight'] - 1;
  94. }
  95. }
  96. function _simpletest_format_summary_line($summary) {
  97. $args = array(
  98. '@pass' => format_plural(isset($summary['#pass']) ? $summary['#pass'] : 0, '1 pass', '@count passes'),
  99. '@fail' => format_plural(isset($summary['#fail']) ? $summary['#fail'] : 0, '1 fail', '@count fails'),
  100. '@exception' => format_plural(isset($summary['#exception']) ? $summary['#exception'] : 0, '1 exception', '@count exceptions'),
  101. );
  102. if (!$summary['#debug']) {
  103. return t('@pass, @fail, and @exception', $args);
  104. }
  105. $args['@debug'] = format_plural(isset($summary['#debug']) ? $summary['#debug'] : 0, '1 debug message', '@count debug messages');
  106. return t('@pass, @fail, @exception, and @debug', $args);
  107. }
  108. /**
  109. * Actually runs tests.
  110. *
  111. * @param $test_list
  112. * List of tests to run.
  113. * @param $reporter
  114. * Which reporter to use. Allowed values are: text, xml, html and drupal,
  115. * drupal being the default.
  116. */
  117. function simpletest_run_tests($test_list, $reporter = 'drupal') {
  118. $test_id = db_insert('simpletest_test_id')
  119. ->useDefaults(array('test_id'))
  120. ->execute();
  121. // Clear out the previous verbose files.
  122. file_unmanaged_delete_recursive('public://simpletest/verbose');
  123. // Get the info for the first test being run.
  124. $first_test = array_shift($test_list);
  125. $first_instance = new $first_test();
  126. array_unshift($test_list, $first_test);
  127. $info = $first_instance->getInfo();
  128. $batch = array(
  129. 'title' => t('Running tests'),
  130. 'operations' => array(
  131. array('_simpletest_batch_operation', array($test_list, $test_id)),
  132. ),
  133. 'finished' => '_simpletest_batch_finished',
  134. 'progress_message' => '',
  135. 'css' => array(drupal_get_path('module', 'simpletest') . '/simpletest.css'),
  136. 'init_message' => t('Processing test @num of @max - %test.', array('%test' => $info['name'], '@num' => '1', '@max' => count($test_list))),
  137. );
  138. batch_set($batch);
  139. module_invoke_all('test_group_started');
  140. return $test_id;
  141. }
  142. /**
  143. * Batch operation callback.
  144. */
  145. function _simpletest_batch_operation($test_list_init, $test_id, &$context) {
  146. // Get working values.
  147. if (!isset($context['sandbox']['max'])) {
  148. // First iteration: initialize working values.
  149. $test_list = $test_list_init;
  150. $context['sandbox']['max'] = count($test_list);
  151. $test_results = array('#pass' => 0, '#fail' => 0, '#exception' => 0, '#debug' => 0);
  152. }
  153. else {
  154. // Nth iteration: get the current values where we last stored them.
  155. $test_list = $context['sandbox']['tests'];
  156. $test_results = $context['sandbox']['test_results'];
  157. }
  158. $max = $context['sandbox']['max'];
  159. // Perform the next test.
  160. $test_class = array_shift($test_list);
  161. $test = new $test_class($test_id);
  162. $test->run();
  163. $size = count($test_list);
  164. $info = $test->getInfo();
  165. module_invoke_all('test_finished', $test->results);
  166. // Gather results and compose the report.
  167. $test_results[$test_class] = $test->results;
  168. foreach ($test_results[$test_class] as $key => $value) {
  169. $test_results[$key] += $value;
  170. }
  171. $test_results[$test_class]['#name'] = $info['name'];
  172. $items = array();
  173. foreach (element_children($test_results) as $class) {
  174. array_unshift($items, '<div class="simpletest-' . ($test_results[$class]['#fail'] + $test_results[$class]['#exception'] ? 'fail' : 'pass') . '">' . t('@name: @summary', array('@name' => $test_results[$class]['#name'], '@summary' => _simpletest_format_summary_line($test_results[$class]))) . '</div>');
  175. }
  176. $context['message'] = t('Processed test @num of @max - %test.', array('%test' => $info['name'], '@num' => $max - $size, '@max' => $max));
  177. $context['message'] .= '<div class="simpletest-' . ($test_results['#fail'] + $test_results['#exception'] ? 'fail' : 'pass') . '">Overall results: ' . _simpletest_format_summary_line($test_results) . '</div>';
  178. $context['message'] .= theme('item_list', array('items' => $items));
  179. // Save working values for the next iteration.
  180. $context['sandbox']['tests'] = $test_list;
  181. $context['sandbox']['test_results'] = $test_results;
  182. // The test_id is the only thing we need to save for the report page.
  183. $context['results']['test_id'] = $test_id;
  184. // Multistep processing: report progress.
  185. $context['finished'] = 1 - $size / $max;
  186. }
  187. function _simpletest_batch_finished($success, $results, $operations, $elapsed) {
  188. if ($success) {
  189. drupal_set_message(t('The test run finished in @elapsed.', array('@elapsed' => $elapsed)));
  190. }
  191. else {
  192. // Use the test_id passed as a parameter to _simpletest_batch_operation().
  193. $test_id = $operations[0][1][1];
  194. // Retrieve the last database prefix used for testing and the last test
  195. // class that was run from. Use the information to read the lgo file
  196. // in case any fatal errors caused the test to crash.
  197. list($last_prefix, $last_test_class) = simpletest_last_test_get($test_id);
  198. simpletest_log_read($test_id, $last_prefix, $last_test_class);
  199. drupal_set_message(t('The test run did not successfully finish.'), 'error');
  200. drupal_set_message(t('Use the <em>Clean environment</em> button to clean-up temporary files and tables.'), 'warning');
  201. }
  202. module_invoke_all('test_group_finished');
  203. }
  204. /**
  205. * Get information about the last test that ran given a test ID.
  206. *
  207. * @param $test_id
  208. * The test ID to get the last test from.
  209. * @return
  210. * Array containing the last database prefix used and the last test class
  211. * that ran.
  212. */
  213. function simpletest_last_test_get($test_id) {
  214. $last_prefix = db_query_range('SELECT last_prefix FROM {simpletest_test_id} WHERE test_id = :test_id', 0, 1, array(':test_id' => $test_id))->fetchField();
  215. $last_test_class = db_query_range('SELECT test_class FROM {simpletest} WHERE test_id = :test_id ORDER BY message_id DESC', 0, 1, array(':test_id' => $test_id))->fetchField();
  216. return array($last_prefix, $last_test_class);
  217. }
  218. /**
  219. * Read the error log and report any errors as assertion failures.
  220. *
  221. * The errors in the log should only be fatal errors since any other errors
  222. * will have been recorded by the error handler.
  223. *
  224. * @param $test_id
  225. * The test ID to which the log relates.
  226. * @param $prefix
  227. * The database prefix to which the log relates.
  228. * @param $test_class
  229. * The test class to which the log relates.
  230. * @param $during_test
  231. * Indicates that the current file directory path is a temporary file
  232. * file directory used during testing.
  233. * @return
  234. * Found any entries in log.
  235. */
  236. function simpletest_log_read($test_id, $prefix, $test_class, $during_test = FALSE) {
  237. $log = 'public://' . ($during_test ? '' : '/simpletest/' . substr($prefix, 10)) . '/error.log';
  238. $found = FALSE;
  239. if (file_exists($log)) {
  240. foreach (file($log) as $line) {
  241. if (preg_match('/\[.*?\] (.*?): (.*?) in (.*) on line (\d+)/', $line, $match)) {
  242. // Parse PHP fatal errors for example: PHP Fatal error: Call to
  243. // undefined function break_me() in /path/to/file.php on line 17
  244. $caller = array(
  245. 'line' => $match[4],
  246. 'file' => $match[3],
  247. );
  248. DrupalTestCase::insertAssert($test_id, $test_class, FALSE, $match[2], $match[1], $caller);
  249. }
  250. else {
  251. // Unknown format, place the entire message in the log.
  252. DrupalTestCase::insertAssert($test_id, $test_class, FALSE, $line, 'Fatal error');
  253. }
  254. $found = TRUE;
  255. }
  256. }
  257. return $found;
  258. }
  259. /**
  260. * Get a list of all of the tests provided by the system.
  261. *
  262. * The list of test classes is loaded from the registry where it looks for
  263. * files ending in ".test". Once loaded the test list is cached and stored in
  264. * a static variable. In order to list tests provided by disabled modules
  265. * hook_registry_files_alter() is used to forcefully add them to the registry.
  266. *
  267. * @return
  268. * An array of tests keyed with the groups specified in each of the tests
  269. * getInfo() method and then keyed by the test class. An example of the array
  270. * structure is provided below.
  271. *
  272. * @code
  273. * $groups['Blog'] => array(
  274. * 'BlogTestCase' => array(
  275. * 'name' => 'Blog functionality',
  276. * 'description' => 'Create, view, edit, delete, ...',
  277. * 'group' => 'Blog',
  278. * ),
  279. * );
  280. * @endcode
  281. * @see simpletest_registry_files_alter()
  282. */
  283. function simpletest_test_get_all() {
  284. $groups = &drupal_static(__FUNCTION__);
  285. if (!$groups) {
  286. // Load test information from cache if available, otherwise retrieve the
  287. // information from each tests getInfo() method.
  288. if ($cache = cache_get('simpletest', 'cache')) {
  289. $groups = $cache->data;
  290. }
  291. else {
  292. // Select all clases in files ending with .test.
  293. $classes = db_query("SELECT name FROM {registry} WHERE type = :type AND filename LIKE :name", array(':type' => 'class', ':name' => '%.test'))->fetchCol();
  294. // Check that each class has a getInfo() method and store the information
  295. // in an array keyed with the group specified in the test information.
  296. $groups = array();
  297. foreach ($classes as $class) {
  298. // Test classes need to implement getInfo() to be valid.
  299. if (class_exists($class) && method_exists($class, 'getInfo')) {
  300. $info = call_user_func(array($class, 'getInfo'));
  301. // If this test class requires a non-existing module, skip it.
  302. if (!empty($info['dependencies'])) {
  303. foreach ($info['dependencies'] as $module) {
  304. if (!drupal_get_filename('module', $module)) {
  305. continue 2;
  306. }
  307. }
  308. }
  309. $groups[$info['group']][$class] = $info;
  310. }
  311. }
  312. // Sort the groups and tests within the groups by name.
  313. uksort($groups, 'strnatcasecmp');
  314. foreach ($groups as $group => &$tests) {
  315. uksort($tests, 'strnatcasecmp');
  316. }
  317. // Allow modules extending core tests to disable originals.
  318. drupal_alter('simpletest', $groups);
  319. cache_set('simpletest', $groups);
  320. }
  321. }
  322. return $groups;
  323. }
  324. /**
  325. * Implements hook_registry_files_alter().
  326. *
  327. * Add the test files for disabled modules so that we get a list containing
  328. * all the avialable tests.
  329. */
  330. function simpletest_registry_files_alter(&$files, $modules) {
  331. foreach ($modules as $module) {
  332. // Only add test files for disabled modules, as enabled modules should
  333. // already include any test files they provide.
  334. if (!$module->status) {
  335. $dir = $module->dir;
  336. if (!empty($module->info['files'])) {
  337. foreach ($module->info['files'] as $file) {
  338. if (substr($file, -5) == '.test') {
  339. $files["$dir/$file"] = array('module' => $module->name, 'weight' => $module->weight);
  340. }
  341. }
  342. }
  343. }
  344. }
  345. }
  346. /**
  347. * Generate test file.
  348. */
  349. function simpletest_generate_file($filename, $width, $lines, $type = 'binary-text') {
  350. $size = $width * $lines - $lines;
  351. // Generate random text
  352. $text = '';
  353. for ($i = 0; $i < $size; $i++) {
  354. switch ($type) {
  355. case 'text':
  356. $text .= chr(rand(32, 126));
  357. break;
  358. case 'binary':
  359. $text .= chr(rand(0, 31));
  360. break;
  361. case 'binary-text':
  362. default:
  363. $text .= rand(0, 1);
  364. break;
  365. }
  366. }
  367. $text = wordwrap($text, $width - 1, "\n", TRUE) . "\n"; // Add \n for symmetrical file.
  368. // Create filename.
  369. file_put_contents('public://' . $filename . '.txt', $text);
  370. return $filename;
  371. }
  372. /**
  373. * Remove all temporary database tables and directories.
  374. */
  375. function simpletest_clean_environment() {
  376. simpletest_clean_database();
  377. simpletest_clean_temporary_directories();
  378. if (variable_get('simpletest_clear_results', TRUE)) {
  379. $count = simpletest_clean_results_table();
  380. drupal_set_message(format_plural($count, 'Removed 1 test result.', 'Removed @count test results.'));
  381. }
  382. else {
  383. drupal_set_message(t('Clear results is disabled and the test results table will not be cleared.'), 'warning');
  384. }
  385. // Detect test classes that have been added, renamed or deleted.
  386. registry_rebuild();
  387. cache_clear_all('simpletest', 'cache');
  388. }
  389. /**
  390. * Removed prefixed tables from the database that are left over from crashed tests.
  391. */
  392. function simpletest_clean_database() {
  393. $tables = db_find_tables(Database::getConnection()->prefixTables('{simpletest}') . '%');
  394. $schema = drupal_get_schema_unprocessed('simpletest');
  395. $count = 0;
  396. foreach (array_diff_key($tables, $schema) as $table) {
  397. // Strip the prefix and skip tables without digits following "simpletest",
  398. // e.g. {simpletest_test_id}.
  399. if (preg_match('/simpletest\d+.*/', $table, $matches)) {
  400. db_drop_table($matches[0]);
  401. $count++;
  402. }
  403. }
  404. if ($count > 0) {
  405. drupal_set_message(format_plural($count, 'Removed 1 leftover table.', 'Removed @count leftover tables.'));
  406. }
  407. else {
  408. drupal_set_message(t('No leftover tables to remove.'));
  409. }
  410. }
  411. /**
  412. * Find all leftover temporary directories and remove them.
  413. */
  414. function simpletest_clean_temporary_directories() {
  415. $count = 0;
  416. if (is_dir('public://simpletest')) {
  417. $files = scandir('public://simpletest');
  418. foreach ($files as $file) {
  419. $path = 'public://simpletest/' . $file;
  420. if (is_dir($path) && is_numeric($file)) {
  421. file_unmanaged_delete_recursive($path);
  422. $count++;
  423. }
  424. }
  425. }
  426. if ($count > 0) {
  427. drupal_set_message(format_plural($count, 'Removed 1 temporary directory.', 'Removed @count temporary directories.'));
  428. }
  429. else {
  430. drupal_set_message(t('No temporary directories to remove.'));
  431. }
  432. }
  433. /**
  434. * Clear the test result tables.
  435. *
  436. * @param $test_id
  437. * Test ID to remove results for, or NULL to remove all results.
  438. * @return
  439. * The number of results removed.
  440. */
  441. function simpletest_clean_results_table($test_id = NULL) {
  442. if (variable_get('simpletest_clear_results', TRUE)) {
  443. if ($test_id) {
  444. $count = db_query('SELECT COUNT(test_id) FROM {simpletest_test_id} WHERE test_id = :test_id', array(':test_id' => $test_id))->fetchField();
  445. db_delete('simpletest')
  446. ->condition('test_id', $test_id)
  447. ->execute();
  448. db_delete('simpletest_test_id')
  449. ->condition('test_id', $test_id)
  450. ->execute();
  451. }
  452. else {
  453. $count = db_query('SELECT COUNT(test_id) FROM {simpletest_test_id}')->fetchField();
  454. // Clear test results.
  455. db_delete('simpletest')->execute();
  456. db_delete('simpletest_test_id')->execute();
  457. }
  458. return $count;
  459. }
  460. return 0;
  461. }
  462. /**
  463. * Implements hook_mail_alter().
  464. *
  465. * Aborts sending of messages with ID 'simpletest_cancel_test'.
  466. *
  467. * @see MailTestCase::testCancelMessage()
  468. */
  469. function simpletest_mail_alter(&$message) {
  470. if ($message['id'] == 'simpletest_cancel_test') {
  471. $message['send'] = FALSE;
  472. }
  473. }