simpletest.module 13.1 KB
Newer Older
1 2 3
<?php
// $Id$

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

9 10 11 12 13 14
/**
 * Implementation of hook_help().
 */
function simpletest_help($path, $arg) {
  switch ($path) {
    case 'admin/help#simpletest':
15 16 17 18 19
      $output  = '<p>' . t('The SimpleTest module is a framework for running automated unit tests in Drupal. 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.') . '</p>';
      $output .= '<p>' . t('Visit <a href="@admin-simpletest">Administer >> Site building >> SimpleTest</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.)', array('@admin-simpletest' => url('admin/development/testing'))) . '</p>';
      $output .= '<p>' . t('After the tests have 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 a 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 fails or exceptions, the results are expanded, and the tests that had issues will be indicated in red or pink rows. Use these results to refine your code and tests until all tests return a pass.') . '</p>';
      $output .= '<p>' . t('For more information on creating and modifying your own tests, see the <a href="@simpletest-api">SimpleTest API Documentation</a> in the Drupal handbook.', array('@simpletest-api' => 'http://drupal.org/simpletest')) . '</p>';
      $output .= '<p>' . t('For more information, see the online handbook entry for <a href="@simpletest">SimpleTest module</a>.', array('@simpletest' => 'http://drupal.org/handbook/modules/simpletest')) . '</p>';
20 21 22 23 24 25 26 27
      return $output;
  }
}

/**
 * Implementation of hook_menu().
 */
function simpletest_menu() {
28 29 30 31 32 33 34 35 36
  $items['admin/development'] = array(
    'title' => 'Development',
    'description' => 'Development tools.',
    'position' => 'right',
    'weight' => -7,
    'page callback' => 'system_admin_menu_block_page',
    'access arguments' => array('access administration pages'),
  );
  $items['admin/development/testing'] = array(
37
    'title' => 'Testing',
38 39
    'page callback' => 'drupal_get_form',
    'page arguments' => array('simpletest_test_form'),
40 41 42
    'description' => 'Run tests against Drupal core and your active modules. These tests help assure that your site code is working as designed.',
    'access arguments' => array('administer unit tests'),
  );
43 44 45 46 47 48 49 50
  $items['admin/development/testing/results/%'] = array(
    'title' => 'Test result',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('simpletest_result_form', 4),
    'description' => 'View result of tests.',
    'access arguments' => array('administer unit tests'),
    'type' => MENU_CALLBACK,
  );
51 52 53 54 55 56 57 58
  return $items;
}

/**
 * Implementation of hook_perm().
 */
function simpletest_perm() {
  return array(
59 60 61 62
    'administer unit tests' => array(
      'title' => t('Administer unit tests'),
      'description' => t('Manage and run automated testing. %warning', array('%warning' => t('Warning: Give to trusted roles only; this permission has security implications.'))),
    ),
63 64 65 66
  );
}

/**
67
 * Implementation of hook_theme().
68 69 70
 */
function simpletest_theme() {
  return array(
71
    'simpletest_test_table' => array(
72
      'arguments' => array('table' => NULL),
73
      'file' => 'simpletest.pages.inc',
74 75
    ),
    'simpletest_result_summary' => array(
76
      'arguments' => array('form' => NULL),
77
      'file' => 'simpletest.pages.inc',
78 79 80 81
    ),
  );
}

82 83 84 85 86 87 88 89 90 91 92 93
/**
 * Implementation of hook_js_alter().
 */
function simpletest_js_alter(&$javascript) {
  // Since SimpleTest is a special use case for the table select, stick the
  // SimpleTest JavaScript above the table select.
  $simpletest = drupal_get_path('module', 'simpletest') . '/simpletest.js';
  if (array_key_exists($simpletest, $javascript) && array_key_exists('misc/tableselect.js', $javascript)) {
    $javascript[$simpletest]['weight'] = $javascript['misc/tableselect.js']['weight'] - 1;
  }
}

94
function _simpletest_format_summary_line($summary) {
95
  return t('@pass, @fail, and @exception', array(
96 97 98 99 100 101
    '@pass' => format_plural(isset($summary['#pass']) ? $summary['#pass'] : 0, '1 pass', '@count passes'),
    '@fail' => format_plural(isset($summary['#fail']) ? $summary['#fail'] : 0, '1 fail', '@count fails'),
    '@exception' => format_plural(isset($summary['#exception']) ? $summary['#exception'] : 0, '1 exception', '@count exceptions'),
  ));
}

