Projet

Général

Profil

Paste
Télécharger (23,5 ko) Statistiques
| Branche: | Révision:

root / drupal7 / modules / simpletest / simpletest.module @ 582db59d

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
              if (!drupal_get_filename('module', $module)) {
378
                continue 2;
379
              }
380
            }
381
          }
382

    
383
          $groups[$info['group']][$class] = $info;
384
        }
385
      }
386

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

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

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

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

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

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

    
434
  // Static cache for extension paths.
435
  // This cache is lazily filled as soon as it is needed.
436
  static $extensions;
437

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

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

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

    
454
      // Check if the second namespace fragment is a known extension name.
455
      if (isset($extensions[$extension])) {
456

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

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

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

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

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

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

    
535
  // Create filename.
536
  file_put_contents('public://' . $filename . '.txt', $text);
537
  return $filename;
538
}
539

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

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

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

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

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

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

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

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

    
630
      // Clear test results.
631
      db_delete('simpletest')->execute();
632
      db_delete('simpletest_test_id')->execute();
633
    }
634

    
635
    return $count;
636
  }
637
  return 0;
638
}
639

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