Project

General

Profile

Paste
Download (23.6 KB) Statistics
| Branch: | Revision:

root / drupal7 / modules / simpletest / simpletest.module @ b0dc3a2e

1
<?php
2

    
3
/**
4
 * @file
5
 * Provides testing functionality.
6
 */
7

    
8
/**
9
 * Implements hook_help().
10
 */
11
function simpletest_help($path, $arg) {
12
  switch ($path) {
13
    case 'admin/help#simpletest':
14
      $output = '';
15
      $output .= '<h3>' . t('About') . '</h3>';
16
      $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>';
17
      $output .= '<h3>' . t('Uses') . '</h3>';
18
      $output .= '<dl>';
19
      $output .= '<dt>' . t('Running tests') . '</dt>';
20
      $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>';
21
      $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>';
22
      $output .= '</dl>';
23
      return $output;
24
  }
25
}
26

    
27
/**
28
 * Implements hook_menu().
29
 */
30
function simpletest_menu() {
31
  $items['admin/config/development/testing'] = array(
32
    'title' => 'Testing',
33
    'page callback' => 'drupal_get_form',
34
    'page arguments' => array('simpletest_test_form'),
35
    'description' => 'Run tests against Drupal core and your active modules. These tests help assure that your site code is working as designed.',
36
    'access arguments' => array('administer unit tests'),
37
    'file' => 'simpletest.pages.inc',
38
    'weight' => -5,
39
  );
40
  $items['admin/config/development/testing/list'] = array(
41
    'title' => 'List',
42
    'type' => MENU_DEFAULT_LOCAL_TASK,
43
  );
44
  $items['admin/config/development/testing/settings'] = array(
45
    'title' => 'Settings',
46
    'page callback' => 'drupal_get_form',
47
    'page arguments' => array('simpletest_settings_form'),
48
    'access arguments' => array('administer unit tests'),
49
    'type' => MENU_LOCAL_TASK,
50
    'file' => 'simpletest.pages.inc',
51
  );
52
  $items['admin/config/development/testing/results/%'] = array(
53
    'title' => 'Test result',
54
    'page callback' => 'drupal_get_form',
55
    'page arguments' => array('simpletest_result_form', 5),
56
    'description' => 'View result of tests.',
57
    'access arguments' => array('administer unit tests'),
58
    'file' => 'simpletest.pages.inc',
59
  );
60
  return $items;
61
}
62

    
63
/**
64
 * Implements hook_permission().
65
 */
66
function simpletest_permission() {
67
  return array(
68
    'administer unit tests' => array(
69
      'title' => t('Administer tests'),
70
      'restrict access' => TRUE,
71
    ),
72
  );
73
}
74

    
75
/**
76
 * Implements hook_theme().
77
 */
78
function simpletest_theme() {
79
  return array(
80
    'simpletest_test_table' => array(
81
      'render element' => 'table',
82
      'file' => 'simpletest.pages.inc',
83
    ),
84
    'simpletest_result_summary' => array(
85
      'render element' => 'form',
86
      'file' => 'simpletest.pages.inc',
87
    ),
88
  );
89
}
90

    
91
/**
92
 * Implements hook_js_alter().
93
 */
94
function simpletest_js_alter(&$javascript) {
95
  // Since SimpleTest is a special use case for the table select, stick the
96
  // SimpleTest JavaScript above the table select.
97
  $simpletest = drupal_get_path('module', 'simpletest') . '/simpletest.js';
98
  if (array_key_exists($simpletest, $javascript) && array_key_exists('misc/tableselect.js', $javascript)) {
99
    $javascript[$simpletest]['weight'] = $javascript['misc/tableselect.js']['weight'] - 1;
100
  }
101
}
102

    
103
function _simpletest_format_summary_line($summary) {
104
  $args = array(
105
    '@pass' => format_plural(isset($summary['#pass']) ? $summary['#pass'] : 0, '1 pass', '@count passes'),
106
    '@fail' => format_plural(isset($summary['#fail']) ? $summary['#fail'] : 0, '1 fail', '@count fails'),
107
    '@exception' => format_plural(isset($summary['#exception']) ? $summary['#exception'] : 0, '1 exception', '@count exceptions'),
108
  );
109
  if (!$summary['#debug']) {
110
    return t('@pass, @fail, and @exception', $args);
111
  }
112
  $args['@debug'] = format_plural(isset($summary['#debug']) ? $summary['#debug'] : 0, '1 debug message', '@count debug messages');
113
  return t('@pass, @fail, @exception, and @debug', $args);
114
}
115

    
116
/**
117
 * Actually runs tests.
118
 *
119
 * @param $test_list
120
 *   List of tests to run.
121
 * @param $reporter
122
 *   Which reporter to use. Allowed values are: text, xml, html and drupal,
123
 *   drupal being the default.
124
 */
