-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
Copy pathTestRunner.php
455 lines (387 loc) · 15.1 KB
/
TestRunner.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
<?php declare(strict_types=1);
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Framework;
use const PHP_EOL;
use function assert;
use function class_exists;
use function defined;
use function extension_loaded;
use function get_include_path;
use function hrtime;
use function serialize;
use function sprintf;
use function sys_get_temp_dir;
use function tempnam;
use function unlink;
use function var_export;
use AssertionError;
use PHPUnit\Event;
use PHPUnit\Event\NoPreviousThrowableException;
use PHPUnit\Event\TestData\MoreThanOneDataSetFromDataProviderException;
use PHPUnit\Event\TestData\NoDataSetFromDataProviderException;
use PHPUnit\Metadata\Api\CodeCoverage as CodeCoverageMetadataApi;
use PHPUnit\Metadata\Parser\Registry as MetadataRegistry;
use PHPUnit\Runner\CodeCoverage;
use PHPUnit\Runner\ErrorHandler;
use PHPUnit\TextUI\Configuration\Configuration;
use PHPUnit\TextUI\Configuration\Registry as ConfigurationRegistry;
use PHPUnit\Util\GlobalState;
use PHPUnit\Util\PHP\AbstractPhpProcess;
use ReflectionClass;
use SebastianBergmann\CodeCoverage\Exception as OriginalCodeCoverageException;
use SebastianBergmann\CodeCoverage\StaticAnalysisCacheNotConfiguredException;
use SebastianBergmann\CodeCoverage\UnintentionallyCoveredCodeException;
use SebastianBergmann\Invoker\Invoker;
use SebastianBergmann\Invoker\TimeoutException;
use SebastianBergmann\Template\Template;
use Throwable;
/**
* @internal This class is not covered by the backward compatibility promise for PHPUnit
*/
final class TestRunner
{
private ?bool $timeLimitCanBeEnforced = null;
private readonly Configuration $configuration;
public function __construct()
{
$this->configuration = ConfigurationRegistry::get();
}
/**
* @throws \PHPUnit\Runner\Exception
* @throws \SebastianBergmann\CodeCoverage\InvalidArgumentException
* @throws CodeCoverageException
* @throws MoreThanOneDataSetFromDataProviderException
* @throws NoDataSetFromDataProviderException
* @throws UnintentionallyCoveredCodeException
*/
public function run(TestCase $test): void
{
Assert::resetCount();
if ($this->configuration->registerMockObjectsFromTestArgumentsRecursively()) {
$test->registerMockObjectsFromTestArgumentsRecursively();
}
$shouldCodeCoverageBeCollected = (new CodeCoverageMetadataApi)->shouldCodeCoverageBeCollectedFor(
$test::class,
$test->name(),
);
$error = false;
$failure = false;
$incomplete = false;
$risky = false;
$skipped = false;
ErrorHandler::instance()->enable();
$collectCodeCoverage = CodeCoverage::instance()->isActive() &&
$shouldCodeCoverageBeCollected;
if ($collectCodeCoverage) {
CodeCoverage::instance()->start($test);
}
try {
if ($this->canTimeLimitBeEnforced() &&
$this->shouldTimeLimitBeEnforced($test)) {
$risky = $this->runTestWithTimeout($test);
} else {
$test->runBare();
}
} catch (AssertionFailedError $e) {
$failure = true;
if ($e instanceof IncompleteTestError) {
$incomplete = true;
} elseif ($e instanceof SkippedTest) {
$skipped = true;
}
} catch (AssertionError $e) {
$test->addToAssertionCount(1);
$failure = true;
$frame = $e->getTrace()[0];
assert(isset($frame['file']));
assert(isset($frame['line']));
$e = new AssertionFailedError(
sprintf(
'%s in %s:%s',
$e->getMessage(),
$frame['file'],
$frame['line'],
),
);
} catch (Throwable $e) {
$error = true;
}
$test->addToAssertionCount(Assert::getCount());
if ($this->configuration->reportUselessTests() &&
!$test->doesNotPerformAssertions() &&
$test->numberOfAssertionsPerformed() === 0) {
$risky = true;
}
if (!$error && !$failure && !$incomplete && !$skipped && !$risky &&
$this->configuration->requireCoverageMetadata() &&
!$this->hasCoverageMetadata($test::class, $test->name())) {
Event\Facade::emitter()->testConsideredRisky(
$test->valueObjectForEvents(),
'This test does not define a code coverage target but is expected to do so',
);
$risky = true;
}
if ($collectCodeCoverage) {
$append = !$risky && !$incomplete && !$skipped;
$linesToBeCovered = [];
$linesToBeUsed = [];
if ($append) {
try {
$linesToBeCovered = (new CodeCoverageMetadataApi)->linesToBeCovered(
$test::class,
$test->name(),
);
$linesToBeUsed = (new CodeCoverageMetadataApi)->linesToBeUsed(
$test::class,
$test->name(),
);
} catch (InvalidCoversTargetException $cce) {
Event\Facade::emitter()->testTriggeredPhpunitWarning(
$test->valueObjectForEvents(),
$cce->getMessage(),
);
}
}
try {
CodeCoverage::instance()->stop(
$append,
$linesToBeCovered,
$linesToBeUsed,
);
} catch (UnintentionallyCoveredCodeException $cce) {
Event\Facade::emitter()->testConsideredRisky(
$test->valueObjectForEvents(),
'This test executed code that is not listed as code to be covered or used:' .
PHP_EOL .
$cce->getMessage(),
);
} catch (OriginalCodeCoverageException $cce) {
$error = true;
$e = $e ?? $cce;
}
}
ErrorHandler::instance()->disable();
if (!$incomplete &&
!$skipped &&
$this->configuration->reportUselessTests() &&
!$test->doesNotPerformAssertions() &&
$test->numberOfAssertionsPerformed() === 0) {
Event\Facade::emitter()->testConsideredRisky(
$test->valueObjectForEvents(),
'This test did not perform any assertions',
);
}
if ($test->doesNotPerformAssertions() &&
$test->numberOfAssertionsPerformed() > 0) {
Event\Facade::emitter()->testConsideredRisky(
$test->valueObjectForEvents(),
sprintf(
'This test is not expected to perform assertions but performed %d assertions',
$test->numberOfAssertionsPerformed(),
),
);
}
if ($test->hasUnexpectedOutput()) {
Event\Facade::emitter()->testPrintedUnexpectedOutput($test->output());
}
if ($this->configuration->disallowTestOutput() && $test->hasUnexpectedOutput()) {
Event\Facade::emitter()->testConsideredRisky(
$test->valueObjectForEvents(),
sprintf(
'This test printed output: %s',
$test->output(),
),
);
}
if ($test->wasPrepared()) {
Event\Facade::emitter()->testFinished(
$test->valueObjectForEvents(),
$test->numberOfAssertionsPerformed(),
);
}
}
/**
* @throws \PHPUnit\Runner\Exception
* @throws \PHPUnit\Util\Exception
* @throws \SebastianBergmann\Template\InvalidArgumentException
* @throws Exception
* @throws MoreThanOneDataSetFromDataProviderException
* @throws NoPreviousThrowableException
* @throws ProcessIsolationException
* @throws StaticAnalysisCacheNotConfiguredException
*/
public function runInSeparateProcess(TestCase $test, bool $runEntireClass, bool $preserveGlobalState): void
{
$class = new ReflectionClass($test);
if ($runEntireClass) {
$template = new Template(
__DIR__ . '/../Util/PHP/Template/TestCaseClass.tpl',
);
} else {
$template = new Template(
__DIR__ . '/../Util/PHP/Template/TestCaseMethod.tpl',
);
}
$bootstrap = '';
$constants = '';
$globals = '';
$includedFiles = '';
$iniSettings = '';
if (ConfigurationRegistry::get()->hasBootstrap()) {
$bootstrap = ConfigurationRegistry::get()->bootstrap();
}
if ($preserveGlobalState) {
$constants = GlobalState::getConstantsAsString();
$globals = GlobalState::getGlobalsAsString();
$includedFiles = GlobalState::getIncludedFilesAsString();
$iniSettings = GlobalState::getIniSettingsAsString();
}
$coverage = CodeCoverage::instance()->isActive() ? 'true' : 'false';
$linesToBeIgnored = var_export(CodeCoverage::instance()->linesToBeIgnored(), true);
if (defined('PHPUNIT_COMPOSER_INSTALL')) {
$composerAutoload = var_export(PHPUNIT_COMPOSER_INSTALL, true);
} else {
$composerAutoload = '\'\'';
}
if (defined('__PHPUNIT_PHAR__')) {
$phar = var_export(__PHPUNIT_PHAR__, true);
} else {
$phar = '\'\'';
}
$data = var_export(serialize($test->providedData()), true);
$dataName = var_export($test->dataName(), true);
$dependencyInput = var_export(serialize($test->dependencyInput()), true);
$includePath = var_export(get_include_path(), true);
// must do these fixes because TestCaseMethod.tpl has unserialize('{data}') in it, and we can't break BC
// the lines above used to use addcslashes() rather than var_export(), which breaks null byte escape sequences
$data = "'." . $data . ".'";
$dataName = "'.(" . $dataName . ").'";
$dependencyInput = "'." . $dependencyInput . ".'";
$includePath = "'." . $includePath . ".'";
$offset = hrtime();
$serializedConfiguration = $this->saveConfigurationForChildProcess();
$var = [
'bootstrap' => $bootstrap,
'composerAutoload' => $composerAutoload,
'phar' => $phar,
'filename' => $class->getFileName(),
'className' => $class->getName(),
'collectCodeCoverageInformation' => $coverage,
'linesToBeIgnored' => $linesToBeIgnored,
'data' => $data,
'dataName' => $dataName,
'dependencyInput' => $dependencyInput,
'constants' => $constants,
'globals' => $globals,
'include_path' => $includePath,
'included_files' => $includedFiles,
'iniSettings' => $iniSettings,
'name' => $test->name(),
'offsetSeconds' => $offset[0],
'offsetNanoseconds' => $offset[1],
'serializedConfiguration' => $serializedConfiguration,
];
if (!$runEntireClass) {
$var['methodName'] = $test->name();
}
$template->setVar($var);
$php = AbstractPhpProcess::factory();
$php->runTestJob($template->render(), $test);
@unlink($serializedConfiguration);
}
/**
* @psalm-param class-string $className
* @psalm-param non-empty-string $methodName
*/
private function hasCoverageMetadata(string $className, string $methodName): bool
{
$metadata = MetadataRegistry::parser()->forClassAndMethod($className, $methodName);
if ($metadata->isCovers()->isNotEmpty()) {
return true;
}
if ($metadata->isCoversClass()->isNotEmpty()) {
return true;
}
if ($metadata->isCoversFunction()->isNotEmpty()) {
return true;
}
if ($metadata->isCoversNothing()->isNotEmpty()) {
return true;
}
return false;
}
private function canTimeLimitBeEnforced(): bool
{
if ($this->timeLimitCanBeEnforced !== null) {
return $this->timeLimitCanBeEnforced;
}
if (!class_exists(Invoker::class)) {
$this->timeLimitCanBeEnforced = false;
return $this->timeLimitCanBeEnforced;
}
$this->timeLimitCanBeEnforced = (new Invoker)->canInvokeWithTimeout();
return $this->timeLimitCanBeEnforced;
}
private function shouldTimeLimitBeEnforced(TestCase $test): bool
{
if (!$this->configuration->enforceTimeLimit()) {
return false;
}
if (!(($this->configuration->defaultTimeLimit() || $test->size()->isKnown()))) {
return false;
}
if (extension_loaded('xdebug') && xdebug_is_debugger_active()) {
return false;
}
return true;
}
/**
* @throws Throwable
*/
private function runTestWithTimeout(TestCase $test): bool
{
$_timeout = $this->configuration->defaultTimeLimit();
if ($test->size()->isSmall()) {
$_timeout = $this->configuration->timeoutForSmallTests();
} elseif ($test->size()->isMedium()) {
$_timeout = $this->configuration->timeoutForMediumTests();
} elseif ($test->size()->isLarge()) {
$_timeout = $this->configuration->timeoutForLargeTests();
}
try {
(new Invoker)->invoke([$test, 'runBare'], [], $_timeout);
} catch (TimeoutException) {
Event\Facade::emitter()->testConsideredRisky(
$test->valueObjectForEvents(),
sprintf(
'This test was aborted after %d second%s',
$_timeout,
$_timeout !== 1 ? 's' : '',
),
);
return true;
}
return false;
}
/**
* @throws ProcessIsolationException
*/
private function saveConfigurationForChildProcess(): string
{
$path = tempnam(sys_get_temp_dir(), 'phpunit_');
if (!$path) {
throw new ProcessIsolationException;
}
if (!ConfigurationRegistry::saveTo($path)) {
throw new ProcessIsolationException;
}
return $path;
}
}