forked from sebastianbergmann/phpunit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTestSuite.php
728 lines (610 loc) · 18.9 KB
/
TestSuite.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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
<?php declare(strict_types=1);
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* 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 array_merge;
use function array_pop;
use function array_reverse;
use function assert;
use function call_user_func;
use function class_exists;
use function count;
use function implode;
use function is_callable;
use function is_file;
use function is_subclass_of;
use function sprintf;
use function str_ends_with;
use function str_starts_with;
use function trim;
use Iterator;
use IteratorAggregate;
use PHPUnit\Event;
use PHPUnit\Event\Code\TestMethod;
use PHPUnit\Event\NoPreviousThrowableException;
use PHPUnit\Metadata\Api\Dependencies;
use PHPUnit\Metadata\Api\Groups;
use PHPUnit\Metadata\Api\HookMethods;
use PHPUnit\Metadata\Api\Requirements;
use PHPUnit\Metadata\MetadataCollection;
use PHPUnit\Runner\Exception as RunnerException;
use PHPUnit\Runner\Filter\Factory;
use PHPUnit\Runner\PhptTestCase;
use PHPUnit\Runner\TestSuiteLoader;
use PHPUnit\TestRunner\TestResult\Facade as TestResultFacade;
use PHPUnit\Util\Filter;
use PHPUnit\Util\Reflection;
use PHPUnit\Util\Test as TestUtil;
use ReflectionClass;
use ReflectionMethod;
use SebastianBergmann\CodeCoverage\InvalidArgumentException;
use SebastianBergmann\CodeCoverage\UnintentionallyCoveredCodeException;
use Throwable;
/**
* @template-implements IteratorAggregate<int, Test>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise for PHPUnit
*
* @internal This class is not covered by the backward compatibility promise for PHPUnit
*/
class TestSuite implements IteratorAggregate, Reorderable, Test
{
/**
* @var non-empty-string
*/
private string $name;
/**
* @var array<non-empty-string, list<non-empty-string>>
*/
private array $groups = [];
/**
* @var ?list<ExecutionOrderDependency>
*/
private ?array $requiredTests = null;
/**
* @var list<Test>
*/
private array $tests = [];
/**
* @var ?list<ExecutionOrderDependency>
*/
private ?array $providedTests = null;
private ?Factory $iteratorFilter = null;
private bool $wasRun = false;
/**
* @param non-empty-string $name
*/
public static function empty(string $name): static
{
return new static($name);
}
/**
* @param ReflectionClass<TestCase> $class
* @param list<non-empty-string> $groups
*/
public static function fromClassReflector(ReflectionClass $class, array $groups = []): static
{
$testSuite = new static($class->getName());
foreach (Reflection::publicMethodsDeclaredDirectlyInTestClass($class) as $method) {
if (!TestUtil::isTestMethod($method)) {
continue;
}
$testSuite->addTestMethod($class, $method, $groups);
}
if ($testSuite->isEmpty()) {
Event\Facade::emitter()->testRunnerTriggeredWarning(
sprintf(
'No tests found in class "%s".',
$class->getName(),
),
);
}
return $testSuite;
}
/**
* @param non-empty-string $name
*/
final private function __construct(string $name)
{
$this->name = $name;
}
/**
* Adds a test to the suite.
*
* @param list<non-empty-string> $groups
*/
public function addTest(Test $test, array $groups = []): void
{
if ($test instanceof self) {
$this->tests[] = $test;
$this->clearCaches();
return;
}
assert($test instanceof TestCase || $test instanceof PhptTestCase);
$class = new ReflectionClass($test);
if ($class->isAbstract()) {
return;
}
$this->tests[] = $test;
$this->clearCaches();
if ($this->containsOnlyVirtualGroups($groups)) {
$groups[] = 'default';
}
if ($test instanceof TestCase) {
$id = $test->valueObjectForEvents()->id();
$test->setGroups($groups);
} else {
$id = $test->valueObjectForEvents()->id();
}
foreach ($groups as $group) {
if (!isset($this->groups[$group])) {
$this->groups[$group] = [$id];
} else {
$this->groups[$group][] = $id;
}
}
}
/**
* Adds the tests from the given class to the suite.
*
* @param ReflectionClass<TestCase> $testClass
* @param list<non-empty-string> $groups
*
* @throws Exception
*/
public function addTestSuite(ReflectionClass $testClass, array $groups = []): void
{
if ($testClass->isAbstract()) {
throw new Exception(
sprintf(
'Class %s is abstract',
$testClass->getName(),
),
);
}
if (!$testClass->isSubclassOf(TestCase::class)) {
throw new Exception(
sprintf(
'Class %s is not a subclass of %s',
$testClass->getName(),
TestCase::class,
),
);
}
$this->addTest(self::fromClassReflector($testClass, $groups), $groups);
}
/**
* Wraps both <code>addTest()</code> and <code>addTestSuite</code>
* as well as the separate import statements for the user's convenience.
*
* If the named file cannot be read or there are no new tests that can be
* added, a <code>PHPUnit\Framework\WarningTestCase</code> will be created instead,
* leaving the current test run untouched.
*
* @param list<non-empty-string> $groups
*
* @throws Exception
*/
public function addTestFile(string $filename, array $groups = []): void
{
try {
if (str_ends_with($filename, '.phpt') && is_file($filename)) {
$this->addTest(new PhptTestCase($filename));
} else {
$this->addTestSuite(
(new TestSuiteLoader)->load($filename),
$groups,
);
}
} catch (RunnerException $e) {
Event\Facade::emitter()->testRunnerTriggeredWarning(
$e->getMessage(),
);
}
}
/**
* Wrapper for addTestFile() that adds multiple test files.
*
* @param iterable<string> $fileNames
*
* @throws Exception
*/
public function addTestFiles(iterable $fileNames): void
{
foreach ($fileNames as $filename) {
$this->addTestFile((string) $filename);
}
}
/**
* Counts the number of test cases that will be run by this test.
*/
public function count(): int
{
$numTests = 0;
foreach ($this as $test) {
$numTests += count($test);
}
return $numTests;
}
public function isEmpty(): bool
{
foreach ($this as $test) {
if (count($test) !== 0) {
return false;
}
}
return true;
}
/**
* @return non-empty-string
*/
public function name(): string
{
return $this->name;
}
/**
* @return array<non-empty-string, list<non-empty-string>>
*/
public function groups(): array
{
return $this->groups;
}
/**
* @return list<PhptTestCase|TestCase>
*/
public function collect(): array
{
$tests = [];
foreach ($this as $test) {
if ($test instanceof self) {
$tests = array_merge($tests, $test->collect());
continue;
}
assert($test instanceof TestCase || $test instanceof PhptTestCase);
$tests[] = $test;
}
return $tests;
}
/**
* @throws CodeCoverageException
* @throws Event\RuntimeException
* @throws Exception
* @throws InvalidArgumentException
* @throws NoPreviousThrowableException
* @throws UnintentionallyCoveredCodeException
*/
public function run(): void
{
if ($this->wasRun) {
// @codeCoverageIgnoreStart
throw new Exception('The tests aggregated by this TestSuite were already run');
// @codeCoverageIgnoreEnd
}
$this->wasRun = true;
if ($this->isEmpty()) {
return;
}
$emitter = Event\Facade::emitter();
$testSuiteValueObjectForEvents = Event\TestSuite\TestSuiteBuilder::from($this);
$emitter->testSuiteStarted($testSuiteValueObjectForEvents);
if (!$this->invokeMethodsBeforeFirstTest($emitter, $testSuiteValueObjectForEvents)) {
return;
}
/** @var list<Test> $tests */
$tests = [];
foreach ($this as $test) {
$tests[] = $test;
}
$tests = array_reverse($tests);
$this->tests = [];
$this->groups = [];
while (($test = array_pop($tests)) !== null) {
if (TestResultFacade::shouldStop()) {
$emitter->testRunnerExecutionAborted();
break;
}
$test->run();
}
$this->invokeMethodsAfterLastTest($emitter);
$emitter->testSuiteFinished($testSuiteValueObjectForEvents);
}
/**
* Returns the tests as an enumeration.
*
* @return list<Test>
*/
public function tests(): array
{
return $this->tests;
}
/**
* Set tests of the test suite.
*
* @param list<Test> $tests
*/
public function setTests(array $tests): void
{
$this->tests = $tests;
}
/**
* Mark the test suite as skipped.
*
* @throws SkippedTestSuiteError
*/
public function markTestSuiteSkipped(string $message = ''): never
{
throw new SkippedTestSuiteError($message);
}
/**
* Returns an iterator for this test suite.
*/
public function getIterator(): Iterator
{
$iterator = new TestSuiteIterator($this);
if ($this->iteratorFilter !== null) {
$iterator = $this->iteratorFilter->factory($iterator, $this);
}
return $iterator;
}
public function injectFilter(Factory $filter): void
{
$this->iteratorFilter = $filter;
foreach ($this as $test) {
if ($test instanceof self) {
$test->injectFilter($filter);
}
}
}
/**
* @return list<ExecutionOrderDependency>
*/
public function provides(): array
{
if ($this->providedTests === null) {
$this->providedTests = [];
if (is_callable($this->sortId(), true)) {
$this->providedTests[] = new ExecutionOrderDependency($this->sortId());
}
foreach ($this->tests as $test) {
if (!($test instanceof Reorderable)) {
continue;
}
$this->providedTests = ExecutionOrderDependency::mergeUnique($this->providedTests, $test->provides());
}
}
return $this->providedTests;
}
/**
* @return list<ExecutionOrderDependency>
*/
public function requires(): array
{
if ($this->requiredTests === null) {
$this->requiredTests = [];
foreach ($this->tests as $test) {
if (!($test instanceof Reorderable)) {
continue;
}
$this->requiredTests = ExecutionOrderDependency::mergeUnique(
ExecutionOrderDependency::filterInvalid($this->requiredTests),
$test->requires(),
);
}
$this->requiredTests = ExecutionOrderDependency::diff($this->requiredTests, $this->provides());
}
return $this->requiredTests;
}
public function sortId(): string
{
return $this->name() . '::class';
}
/**
* @phpstan-assert-if-true class-string<TestCase> $this->name
*/
public function isForTestClass(): bool
{
return class_exists($this->name, false) && is_subclass_of($this->name, TestCase::class);
}
/**
* @param ReflectionClass<TestCase> $class
* @param list<non-empty-string> $groups
*
* @throws Exception
*/
protected function addTestMethod(ReflectionClass $class, ReflectionMethod $method, array $groups): void
{
$className = $class->getName();
$methodName = $method->getName();
assert(!empty($methodName));
try {
$test = (new TestBuilder)->build($class, $methodName, $groups);
} catch (InvalidDataProviderException $e) {
Event\Facade::emitter()->testTriggeredPhpunitError(
new TestMethod(
$className,
$methodName,
$class->getFileName(),
$method->getStartLine(),
Event\Code\TestDoxBuilder::fromClassNameAndMethodName(
$className,
$methodName,
),
MetadataCollection::fromArray([]),
Event\TestData\TestDataCollection::fromArray([]),
),
sprintf(
"The data provider specified for %s::%s is invalid\n%s",
$className,
$methodName,
$this->throwableToString($e),
),
);
return;
}
if ($test instanceof TestCase || $test instanceof DataProviderTestSuite) {
$test->setDependencies(
Dependencies::dependencies($class->getName(), $methodName),
);
}
$this->addTest(
$test,
array_merge(
$groups,
(new Groups)->groups($class->getName(), $methodName),
),
);
}
private function clearCaches(): void
{
$this->providedTests = null;
$this->requiredTests = null;
}
/**
* @param list<non-empty-string> $groups
*/
private function containsOnlyVirtualGroups(array $groups): bool
{
foreach ($groups as $group) {
if (!str_starts_with($group, '__phpunit_')) {
return false;
}
}
return true;
}
private function methodDoesNotExistOrIsDeclaredInTestCase(string $methodName): bool
{
$reflector = new ReflectionClass($this->name);
return !$reflector->hasMethod($methodName) ||
$reflector->getMethod($methodName)->getDeclaringClass()->getName() === TestCase::class;
}
/**
* @throws Exception
*/
private function throwableToString(Throwable $t): string
{
$message = $t->getMessage();
if (empty(trim($message))) {
$message = '<no message>';
}
if ($t instanceof InvalidDataProviderException) {
return sprintf(
"%s\n%s",
$message,
Filter::stackTraceFromThrowableAsString($t),
);
}
return sprintf(
"%s: %s\n%s",
$t::class,
$message,
Filter::stackTraceFromThrowableAsString($t),
);
}
/**
* @throws Exception
* @throws NoPreviousThrowableException
*/
private function invokeMethodsBeforeFirstTest(Event\Emitter $emitter, Event\TestSuite\TestSuite $testSuiteValueObjectForEvents): bool
{
if (!$this->isForTestClass()) {
return true;
}
$methods = (new HookMethods)->hookMethods($this->name)['beforeClass']->methodNamesSortedByPriority();
$calledMethods = [];
$emitCalledEvent = true;
$result = true;
foreach ($methods as $method) {
if ($this->methodDoesNotExistOrIsDeclaredInTestCase($method)) {
continue;
}
$calledMethod = new Event\Code\ClassMethod(
$this->name,
$method,
);
try {
$missingRequirements = (new Requirements)->requirementsNotSatisfiedFor($this->name, $method);
if ($missingRequirements !== []) {
$emitCalledEvent = false;
$this->markTestSuiteSkipped(implode(PHP_EOL, $missingRequirements));
}
call_user_func([$this->name, $method]);
} catch (Throwable $t) {
}
if ($emitCalledEvent) {
$emitter->testBeforeFirstTestMethodCalled(
$this->name,
$calledMethod,
);
$calledMethods[] = $calledMethod;
}
if (isset($t) && $t instanceof SkippedTest) {
$emitter->testSuiteSkipped(
$testSuiteValueObjectForEvents,
$t->getMessage(),
);
return false;
}
if (isset($t)) {
$emitter->testBeforeFirstTestMethodErrored(
$this->name,
$calledMethod,
Event\Code\ThrowableBuilder::from($t),
);
$result = false;
}
}
if (!empty($calledMethods)) {
$emitter->testBeforeFirstTestMethodFinished(
$this->name,
...$calledMethods,
);
}
return $result;
}
private function invokeMethodsAfterLastTest(Event\Emitter $emitter): void
{
if (!$this->isForTestClass()) {
return;
}
$methods = (new HookMethods)->hookMethods($this->name)['afterClass']->methodNamesSortedByPriority();
$calledMethods = [];
foreach ($methods as $method) {
if ($this->methodDoesNotExistOrIsDeclaredInTestCase($method)) {
continue;
}
$calledMethod = new Event\Code\ClassMethod(
$this->name,
$method,
);
try {
call_user_func([$this->name, $method]);
} catch (Throwable $t) {
}
$emitter->testAfterLastTestMethodCalled(
$this->name,
$calledMethod,
);
$calledMethods[] = $calledMethod;
if (isset($t)) {
$emitter->testAfterLastTestMethodErrored(
$this->name,
$calledMethod,
Event\Code\ThrowableBuilder::from($t),
);
}
}
if (!empty($calledMethods)) {
$emitter->testAfterLastTestMethodFinished(
$this->name,
...$calledMethods,
);
}
}
}