125
function simpletest_run_tests($test_list, $reporter = 'drupal') {
126
  $test_id = db_insert('simpletest_test_id')
127
    ->useDefaults(array('test_id'))
128
    ->execute();
129

    
130
  // Clear out the previous verbose files.
131
  file_unmanaged_delete_recursive('public://simpletest/verbose');
132

    
133
  // Get the info for the first test being run.
134
  $first_test = array_shift($test_list);
135
  $first_instance = new $first_test();
136
  array_unshift($test_list, $first_test);
137
  $info = $first_instance->getInfo();
138

    
139
  $batch = array(
140
    'title' => t('Running tests'),
141
    'operations' => array(
142
      array('_simpletest_batch_operation', array($test_list, $test_id)),
143
    ),
144
    'finished' => '_simpletest_batch_finished',
145
    'progress_message' => '',
146
    'css' => array(drupal_get_path('module', 'simpletest') . '/simpletest.css'),
147
    'init_message' => t('Processing test @num of @max - %test.', array('%test' => $info['name'], '@num' => '1', '@max' => count($test_list))),
148
  );
149
  batch_set($batch);
150

    
151
  module_invoke_all('test_group_started');
152

    
153
  return $test_id;
154
}
155

    
156
/**
157
 * Implements callback_batch_operation().
158
 */
159
function _simpletest_batch_operation($test_list_init, $test_id, &$context) {
160
  simpletest_classloader_register();
161
  // Get working values.
162
  if (!isset($context['sandbox']['max'])) {
163
    // First iteration: initialize working values.
164
    $test_list = $test_list_init;
165
    $context['sandbox']['max'] = count($test_list);
166
    $test_results = array('#pass' => 0, '#fail' => 0, '#exception' => 0, '#debug' => 0);
167
  }
168
  else {
169
    // Nth iteration: get the current values where we last stored them.
170
    $test_list = $context['sandbox']['tests'];
171
    $test_results = $context['sandbox']['test_results'];
172
  }
173
  $max = $context['sandbox']['max'];
174

    
175
  // Perform the next test.
176
  $test_class = array_shift($test_list);
177
  $test = new $test_class($test_id);
178
  $test->run();
179
  $size = count($test_list);
180
  $info = $test->getInfo();
181

    
182
  module_invoke_all('test_finished', $test->results);
183

    
184
  // Gather results and compose the report.
185
  $test_results[$test_class] = $test->results;
186
  foreach ($test_results[$test_class] as $key => $value) {
187
    $test_results[$key] += $value;
188
  }
189
  $test_results[$test_class]['#name'] = $info['name'];
190
  $items = array();
191
  foreach (element_children($test_results) as $class) {
192
    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>');
193
  }
194
  $context['message'] = t('Processed test @num of @max - %test.', array('%test' => $info['name'], '@num' => $max - $size, '@max' => $max));
195
  $context['message'] .= '<div class="simpletest-' . ($test_results['#fail'] + $test_results['#exception'] ? 'fail' : 'pass') . '">Overall results: ' . _simpletest_format_summary_line($test_results) . '</div>';
196
  $context['message'] .= theme('item_list', array('items' => $items));
197

    
198
  // Save working values for the next iteration.
199
  $context['sandbox']['tests'] = $test_list;
200
  $context['sandbox']['test_results'] = $test_results;
201
  // The test_id is the only thing we need to save for the report page.
202
  $context['results']['test_id'] = $test_id;
203

    
204
  // Multistep processing: report progress.
205
  $context['finished'] = 1 - $size / $max;
206
}
207

    
208
/**
209
 * Implements callback_batch_finished().
210
 */
