Projet

Général

Profil

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

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

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
 * Batch operation callback.
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
function _simpletest_batch_finished($success, $results, $operations, $elapsed) {
209
  if ($success) {
210
    drupal_set_message(t('The test run finished in @elapsed.', array('@elapsed' => $elapsed)));
211
  }
212
  else {
213
    // Use the test_id passed as a parameter to _simpletest_batch_operation().
214
    $test_id = $operations[0][1][1];
215

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

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

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

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

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

    
315
  if (!$groups) {
316
    // Register a simple class loader for PSR-0 test classes.
317
    simpletest_classloader_register();
318

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

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

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

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

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

    
371
          // If this test class requires a non-existing module, skip it.
372
          if (!empty($info['dependencies'])) {
373
            foreach ($info['dependencies'] as $module) {
374
              if (!drupal_get_filename('module', $module)) {
375
                continue 2;
376
              }
377
            }
378
          }
379

    
380
          $groups[$info['group']][$class] = $info;
381
        }
382
      }
383

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

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

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

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

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

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

    
431
  // Static cache for extension paths.
432
  // This cache is lazily filled as soon as it is needed.
433
  static $extensions;
434

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

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

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

    
451
      // Check if the second namespace fragment is a known extension name.
452
      if (isset($extensions[$extension])) {
453

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

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

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

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

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

    
508
/**
509
 * Generate test file.
510
 */
511
function simpletest_generate_file($filename, $width, $lines, $type = 'binary-text') {
512
  $size = $width * $lines - $lines;
513

    
514
  // Generate random text
515
  $text = '';
516
  for ($i = 0; $i < $size; $i++) {
517
    switch ($type) {
518
      case 'text':
519
        $text .= chr(rand(32, 126));
520
        break;
521
      case 'binary':
522
        $text .= chr(rand(0, 31));
523
        break;
524
      case 'binary-text':
525
      default:
526
        $text .= rand(0, 1);
527
        break;
528
    }
529
  }
530
  $text = wordwrap($text, $width - 1, "\n", TRUE) . "\n"; // Add \n for symmetrical file.
531

    
532
  // Create filename.
533
  file_put_contents('public://' . $filename . '.txt', $text);
534
  return $filename;
535
}
536

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

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

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

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

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

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

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

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

    
627
      // Clear test results.
628
      db_delete('simpletest')->execute();
629
      db_delete('simpletest_test_id')->execute();
630
    }
631

    
632
    return $count;
633
  }
634
  return 0;
635
}
636

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