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

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

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

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

/**
32
 * Implements hook_menu().
33 34
 */
function simpletest_menu() {
35
  $items['admin/config/development/testing'] = array(
36
    'title' => 'Testing',
37
    'description' => 'Run tests against Drupal core and your modules. These tests help assure that your site code is working as designed.',
38
    'route_name' => 'simpletest_test_form',
39
    'weight' => -5,
40
  );
41
  $items['admin/config/development/testing/list'] = array(
42 43 44
    'title' => 'List',
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );
45
  $items['admin/config/development/testing/settings'] = array(
46
    'title' => 'Settings',
47
    'route_name' => 'simpletest_settings',
48 49
    'access arguments' => array('administer unit tests'),
    'type' => MENU_LOCAL_TASK,
50
    'weight' => 100,
51
  );
52
  $items['admin/config/development/testing/results/%'] = array(
53 54
    'title' => 'Test result',
    'description' => 'View result of tests.',
55
    'route_name' => 'simpletest_result_form',
56
  );
57 58 59 60
  return $items;
}

/**
61
 * Implements hook_permission().
62
 */
63
function simpletest_permission() {
64
  return array(
65
    'administer unit tests' => array(
66
      'title' => t('Administer tests'),
67
      'restrict access' => TRUE,
68
    ),
69 70 71 72
  );
}

/**
73
 * Implements hook_theme().
74 75 76
 */
function simpletest_theme() {
  return array(
77
    'simpletest_test_table' => array(
78
      'render element' => 'table',
79
      'file' => 'simpletest.theme.inc',
80 81
    ),
    'simpletest_result_summary' => array(
82
      'render element' => 'form',
83
      'file' => 'simpletest.theme.inc',
84 85 86 87
    ),
  );
}

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

100
function _simpletest_format_summary_line($summary) {
101
  $args = array(
102 103 104
    '@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'),
105 106 107 108 109 110
  );
  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);
111 112
}

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

127
  $phpunit_tests = isset($test_list['UnitTest']) ? $test_list['UnitTest'] : array();
128 129 130 131
  if ($phpunit_tests) {
    $phpunit_results = simpletest_run_phpunit_tests($test_id, $phpunit_tests);
    simpletest_process_phpunit_results($phpunit_results);
  }
132 133 134 135 136 137 138 139 140

  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'];

141
  // Clear out the previous verbose files.
142
  file_unmanaged_delete_recursive('public://simpletest/verbose');
143

144 145 146 147 148 149
  // 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();

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

162
  Drupal::moduleHandler()->invokeAll('test_group_started');
163

164
  return $test_id;
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
/**
 * 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) {
236
  $phpunit_bin = simpletest_phpunit_command();
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

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

265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
/**
 * 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;
}

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

308
  Drupal::moduleHandler()->invokeAll('test_finished', array($test->results));
309

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

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

338
function _simpletest_batch_finished($success, $results, $operations, $elapsed) {
339
  if ($success) {
340
    drupal_set_message(t('The test run finished in @elapsed.', array('@elapsed' => $elapsed)));
341 342
  }
  else {
343
    // Use the test_id passed as a parameter to _simpletest_batch_operation().
344 345 346 347 348 349 350 351
    $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);

352
    drupal_set_message(t('The test run did not successfully finish.'), 'error');
353
    drupal_set_message(t('Use the <em>Clean environment</em> button to clean-up temporary files and tables.'), 'warning');
354
  }
355
  Drupal::moduleHandler()->invokeAll('test_group_finished');
356 357
}

358
/**
359 360 361 362 363 364 365 366 367
 * 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) {
368 369
  $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();
370 371 372
  return array($last_prefix, $last_test_class);
}

373 374 375 376 377 378 379
/**
 * 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
380 381 382 383 384 385 386 387 388 389
 *   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.
390
 */
391
function simpletest_log_read($test_id, $prefix, $test_class, $during_test = FALSE) {
392
  $log = 'public://' . ($during_test ? '' : '/simpletest/' . substr($prefix, 10)) . '/error.log';
393
  $found = FALSE;
394 395
  if (file_exists($log)) {
    foreach (file($log) as $line) {
396 397 398
      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
399
        $caller = array(
400 401
          'line' => $match[4],
          'file' => $match[3],
402
        );
403
        TestBase::insertAssert($test_id, $test_class, FALSE, $match[2], $match[1], $caller);
404 405
      }
      else {
406
        // Unknown format, place the entire message in the log.
407
        TestBase::insertAssert($test_id, $test_class, FALSE, $line, 'Fatal error');
408
      }
409
      $found = TRUE;
410 411
    }
  }
412
  return $found;
413 414
}

415
/**
416 417
 * Get a list of all of the tests provided by the system.
 *
418 419 420
 * 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.
421
 *
422
 * @return
423 424 425 426 427
 *   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
428 429 430 431 432
 *     $groups['Block'] => array(
 *       'BlockTestCase' => array(
 *         'name' => 'Block functionality',
 *         'description' => 'Add, edit and delete custom block...',
 *         'group' => 'Block',
433 434 435
 *       ),
 *     );
 *   @endcode
436
 */
437 438
function simpletest_test_get_all() {
  $groups = &drupal_static(__FUNCTION__);
439

440
  if (!$groups) {
441 442 443 444
    // Make sure that namespaces for disabled modules are registered so that the
    // checks below will find them.
    simpletest_classloader_register();

445 446
    // Load test information from cache if available, otherwise retrieve the
    // information from each tests getInfo() method.
447
    if ($cache = cache()->get('simpletest')) {
448
      $groups = $cache->data;
449
    }
450
    else {
451
      // Select all PSR-0 classes in the Tests namespace of all modules.
452
      $classes = array();
453 454
      $module_data = system_rebuild_module_data();
      $all_data = $module_data + system_rebuild_theme_data();
455
      $all_data += drupal_system_listing('/\.profile$/', 'profiles', 'name');
456
      foreach ($all_data as $name => $data) {
457
        // Build directory in which the test files would reside.
458
        $tests_dir = DRUPAL_ROOT . '/' . dirname($data->uri) . '/lib/Drupal/' . $name . '/Tests';
459 460 461 462
        // Scan it for test files if it exists.
        if (is_dir($tests_dir)) {
          $files = file_scan_directory($tests_dir, '/.*\.php/');
          if (!empty($files)) {
463
            $basedir = DRUPAL_ROOT . '/' . dirname($data->uri) . '/lib/';
464 465 466 467 468 469 470 471 472 473 474 475 476
            foreach ($files as $file) {
              // Convert the file name into the namespaced class name.
              $replacements = array(
                '/' => '\\',
                $basedir => '',
                '.php' => '',
              );
              $classes[] = strtr($file->uri, $replacements);
            }
          }
        }
      }

477 478
      // Check that each class has a getInfo() method and store the information
      // in an array keyed with the group specified in the test information.
479
      $groups = array();
480
      foreach ($classes as $class) {
481
        // Test classes need to implement getInfo() to be valid.
482 483 484
        if (class_exists($class) && method_exists($class, 'getInfo')) {
          $info = call_user_func(array($class, 'getInfo'));

485 486 487
          // If this test class requires a non-existing module, skip it.
          if (!empty($info['dependencies'])) {
            foreach ($info['dependencies'] as $module) {
488
              if (!isset($module_data[$module])) {
489 490 491
                continue 2;
              }
            }
492
          }
493

494 495 496
          $groups[$info['group']][$class] = $info;
        }
      }
497

498 499 500 501
      // Sort the groups and tests within the groups by name.
      uksort($groups, 'strnatcasecmp');
      foreach ($groups as $group => &$tests) {
        uksort($tests, 'strnatcasecmp');
502
      }
503

504 505
      // Allow modules extending core tests to disable originals.
      drupal_alter('simpletest', $groups);
506
      cache()->set('simpletest', $groups);
507
    }
508
  }
509
  return $groups;
510
}
511

512 513 514 515
/**
 * Registers namespaces for disabled modules.
 */
function simpletest_classloader_register() {
516 517 518 519 520 521 522
  // @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'),
  );
523 524 525

  $classloader = drupal_classloader();

526 527 528 529
  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));
530
      $classloader->add('Drupal\\' . $name . '\\Tests', DRUPAL_ROOT . '/' . dirname($file->uri) . '/tests');
531 532 533
      // While being there, prime drupal_get_filename().
      drupal_get_filename($type, $name, $file->uri);
    }
534
  }
535

536
  // Register the core test directory so we can find \Drupal\UnitTestCase.
537
  $classloader->add('Drupal\\Tests', DRUPAL_ROOT . '/core/tests');
538 539
}

540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561
/**
 * 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;
    }
  }
562 563
  // Add \n for symmetrical file.
  $text = wordwrap($text, $width - 1, "\n", TRUE) . "\n";
564 565

  // Create filename.
566
  file_put_contents('public://' . $filename . '.txt', $text);
567 568 569
  return $filename;
}

570 571 572 573 574 575
/**
 * Remove all temporary database tables and directories.
 */
function simpletest_clean_environment() {
  simpletest_clean_database();
  simpletest_clean_temporary_directories();
576
  if (Drupal::config('simpletest.settings')->get('clear_results')) {
577 578 579 580 581 582
    $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');
  }
583 584

  // Detect test classes that have been added, renamed or deleted.
585
  cache()->delete('simpletest');
586
  cache()->delete('simpletest_phpunit');
587 588 589
}

/**
590
 * Remove prefixed tables from the database from crashed tests.
591 592
 */
function simpletest_clean_database() {
593
  $tables = db_find_tables(Database::getConnection()->prefixTables('{simpletest}') . '%');
594
  $schema = drupal_get_schema_unprocessed('simpletest');
595
  $count = 0;
596
  foreach (array_diff_key($tables, $schema) as $table) {
597 598
    // Strip the prefix and skip tables without digits following "simpletest",
    // e.g. {simpletest_test_id}.
599
    if (preg_match('/simpletest\d+.*/', $table, $matches)) {
600
      db_drop_table($matches[0]);
601
      $count++;
602
    }
603 604
  }

605 606
  if ($count > 0) {
    drupal_set_message(format_plural($count, 'Removed 1 leftover table.', 'Removed @count leftover tables.'));
607 608
  }
  else {
609
    drupal_set_message(t('No leftover tables to remove.'));
610 611 612 613
  }
}

/**
614
 * Find all leftover temporary directories and remove them.
615 616 617
 */
function simpletest_clean_temporary_directories() {
  $count = 0;
618 619 620 621
  if (is_dir('public://simpletest')) {
    $files = scandir('public://simpletest');
    foreach ($files as $file) {
      $path = 'public://simpletest/' . $file;
622
      if (is_dir($path) && (is_numeric($file) || strpos($file, 'config_simpletest') !== FALSE)) {
623
        file_unmanaged_delete_recursive($path, array('Drupal\simpletest\TestBase', 'filePreDeleteCallback'));
624 625
        $count++;
      }
626 627 628 629
    }
  }

  if ($count > 0) {
630
    drupal_set_message(format_plural($count, 'Removed 1 temporary directory.', 'Removed @count temporary directories.'));
631 632 633 634 635 636
  }
  else {
    drupal_set_message(t('No temporary directories to remove.'));
  }
}

637
/**
638 639 640 641 642
 * Clear the test result tables.
 *
 * @param $test_id
 *   Test ID to remove results for, or NULL to remove all results.
 * @return
643
 *   The number of results removed.
644
 */
645
function simpletest_clean_results_table($test_id = NULL) {
646
  if (Drupal::config('simpletest.settings')->get('clear_results')) {
647
    if ($test_id) {
648
      $count = db_query('SELECT COUNT(test_id) FROM {simpletest_test_id} WHERE test_id = :test_id', array(':test_id' => $test_id))->fetchField();
649

650
      db_delete('simpletest')
651 652
        ->condition('test_id', $test_id)
        ->execute();
653
      db_delete('simpletest_test_id')
654 655 656 657
        ->condition('test_id', $test_id)
        ->execute();
    }
    else {
658
      $count = db_query('SELECT COUNT(test_id) FROM {simpletest_test_id}')->fetchField();
659

660
      // Clear test results.
661 662
      db_delete('simpletest')->execute();
      db_delete('simpletest_test_id')->execute();
663
    }
664

665
    return $count;
666
  }
667
  return 0;
668
}
669 670 671 672 673 674 675 676 677 678 679 680 681

/**
 * 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;
  }
}
682 683 684 685 686 687 688 689 690 691 692 693

/**
 * Implements hook_library_info().
 */
function simpletest_library_info() {
  $libraries['drupal.simpletest'] = array(
    'title' => 'Simpletest',
    'version' => VERSION,
    'js' => array(
      drupal_get_path('module', 'simpletest') . '/simpletest.js' => array(),
    ),
    'css' => array(
694
      drupal_get_path('module', 'simpletest') . '/css/simpletest.module.css' => array(),
695 696 697 698
    ),
    'dependencies' => array(
      array('system', 'jquery'),
      array('system', 'drupal'),
699
      array('system', 'drupalSettings'),
700 701
      array('system', 'jquery.once'),
      array('system', 'drupal.tableselect'),
702
      array('system', 'drupal.debounce'),
703 704 705 706 707
    ),
  );

  return $libraries;
}
708 709 710 711 712 713 714 715

/**
 * Get PHPUnit Classes
 *
 * @param bool $name_only
 *  If TRUE, returns a flat array of class names only.
 */
function simpletest_phpunit_get_available_tests() {
716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735
  // Try to load the class names array from cache.
  if ($cache = \Drupal::cache()->get('simpletest_phpunit')) {
    $test_classes = $cache->data;
  }
  else {
    // 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());
      }
736

737 738 739 740
      $name = get_class($test);
      if (!array_key_exists($name, $test_classes)) {
        $test_classes[$name] = $test->getInfo();
      }
741
    }
742 743 744

    // Since we have recalculated, we now need to store the new data into cache.
    \Drupal::cache()->set('simpletest_phpunit', $test_classes);
745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761
  }

  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) {
762 763 764 765
  $contents = @file_get_contents($phpunit_xml_file);
  if (!$contents) {
    return;
  }
766 767 768 769
  $xml = new SimpleXMLElement($contents);
  $records = array();
  foreach ($xml->testsuite as $testsuite) {
    foreach ($testsuite as $suite) {
770 771 772 773 774 775 776 777
      // 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);
778 779 780 781 782
      }
    }
  }
  return $records;
}
783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801

/**
 * Find all testcases recursively from a testsuite list.
 *
 * @param array $suite
 *   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;
    }
802
    elseif (isset($testcase->testcase) && ((int) $testcase->attributes()->tests) > 0) {
803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851
      foreach ($testcase->testcase as $childtestcase) {
        $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;
}