211
function _simpletest_batch_finished($success, $results, $operations, $elapsed) {
212
  if ($success) {
213
    drupal_set_message(t('The test run finished in @elapsed.', array('@elapsed' => $elapsed)));
214
  }
215
  else {
216
    // Use the test_id passed as a parameter to _simpletest_batch_operation().
217
    $test_id = $operations[0][1][1];
218

    
219
    // Retrieve the last database prefix used for testing and the last test
220
    // class that was run from. Use the information to read the lgo file
221
    // in case any fatal errors caused the test to crash.
222
    list($last_prefix, $last_test_class) = simpletest_last_test_get($test_id);
223
    simpletest_log_read($test_id, $last_prefix, $last_test_class);
224

    
225
    drupal_set_message(t('The test run did not successfully finish.'), 'error');
226
    drupal_set_message(t('Use the <em>Clean environment</em> button to clean-up temporary files and tables.'), 'warning');
227
  }
228
  module_invoke_all('test_group_finished');
229
}
230

    
231
/**
232
 * Get information about the last test that ran given a test ID.
233
 *
234
 * @param $test_id
235
 *   The test ID to get the last test from.
236
 * @return
237
 *   Array containing the last database prefix used and the last test class
238
 *   that ran.
239
 */
240
function simpletest_last_test_get($test_id) {
241
  $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();
242
  $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();
243
  return array($last_prefix, $last_test_class);
244
}
245

    
246
/**
247
 * Read the error log and report any errors as assertion failures.
248
 *
249
 * The errors in the log should only be fatal errors since any other errors
250
 * will have been recorded by the error handler.
251
 *
252
 * @param $test_id
253
 *   The test ID to which the log relates.
254
 * @param $prefix
255
 *   The database prefix to which the log relates.
256
 * @param $test_class
257
 *   The test class to which the log relates.
258
 * @param $during_test
259
 *   Indicates that the current file directory path is a temporary file
260
 *   file directory used during testing.
261
 * @return
262
 *   Found any entries in log.
263
 */
264
function simpletest_log_read($test_id, $prefix, $test_class, $during_test = FALSE) {
265
  $log = 'public://' . ($during_test ? '' : '/simpletest/' . substr($prefix, 10)) . '/error.log';
266
  $found = FALSE;
267
  if (file_exists($log)) {
268
    foreach (file($log) as $line) {
269
      if (preg_match('/\[.*?\] (.*?): (.*?) in (.*) on line (\d+)/', $line, $match)) {
270
        // Parse PHP fatal errors for example: PHP Fatal error: Call to
271
        // undefined function break_me() in /path/to/file.php on line 17
272
        $caller = array(
273
          'line' => $match[4],
274
          'file' => $match[3],
275
        );
276
        DrupalTestCase::insertAssert($test_id, $test_class, FALSE, $match[2], $match[1], $caller);
277
      }
278
      else {
279
        // Unknown format, place the entire message in the log.
280
        DrupalTestCase::insertAssert($test_id, $test_class, FALSE, $line, 'Fatal error');
281
      }
282
      $found = TRUE;
283
    }
284
  }
285
  return $found;
286
}
287

    
288
/**
289
 * Get a list of all of the tests provided by the system.
290
 *
291
 * The list of test classes is loaded from the registry where it looks for
292
 * files ending in ".test". Once loaded the test list is cached and stored in
293
 * a static variable. In order to list tests provided by disabled modules
294
 * hook_registry_files_alter() is used to forcefully add them to the registry.
295
 *
296
 * PSR-0 classes are found by searching the designated directory for each module
297
 * for files matching the PSR-0 standard.
298
 *
299
 * @return
300
 *   An array of tests keyed with the groups specified in each of the tests
301
 *   getInfo() method and then keyed by the test class. An example of the array
302
 *   structure is provided below.
303
 *
304
 *   @code
305
 *     $groups['Blog'] => array(
306
 *       'BlogTestCase' => array(
307
 *         'name' => 'Blog functionality',
308
 *         'description' => 'Create, view, edit, delete, ...',
309
 *         'group' => 'Blog',
310
 *       ),
311
 *     );
312
 *   @endcode
313
 * @see simpletest_registry_files_alter()
314
 */
