simpletest.module 30.6 KB
Newer Older
1
2
<?php

3
use Drupal\Core\Database\Database;
4
use Drupal\Core\Page\HtmlPage;
5
use Drupal\simpletest\TestBase;
6
use Symfony\Component\Process\PhpExecutableFinder;
7

8
9
10
11
12
/**
 * @file
 * Provides testing functionality.
 */

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

/**
33
 * Implements hook_menu().
34
35
 */
function simpletest_menu() {
36
  $items['admin/config/development/testing'] = array(
37
    'title' => 'Testing',
38
    'description' => 'Run tests against Drupal core and your modules. These tests help assure that your site code is working as designed.',
39
    'route_name' => 'simpletest.test_form',
40
    'weight' => -5,
41
  );
42
  $items['admin/config/development/testing/results/%'] = array(
43
44
    'title' => 'Test result',
    'description' => 'View result of tests.',
45
    'route_name' => 'simpletest.result_form',
46
  );
47
48
49
  return $items;
}

50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/**
 * Implements hook_menu_link_defaults().
 */
function simpletest_menu_link_defaults() {
  $links['simpletest.admin.config.development.testing'] = array(
    'link_title' => 'Testing',
    'description' => 'Run tests against Drupal core and your modules. These tests help assure that your site code is working as designed.',
    'route_name' => 'simpletest.test_form',
    'parent' => 'system.admin.config.development',
    'weight' => -5,
  );

  return $links;
}

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

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

93
/**
94
 * Implements hook_js_alter().
95
96
97
98
99
 */
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';
100
101
  if (array_key_exists($simpletest, $javascript) && array_key_exists('core/misc/tableselect.js', $javascript)) {
    $javascript[$simpletest]['weight'] = $javascript['core/misc/tableselect.js']['weight'] - 1;
102
103
104
  }
}

105
function _simpletest_format_summary_line($summary) {
106
  $args = array(
107
108
109
    '@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'),
110
111
112
113
114
115
  );
  if (!$summary['#debug']) {
    return t('@pass, @fail, and @exception', $args);
  }
  $args['@debug'] = format_plural(isset($summary['#debug']) ? $summary['#debug'] : 0, '1 debug message', '@count debug messages');
  return t('@pass, @fail, @exception, and @debug', $args);
116
117
}

118
/**
119
120
 * Actually runs tests.
 *
121
122
123
124
125
 * @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.
126
 */
127
function simpletest_run_tests($test_list, $reporter = 'drupal') {
128
129
130
  $test_id = db_insert('simpletest_test_id')
    ->useDefaults(array('test_id'))
    ->execute();
131

132
  $phpunit_tests = isset($test_list['UnitTest']) ? $test_list['UnitTest'] : array();
133
134
135
136
  if ($phpunit_tests) {
    $phpunit_results = simpletest_run_phpunit_tests($test_id, $phpunit_tests);
    simpletest_process_phpunit_results($phpunit_results);
  }
137
138
139
140
141
142
143
144
145

  if (!array_key_exists('WebTest', $test_list) || empty($test_list['WebTest'])) {
    // Early return if there are no WebTests to run.
    return $test_id;
  }

  // Contine with SimpleTests only.
  $test_list = $test_list['WebTest'];

146
  // Clear out the previous verbose files.
147
  file_unmanaged_delete_recursive('public://simpletest/verbose');
148

149
150
151
152
153
154
  // 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();

155
  $batch = array(
156
    'title' => t('Running tests'),
157
158
    'operations' => array(
      array('_simpletest_batch_operation', array($test_list, $test_id)),
159
    ),
160
    'finished' => '_simpletest_batch_finished',
161
    'progress_message' => '',
162
    'css' => array(drupal_get_path('module', 'simpletest') . '/css/simpletest.module.css'),
163
    'init_message' => t('Processing test @num of @max - %test.', array('%test' => $info['name'], '@num' => '1', '@max' => count($test_list))),
164
165
  );
  batch_set($batch);
166

167
  \Drupal::moduleHandler()->invokeAll('test_group_started');
168

169
  return $test_id;
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
/**
 * Executes phpunit tests and returns the results of the run.
 *
 * @param $test_id
 *   The current test ID.
 * @param $unescaped_test_classnames
 *   An array of test class names, including full namespaces, to be passed as
 *   a regular expression to phpunit's --filter option.
 *
 * @return array
 *   The parsed results of phpunit's junit xml output, in the format of the
 *   simpletest table's schema.
 */
function simpletest_run_phpunit_tests($test_id, array $unescaped_test_classnames) {
  $phpunit_file = simpletest_phpunit_xml_filepath($test_id);
  simpletest_phpunit_run_command($unescaped_test_classnames, $phpunit_file);
  return simpletest_phpunit_xml_to_rows($test_id, $phpunit_file);
}

/**
 * Inserts the parsed phpunit results into the simpletest table.
 *
 * @param array $phpunit_results
 *   An array of test results returned from simpletest_phpunit_xml_to_rows.
 */
function simpletest_process_phpunit_results($phpunit_results) {
  // Insert the results of the phpunit test run into the db so the results are
  // displayed along with simpletest's results.
  if (!empty($phpunit_results)) {
    $query = db_insert('simpletest')->fields(array_keys($phpunit_results[0]));
    foreach ($phpunit_results as $result) {
      $query->values($result);
    }
    $query->execute();
  }
}

/**
 * Returns the path to use for phpunit's --log-junit option.
 *
 * @param $test_id
 *   The current test ID.
 * @return string
 *   Path to the phpunit xml file to use for the current test_id.
 */
function simpletest_phpunit_xml_filepath($test_id) {
  return drupal_realpath('public://simpletest') . '/phpunit-' . $test_id . '.xml';
}

/**
 * Returns the path to core's phpunit.xml.dist configuration file.
 *
 * @return string
 *   Path to core's phpunit.xml.dist configuration file.
 */
function simpletest_phpunit_configuration_filepath() {
  return DRUPAL_ROOT . '/core/phpunit.xml.dist';
}

/**
 * Executes the phpunit command.
 *
 * @param array $unescaped_test_classnames
 *   An array of test class names, including full namespaces, to be passed as
 *   a regular expression to phpunit's --filter option.
 * @param string $phpunit_file
 *   A filepath to use for phpunit's --log-junit option.
 */
function simpletest_phpunit_run_command(array $unescaped_test_classnames, $phpunit_file) {
241
  $phpunit_bin = simpletest_phpunit_command();
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

  // Double escape namespaces so they'll work in a regexp.
  $escaped_test_classnames = array_map(function($class) {
    return addslashes($class);
  }, $unescaped_test_classnames);

  $filter_string = implode("|", $escaped_test_classnames);

  $command = array(
    $phpunit_bin,
    '--filter',
    escapeshellarg($filter_string),
    '--log-junit',
    escapeshellarg($phpunit_file),
  );

  // Need to change directories before running the command so that we can use
  // relative paths in the configuration file's exclusions.
  $old_cwd = getcwd();
  chdir(DRUPAL_ROOT . "/core");

  // exec in a subshell so that the environment is isolated when running tests
  // via the simpletest UI.
  $ret = exec(join($command, " "));
  chdir($old_cwd);
  return $ret;
}

270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
/**
 * Returns the command to run PHPUnit.
 */
function simpletest_phpunit_command() {
  // Don't use the committed version in composer's bin dir if running on
  // windows.
  if (substr(PHP_OS, 0, 3) == 'WIN') {
    $php_executable_finder = new PhpExecutableFinder();
    $php = $php_executable_finder->find();
    $phpunit_bin = escapeshellarg($php) . " -f " . escapeshellarg(DRUPAL_ROOT . "/core/vendor/phpunit/phpunit/composer/bin/phpunit") . " --";
  }
  else {
    $phpunit_bin = DRUPAL_ROOT . "/core/vendor/bin/phpunit";
  }
  return $phpunit_bin;
}

287
288
289
290
/**
 * Batch operation callback.
 */
function _simpletest_batch_operation($test_list_init, $test_id, &$context) {
291
  simpletest_classloader_register();
292
293
294
295
296
  // Get working values.
  if (!isset($context['sandbox']['max'])) {
    // First iteration: initialize working values.
    $test_list = $test_list_init;
    $context['sandbox']['max'] = count($test_list);
297
    $test_results = array('#pass' => 0, '#fail' => 0, '#exception' => 0, '#debug' => 0);
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
  }
  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();

313
  \Drupal::moduleHandler()->invokeAll('test_finished', array($test->results));
314

315
  // Gather results and compose the report.
316
  $test_results[$test_class] = $test->results;
317
318
319
320
321
322
  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) {
323
    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>');
324
  }
325
326
  $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>';
327
328
329
330
331
  $item_list = array(
    '#theme' => 'item_list',
    '#items' => $items,
  );
  $context['message'] .= drupal_render($item_list);
332
333
334
335
336
337
338
339
340
341
342

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

343
function _simpletest_batch_finished($success, $results, $operations, $elapsed) {
344
  if ($success) {
345
    drupal_set_message(t('The test run finished in @elapsed.', array('@elapsed' => $elapsed)));
346
347
  }
  else {
348
    // Use the test_id passed as a parameter to _simpletest_batch_operation().
349
350
351
352
353
354
355
356
    $test_id = $operations[0][1][1];

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

357
    drupal_set_message(t('The test run did not successfully finish.'), 'error');
358
    drupal_set_message(t('Use the <em>Clean environment</em> button to clean-up temporary files and tables.'), 'warning');
359
  }
360
  \Drupal::moduleHandler()->invokeAll('test_group_finished');
361
362
}

363
/**
364
365
366
367
368
369
370
371
372
 * Get information about the last test that ran given a test ID.
 *
 * @param $test_id
 *   The test ID to get the last test from.
 * @return
 *   Array containing the last database prefix used and the last test class
 *   that ran.
 */
function simpletest_last_test_get($test_id) {
373
374
  $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();
  $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();
375
376
377
  return array($last_prefix, $last_test_class);
}

378
379
380
381
382
383
384
/**
 * Read the error log and report any errors as assertion failures.
 *
 * The errors in the log should only be fatal errors since any other errors
 * will have been recorded by the error handler.
 *
 * @param $test_id
385
386
387
388
389
390
391
392
393
394
 *   The test ID to which the log relates.
 * @param $prefix
 *   The database prefix to which the log relates.
 * @param $test_class
 *   The test class to which the log relates.
 * @param $during_test
 *   Indicates that the current file directory path is a temporary file
 *   file directory used during testing.
 * @return
 *   Found any entries in log.
395
 */
396
function simpletest_log_read($test_id, $prefix, $test_class, $during_test = FALSE) {
397
  $log = 'public://' . ($during_test ? '' : '/simpletest/' . substr($prefix, 10)) . '/error.log';
398
  $found = FALSE;
399
400
  if (file_exists($log)) {
    foreach (file($log) as $line) {
401
402
403
      if (preg_match('/\[.*?\] (.*?): (.*?) in (.*) on line (\d+)/', $line, $match)) {
        // Parse PHP fatal errors for example: PHP Fatal error: Call to
        // undefined function break_me() in /path/to/file.php on line 17
404
        $caller = array(
405
406
          'line' => $match[4],
          'file' => $match[3],
407
        );
408
        TestBase::insertAssert($test_id, $test_class, FALSE, $match[2], $match[1], $caller);
409
410
      }
      else {
411
        // Unknown format, place the entire message in the log.
412
        TestBase::insertAssert($test_id, $test_class, FALSE, $line, 'Fatal error');
413
      }
414
      $found = TRUE;
415
416
    }
  }
417
  return $found;
418
419
}

420
/**
421
422
 * Get a list of all of the tests provided by the system.
 *
423
424
425
 * The list of test classes is loaded by searching the designated directory for
 * each module for files matching the PSR-0 standard. Once loaded the test list
 * is cached and stored in a static variable.
426
 *
427
428
429
430
 * @param string $module
 *   Name of a module. If set then only tests belonging to this module are
 *   returned.
 *
431
 * @return
432
433
434
435
436
 *   An array of tests keyed with the groups specified in each of the tests
 *   getInfo() method and then keyed by the test class. An example of the array
 *   structure is provided below.
 *
 *   @code
437
438
439
440
441
 *     $groups['Block'] => array(
 *       'BlockTestCase' => array(
 *         'name' => 'Block functionality',
 *         'description' => 'Add, edit and delete custom block...',
 *         'group' => 'Block',
442
443
444
 *       ),
 *     );
 *   @endcode
445
 */
446
447
448
function simpletest_test_get_all($module = NULL) {
  $all_groups = &drupal_static(__FUNCTION__);
  $cid = "simpletest:$module";
449

450
451
452
  if (!isset($all_groups[$cid])) {
    $all_groups[$cid] = array();
    $groups = &$all_groups[$cid];
453
454
455
456
    // Make sure that namespaces for disabled modules are registered so that the
    // checks below will find them.
    simpletest_classloader_register();

457
458
    // Load test information from cache if available, otherwise retrieve the
    // information from each tests getInfo() method.
459
    if ($cache = cache()->get($cid)) {
460
      $groups = $cache->data;
461
    }
462
    else {
463
      // Select all PSR-0 classes in the Tests namespace of all modules.
464
      $classes = array();
465
466
      $module_data = system_rebuild_module_data();
      $all_data = $module_data + system_rebuild_theme_data();
467
      $all_data += drupal_system_listing('/\.profile$/', 'profiles', 'name');
468
469
470
471
472
473
      // If module is set then we keep only that one module.
      if (isset($module)) {
        $all_data = array(
          $module => $all_data[$module],
        );
      }
474
      foreach ($all_data as $name => $data) {
475
        // Build directory in which the test files would reside.
476
        $tests_dir = DRUPAL_ROOT . '/' . dirname($data->uri) . '/lib/Drupal/' . $name . '/Tests';
477
478
479
480
        // Scan it for test files if it exists.
        if (is_dir($tests_dir)) {
          $files = file_scan_directory($tests_dir, '/.*\.php/');
          if (!empty($files)) {
481
            $basedir = DRUPAL_ROOT . '/' . dirname($data->uri) . '/lib/';
482
483
484
485
486
487
488
489
490
491
492
493
494
            foreach ($files as $file) {
              // Convert the file name into the namespaced class name.
              $replacements = array(
                '/' => '\\',
                $basedir => '',
                '.php' => '',
              );
              $classes[] = strtr($file->uri, $replacements);
            }
          }
        }
      }

495
496
      // Check that each class has a getInfo() method and store the information
      // in an array keyed with the group specified in the test information.
497
      $groups = array();
498
      foreach ($classes as $class) {
499
        // Test classes need to implement getInfo() to be valid.
500
        if (class_exists($class) && method_exists($class, 'getInfo')) {
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
          $reflectionClass = new ReflectionClass($class);
          // Skip abstract classes and interfaces.
          if ($reflectionClass->isInstantiable()) {
            $reflectionMethod = new ReflectionMethod($class, 'getInfo');
            $declaringClass = $reflectionMethod->getDeclaringClass()->getName();
            // Avoid testing intermediate classes which do not implement the
            // method.
            if ($class == $declaringClass) {
              $info = call_user_func(array($class, 'getInfo'));
            }
            else {
              continue;
            }
          }
          else {
            continue;
          }
518
519
          // If this test class requires a non-existing module, skip it.
          if (!empty($info['dependencies'])) {
520
521
            foreach ($info['dependencies'] as $dependency) {
              if (!isset($dependency_data[$dependency])) {
522
523
524
                continue 2;
              }
            }
525
          }
526

527
528
529
          $groups[$info['group']][$class] = $info;
        }
      }
530

531
532
      // Sort the groups and tests within the groups by name.
      uksort($groups, 'strnatcasecmp');
533
      foreach ($groups as &$tests) {
534
        uksort($tests, 'strnatcasecmp');
535
      }
536

537
538
      // Allow modules extending core tests to disable originals.
      drupal_alter('simpletest', $groups);
539
      cache()->set($cid, $groups);
540
    }
541
  }
542
  return $all_groups[$cid];
543
}
544

545
546
547
548
/**
 * Registers namespaces for disabled modules.
 */
function simpletest_classloader_register() {
549
550
551
552
553
554
555
  // @see drupal_get_filename()
  $types = array(
    'theme_engine' => array('dir' => 'themes/engines', 'extension' => 'engine'),
    'module' => array('dir' => 'modules', 'extension' => 'module'),
    'theme' => array('dir' => 'themes', 'extension' => 'info'),
    'profile' => array('dir' => 'profiles', 'extension' => 'profile'),
  );
556
557
558

  $classloader = drupal_classloader();

559
560
561
562
  foreach ($types as $type => $info) {
    $matches = drupal_system_listing('/^' . DRUPAL_PHP_FUNCTION_PATTERN . '\.' . $info['extension'] . '$/', $info['dir']);
    foreach ($matches as $name => $file) {
      drupal_classloader_register($name, dirname($file->uri));
563
      $classloader->add('Drupal\\' . $name . '\\Tests', DRUPAL_ROOT . '/' . dirname($file->uri) . '/tests');
564
565
566
      // While being there, prime drupal_get_filename().
      drupal_get_filename($type, $name, $file->uri);
    }
567
  }
568

569
  // Register the core test directory so we can find \Drupal\UnitTestCase.
570
  $classloader->add('Drupal\\Tests', DRUPAL_ROOT . '/core/tests');
571
572
}

573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
/**
 * Generate test file.
 */
function simpletest_generate_file($filename, $width, $lines, $type = 'binary-text') {
  $size = $width * $lines - $lines;

  // Generate random text
  $text = '';
  for ($i = 0; $i < $size; $i++) {
    switch ($type) {
      case 'text':
        $text .= chr(rand(32, 126));
        break;
      case 'binary':
        $text .= chr(rand(0, 31));
        break;
      case 'binary-text':
      default:
        $text .= rand(0, 1);
        break;
    }
  }
595
596
  // Add \n for symmetrical file.
  $text = wordwrap($text, $width - 1, "\n", TRUE) . "\n";
597
598

  // Create filename.
599
  file_put_contents('public://' . $filename . '.txt', $text);
600
601
602
  return $filename;
}

603
604
605
606
607
608
/**
 * Remove all temporary database tables and directories.
 */
function simpletest_clean_environment() {
  simpletest_clean_database();
  simpletest_clean_temporary_directories();
609
  if (\Drupal::config('simpletest.settings')->get('clear_results')) {
610
611
612
613
614
615
    $count = simpletest_clean_results_table();
    drupal_set_message(format_plural($count, 'Removed 1 test result.', 'Removed @count test results.'));
  }
  else {
    drupal_set_message(t('Clear results is disabled and the test results table will not be cleared.'), 'warning');
  }
616
617

  // Detect test classes that have been added, renamed or deleted.
618
  cache()->delete('simpletest');
619
  cache()->delete('simpletest_phpunit');
620
621
622
}

/**
623
 * Remove prefixed tables from the database from crashed tests.
624
625
 */
function simpletest_clean_database() {
626
  $tables = db_find_tables(Database::getConnection()->prefixTables('{simpletest}') . '%');
627
  $schema = drupal_get_schema_unprocessed('simpletest');
628
  $count = 0;
629
  foreach (array_diff_key($tables, $schema) as $table) {
630
631
    // Strip the prefix and skip tables without digits following "simpletest",
    // e.g. {simpletest_test_id}.
632
    if (preg_match('/simpletest\d+.*/', $table, $matches)) {
633
      db_drop_table($matches[0]);
634
      $count++;
635
    }
636
637
  }

638
639
  if ($count > 0) {
    drupal_set_message(format_plural($count, 'Removed 1 leftover table.', 'Removed @count leftover tables.'));
640
641
  }
  else {
642
    drupal_set_message(t('No leftover tables to remove.'));
643
644
645
646
  }
}

/**
647
 * Find all leftover temporary directories and remove them.
648
649
650
 */
function simpletest_clean_temporary_directories() {
  $count = 0;
651
652
653
654
  if (is_dir('public://simpletest')) {
    $files = scandir('public://simpletest');
    foreach ($files as $file) {
      $path = 'public://simpletest/' . $file;
655
      if (is_dir($path) && (is_numeric($file) || strpos($file, 'config_simpletest') !== FALSE)) {
656
        file_unmanaged_delete_recursive($path, array('Drupal\simpletest\TestBase', 'filePreDeleteCallback'));
657
658
        $count++;
      }
659
660
661
662
    }
  }

  if ($count > 0) {
663
    drupal_set_message(format_plural($count, 'Removed 1 temporary directory.', 'Removed @count temporary directories.'));
664
665
666
667
668
669
  }
  else {
    drupal_set_message(t('No temporary directories to remove.'));
  }
}

670
/**
671
672
673
674
675
 * Clear the test result tables.
 *
 * @param $test_id
 *   Test ID to remove results for, or NULL to remove all results.
 * @return
676
 *   The number of results removed.
677
 */
678
function simpletest_clean_results_table($test_id = NULL) {
679
  if (\Drupal::config('simpletest.settings')->get('clear_results')) {
680
    if ($test_id) {
681
      $count = db_query('SELECT COUNT(test_id) FROM {simpletest_test_id} WHERE test_id = :test_id', array(':test_id' => $test_id))->fetchField();
682

683
      db_delete('simpletest')
684
685
        ->condition('test_id', $test_id)
        ->execute();
686
      db_delete('simpletest_test_id')
687
688
689
690
        ->condition('test_id', $test_id)
        ->execute();
    }
    else {
691
      $count = db_query('SELECT COUNT(test_id) FROM {simpletest_test_id}')->fetchField();
692

693
      // Clear test results.
694
695
      db_delete('simpletest')->execute();
      db_delete('simpletest_test_id')->execute();
696
    }
697

698
    return $count;
699
  }
700
  return 0;
701
}
702
703
704
705
706
707
708
709
710
711
712
713
714

/**
 * Implements hook_mail_alter().
 *
 * Aborts sending of messages with ID 'simpletest_cancel_test'.
 *
 * @see MailTestCase::testCancelMessage()
 */
function simpletest_mail_alter(&$message) {
  if ($message['id'] == 'simpletest_cancel_test') {
    $message['send'] = FALSE;
  }
}
715
716
717
718
719
720
721

/**
 * Implements hook_library_info().
 */
function simpletest_library_info() {
  $libraries['drupal.simpletest'] = array(
    'title' => 'Simpletest',
722
    'version' => \Drupal::VERSION,
723
724
725
726
    'js' => array(
      drupal_get_path('module', 'simpletest') . '/simpletest.js' => array(),
    ),
    'css' => array(
727
      drupal_get_path('module', 'simpletest') . '/css/simpletest.module.css' => array(),
728
729
730
731
    ),
    'dependencies' => array(
      array('system', 'jquery'),
      array('system', 'drupal'),
732
      array('system', 'drupalSettings'),
733
734
      array('system', 'jquery.once'),
      array('system', 'drupal.tableselect'),
735
      array('system', 'drupal.debounce'),
736
737
738
739
740
    ),
  );

  return $libraries;
}
741
742

/**
743
 * Gets PHPUnit Classes.
744
 *
745
746
747
748
749
750
 * @param string $module
 *   Name of a module. If set then only tests belonging to this module is
 *   returned.
 *
 * @return array
 *   Returns an array of test classes.
751
 */
752
function simpletest_phpunit_get_available_tests($module = NULL) {
753
  // Try to load the class names array from cache.
754
755
  $cid = 'simpletest_phpunit:' . $module;
  if ($cache = \Drupal::cache()->get($cid)) {
756
757
758
    $test_classes = $cache->data;
  }
  else {
759
760
761
762
    if ($module) {
      $prefix = 'Drupal\\' . $module . '\\';
      $n = strlen($prefix);
    }
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
    // If there was no cached data available we have to find the tests.
    // Load the PHPUnit configuration file, which tells us where to find the
    // tests.
    $phpunit_config = simpletest_phpunit_configuration_filepath();
    $configuration = PHPUnit_Util_Configuration::getInstance($phpunit_config);
    // Find all the tests and get a list of unique class names.
    $test_suite = $configuration->getTestSuiteConfiguration(NULL);
    $test_classes = array();
    foreach ($test_suite as $test) {
      // PHPUnit returns a warning message if something is wrong with a test,
      // throw an exception to avoid an error when trying to call getInfo() on
      // this.
      if ($test instanceof PHPUnit_Framework_Warning) {
        throw new RuntimeException($test->getMessage());
      }
778

779
      $name = get_class($test);
780
      if (!array_key_exists($name, $test_classes) && (!$module || substr($name, 0, $n) == $prefix)) {
781
782
        $test_classes[$name] = $test->getInfo();
      }
783
    }
784
785

    // Since we have recalculated, we now need to store the new data into cache.
786
    \Drupal::cache()->set($cid, $test_classes);
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
  }

  return $test_classes;
}

/**
 * Converts phpunit's junit xml output to an array.
 *
 * The returned array of rows is in a format that can be inserted into the
 * simpletest results table.
 *
 * @param $test_id
 *   The current test ID.
 * @param $phpunit_xml_file
 *   Path to the phpunit xml file.
 */
function simpletest_phpunit_xml_to_rows($test_id, $phpunit_xml_file) {
804
805
806
807
  $contents = @file_get_contents($phpunit_xml_file);
  if (!$contents) {
    return;
  }
808
809
810
811
  $xml = new SimpleXMLElement($contents);
  $records = array();
  foreach ($xml->testsuite as $testsuite) {
    foreach ($testsuite as $suite) {
812
813
814
815
816
817
818
819
      // The file element won't be on testcase objects created with
      // @dataProvider, so just use the one from the test suite at this level
      // because it should be the same.
      $file = (string) $suite->attributes()->file;

      $testcases = simpletest_phpunit_find_testcases($suite);
      foreach ($testcases as $testcase) {
        $records[] = simpletest_phpunit_testcase_to_row($test_id, $testcase, $file);
820
821
822
823
824
      }
    }
  }
  return $records;
}
825
826
827
828

/**
 * Find all testcases recursively from a testsuite list.
 *
829
 * @param \SimpleXMLElement[] $suite
830
831
832
833
834
835
836
837
838
839
840
841
842
843
 *   The list of testcases contained in the PHPUnit XML.
 *
 * @return array
 *   A list of all testcases.
 */
function simpletest_phpunit_find_testcases($suite) {
  $testcases = array();

  foreach ($suite as $testcase) {
    // Beside from being 'testcases', it could be also a group of testcases.
    // This happens if you use a data provider in the phpunit tests.
    if ($testcase->getName() === 'testcase') {
      $testcases[] = $testcase;
    }
844
    elseif (isset($testcase->testcase) && ((int) $testcase->attributes()->tests) > 0) {
845
      foreach ($testcase->testcase as $childtestcase) {
846
847
        // Add the class attribute since the child test case will not have it.
        $childtestcase->addAttribute('class', $suite->attributes()->name);
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
        $testcases[] = $childtestcase;
      }
    }
  }
  return $testcases;
}

/**
 * Converts a PHPUnit testcase result to a simpletest result row.
 *
 * @param int $test_id
 *   The current test ID.
 * @param \SimpleXMLElement $testcase
 *   The PHPUnit testcase represented as XML element.
 * @param string $file
 *   The path to test file, which was executed.
 *
 * @return array
 *   An array containg the simpletest result row.
 */
function simpletest_phpunit_testcase_to_row($test_id, \SimpleXMLElement $testcase, $file) {
  $message = '';
  $pass = TRUE;
  if ($testcase->failure) {
    $lines = explode("\n", $testcase->failure);
    $message = $lines[2];
    $pass = FALSE;
  }
  if ($testcase->error) {
    $message = $testcase->error;
    $pass = FALSE;
  }

  $attributes = $testcase->attributes();

  $record = array(
    'test_id' => $test_id,
    'test_class' => (string) $attributes->class,
    'status' => $pass ? 'pass' : 'fail',
    'message' => $message,
    // @todo: Check on the proper values for this.
    'message_group' => 'Other',
    'function' => $attributes->class . '->' . $attributes->name . '()',
    'line' => $attributes->line ?: 0,
    'file' => $file,
  );
  return $record;
}