102
/**
103 104
 * Actually runs tests.
 *
105 106 107 108 109
 * @param $test_list
 *   List of tests to run.
 * @param $reporter
 *   Which reporter to use. Allowed values are: text, xml, html and drupal,
 *   drupal being the default.
110
 */
111
function simpletest_run_tests($test_list, $reporter = 'drupal') {
112
  cache_clear_all();
113
  $test_id = db_insert('simpletest_test_id')->useDefaults(array('test_id'))->execute();
114

115 116 117 118 119 120
  // Get the info for the first test being run.
  $first_test = array_shift($test_list);
  $first_instance = new $first_test();
  array_unshift($test_list, $first_test);
  $info = $first_instance->getInfo();

121 122 123 124
  $batch = array(
    'title' => t('Running SimpleTests'),
    'operations' => array(
      array('_simpletest_batch_operation', array($test_list, $test_id)),
125
    ),
126
    'finished' => '_simpletest_batch_finished',
127
    'progress_message' => '',
128
    'css' => array(drupal_get_path('module', 'simpletest') . '/simpletest.css'),
129
    'init_message' => t('Processing test @num of @max - %test.', array('%test' => $info['name'], '@num' => '1', '@max' => count($test_list))),
130 131
  );
  batch_set($batch);
132

133
  module_invoke_all('test_group_started');
134

135 136 137 138 139 140
  // Normally, the forms portion of the batch API takes care of calling
  // batch_process(), but in the process it saves the whole $form into the
  // database (which is huge for the test selection form).
  // By calling batch_process() directly, we skip that behavior and ensure
  // that we don't exceed the size of data that can be sent to the database
  // (max_allowed_packet on MySQL).
141
  batch_process('admin/development/testing/results/' . $test_id);
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
}

/**
 * Batch operation callback.
 */