315
function simpletest_test_get_all() {
316
  $groups = &drupal_static(__FUNCTION__);
317

    
318
  if (!$groups) {
319
    // Register a simple class loader for PSR-0 test classes.
320
    simpletest_classloader_register();
321

    
322
    // Load test information from cache if available, otherwise retrieve the
323
    // information from each tests getInfo() method.
324
    if ($cache = cache_get('simpletest', 'cache')) {
325
      $groups = $cache->data;
326
    }
327
    else {
328
      // Select all clases in files ending with .test.
329
      $classes = db_query("SELECT name FROM {registry} WHERE type = :type AND filename LIKE :name", array(':type' => 'class', ':name' => '%.test'))->fetchCol();
330

    
331
      // Also discover PSR-0 test classes, if the PHP version allows it.
332
      if (version_compare(PHP_VERSION, '5.3') > 0) {
333

    
334
        // Select all PSR-0 and PSR-4 classes in the Tests namespace of all
335
        // modules.
336
        $system_list = db_query("SELECT name, filename FROM {system}")->fetchAllKeyed();
337

    
338
        foreach ($system_list as $name => $filename) {
339
          $module_dir = DRUPAL_ROOT . '/' . dirname($filename);
340
          // Search both the 'lib/Drupal/mymodule' directory (for PSR-0 classes)
341
          // and the 'src' directory (for PSR-4 classes).
342
          foreach(array('lib/Drupal/' . $name, 'src') as $subdir) {
343
            // Build directory in which the test files would reside.
344
            $tests_dir = $module_dir . '/' . $subdir . '/Tests';
345
            // Scan it for test files if it exists.
346
            if (is_dir($tests_dir)) {
347
              $files = file_scan_directory($tests_dir, '/.*\.php/');
348
              if (!empty($files)) {
349
                foreach ($files as $file) {
350
                  // Convert the file name into the namespaced class name.
351
                  $replacements = array(
352
                    '/' => '\\',
353
                    $module_dir . '/' => '',
354
                    'lib/' => '',
355
                    'src/' => 'Drupal\\' . $name . '\\',
356
                    '.php' => '',
357
                  );
358
                  $classes[] = strtr($file->uri, $replacements);
359
                }
360
              }
361
            }
362
          }
363
        }
364
      }
365

    
366
      // Check that each class has a getInfo() method and store the information
367
      // in an array keyed with the group specified in the test information.
368
      $groups = array();
369
      foreach ($classes as $class) {
370
        // Test classes need to implement getInfo() to be valid.
371
        if (class_exists($class) && method_exists($class, 'getInfo')) {
372
          $info = call_user_func(array($class, 'getInfo'));
373

    
374
          // If this test class requires a non-existing module, skip it.
375
          if (!empty($info['dependencies'])) {
376
            foreach ($info['dependencies'] as $module) {
377
              // Pass FALSE as fourth argument so no error gets created for
378
              // the missing file.
379
              $found_module = drupal_get_filename('module', $module, NULL, FALSE);
380
              if (!$found_module) {
381
                continue 2;
382
              }
383
            }
384
          }
385

    
386
          $groups[$info['group']][$class] = $info;
387
        }
388
      }
389

    
390
      // Sort the groups and tests within the groups by name.
391
      uksort($groups, 'strnatcasecmp');
392
      foreach ($groups as $group => &$tests) {
393
        uksort($tests, 'strnatcasecmp');
394
      }
395

    
396
      // Allow modules extending core tests to disable originals.
397
      drupal_alter('simpletest', $groups);
398
      cache_set('simpletest', $groups);
399
    }
400
  }
401
  return $groups;
402
}
403

    
404
/*
405
 * Register a simple class loader that can find D8-style PSR-0 test classes.
406
 *
407
 * Other PSR-0 class loading can happen in contrib, but those contrib class
408
 * loader modules will not be enabled when testbot runs. So we need to do this
409
 * one in core.
410
 */
411
function simpletest_classloader_register() {
412

    
413
  // Prevent duplicate classloader registration.
414
  static $first_run = TRUE;
415
  if (!$first_run) {
416
    return;
417
  }
418
  $first_run = FALSE;
419

    
420
  // Only register PSR-0 class loading if we are on PHP 5.3 or higher.
421
  if (version_compare(PHP_VERSION, '5.3') > 0) {
422
    spl_autoload_register('_simpletest_autoload_psr4_psr0');
423
  }
424
}
425

    
426
/**
427
 * Autoload callback to find PSR-4 and PSR-0 test classes.
428
 *
429
 * Looks in the 'src/Tests' and in the 'lib/Drupal/mymodule/Tests' directory of
430
 * modules for the class.
431
 *
432
 * This will only work on classes where the namespace is of the pattern
433
 *   "Drupal\$extension\Tests\.."
434
 */
435
function _simpletest_autoload_psr4_psr0($class) {
436

    
437
  // Static cache for extension paths.
438
  // This cache is lazily filled as soon as it is needed.
439
  static $extensions;
440

    
441
  // Check that the first namespace fragment is "Drupal\"
442
  if (substr($class, 0, 7) === 'Drupal\\') {
443
    // Find the position of the second namespace separator.
444
    $pos = strpos($class, '\\', 7);
445
    // Check that the third namespace fragment is "\Tests\".
446
    if (substr($class, $pos, 7) === '\\Tests\\') {
447

    
448
      // Extract the second namespace fragment, which we expect to be the
449
      // extension name.
450
      $extension = substr($class, 7, $pos - 7);
451

    
452
      // Lazy-load the extension paths, both enabled and disabled.
453
      if (!isset($extensions)) {
454
        $extensions = db_query("SELECT name, filename FROM {system}")->fetchAllKeyed();
455
      }
456

    
457
      // Check if the second namespace fragment is a known extension name.
458
      if (isset($extensions[$extension])) {
459

    
460
        // Split the class into namespace and classname.
461
        $nspos = strrpos($class, '\\');
462
        $namespace = substr($class, 0, $nspos);
463
        $classname = substr($class, $nspos + 1);
464

    
465
        // Try the PSR-4 location first, and the PSR-0 location as a fallback.
466
        // Build the PSR-4 filepath where we expect the class to be defined.
467
        $psr4_path = dirname($extensions[$extension]) . '/src/' .
468
          str_replace('\\', '/', substr($namespace, strlen('Drupal\\' . $extension . '\\'))) . '/' .
469
          str_replace('_', '/', $classname) . '.php';
470

    
471
        // Include the file, if it does exist.
472
        if (file_exists($psr4_path)) {
473
          include $psr4_path;
474
        }
475
        else {
476
          // Build the PSR-0 filepath where we expect the class to be defined.
477
          $psr0_path = dirname($extensions[$extension]) . '/lib/' .
478
            str_replace('\\', '/', $namespace) . '/' .
479
            str_replace('_', '/', $classname) . '.php';
480

    
481
          // Include the file, if it does exist.
482
          if (file_exists($psr0_path)) {
483
            include $psr0_path;
484
          }
485
        }
486
      }
487
    }
488
  }
489
}
490

    
491
/**
492
 * Implements hook_registry_files_alter().
493
 *
494
 * Add the test files for disabled modules so that we get a list containing
495
 * all the avialable tests.
496
 */
497
function simpletest_registry_files_alter(&$files, $modules) {
498
  foreach ($modules as $module) {
499
    // Only add test files for disabled modules, as enabled modules should
500
    // already include any test files they provide.
501
    if (!$module->status) {
502
      $dir = $module->dir;
503
      if (!empty($module->info['files'])) {
504
        foreach ($module->info['files'] as $file) {
505
          if (substr($file, -5) == '.test') {
506
            $files["$dir/$file"] = array('module' => $module->name, 'weight' => $module->weight);
507
          }
508
        }
509
      }
510
    }
511
  }
512
}
513

    
514
/**
515
 * Generate test file.
516
 */
517
function simpletest_generate_file($filename, $width, $lines, $type = 'binary-text') {
518
  $text = '';
519
  for ($i = 0; $i < $lines; $i++) {
520
    // Generate $width - 1 characters to leave space for the "\n" character.
521
    for ($j = 0; $j < $width - 1; $j++) {
522
      switch ($type) {
523
        case 'text':
524
          $text .= chr(rand(32, 126));
525
          break;
526
        case 'binary':
527
          $text .= chr(rand(0, 31));
528
          break;
529
        case 'binary-text':
530
        default:
531
          $text .= rand(0, 1);
532
          break;
533
      }
534
    }
535
    $text .= "\n";
536
  }
537

    
538
  // Create filename.
539
  file_put_contents('public://' . $filename . '.txt', $text);
540
  return $filename;
541
}
542

    
543
/**
544
 * Remove all temporary database tables and directories.
545
 */
