1: <?php
2:
3: declare(strict_types=1);
4:
5: namespace Atk4\Core\Phpunit;
6:
7: use Atk4\Core\WarnDynamicPropertyTrait;
8: use PHPUnit\Framework\TestCase as BaseTestCase;
9: use PHPUnit\Framework\TestResult;
10: use PHPUnit\Metadata\Api\CodeCoverage as CodeCoverageMetadata;
11: use PHPUnit\Runner\BaseTestRunner;
12: use PHPUnit\Runner\CodeCoverage;
13: use PHPUnit\Util\Test as TestUtil;
14: use SebastianBergmann\CodeCoverage\CodeCoverage as CodeCoverageRaw;
15:
16: if (\PHP_VERSION_ID >= 8_01_00) {
17: trait Phpunit9xTestCaseTrait
18: {
19: #[\Override]
20: protected function onNotSuccessfulTest(\Throwable $e): never
21: {
22: $this->_onNotSuccessfulTest($e);
23: }
24: }
25: } else {
26: trait Phpunit9xTestCaseTrait
27: {
28: #[\Override]
29: protected function onNotSuccessfulTest(\Throwable $e): void
30: {
31: $this->_onNotSuccessfulTest($e);
32: }
33: }
34: }
35:
36: /**
37: * Generic TestCase for PHPUnit tests for ATK4 repos.
38: */
39: abstract class TestCase extends BaseTestCase
40: {
41: use Phpunit9xTestCaseTrait;
42: use WarnDynamicPropertyTrait;
43:
44: final public static function isPhpunit9x(): bool
45: {
46: return (new \ReflectionClass(self::class))->hasMethod('getStatus');
47: }
48:
49: #[\Override]
50: protected function setUp(): void
51: {
52: // rerun data providers to fix coverage when coverage for test files is enabled
53: // https://github.com/sebastianbergmann/php-code-coverage/issues/920
54: $staticClass = get_class(new class() {
55: /** @var array<string, true> */
56: public static $processedMethods = [];
57: });
58: $classRefl = new \ReflectionClass(static::class);
59: foreach ($classRefl->getMethods() as $methodRefl) {
60: $methodDoc = $methodRefl->getDocComment();
61: if ($methodDoc !== false && preg_match_all('~@dataProvider[ \t]+([\w\x7f-\xff]+::)?([\w\x7f-\xff]+)~', $methodDoc, $matchesAll, \PREG_SET_ORDER)) {
62: foreach ($matchesAll as $matches) {
63: $providerClassRefl = $matches[1] === '' ? $classRefl : new \ReflectionClass($matches[1]);
64: $providerMethodRefl = $providerClassRefl->getMethod($matches[2]);
65: $key = $providerClassRefl->getName() . '::' . $providerMethodRefl->getName();
66: if (!isset($staticClass::$processedMethods[$key])) {
67: $staticClass::$processedMethods[$key] = true;
68: $providerInstance = $providerClassRefl->newInstanceWithoutConstructor();
69: $provider = $providerMethodRefl->invoke($providerInstance);
70: if (!is_array($provider)) {
71: // yield all provider data
72: iterator_to_array($provider);
73: }
74: }
75: }
76: }
77: }
78:
79: parent::setUp();
80: }
81:
82: #[\Override]
83: protected function tearDown(): void
84: {
85: parent::tearDown();
86:
87: // release objects from TestCase instance as it is never released
88: // https://github.com/sebastianbergmann/phpunit/issues/4705
89: $classes = [];
90: $class = static::class;
91: do {
92: $classes[] = $class;
93: $class = get_parent_class($class);
94: } while ($class !== BaseTestCase::class);
95: unset($class);
96: foreach (array_reverse($classes) as $class) {
97: \Closure::bind(function () use ($class) {
98: foreach (array_keys(array_intersect_key(array_diff_key(get_object_vars($this), get_class_vars(BaseTestCase::class)), get_class_vars($class))) as $k) {
99: $reflectionProperty = new \ReflectionProperty($class, $k);
100: if (\PHP_MAJOR_VERSION < 8
101: ? array_key_exists($k, $reflectionProperty->getDeclaringClass()->getDefaultProperties())
102: : (null ?? $reflectionProperty->hasDefaultValue()) // @phpstan-ignore-line for PHP 7.x
103: ) {
104: $this->{$k} = \PHP_MAJOR_VERSION < 8
105: ? $reflectionProperty->getDeclaringClass()->getDefaultProperties()[$k]
106: : (null ?? $reflectionProperty->getDefaultValue()); // @phpstan-ignore-line for PHP 7.x
107: } else {
108: unset($this->{$k});
109: }
110: }
111: }, $this, $class)();
112: }
113:
114: // once PHP 8.0 support is dropped, needed only once, see:
115: // https://github.com/php/php-src/commit/b58d74547f7700526b2d7e632032ed808abab442
116: if (\PHP_VERSION_ID < 80100) {
117: gc_collect_cycles();
118: }
119: gc_collect_cycles();
120:
121: // fix coverage for skipped/incomplete tests
122: // based on https://github.com/sebastianbergmann/phpunit/blob/9.5.21/src/Framework/TestResult.php#L830 https://github.com/sebastianbergmann/phpunit/blob/10.4.2/src/Framework/TestRunner.php#L154
123: // and https://github.com/sebastianbergmann/phpunit/blob/9.5.21/src/Framework/TestResult.php#L857 https://github.com/sebastianbergmann/phpunit/blob/10.4.2/src/Framework/TestRunner.php#L178
124: if (self::isPhpunit9x() ? in_array($this->getStatus(), [BaseTestRunner::STATUS_SKIPPED, BaseTestRunner::STATUS_INCOMPLETE], true) : $this->status()->isSkipped() || $this->status()->isIncomplete()) {
125: $coverage = self::isPhpunit9x() ? $this->getTestResultObject()->getCodeCoverage() : (CodeCoverage::instance()->isActive() ? CodeCoverage::instance() : null);
126: if ($coverage !== null) {
127: $coverageId = self::isPhpunit9x() ? \Closure::bind(static fn () => $coverage->currentId, null, CodeCoverageRaw::class)() : (\Closure::bind(static fn () => $coverage->collecting, null, CodeCoverage::class)() ? $this : null);
128: if ($coverageId !== null) {
129: $linesToBeCovered = self::isPhpunit9x() ? TestUtil::getLinesToBeCovered(static::class, $this->getName(false)) : (new CodeCoverageMetadata())->linesToBeCovered(static::class, $this->name());
130: $linesToBeUsed = self::isPhpunit9x() ? TestUtil::getLinesToBeUsed(static::class, $this->getName(false)) : (new CodeCoverageMetadata())->linesToBeUsed(static::class, $this->name());
131: $coverage->stop(true, $linesToBeCovered, $linesToBeUsed);
132: $coverage->start($coverageId);
133: }
134: }
135: }
136: }
137:
138: private function releaseObjectsFromExceptionTrace(\Throwable $e): void
139: {
140: $replaceObjectsFx = static function ($v) use (&$replaceObjectsFx) {
141: if (is_object($v) && !$v instanceof \DateTimeInterface) {
142: $v = 'object of ' . get_debug_type($v) . ' class unreferenced by ' . self::class;
143: } elseif (is_array($v)) {
144: $v = array_map($replaceObjectsFx, $v);
145: }
146:
147: return $v;
148: };
149:
150: $traceReflectionProperty = new \ReflectionProperty($e instanceof \Exception ? \Exception::class : \Error::class, 'trace');
151: $traceReflectionProperty->setAccessible(true);
152: $traceReflectionProperty->setValue($e, $replaceObjectsFx($traceReflectionProperty->getValue($e)));
153: if ($e instanceof \Atk4\Core\Exception) {
154: $paramsReflectionProperty = new \ReflectionProperty(\Atk4\Core\Exception::class, 'params');
155: $paramsReflectionProperty->setAccessible(true);
156: $paramsReflectionProperty->setValue($e, $replaceObjectsFx($paramsReflectionProperty->getValue($e)));
157: }
158:
159: if ($e->getPrevious() !== null) {
160: $this->releaseObjectsFromExceptionTrace($e->getPrevious());
161: }
162: }
163:
164: /**
165: * @return never
166: */
167: protected function _onNotSuccessfulTest(\Throwable $e): void
168: {
169: // release objects from uncaught exception as it is never released
170: $this->releaseObjectsFromExceptionTrace($e);
171:
172: // once PHP 8.0 support is dropped, needed only once, see:
173: // https://github.com/php/php-src/commit/b58d74547f7700526b2d7e632032ed808abab442
174: if (\PHP_VERSION_ID < 80100) {
175: gc_collect_cycles();
176: }
177: gc_collect_cycles();
178:
179: parent::onNotSuccessfulTest($e);
180: }
181: }
182: