summaryrefslogtreecommitdiff
path: root/modules/simpletest/simpletest.module
blob: cad833381edd44f9da13bd8534678bf6779645f7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
<?php
// $Id$

/**
 * @file
 * Provides testing functionality.
 */

/**
 * Implementation of hook_help().
 */
function simpletest_help($path, $arg) {
  switch ($path) {
    case 'admin/help#simpletest':
      $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>';
      return $output;
  }
}

/**
 * Implementation of hook_menu().
 */
function simpletest_menu() {
  $items['admin/development'] = array(
    'title' => 'Development',
    'description' => 'Development tools.',
    'position' => 'right',
    'weight' => -7,
    'page callback' => 'system_admin_menu_block_page',
    'access callback' => 'system_admin_menu_block_access',
    'access arguments' => array('admin/development', 'access administration pages'),
  );
  $items['admin/development/testing'] = array(
    'title' => 'Testing',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('simpletest_test_form'),
    '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'),
  );
  $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,
  );
  return $items;
}

/**
 * Implementation of hook_perm().
 */
function simpletest_perm() {
  return array(
    '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.'))),
    ),
  );
}

/**
 * Implementation of hook_theme().
 */
function simpletest_theme() {
  return array(
    'simpletest_test_table' => array(
      'arguments' => array('table' => NULL),
      'file' => 'simpletest.pages.inc',
    ),
    'simpletest_result_summary' => array(
      'arguments' => array('form' => NULL),
      'file' => 'simpletest.pages.inc',
    ),
  );
}

/**
 * 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;
  }
}

function _simpletest_format_summary_line($summary) {
  return t('@pass, @fail, and @exception', array(
    '@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'),
  ));
}

/**
 * Actually runs tests.
 *
 * @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.
 */
function simpletest_run_tests($test_list, $reporter = 'drupal') {
  cache_clear_all();
  $test_id = db_insert('simpletest_test_id')->useDefaults(array('test_id'))->execute();

  // 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();

  $batch = array(
    'title' => t('Running SimpleTests'),
    'operations' => array(
      array('_simpletest_batch_operation', array($test_list, $test_id)),
    ),
    'finished' => '_simpletest_batch_finished',
    'progress_message' => '',
    'css' => array(drupal_get_path('module', 'simpletest') . '/simpletest.css'),
    'init_message' => t('Processing test @num of @max - %test.', array('%test' => $info['name'], '@num' => '1', '@max' => count($test_list))),
  );
  batch_set($batch);

  module_invoke_all('test_group_started');

  // 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).
  batch_process('admin/development/testing/results/' . $test_id);
}

/**
 * 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();

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

  // Gather results and compose the report.
  $test_results[$test_class] = $test->results;
  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) {
    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>');
  }
  $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);

  // 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;
}

function _simpletest_batch_finished($success, $results, $operations, $elapsed) {
  if ($success) {
    drupal_set_message(t('The tests finished in @elapsed.', array('@elapsed' => $elapsed)));
  }
  else {
    drupal_set_message(t('The tests did not successfully finish.'), 'error');
  }
  module_invoke_all('test_group_finished');
}

/**
 * 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() {
  static $classes;
  if (!isset($classes)) {
    require_once DRUPAL_ROOT . '/' . drupal_get_path('module', 'simpletest') . '/drupal_web_test_case.php';
    $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)) {
        foreach (file_scan_directory($tests_directory, '/\.test$/') as $file) {
          $files[] = $file->filepath;
        }
      }
    }

    $existing_classes = get_declared_classes();
    foreach ($files as $file) {
      include_once DRUPAL_ROOT . '/' . $file;
    }
    $classes = array_values(array_diff(get_declared_classes(), $existing_classes));
    foreach ($classes as $key => $class) {
      if (!is_subclass_of($class, 'DrupalTestCase') || !method_exists($class, 'getInfo')) {
        unset($classes[$key]);
      }
    }
  }
  if (count($classes) == 0) {
    drupal_set_message('No test cases found.', 'error');
    return FALSE;
  }
  return $classes;
}

/**
 * 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();
  foreach ($tests as $test) {
    $info = call_user_func(array($test, 'getInfo'));
    $groups[$info['group']][$test] = $info;
  }
  uksort($groups, 'strnatcasecmp');
  return $groups;
}

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

/**
 * Removed prefixed tables from the database that are left over from crashed tests.
 */
function simpletest_clean_database() {
  $tables = db_find_tables(Database::getConnection()->prefixTables('{simpletest}') . '%');
  $schema = drupal_get_schema_unprocessed('simpletest');
  $ret = array();
  foreach (array_diff_key($tables, $schema) as $table) {
    // Strip the prefix and skip tables without digits following "simpletest",
    // e.g. {simpletest_test_id}.
    if (preg_match('/simpletest\d+.*/', $table, $matches)) {
      db_drop_table($ret, $matches[0]);
    }
  }

  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) {
    $path = file_directory_path() . '/' . $file;
    if (is_dir($path) && preg_match('/^simpletest\d+/', $file)) {
      file_unmanaged_delete_recursive($path);
      $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.'));
  }
}

/**
 * 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.
 */
function simpletest_clean_results_table($test_id = NULL) {
  if (variable_get('simpletest_clear_results', TRUE)) {
    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}'));

      // Clear test results.
      db_delete("simpletest")->execute();
      db_delete("simpletest_test_id")->execute();
    }

    return $count;
  }
  return FALSE;
}