546
function simpletest_clean_environment() {
547
  simpletest_clean_database();
548
  simpletest_clean_temporary_directories();
549
  if (variable_get('simpletest_clear_results', TRUE)) {
550
    $count = simpletest_clean_results_table();
551
    drupal_set_message(format_plural($count, 'Removed 1 test result.', 'Removed @count test results.'));
552
  }
553
  else {
554
    drupal_set_message(t('Clear results is disabled and the test results table will not be cleared.'), 'warning');
555
  }
556

    
557
  // Detect test classes that have been added, renamed or deleted.
558
  registry_rebuild();
559
  cache_clear_all('simpletest', 'cache');
560
}
561

    
562
/**
563
 * Removed prefixed tables from the database that are left over from crashed tests.
564
 */
565
function simpletest_clean_database() {
566
  $tables = db_find_tables(Database::getConnection()->prefixTables('{simpletest}') . '%');
567
  $schema = drupal_get_schema_unprocessed('simpletest');
568
  $count = 0;
569
  foreach (array_diff_key($tables, $schema) as $table) {
570
    // Strip the prefix and skip tables without digits following "simpletest",
571
    // e.g. {simpletest_test_id}.
572
    if (preg_match('/simpletest\d+.*/', $table, $matches)) {
573
      db_drop_table($matches[0]);
574
      $count++;
575
    }
576
  }
577

    
578
  if ($count > 0) {
579
    drupal_set_message(format_plural($count, 'Removed 1 leftover table.', 'Removed @count leftover tables.'));
580
  }
581
  else {
582
    drupal_set_message(t('No leftover tables to remove.'));
583
  }
584
}
585

    
586
/**
587
 * Find all leftover temporary directories and remove them.
588
 */
589
function simpletest_clean_temporary_directories() {
590
  $count = 0;
591
  if (is_dir('public://simpletest')) {
592
    $files = scandir('public://simpletest');
593
    foreach ($files as $file) {
594
      $path = 'public://simpletest/' . $file;
595
      if (is_dir($path) && is_numeric($file)) {
596
        file_unmanaged_delete_recursive($path);
597
        $count++;
598
      }
599
    }
600
  }
601

    
602
  if ($count > 0) {
603
    drupal_set_message(format_plural($count, 'Removed 1 temporary directory.', 'Removed @count temporary directories.'));
604
  }
605
  else {
606
    drupal_set_message(t('No temporary directories to remove.'));
607
  }
608
}
609

    
610
/**
611
 * Clear the test result tables.
612
 *
613
 * @param $test_id
614
 *   Test ID to remove results for, or NULL to remove all results.
615
 * @return
616
 *   The number of results removed.
617
 */
618
function simpletest_clean_results_table($test_id = NULL) {
619
  if (variable_get('simpletest_clear_results', TRUE)) {
620
    if ($test_id) {
621
      $count = db_query('SELECT COUNT(test_id) FROM {simpletest_test_id} WHERE test_id = :test_id', array(':test_id' => $test_id))->fetchField();
622

    
623
      db_delete('simpletest')
624
        ->condition('test_id', $test_id)
625
        ->execute();
626
      db_delete('simpletest_test_id')
627
        ->condition('test_id', $test_id)
628
        ->execute();
629
    }
630
    else {
631
      $count = db_query('SELECT COUNT(test_id) FROM {simpletest_test_id}')->fetchField();
632

    
633
      // Clear test results.
634
      db_delete('simpletest')->execute();
635
      db_delete('simpletest_test_id')->execute();
636
    }
637

    
638
    return $count;
639
  }
640
  return 0;
641
}
642

    
643
/**
644
 * Implements hook_mail_alter().
645
 *
646
 * Aborts sending of messages with ID 'simpletest_cancel_test'.
647
 *
648
 * @see MailTestCase::testCancelMessage()
649
 */
650
function simpletest_mail_alter(&$message) {
651
  if ($message['id'] == 'simpletest_cancel_test') {
652
    $message['send'] = FALSE;
653
  }
654
}