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

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

8
use Drupal\Core\Asset\AttachedAssetsInterface;
9
use Drupal\Core\Database\Database;
10
use Drupal\Core\Render\Element;
11
use Drupal\Core\Routing\RouteMatchInterface;
12
use Drupal\simpletest\TestBase;
13
use Drupal\Core\Test\TestDatabase;
14
use Drupal\simpletest\TestDiscovery;
15
use Drupal\Tests\Listeners\SimpletestUiPrinter;
16
use PHPUnit\Framework\TestCase;
17
use Symfony\Component\Process\PhpExecutableFinder;
18
use Drupal\Core\Test\TestStatus;
19

20
/**
21
 * Implements hook_help().
22
 */
23
function simpletest_help($route_name, RouteMatchInterface $route_match) {
24
25
  switch ($route_name) {
    case 'help.page.simpletest':
26
27
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
28
      $output .= '<p>' . t('The Testing module provides a framework for running automated 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 <a href=":simpletest">online documentation for the Testing module</a>.', [':simpletest' => 'https://www.drupal.org/documentation/modules/simpletest']) . '</p>';
29
30
31
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl>';
      $output .= '<dt>' . t('Running tests') . '</dt>';
32
      $output .= '<dd><p>' . 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.', [':admin-simpletest' => \Drupal::url('simpletest.test_form')]) . '</p>';
33
      $output .= '<p>' . 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.') . '</p></dd>';
34
      $output .= '</dl>';
35
      return $output;
36

37
    case 'simpletest.test_form':
38
39
      $output = t('Select the test(s) or test group(s) you would like to run, and click <em>Run tests</em>.');
      return $output;
40
41
42
43
  }
}

/**
44
 * Implements hook_theme().
45
46
 */
function simpletest_theme() {
47
48
49
50
51
  return [
    'simpletest_result_summary' => [
      'variables' => ['label' => NULL, 'items' => [], 'pass' => 0, 'fail' => 0, 'exception' => 0, 'debug' => 0],
    ],
  ];
52
53
}

54
/**
55
 * Implements hook_js_alter().
56
 */
57
function simpletest_js_alter(&$javascript, AttachedAssetsInterface $assets) {
58
59
60
  // 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';
61
62
  if (array_key_exists($simpletest, $javascript) && array_key_exists('core/misc/tableselect.js', $javascript)) {
    $javascript[$simpletest]['weight'] = $javascript['core/misc/tableselect.js']['weight'] - 1;
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
/**
 * Prepares variables for simpletest result summary templates.
 *
 * Default template: simpletest-result-summary.html.twig.
 *
 * @param array $variables
 *   An associative array containing:
 *   - label: An optional label to be rendered before the results.
 *   - ok: The overall group result pass or fail.
 *   - pass: The number of passes.
 *   - fail: The number of fails.
 *   - exception: The number of exceptions.
 *   - debug: The number of debug messages.
 */
function template_preprocess_simpletest_result_summary(&$variables) {
  $variables['items'] = _simpletest_build_summary_line($variables);
}

/**
 * Formats each test result type pluralized summary.
 *
 * @param array $summary
 *   A summary of the test results.
 *
 * @return array
 *   The pluralized test summary items.
 */
function _simpletest_build_summary_line($summary) {
  $translation = \Drupal::translation();
  $items['pass'] = $translation->formatPlural($summary['pass'], '1 pass', '@count passes');
  $items['fail'] = $translation->formatPlural($summary['fail'], '1 fail', '@count fails');
  $items['exception'] = $translation->formatPlural($summary['exception'], '1 exception', '@count exceptions');
  if ($summary['debug']) {
    $items['debug'] = $translation->formatPlural($summary['debug'], '1 debug message', '@count debug messages');
100
  }
101
102
103
104
105
106
107
108
109
110
111
112
113
114
  return $items;
}

/**
 * Formats test result summaries into a comma separated string for run-tests.sh.
 *
 * @param array $summary
 *   A summary of the test results.
 *
 * @return string
 *   A concatenated string of the formatted test results.
 */
function _simpletest_format_summary_line($summary) {
  $parts = _simpletest_build_summary_line($summary);
115
  return implode(', ', $parts);
116
117
}

118
/**
119
 * Runs tests.
120
 *
121
122
 * @param $test_list
 *   List of tests to run.
123
124
125
 *
 * @return string
 *   The test ID.
126
 */
127
function simpletest_run_tests($test_list) {
128
129
130
131
132
133
134
  // We used to separate PHPUnit and Simpletest tests for a performance
  // optimization. In order to support backwards compatibility check if these
  // keys are set and create a single test list.
  // @todo https://www.drupal.org/node/2748967 Remove BC support in Drupal 9.
  if (isset($test_list['simpletest'])) {
    $test_list = array_merge($test_list, $test_list['simpletest']);
    unset($test_list['simpletest']);
135
  }
136
137
138
  if (isset($test_list['phpunit'])) {
    $test_list = array_merge($test_list, $test_list['phpunit']);
    unset($test_list['phpunit']);
139
140
  }

141
  $test_id = db_insert('simpletest_test_id')
142
    ->useDefaults(['test_id'])
143
    ->execute();
144

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

148
  // Get the info for the first test being run.
149
  $first_test = reset($test_list);
150
  $info = TestDiscovery::getTestInfo($first_test);
151

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

164
  \Drupal::moduleHandler()->invokeAll('test_group_started');
165

166
  return $test_id;
167
168
}

169
/**
170
 * Executes PHPUnit tests and returns the results of the run.
171
172
173
174
175
 *
 * @param $test_id
 *   The current test ID.
 * @param $unescaped_test_classnames
 *   An array of test class names, including full namespaces, to be passed as
176
 *   a regular expression to PHPUnit's --filter option.
177
178
179
 * @param int $status
 *   (optional) The exit status code of the PHPUnit process will be assigned to
 *   this variable.
180
181
 *
 * @return array
182
183
 *   The parsed results of PHPUnit's JUnit XML output, in the format of
 *   {simpletest}'s schema.
184
 */
185
function simpletest_run_phpunit_tests($test_id, array $unescaped_test_classnames, &$status = NULL) {
186
  $phpunit_file = simpletest_phpunit_xml_filepath($test_id);
187
  simpletest_phpunit_run_command($unescaped_test_classnames, $phpunit_file, $status, $output);
188

189
190
191
  $rows = [];
  if ($status == TestStatus::PASS) {
    $rows = simpletest_phpunit_xml_to_rows($test_id, $phpunit_file);
192
  }
193
  else {
194
195
196
    $rows[] = [
      'test_id' => $test_id,
      'test_class' => implode(",", $unescaped_test_classnames),
197
      'status' => TestStatus::label($status),
198
199
200
201
202
203
204
      'message' => 'PHPunit Test failed to complete; Error: ' . implode("\n", $output),
      'message_group' => 'Other',
      'function' => implode(",", $unescaped_test_classnames),
      'line' => '0',
      'file' => $phpunit_file,
    ];
  }
205
  return $rows;
206
207
208
}

/**
209
 * Inserts the parsed PHPUnit results into {simpletest}.
210
 *
211
212
 * @param array[] $phpunit_results
 *   An array of test results returned from simpletest_phpunit_xml_to_rows().
213
214
 */
function simpletest_process_phpunit_results($phpunit_results) {
215
216
  // Insert the results of the PHPUnit test run into the database so the results
  // are displayed along with Simpletest's results.
217
  if (!empty($phpunit_results)) {
218
    $query = TestDatabase::getConnection()
219
220
      ->insert('simpletest')
      ->fields(array_keys($phpunit_results[0]));
221
222
223
224
225
226
227
    foreach ($phpunit_results as $result) {
      $query->values($result);
    }
    $query->execute();
  }
}

228
229
230
231
232
233
234
235
236
237
238
239
240
/**
 * Maps phpunit results to a data structure for batch messages and run-tests.sh.
 *
 * @param array $results
 *   The output from simpletest_run_phpunit_tests().
 *
 * @return array
 *   The test result summary. A row per test class.
 */
function simpletest_summarize_phpunit_result($results) {
  $summaries = [];
  foreach ($results as $result) {
    if (!isset($summaries[$result['test_class']])) {
241
      $summaries[$result['test_class']] = [
242
243
244
245
        '#pass' => 0,
        '#fail' => 0,
        '#exception' => 0,
        '#debug' => 0,
246
      ];
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
    }

    switch ($result['status']) {
      case 'pass':
        $summaries[$result['test_class']]['#pass']++;
        break;

      case 'fail':
        $summaries[$result['test_class']]['#fail']++;
        break;

      case 'exception':
        $summaries[$result['test_class']]['#exception']++;
        break;

      case 'debug':
        $summaries[$result['test_class']]['#debug']++;
        break;
    }
  }
  return $summaries;
}

270
/**
271
 * Returns the path to use for PHPUnit's --log-junit option.
272
273
274
 *
 * @param $test_id
 *   The current test ID.
275
 *
276
 * @return string
277
 *   Path to the PHPUnit XML file to use for the current $test_id.
278
279
 */
function simpletest_phpunit_xml_filepath($test_id) {
280
  return \Drupal::service('file_system')->realpath('public://simpletest') . '/phpunit-' . $test_id . '.xml';
281
282
283
284
285
286
}

/**
 * Returns the path to core's phpunit.xml.dist configuration file.
 *
 * @return string
287
 *   The path to core's phpunit.xml.dist configuration file.
288
289
290
291
292
293
 *
 * @deprecated in Drupal 8.4.x for removal before Drupal 9.0.0. PHPUnit test
 *   runners should change directory into core/ and then run the phpunit tool.
 *   See simpletest_phpunit_run_command() for an example.
 *
 * @see simpletest_phpunit_run_command()
294
295
 */
function simpletest_phpunit_configuration_filepath() {
296
  @trigger_error('The ' . __FUNCTION__ . ' function is deprecated since version 8.4.x and will be removed in 9.0.0.', E_USER_DEPRECATED);
297
  return \Drupal::root() . '/core/phpunit.xml.dist';
298
299
300
}

/**
301
 * Executes the PHPUnit command.
302
303
304
 *
 * @param array $unescaped_test_classnames
 *   An array of test class names, including full namespaces, to be passed as
305
 *   a regular expression to PHPUnit's --filter option.
306
 * @param string $phpunit_file
307
 *   A filepath to use for PHPUnit's --log-junit option.
308
309
310
 * @param int $status
 *   (optional) The exit status code of the PHPUnit process will be assigned to
 *   this variable.
311
312
 * @param string $output
 *   (optional) The output by running the phpunit command.
313
314
 *
 * @return string
315
 *   The results as returned by exec().
316
 */
317
function simpletest_phpunit_run_command(array $unescaped_test_classnames, $phpunit_file, &$status = NULL, &$output = NULL) {
318
  global $base_url;
319
320
321
  // Setup an environment variable containing the database connection so that
  // functional tests can connect to the database.
  putenv('SIMPLETEST_DB=' . Database::getConnectionInfoAsUrl());
322
323
324
325
326
327
328

  // Setup an environment variable containing the base URL, if it is available.
  // This allows functional tests to browse the site under test. When running
  // tests via CLI, core/phpunit.xml.dist or core/scripts/run-tests.sh can set
  // this variable.
  if ($base_url) {
    putenv('SIMPLETEST_BASE_URL=' . $base_url);
329
    putenv('BROWSERTEST_OUTPUT_DIRECTORY=' . \Drupal::service('file_system')->realpath('public://simpletest'));
330
  }
331
  $phpunit_bin = simpletest_phpunit_command();
332

333
  $command = [
334
335
336
    $phpunit_bin,
    '--log-junit',
    escapeshellarg($phpunit_file),
337
    '--printer',
338
    escapeshellarg(SimpletestUiPrinter::class),
339
  ];
340

341
342
343
344
345
346
347
348
349
350
351
352
  // Optimized for running a single test.
  if (count($unescaped_test_classnames) == 1) {
    $class = new \ReflectionClass($unescaped_test_classnames[0]);
    $command[] = escapeshellarg($class->getFileName());
  }
  else {
    // 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);
353
    $command = array_merge($command, [
354
355
      '--filter',
      escapeshellarg($filter_string),
356
    ]);
357
358
  }

359
360
361
  // Need to change directories before running the command so that we can use
  // relative paths in the configuration file's exclusions.
  $old_cwd = getcwd();
362
  chdir(\Drupal::root() . "/core");
363
364
365

  // exec in a subshell so that the environment is isolated when running tests
  // via the simpletest UI.
366
367
  $ret = exec(join($command, " "), $output, $status);

368
  chdir($old_cwd);
369
  putenv('SIMPLETEST_DB=');
370
371
  if ($base_url) {
    putenv('SIMPLETEST_BASE_URL=');
372
    putenv('BROWSERTEST_OUTPUT_DIRECTORY=');
373
  }
374
375
376
  return $ret;
}

377
378
/**
 * Returns the command to run PHPUnit.
379
380
381
 *
 * @return string
 *   The command that can be run through exec().
382
383
 */
function simpletest_phpunit_command() {
384
385
386
387
388
389
  // Load the actual autoloader being used and determine its filename using
  // reflection. We can determine the vendor directory based on that filename.
  $autoloader = require \Drupal::root() . '/autoload.php';
  $reflector = new ReflectionClass($autoloader);
  $vendor_dir = dirname(dirname($reflector->getFileName()));

390
391
392
  // The file in Composer's bin dir is a *nix link, which does not work when
  // extracted from a tarball and generally not on Windows.
  $command = $vendor_dir . '/phpunit/phpunit/phpunit';
393
  if (substr(PHP_OS, 0, 3) == 'WIN') {
394
    // On Windows it is necessary to run the script using the PHP executable.
395
396
    $php_executable_finder = new PhpExecutableFinder();
    $php = $php_executable_finder->find();
397
    $command = $php . ' -f ' . escapeshellarg($command) . ' --';
398
  }
399
  return $command;
400
401
}

402
/**
403
 * Implements callback_batch_operation().
404
405
 */
function _simpletest_batch_operation($test_list_init, $test_id, &$context) {
406
  simpletest_classloader_register();
407
408
409
410
411
  // Get working values.
  if (!isset($context['sandbox']['max'])) {
    // First iteration: initialize working values.
    $test_list = $test_list_init;
    $context['sandbox']['max'] = count($test_list);
412
    $test_results = ['#pass' => 0, '#fail' => 0, '#exception' => 0, '#debug' => 0];
413
414
415
416
417
418
419
420
421
422
  }
  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);
423
  if (is_subclass_of($test_class, TestCase::class)) {
424
425
426
427
428
429
430
    $phpunit_results = simpletest_run_phpunit_tests($test_id, [$test_class]);
    simpletest_process_phpunit_results($phpunit_results);
    $test_results[$test_class] = simpletest_summarize_phpunit_result($phpunit_results)[$test_class];
  }
  else {
    $test = new $test_class($test_id);
    $test->run();
431
    \Drupal::moduleHandler()->invokeAll('test_finished', [$test->results]);
432
433
    $test_results[$test_class] = $test->results;
  }
434
  $size = count($test_list);
435
  $info = TestDiscovery::getTestInfo($test_class);
436
437
438
439
440
441

  // Gather results and compose the report.
  foreach ($test_results[$test_class] as $key => $value) {
    $test_results[$key] += $value;
  }
  $test_results[$test_class]['#name'] = $info['name'];
442
  $items = [];
443
  foreach (Element::children($test_results) as $class) {
444
    $class_test_result = $test_results[$class] + [
445
446
      '#theme' => 'simpletest_result_summary',
      '#label' => t($test_results[$class]['#name'] . ':'),
447
    ];
448
    array_unshift($items, drupal_render($class_test_result));
449
  }
450
451
  $context['message'] = t('Processed test @num of @max - %test.', ['%test' => $info['name'], '@num' => $max - $size, '@max' => $max]);
  $overall_results = $test_results + [
452
453
    '#theme' => 'simpletest_result_summary',
    '#label' => t('Overall results:'),
454
  ];
455
  $context['message'] .= drupal_render($overall_results);
456

457
  $item_list = [
458
459
    '#theme' => 'item_list',
    '#items' => $items,
460
  ];
461
  $context['message'] .= drupal_render($item_list);
462
463
464
465
466
467
468
469
470
471
472

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

473
474
475
/**
 * Implements callback_batch_finished().
 */
476
function _simpletest_batch_finished($success, $results, $operations, $elapsed) {
477
  if ($success) {
478
    drupal_set_message(t('The test run finished in @elapsed.', ['@elapsed' => $elapsed]));
479
480
  }
  else {
481
    // Use the test_id passed as a parameter to _simpletest_batch_operation().
482
483
484
485
486
487
488
489
    $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);

490
    drupal_set_message(t('The test run did not successfully finish.'), 'error');
491
    drupal_set_message(t('Use the <em>Clean environment</em> button to clean-up temporary files and tables.'), 'warning');
492
  }
493
  \Drupal::moduleHandler()->invokeAll('test_group_finished');
494
495
}

496
/**
497
498
499
500
 * Get information about the last test that ran given a test ID.
 *
 * @param $test_id
 *   The test ID to get the last test from.
501
 * @return array
502
503
504
505
 *   Array containing the last database prefix used and the last test class
 *   that ran.
 */
function simpletest_last_test_get($test_id) {
506
  $last_prefix = TestDatabase::getConnection()
507
    ->queryRange('SELECT last_prefix FROM {simpletest_test_id} WHERE test_id = :test_id', 0, 1, [
508
      ':test_id' => $test_id,
509
    ])
510
    ->fetchField();
511
  $last_test_class = TestDatabase::getConnection()
512
    ->queryRange('SELECT test_class FROM {simpletest} WHERE test_id = :test_id ORDER BY message_id DESC', 0, 1, [
513
      ':test_id' => $test_id,
514
    ])
515
    ->fetchField();
516
  return [$last_prefix, $last_test_class];
517
518
}

519
/**
520
 * Reads the error log and reports any errors as assertion failures.
521
522
523
524
525
 *
 * 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
526
 *   The test ID to which the log relates.
527
 * @param $database_prefix
528
529
530
 *   The database prefix to which the log relates.
 * @param $test_class
 *   The test class to which the log relates.
531
 *
532
533
 * @return bool
 *   Whether any fatal errors were found.
534
 */
535
function simpletest_log_read($test_id, $database_prefix, $test_class) {
536
537
  $test_db = new TestDatabase($database_prefix);
  $log = DRUPAL_ROOT . '/' . $test_db->getTestSitePath() . '/error.log';
538
  $found = FALSE;
539
540
  if (file_exists($log)) {
    foreach (file($log) as $line) {
541
542
543
      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
544
        $caller = [
545
546
          'line' => $match[4],
          'file' => $match[3],
547
        ];
548
        TestBase::insertAssert($test_id, $test_class, FALSE, $match[2], $match[1], $caller);
549
550
      }
      else {
551
        // Unknown format, place the entire message in the log.
552
        TestBase::insertAssert($test_id, $test_class, FALSE, $line, 'Fatal error');
553
      }
554
      $found = TRUE;
555
556
    }
  }
557
  return $found;
558
559
}

560
/**
561
 * Gets a list of all of the tests provided by the system.
562
 *
563
564
565
 * 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.
566
 *
567
568
569
570
 * @param string $extension
 *   (optional) The name of an extension to limit discovery to; e.g., 'node'.
 * @param string[] $types
 *   An array of included test types.
571
 *
572
 * @return array[]
573
574
 *   An array of tests keyed with the groups, and then keyed by test classes.
 *   For example:
575
 *   @code
576
577
578
 *     $groups['Block'] => array(
 *       'BlockTestCase' => array(
 *         'name' => 'Block functionality',
579
 *         'description' => 'Add, edit and delete custom block.',
580
 *         'group' => 'Block',
581
582
583
 *       ),
 *     );
 *   @endcode
584
585
586
587
 *
 * @deprecated in Drupal 8.3.x, for removal before 9.0.0 release. Use
 *   \Drupal::service('test_discovery')->getTestClasses($extension, $types)
 *   instead.
588
 */
589
590
function simpletest_test_get_all($extension = NULL, array $types = []) {
  return \Drupal::service('test_discovery')->getTestClasses($extension, $types);
591
}
592

593
/**
594
595
596
597
 * Registers test namespaces of all extensions and core test classes.
 *
 * @deprecated in Drupal 8.3.x for removal before 9.0.0 release. Use
 *   \Drupal::service('test_discovery')->registerTestNamespaces() instead.
598
599
 */
function simpletest_classloader_register() {
600
  \Drupal::service('test_discovery')->registerTestNamespaces();
601
602
}

603
/**
604
 * Generates a test file.
605
606
 *
 * @param string $filename
607
608
609
 *   The name of the file, including the path. The suffix '.txt' is appended to
 *   the supplied file name and the file is put into the public:// files
 *   directory.
610
611
612
613
614
 * @param int $width
 *   The number of characters on one line.
 * @param int $lines
 *   The number of lines in the file.
 * @param string $type
615
616
617
618
619
620
 *   (optional) The type, one of:
 *   - text: The generated file contains random ASCII characters.
 *   - binary: The generated file contains random characters whose codes are in
 *     the range of 0 to 31.
 *   - binary-text: The generated file contains random sequence of '0' and '1'
 *     values.
621
622
623
 *
 * @return string
 *   The name of the file, including the path.
624
625
626
 */
function simpletest_generate_file($filename, $width, $lines, $type = 'binary-text') {
  $text = '';
627
628
629
630
631
632
633
634
635
636
637
638
639
640
  for ($i = 0; $i < $lines; $i++) {
    // Generate $width - 1 characters to leave space for the "\n" character.
    for ($j = 0; $j < $width - 1; $j++) {
      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;
641
      }
642
    }
643
644
    $text .= "\n";
  }
645
646

  // Create filename.
647
  file_put_contents('public://' . $filename . '.txt', $text);
648
649
650
  return $filename;
}

651
/**
652
 * Removes all temporary database tables and directories.
653
654
655
656
 */
function simpletest_clean_environment() {
  simpletest_clean_database();
  simpletest_clean_temporary_directories();
657
  if (\Drupal::config('simpletest.settings')->get('clear_results')) {
658
    $count = simpletest_clean_results_table();
659
    drupal_set_message(\Drupal::translation()->formatPlural($count, 'Removed 1 test result.', 'Removed @count test results.'));
660
661
662
663
  }
  else {
    drupal_set_message(t('Clear results is disabled and the test results table will not be cleared.'), 'warning');
  }
664
665

  // Detect test classes that have been added, renamed or deleted.
666
667
  \Drupal::cache()->delete('simpletest');
  \Drupal::cache()->delete('simpletest_phpunit');
668
669
670
}

/**
671
 * Removes prefixed tables from the database from crashed tests.
672
673
 */
function simpletest_clean_database() {
674
  $tables = db_find_tables('test%');
675
  $count = 0;
676
677
678
679
  foreach ($tables as $table) {
    // Only drop tables which begin wih 'test' followed by digits, for example,
    // {test12345678node__body}.
    if (preg_match('/^test\d+.*/', $table, $matches)) {
680
      db_drop_table($matches[0]);
681
      $count++;
682
    }
683
684
  }

685
  if ($count > 0) {
686
    drupal_set_message(\Drupal::translation()->formatPlural($count, 'Removed 1 leftover table.', 'Removed @count leftover tables.'));
687
688
  }
  else {
689
    drupal_set_message(t('No leftover tables to remove.'));
690
691
692
693
  }
}

/**
694
 * Finds all leftover temporary directories and removes them.
695
696
697
 */
function simpletest_clean_temporary_directories() {
  $count = 0;
698
699
  if (is_dir(DRUPAL_ROOT . '/sites/simpletest')) {
    $files = scandir(DRUPAL_ROOT . '/sites/simpletest');
700
    foreach ($files as $file) {
701
702
      if ($file[0] != '.') {
        $path = DRUPAL_ROOT . '/sites/simpletest/' . $file;
703
704
705
        file_unmanaged_delete_recursive($path, function ($any_path) {
          @chmod($any_path, 0700);
        });
706
707
        $count++;
      }
708
709
710
711
    }
  }

  if ($count > 0) {
712
    drupal_set_message(\Drupal::translation()->formatPlural($count, 'Removed 1 temporary directory.', 'Removed @count temporary directories.'));
713
714
715
716
717
718
  }
  else {
    drupal_set_message(t('No temporary directories to remove.'));
  }
}

719
/**
720
 * Clears the test result tables.
721
722
723
 *
 * @param $test_id
 *   Test ID to remove results for, or NULL to remove all results.
724
725
726
 *
 * @return int
 *   The number of results that were removed.
727
 */
728
function simpletest_clean_results_table($test_id = NULL) {
729
  if (\Drupal::config('simpletest.settings')->get('clear_results')) {
730
    $connection = TestDatabase::getConnection();
731
    if ($test_id) {
732
      $count = $connection->query('SELECT COUNT(test_id) FROM {simpletest_test_id} WHERE test_id = :test_id', [':test_id' => $test_id])->fetchField();
733

734
      $connection->delete('simpletest')
735
736
        ->condition('test_id', $test_id)
        ->execute();
737
      $connection->delete('simpletest_test_id')
738
739
740
741
        ->condition('test_id', $test_id)
        ->execute();
    }
    else {
742
      $count = $connection->query('SELECT COUNT(test_id) FROM {simpletest_test_id}')->fetchField();
743

744
      // Clear test results.
745
746
      $connection->delete('simpletest')->execute();
      $connection->delete('simpletest_test_id')->execute();
747
    }
748

749
    return $count;
750
  }
751
  return 0;
752
}
753
754
755
756
757
758
759
760
761
762
763
764

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

/**
768
 * Converts PHPUnit's JUnit XML output to an array.
769
770
771
772
 *
 * @param $test_id
 *   The current test ID.
 * @param $phpunit_xml_file
773
774
775
776
777
 *   Path to the PHPUnit XML file.
 *
 * @return array[]
 *   The results as array of rows in a format that can be inserted into
 *   {simpletest}.
778
779
 */
function simpletest_phpunit_xml_to_rows($test_id, $phpunit_xml_file) {
780
781
782
783
  $contents = @file_get_contents($phpunit_xml_file);
  if (!$contents) {
    return;
  }
784
  $records = [];
785
786
787
  $testcases = simpletest_phpunit_find_testcases(new SimpleXMLElement($contents));
  foreach ($testcases as $testcase) {
    $records[] = simpletest_phpunit_testcase_to_row($test_id, $testcase);
788
789
790
  }
  return $records;
}
791
792

/**
793
 * Finds all test cases recursively from a test suite list.
794
 *
795
796
797
798
 * @param \SimpleXMLElement $element
 *   The PHPUnit xml to search for test cases.
 * @param \SimpleXMLElement $suite
 *   (Optional) The parent of the current element. Defaults to NULL.
799
800
 *
 * @return array
801
 *   A list of all test cases.
802
 */
803
function simpletest_phpunit_find_testcases(\SimpleXMLElement $element, \SimpleXMLElement $parent = NULL) {
804
  $testcases = [];
805

806
807
808
809
810
811
812
813
814
815
816
  if (!isset($parent)) {
    $parent = $element;
  }

  if ($element->getName() === 'testcase' && (int) $parent->attributes()->tests > 0) {
    // Add the class attribute if the testcase does not have one. This is the
    // case for tests using a data provider. The name of the parent testsuite
    // will be in the format class::method.
    if (!$element->attributes()->class) {
      $name = explode('::', $parent->attributes()->name, 2);
      $element->addAttribute('class', $name[0]);
817
    }
818
819
820
821
822
823
824
    $testcases[] = $element;
  }
  else {
    foreach ($element as $child) {
      $file = (string) $parent->attributes()->file;
      if ($file && !$child->attributes()->file) {
        $child->addAttribute('file', $file);
825
      }
826
      $testcases = array_merge($testcases, simpletest_phpunit_find_testcases($child, $element));
827
828
829
830
831
832
    }
  }
  return $testcases;
}

/**
833
 * Converts a PHPUnit test case result to a {simpletest} result row.
834
835
836
837
 *
 * @param int $test_id
 *   The current test ID.
 * @param \SimpleXMLElement $testcase
838
 *   The PHPUnit test case represented as XML element.
839
840
 *
 * @return array
841
 *   An array containing the {simpletest} result row.
842
 */
843
function simpletest_phpunit_testcase_to_row($test_id, \SimpleXMLElement $testcase) {
844
845
846
847
848
849
850
851
852
853
854
855
856
857
  $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();

858
  $record = [
859
860
861
862
863
864
865
866
    '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,
867
    'file' => $attributes->file,
868
  ];
869
870
  return $record;
}