function _simpletest_batch_operation($test_list_init, $test_id, &$context) {
  // Ensure that all classes are loaded before we unserialize some instances.
  simpletest_get_all_tests();

  // Get working values.
  if (!isset($context['sandbox']['max'])) {
    // First iteration: initialize working values.
    $test_list = $test_list_init;
    $context['sandbox']['max'] = count($test_list);
    $test_results = array('#pass' => 0, '#fail' => 0, '#exception' => 0);
  }
  else {
    // Nth iteration: get the current values where we last stored them.
    $test_list = $context['sandbox']['tests'];
    $test_results = $context['sandbox']['test_results'];
  }
  $max = $context['sandbox']['max'];

  // Perform the next test.
  $test_class = array_shift($test_list);
  $test = new $test_class($test_id);
  $test->run();
  $size = count($test_list);
  $info = $test->getInfo();

172 173
  module_invoke_all('test_finished', $test->results);

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

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

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

198
function _simpletest_batch_finished($success, $results, $operations, $elapsed) {
199
  if ($success) {
200
    drupal_set_message(t('The tests finished in @elapsed.', array('@elapsed' => $elapsed)));
201 202 203 204
  }
  else {
    drupal_set_message(t('The tests did not successfully finish.'), 'error');
  }
205
  module_invoke_all('test_group_finished');
206 207 208 209 210 211 212 213 214 215
}

/**
 * Get a list of all of the tests.
 *
 * @return
 *   An array of tests, with the class name as the keys and the instantiated
 *   versions of the classes as the values.
 */
function simpletest_get_all_tests() {
216 217
  static $classes;
  if (!isset($classes)) {
218
    require_once DRUPAL_ROOT . '/' . drupal_get_path('module', 'simpletest') . '/drupal_web_test_case.php';
219 220 221 222 223 224 225 226 227 228
    $files = array();
    foreach (array_keys(module_rebuild_cache()) as $module) {
      $module_path = drupal_get_path('module', $module);
      $test = $module_path . "/$module.test";
      if (file_exists($test)) {
        $files[] = $test;
      }

      $tests_directory = $module_path . '/tests';
      if (is_dir($tests_directory)) {
229
        foreach (file_scan_directory($tests_directory, '/\.test$/') as $file) {
230
          $files[] = $file->filepath;
231 232
        }
      }
233 234 235 236
    }

    $existing_classes = get_declared_classes();
    foreach ($files as $file) {
237
      include_once DRUPAL_ROOT . '/' . $file;
238 239 240
    }
    $classes = array_values(array_diff(get_declared_classes(), $existing_classes));
    foreach ($classes as $key => $class) {
241
      if (!is_subclass_of($class, 'DrupalTestCase') || !method_exists($class, 'getInfo')) {
242
        unset($classes[$key]);
243
      }
244
    }
245
  }
246
  if (count($classes) == 0) {
247 248 249
    drupal_set_message('No test cases found.', 'error');
    return FALSE;
  }
250
  return $classes;
251
}
252

253 254 255 256 257 258 259 260 261
/**
 * Categorize the tests into groups.
 *
 * @param $tests
 *   A list of tests from simpletest_get_all_tests.
 * @see simpletest_get_all_tests.
 */
function simpletest_categorize_tests($tests) {
  $groups = array();
262 263 264
  foreach ($tests as $test) {
    $info = call_user_func(array($test, 'getInfo'));
    $groups[$info['group']][$test] = $info;
265
  }
266
  uksort($groups, 'strnatcasecmp');
267
  return $groups;
268 269 270 271 272 273 274 275
}

/**
 * Remove all temporary database tables and directories.
 */
function simpletest_clean_environment() {
  simpletest_clean_database();
  simpletest_clean_temporary_directories();
276 277
  $count = simpletest_clean_results_table();
  drupal_set_message(t('Removed @count test results.', array('@count' => $count)));
278 279 280
}

/**
281
 * Removed prefixed tables from the database that are left over from crashed tests.
282 283
 */
function simpletest_clean_database() {
284
  $tables = db_find_tables(Database::getConnection()->prefixTables('{simpletest}') . '%');
285
  $schema = drupal_get_schema_unprocessed('simpletest');
286
  $ret = array();
287
  foreach (array_diff_key($tables, $schema) as $table) {
288 289
    // Strip the prefix and skip tables without digits following "simpletest",
    // e.g. {simpletest_test_id}.
290 291 292
    if (preg_match('/simpletest\d+.*/', $table, $matches)) {
      db_drop_table($ret, $matches[0]);
    }
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
  }

  if (count($ret) > 0) {
    drupal_set_message(t('Removed @count left over tables.', array('@count' => count($ret))));
  }
  else {
    drupal_set_message(t('No left over tables to remove.'));
  }
}

/**
 * Find all left over temporary directories and remove them.
 */
function simpletest_clean_temporary_directories() {
  $files = scandir(file_directory_path());
  $count = 0;
  foreach ($files as $file) {
310
    $path = file_directory_path() . '/' . $file;
311
    if (is_dir($path) && preg_match('/^simpletest\d+/', $file)) {
312
      file_unmanaged_delete_recursive($path);
313 314 315 316 317 318 319 320 321 322 323 324
      $count++;
    }
  }

  if ($count > 0) {
    drupal_set_message(t('Removed @count temporary directories.', array('@count' => $count)));
  }
  else {
    drupal_set_message(t('No temporary directories to remove.'));
  }
}

325
/**
326 327 328 329 330 331
 * Clear the test result tables.
 *
 * @param $test_id
 *   Test ID to remove results for, or NULL to remove all results.
 * @return
 *   The number of results removed or FALSE.
332
 */
333
function simpletest_clean_results_table($test_id = NULL) {
334
  if (variable_get('simpletest_clear_results', TRUE)) {
335 336 337 338 339 340 341 342 343 344 345 346
    if ($test_id) {
      $count = db_result(db_query('SELECT COUNT(test_id) FROM {simpletest_test_id} WHERE test_id = :test_id', array(':test_id' => $test_id)));

      db_delete("simpletest")
        ->condition('test_id', $test_id)
        ->execute();
      db_delete("simpletest_test_id")
        ->condition('test_id', $test_id)
        ->execute();
    }
    else {
      $count = db_result(db_query('SELECT COUNT(test_id) FROM {simpletest_test_id}'));
347

348 349 350 351
      // Clear test results.
      db_delete("simpletest")->execute();
      db_delete("simpletest_test_id")->execute();
    }
352

353
    return $count;
354
  }
355
  return FALSE;
356
}