simpletest.module 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654
  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. * Implements callback_batch_operation().
  144. */
  145. function _simpletest_batch_operation($test_list_init, $test_id, &$context) {
  146. simpletest_classloader_register();
  147. // Get working values.
  148. if (!isset($context['sandbox']['max'])) {
  149. // First iteration: initialize working values.
  150. $test_list = $test_list_init;
  151. $context['sandbox']['max'] = count($test_list);
  152. $test_results = array('#pass' => 0, '#fail' => 0, '#exception' => 0, '#debug' => 0);
  153. }
  154. else {
  155. // Nth iteration: get the current values where we last stored them.
  156. $test_list = $context['sandbox']['tests'];
  157. $test_results = $context['sandbox']['test_results'];
  158. }
  159. $max = $context['sandbox']['max'];
  160. // Perform the next test.
  161. $test_class = array_shift($test_list);
  162. $test = new $test_class($test_id);
  163. $test->run();
  164. $size = count($test_list);
  165. $info = $test->getInfo();
  166. module_invoke_all('test_finished', $test->results);
  167. // Gather results and compose the report.
  168. $test_results[$test_class] = $test->results;
  169. foreach ($test_results[$test_class] as $key => $value) {
  170. $test_results[$key] += $value;
  171. }
  172. $test_results[$test_class]['#name'] = $info['name'];
  173. $items = array();
  174. foreach (element_children($test_results) as $class) {
  175. 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>');
  176. }
  177. $context['message'] = t('Processed test @num of @max - %test.', array('%test' => $info['name'], '@num' => $max - $size, '@max' => $max));
  178. $context['message'] .= '<div class="simpletest-' . ($test_results['#fail'] + $test_results['#exception'] ? 'fail' : 'pass') . '">Overall results: ' . _simpletest_format_summary_line($test_results) . '</div>';
  179. $context['message'] .= theme('item_list', array('items' => $items));
  180. // Save working values for the next iteration.
  181. $context['sandbox']['tests'] = $test_list;
  182. $context['sandbox']['test_results'] = $test_results;
  183. // The test_id is the only thing we need to save for the report page.
  184. $context['results']['test_id'] = $test_id;
  185. // Multistep processing: report progress.
  186. $context['finished'] = 1 - $size / $max;
  187. }
  188. /**
  189. * Implements callback_batch_finished().
  190. */
  191. function _simpletest_batch_finished($success, $results, $operations, $elapsed) {
  192. if ($success) {
  193. drupal_set_message(t('The test run finished in @elapsed.', array('@elapsed' => $elapsed)));
  194. }
  195. else {
  196. // Use the test_id passed as a parameter to _simpletest_batch_operation().
  197. $test_id = $operations[0][1][1];
  198. // Retrieve the last database prefix used for testing and the last test
  199. // class that was run from. Use the information to read the lgo file
  200. // in case any fatal errors caused the test to crash.
  201. list($last_prefix, $last_test_class) = simpletest_last_test_get($test_id);
  202. simpletest_log_read($test_id, $last_prefix, $last_test_class);
  203. drupal_set_message(t('The test run did not successfully finish.'), 'error');
  204. drupal_set_message(t('Use the <em>Clean environment</em> button to clean-up temporary files and tables.'), 'warning');
  205. }
  206. module_invoke_all('test_group_finished');
  207. }
  208. /**
  209. * Get information about the last test that ran given a test ID.
  210. *
  211. * @param $test_id
  212. * The test ID to get the last test from.
  213. * @return
  214. * Array containing the last database prefix used and the last test class
  215. * that ran.
  216. */
  217. function simpletest_last_test_get($test_id) {
  218. $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();
  219. $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();
  220. return array($last_prefix, $last_test_class);
  221. }
  222. /**
  223. * Read the error log and report any errors as assertion failures.
  224. *
  225. * The errors in the log should only be fatal errors since any other errors
  226. * will have been recorded by the error handler.
  227. *
  228. * @param $test_id
  229. * The test ID to which the log relates.
  230. * @param $prefix
  231. * The database prefix to which the log relates.
  232. * @param $test_class
  233. * The test class to which the log relates.
  234. * @param $during_test
  235. * Indicates that the current file directory path is a temporary file
  236. * file directory used during testing.
  237. * @return
  238. * Found any entries in log.
  239. */
  240. function simpletest_log_read($test_id, $prefix, $test_class, $during_test = FALSE) {
  241. $log = 'public://' . ($during_test ? '' : '/simpletest/' . substr($prefix, 10)) . '/error.log';
  242. $found = FALSE;
  243. if (file_exists($log)) {
  244. foreach (file($log) as $line) {
  245. if (preg_match('/\[.*?\] (.*?): (.*?) in (.*) on line (\d+)/', $line, $match)) {
  246. // Parse PHP fatal errors for example: PHP Fatal error: Call to
  247. // undefined function break_me() in /path/to/file.php on line 17
  248. $caller = array(
  249. 'line' => $match[4],
  250. 'file' => $match[3],
  251. );
  252. DrupalTestCase::insertAssert($test_id, $test_class, FALSE, $match[2], $match[1], $caller);
  253. }
  254. else {
  255. // Unknown format, place the entire message in the log.
  256. DrupalTestCase::insertAssert($test_id, $test_class, FALSE, $line, 'Fatal error');
  257. }
  258. $found = TRUE;
  259. }
  260. }
  261. return $found;
  262. }
  263. /**
  264. * Get a list of all of the tests provided by the system.
  265. *
  266. * The list of test classes is loaded from the registry where it looks for
  267. * files ending in ".test". Once loaded the test list is cached and stored in
  268. * a static variable. In order to list tests provided by disabled modules
  269. * hook_registry_files_alter() is used to forcefully add them to the registry.
  270. *
  271. * PSR-0 classes are found by searching the designated directory for each module
  272. * for files matching the PSR-0 standard.
  273. *
  274. * @return
  275. * An array of tests keyed with the groups specified in each of the tests
  276. * getInfo() method and then keyed by the test class. An example of the array
  277. * structure is provided below.
  278. *
  279. * @code
  280. * $groups['Blog'] => array(
  281. * 'BlogTestCase' => array(
  282. * 'name' => 'Blog functionality',
  283. * 'description' => 'Create, view, edit, delete, ...',
  284. * 'group' => 'Blog',
  285. * ),
  286. * );
  287. * @endcode
  288. * @see simpletest_registry_files_alter()
  289. */
  290. function simpletest_test_get_all() {
  291. $groups = &drupal_static(__FUNCTION__);
  292. if (!$groups) {
  293. // Register a simple class loader for PSR-0 test classes.
  294. simpletest_classloader_register();
  295. // Load test information from cache if available, otherwise retrieve the
  296. // information from each tests getInfo() method.
  297. if ($cache = cache_get('simpletest', 'cache')) {
  298. $groups = $cache->data;
  299. }
  300. else {
  301. // Select all clases in files ending with .test.
  302. $classes = db_query("SELECT name FROM {registry} WHERE type = :type AND filename LIKE :name", array(':type' => 'class', ':name' => '%.test'))->fetchCol();
  303. // Also discover PSR-0 test classes, if the PHP version allows it.
  304. if (version_compare(PHP_VERSION, '5.3') > 0) {
  305. // Select all PSR-0 and PSR-4 classes in the Tests namespace of all
  306. // modules.
  307. $system_list = db_query("SELECT name, filename FROM {system}")->fetchAllKeyed();
  308. foreach ($system_list as $name => $filename) {
  309. $module_dir = DRUPAL_ROOT . '/' . dirname($filename);
  310. // Search both the 'lib/Drupal/mymodule' directory (for PSR-0 classes)
  311. // and the 'src' directory (for PSR-4 classes).
  312. foreach(array('lib/Drupal/' . $name, 'src') as $subdir) {
  313. // Build directory in which the test files would reside.
  314. $tests_dir = $module_dir . '/' . $subdir . '/Tests';
  315. // Scan it for test files if it exists.
  316. if (is_dir($tests_dir)) {
  317. $files = file_scan_directory($tests_dir, '/.*\.php/');
  318. if (!empty($files)) {
  319. foreach ($files as $file) {
  320. // Convert the file name into the namespaced class name.
  321. $replacements = array(
  322. '/' => '\\',
  323. $module_dir . '/' => '',
  324. 'lib/' => '',
  325. 'src/' => 'Drupal\\' . $name . '\\',
  326. '.php' => '',
  327. );
  328. $classes[] = strtr($file->uri, $replacements);
  329. }
  330. }
  331. }
  332. }
  333. }
  334. }
  335. // Check that each class has a getInfo() method and store the information
  336. // in an array keyed with the group specified in the test information.
  337. $groups = array();
  338. foreach ($classes as $class) {
  339. // Test classes need to implement getInfo() to be valid.
  340. if (class_exists($class) && method_exists($class, 'getInfo')) {
  341. $info = call_user_func(array($class, 'getInfo'));
  342. // If this test class requires a non-existing module, skip it.
  343. if (!empty($info['dependencies'])) {
  344. foreach ($info['dependencies'] as $module) {
  345. // Pass FALSE as fourth argument so no error gets created for
  346. // the missing file.
  347. $found_module = drupal_get_filename('module', $module, NULL, FALSE);
  348. if (!$found_module) {
  349. continue 2;
  350. }
  351. }
  352. }
  353. $groups[$info['group']][$class] = $info;
  354. }
  355. }
  356. // Sort the groups and tests within the groups by name.
  357. uksort($groups, 'strnatcasecmp');
  358. foreach ($groups as $group => &$tests) {
  359. uksort($tests, 'strnatcasecmp');
  360. }
  361. // Allow modules extending core tests to disable originals.
  362. drupal_alter('simpletest', $groups);
  363. cache_set('simpletest', $groups);
  364. }
  365. }
  366. return $groups;
  367. }
  368. /*
  369. * Register a simple class loader that can find D8-style PSR-0 test classes.
  370. *
  371. * Other PSR-0 class loading can happen in contrib, but those contrib class
  372. * loader modules will not be enabled when testbot runs. So we need to do this
  373. * one in core.
  374. */
  375. function simpletest_classloader_register() {
  376. // Prevent duplicate classloader registration.
  377. static $first_run = TRUE;
  378. if (!$first_run) {
  379. return;
  380. }
  381. $first_run = FALSE;
  382. // Only register PSR-0 class loading if we are on PHP 5.3 or higher.
  383. if (version_compare(PHP_VERSION, '5.3') > 0) {
  384. spl_autoload_register('_simpletest_autoload_psr4_psr0');
  385. }
  386. }
  387. /**
  388. * Autoload callback to find PSR-4 and PSR-0 test classes.
  389. *
  390. * Looks in the 'src/Tests' and in the 'lib/Drupal/mymodule/Tests' directory of
  391. * modules for the class.
  392. *
  393. * This will only work on classes where the namespace is of the pattern
  394. * "Drupal\$extension\Tests\.."
  395. */
  396. function _simpletest_autoload_psr4_psr0($class) {
  397. // Static cache for extension paths.
  398. // This cache is lazily filled as soon as it is needed.
  399. static $extensions;
  400. // Check that the first namespace fragment is "Drupal\"
  401. if (substr($class, 0, 7) === 'Drupal\\') {
  402. // Find the position of the second namespace separator.
  403. $pos = strpos($class, '\\', 7);
  404. // Check that the third namespace fragment is "\Tests\".
  405. if (substr($class, $pos, 7) === '\\Tests\\') {
  406. // Extract the second namespace fragment, which we expect to be the
  407. // extension name.
  408. $extension = substr($class, 7, $pos - 7);
  409. // Lazy-load the extension paths, both enabled and disabled.
  410. if (!isset($extensions)) {
  411. $extensions = db_query("SELECT name, filename FROM {system}")->fetchAllKeyed();
  412. }
  413. // Check if the second namespace fragment is a known extension name.
  414. if (isset($extensions[$extension])) {
  415. // Split the class into namespace and classname.
  416. $nspos = strrpos($class, '\\');
  417. $namespace = substr($class, 0, $nspos);
  418. $classname = substr($class, $nspos + 1);
  419. // Try the PSR-4 location first, and the PSR-0 location as a fallback.
  420. // Build the PSR-4 filepath where we expect the class to be defined.
  421. $psr4_path = dirname($extensions[$extension]) . '/src/' .
  422. str_replace('\\', '/', substr($namespace, strlen('Drupal\\' . $extension . '\\'))) . '/' .
  423. str_replace('_', '/', $classname) . '.php';
  424. // Include the file, if it does exist.
  425. if (file_exists($psr4_path)) {
  426. include $psr4_path;
  427. }
  428. else {
  429. // Build the PSR-0 filepath where we expect the class to be defined.
  430. $psr0_path = dirname($extensions[$extension]) . '/lib/' .
  431. str_replace('\\', '/', $namespace) . '/' .
  432. str_replace('_', '/', $classname) . '.php';
  433. // Include the file, if it does exist.
  434. if (file_exists($psr0_path)) {
  435. include $psr0_path;
  436. }
  437. }
  438. }
  439. }
  440. }
  441. }
  442. /**
  443. * Implements hook_registry_files_alter().
  444. *
  445. * Add the test files for disabled modules so that we get a list containing
  446. * all the avialable tests.
  447. */
  448. function simpletest_registry_files_alter(&$files, $modules) {
  449. foreach ($modules as $module) {
  450. // Only add test files for disabled modules, as enabled modules should
  451. // already include any test files they provide.
  452. if (!$module->status) {
  453. $dir = $module->dir;
  454. if (!empty($module->info['files'])) {
  455. foreach ($module->info['files'] as $file) {
  456. if (substr($file, -5) == '.test') {
  457. $files["$dir/$file"] = array('module' => $module->name, 'weight' => $module->weight);
  458. }
  459. }
  460. }
  461. }
  462. }
  463. }
  464. /**
  465. * Generate test file.
  466. */
  467. function simpletest_generate_file($filename, $width, $lines, $type = 'binary-text') {
  468. $text = '';
  469. for ($i = 0; $i < $lines; $i++) {
  470. // Generate $width - 1 characters to leave space for the "\n" character.
  471. for ($j = 0; $j < $width - 1; $j++) {
  472. switch ($type) {
  473. case 'text':
  474. $text .= chr(rand(32, 126));
  475. break;
  476. case 'binary':
  477. $text .= chr(rand(0, 31));
  478. break;
  479. case 'binary-text':
  480. default:
  481. $text .= rand(0, 1);
  482. break;
  483. }
  484. }
  485. $text .= "\n";
  486. }
  487. // Create filename.
  488. file_put_contents('public://' . $filename . '.txt', $text);
  489. return $filename;
  490. }
  491. /**
  492. * Remove all temporary database tables and directories.
  493. */
  494. function simpletest_clean_environment() {
  495. simpletest_clean_database();
  496. simpletest_clean_temporary_directories();
  497. if (variable_get('simpletest_clear_results', TRUE)) {
  498. $count = simpletest_clean_results_table();
  499. drupal_set_message(format_plural($count, 'Removed 1 test result.', 'Removed @count test results.'));
  500. }
  501. else {
  502. drupal_set_message(t('Clear results is disabled and the test results table will not be cleared.'), 'warning');
  503. }
  504. // Detect test classes that have been added, renamed or deleted.
  505. registry_rebuild();
  506. cache_clear_all('simpletest', 'cache');
  507. }
  508. /**
  509. * Removed prefixed tables from the database that are left over from crashed tests.
  510. */
  511. function simpletest_clean_database() {
  512. $tables = db_find_tables(Database::getConnection()->prefixTables('{simpletest}') . '%');
  513. $schema = drupal_get_schema_unprocessed('simpletest');
  514. $count = 0;
  515. foreach (array_diff_key($tables, $schema) as $table) {
  516. // Strip the prefix and skip tables without digits following "simpletest",
  517. // e.g. {simpletest_test_id}.
  518. if (preg_match('/simpletest\d+.*/', $table, $matches)) {
  519. db_drop_table($matches[0]);
  520. $count++;
  521. }
  522. }
  523. if ($count > 0) {
  524. drupal_set_message(format_plural($count, 'Removed 1 leftover table.', 'Removed @count leftover tables.'));
  525. }
  526. else {
  527. drupal_set_message(t('No leftover tables to remove.'));
  528. }
  529. }
  530. /**
  531. * Find all leftover temporary directories and remove them.
  532. */
  533. function simpletest_clean_temporary_directories() {
  534. $count = 0;
  535. if (is_dir('public://simpletest')) {
  536. $files = scandir('public://simpletest');
  537. foreach ($files as $file) {
  538. $path = 'public://simpletest/' . $file;
  539. if (is_dir($path) && is_numeric($file)) {
  540. file_unmanaged_delete_recursive($path);
  541. $count++;
  542. }
  543. }
  544. }
  545. if ($count > 0) {
  546. drupal_set_message(format_plural($count, 'Removed 1 temporary directory.', 'Removed @count temporary directories.'));
  547. }
  548. else {
  549. drupal_set_message(t('No temporary directories to remove.'));
  550. }
  551. }
  552. /**
  553. * Clear the test result tables.
  554. *
  555. * @param $test_id
  556. * Test ID to remove results for, or NULL to remove all results.
  557. * @return
  558. * The number of results removed.
  559. */
  560. function simpletest_clean_results_table($test_id = NULL) {
  561. if (variable_get('simpletest_clear_results', TRUE)) {
  562. if ($test_id) {
  563. $count = db_query('SELECT COUNT(test_id) FROM {simpletest_test_id} WHERE test_id = :test_id', array(':test_id' => $test_id))->fetchField();
  564. db_delete('simpletest')
  565. ->condition('test_id', $test_id)
  566. ->execute();
  567. db_delete('simpletest_test_id')
  568. ->condition('test_id', $test_id)
  569. ->execute();
  570. }
  571. else {
  572. $count = db_query('SELECT COUNT(test_id) FROM {simpletest_test_id}')->fetchField();
  573. // Clear test results.
  574. db_delete('simpletest')->execute();
  575. db_delete('simpletest_test_id')->execute();
  576. }
  577. return $count;
  578. }
  579. return 0;
  580. }
  581. /**
  582. * Implements hook_mail_alter().
  583. *
  584. * Aborts sending of messages with ID 'simpletest_cancel_test'.
  585. *
  586. * @see MailTestCase::testCancelMessage()
  587. */
  588. function simpletest_mail_alter(&$message) {
  589. if ($message['id'] == 'simpletest_cancel_test') {
  590. $message['send'] = FALSE;
  591. }
  592. }