Skip to content

Commit 1eeebcc

Browse files
committed
[PHPUnit60] Cache containsAssertCall() per node in AddDoesNotPerformAssertionToNonAssertingTestRector
The cache key printed the whole method body on every call. Store the result as a node attribute instead - same body in different classes no longer shares a result, and no printing is needed. "parent::method()" now checks the class that declares the method, so a method inherited from TestCase through a parent that does not override it is skipped too, instead of parsing TestCase. Add bench/does_not_perform_assertion_cache_bench.php to cover both.
1 parent 745886e commit 1eeebcc

2 files changed

Lines changed: 154 additions & 32 deletions

File tree

Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
/**
6+
* Benchmark for AddDoesNotPerformAssertionToNonAssertingTestRector on many test classes sharing helper methods.
7+
*
8+
* Each test method calls a helper declared in an abstract parent, and one calls "parent::setUp()" that is only
9+
* declared in TestCase. This measures the containsAssertCall() cache and the "parent::" resolution.
10+
*
11+
* Run on both branches to compare. CPU (user+sys) is the reliable metric; wall is noisy.
12+
*/
13+
14+
use PhpParser\Node\Stmt\ClassMethod;
15+
use Rector\DependencyInjection\LazyContainerFactory;
16+
use Rector\PhpParser\Node\BetterNodeFinder;
17+
use Rector\PHPUnit\PHPUnit60\Rector\ClassMethod\AddDoesNotPerformAssertionToNonAssertingTestRector;
18+
use Rector\Testing\TestingParser\TestingParser;
19+
20+
require __DIR__ . '/../vendor/autoload.php';
21+
22+
const PARENTS = 5; // abstract parents extending TestCase, none overrides setUp()
23+
const TESTS_PER_PARENT = 60; // test classes extending each parent
24+
const TEST_METHODS = 8; // non-asserting test methods per test class
25+
const HELPER_STATEMENTS = 5; // statements per helper, to make printing the body realistic
26+
const MAX_CPU_SECONDS = 1.0; // fails in CI above this
27+
28+
$directory = sys_get_temp_dir() . '/rector_phpunit_cache_bench_' . getmypid();
29+
@mkdir($directory);
30+
31+
$writeClass = static function (string $className, string $body) use ($directory): string {
32+
$filePath = $directory . '/' . $className . '.php';
33+
file_put_contents($filePath, "<?php\n\nnamespace Bench;\n\n" . $body);
34+
return $filePath;
35+
};
36+
37+
// make generated classes visible to PHPStan reflection
38+
spl_autoload_register(static function (string $class) use ($directory): void {
39+
if (! str_starts_with($class, 'Bench\\')) {
40+
return;
41+
}
42+
43+
$filePath = $directory . '/' . substr($class, 6) . '.php';
44+
if (is_file($filePath)) {
45+
require_once $filePath;
46+
}
47+
});
48+
49+
$testFilePaths = [];
50+
51+
for ($parent = 0; $parent < PARENTS; ++$parent) {
52+
$parentClassName = sprintf('AbstractCacheParent%d', $parent);
53+
54+
$methods = '';
55+
for ($helper = 0; $helper < TEST_METHODS; ++$helper) {
56+
$statements = '';
57+
for ($statement = 0; $statement < HELPER_STATEMENTS; ++$statement) {
58+
$statements .= " \$items = array_map(fn (\$item) => \$item + {$statement}, \$items);\n";
59+
}
60+
61+
$methods .= " protected function helper{$helper}(array \$items): array\n {\n{$statements} return \$items;\n }\n\n";
62+
}
63+
64+
$writeClass(
65+
$parentClassName,
66+
"abstract class {$parentClassName} extends \PHPUnit\Framework\TestCase\n{\n{$methods}}\n"
67+
);
68+
69+
for ($test = 0; $test < TESTS_PER_PARENT; ++$test) {
70+
$className = sprintf('CacheParent%dTest%d', $parent, $test);
71+
72+
$methods = " public function testRestart(): void\n {\n parent::setUp();\n }\n\n";
73+
for ($testMethod = 0; $testMethod < TEST_METHODS; ++$testMethod) {
74+
$methods .= " public function testSomething{$testMethod}(): void\n {\n \$value = \$this->helper{$testMethod}([1, 2, 3]);\n }\n\n";
75+
}
76+
77+
$testFilePaths[] = $writeClass(
78+
$className,
79+
"final class {$className} extends {$parentClassName}\n{\n{$methods}}\n"
80+
);
81+
}
82+
}
83+
84+
$rectorConfig = (new LazyContainerFactory())->create();
85+
$rectorConfig->boot();
86+
87+
/** @var TestingParser $testingParser */
88+
$testingParser = $rectorConfig->make(TestingParser::class);
89+
90+
/** @var BetterNodeFinder $betterNodeFinder */
91+
$betterNodeFinder = $rectorConfig->make(BetterNodeFinder::class);
92+
93+
$rector = $rectorConfig->make(AddDoesNotPerformAssertionToNonAssertingTestRector::class);
94+
95+
// parse test files up front, parent files are left for the rule to resolve
96+
$classMethods = [];
97+
foreach ($testFilePaths as $testFilePath) {
98+
$stmts = $testingParser->parseFileToDecoratedNodes($testFilePath);
99+
$classMethods = [...$classMethods, ...$betterNodeFinder->findInstanceOf($stmts, ClassMethod::class)];
100+
}
101+
102+
$cpuSeconds = static function (): float {
103+
$usage = getrusage();
104+
return $usage['ru_utime.tv_sec'] + $usage['ru_utime.tv_usec'] / 1_000_000
105+
+ $usage['ru_stime.tv_sec'] + $usage['ru_stime.tv_usec'] / 1_000_000;
106+
};
107+
108+
$wallStart = microtime(true);
109+
$cpuStart = $cpuSeconds();
110+
111+
$changedCount = 0;
112+
foreach ($classMethods as $classMethod) {
113+
if ($rector->refactor($classMethod) instanceof ClassMethod) {
114+
++$changedCount;
115+
}
116+
}
117+
118+
$cpu = $cpuSeconds() - $cpuStart;
119+
$wall = microtime(true) - $wallStart;
120+
121+
array_map('unlink', glob($directory . '/*.php'));
122+
@rmdir($directory);
123+
124+
printf('test classes: %d, test methods: %d, changed: %d%s', count($testFilePaths), count($classMethods), $changedCount, PHP_EOL);
125+
printf('CPU: %.4f s (%.3f ms/method)%s', $cpu, $cpu / count($classMethods) * 1000, PHP_EOL);
126+
printf('wall: %.4f s%s', $wall, PHP_EOL);
127+
128+
if ($cpu > MAX_CPU_SECONDS) {
129+
printf('CPU %.4f s is over the %.1f s limit%s', $cpu, MAX_CPU_SECONDS, PHP_EOL);
130+
exit(1);
131+
}

‎src/NodeAnalyzer/AssertCallAnalyzer.php‎

Lines changed: 23 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -19,14 +19,15 @@
1919
use Rector\NodeTypeResolver\NodeTypeResolver;
2020
use Rector\PhpParser\AstResolver;
2121
use Rector\PhpParser\Node\BetterNodeFinder;
22-
use Rector\PhpParser\Printer\BetterStandardPrinter;
2322
use Rector\PHPUnit\Enum\PHPUnitClassName;
2423
use Rector\StaticTypeMapper\ValueObject\Type\FullyQualifiedObjectType;
2524

2625
final class AssertCallAnalyzer
2726
{
2827
private const int MAX_NESTED_METHOD_CALL_LEVEL = 5;
2928

29+
private const string CONTAINS_ASSERT_CALL_ATTRIBUTE = 'contains_assert_call';
30+
3031
/**
3132
* @see https://docs.phpunit.de/en/12.4/assertions.html
3233
*/
@@ -45,19 +46,13 @@ final class AssertCallAnalyzer
4546
'should',
4647
];
4748

48-
/**
49-
* @var array<string, bool>
50-
*/
51-
private array $containsAssertCallByClassMethod = [];
52-
5349
/**
5450
* This should prevent segfaults while going too deep into to parsed code. Without it, it might end-up with segfault
5551
*/
5652
private int $classMethodNestingLevel = 0;
5753

5854
public function __construct(
5955
private readonly AstResolver $astResolver,
60-
private readonly BetterStandardPrinter $betterStandardPrinter,
6156
private readonly BetterNodeFinder $betterNodeFinder,
6257
private readonly NodeNameResolver $nodeNameResolver,
6358
private readonly NodeTypeResolver $nodeTypeResolver,
@@ -79,25 +74,22 @@ public function containsAssertCall(ClassMethod $classMethod): bool
7974
return false;
8075
}
8176

82-
// the same body means a different method per class, e.g. "$this->helper()" or "parent::test()"
83-
$cacheHash = md5(
84-
$this->betterStandardPrinter->prettyPrint([$classMethod]) . $this->resolveOwnClassName($classMethod)
85-
);
86-
87-
if (isset($this->containsAssertCallByClassMethod[$cacheHash])) {
88-
return $this->containsAssertCallByClassMethod[$cacheHash];
77+
// cached per node, as the same body means a different method per class, e.g. "$this->helper()"
78+
$containsAssertCall = $classMethod->getAttribute(self::CONTAINS_ASSERT_CALL_ATTRIBUTE);
79+
if (is_bool($containsAssertCall)) {
80+
return $containsAssertCall;
8981
}
9082

9183
// A. try "->assert" shallow search first for performance
9284
$hasDirectAssertOrMockCall = $this->hasDirectAssertOrMockCall($classMethod);
9385
if ($hasDirectAssertOrMockCall) {
94-
$this->containsAssertCallByClassMethod[$cacheHash] = true;
86+
$classMethod->setAttribute(self::CONTAINS_ASSERT_CALL_ATTRIBUTE, true);
9587
return true;
9688
}
9789

9890
// B. look for nested calls
9991
$hasNestedAssertOrMockCall = $this->hasNestedAssertCall($classMethod);
100-
$this->containsAssertCallByClassMethod[$cacheHash] = $hasNestedAssertOrMockCall;
92+
$classMethod->setAttribute(self::CONTAINS_ASSERT_CALL_ATTRIBUTE, $hasNestedAssertOrMockCall);
10193

10294
return $hasNestedAssertOrMockCall;
10395
} finally {
@@ -216,25 +208,15 @@ private function resolveClassMethodFromCall(StaticCall|MethodCall $call): ?Class
216208
return null;
217209
}
218210

219-
$className = $this->resolveClassName($call);
211+
$className = $this->resolveClassName($call, $methodName);
220212
if ($className === null) {
221213
return null;
222214
}
223215

224216
return $this->astResolver->resolveClassMethod($className, $methodName);
225217
}
226218

227-
private function resolveOwnClassName(ClassMethod $classMethod): string
228-
{
229-
$classReflection = $this->resolveClassReflection($classMethod);
230-
if (! $classReflection instanceof ClassReflection) {
231-
return '';
232-
}
233-
234-
return $classReflection->getName();
235-
}
236-
237-
private function resolveClassName(StaticCall|MethodCall $call): ?string
219+
private function resolveClassName(StaticCall|MethodCall $call, string $methodName): ?string
238220
{
239221
if ($call instanceof StaticCall && $this->nodeNameResolver->isName($call->class, ObjectReference::PARENT)) {
240222
// "parent" resolves to a union of all ancestors in type resolver, so use the direct parent class instead
@@ -243,12 +225,21 @@ private function resolveClassName(StaticCall|MethodCall $call): ?string
243225
return null;
244226
}
245227

228+
if (! $parentClassReflection->hasNativeMethod($methodName)) {
229+
return null;
230+
}
231+
232+
// the method can be inherited from any ancestor
233+
$declaringClassName = $parentClassReflection->getNativeMethod($methodName)
234+
->getDeclaringClass()
235+
->getName();
236+
246237
// PHPUnit itself has no asserting test methods, no need to parse its huge classes
247-
if ($parentClassReflection->getName() === PHPUnitClassName::TEST_CASE) {
238+
if ($declaringClassName === PHPUnitClassName::TEST_CASE) {
248239
return null;
249240
}
250241

251-
return $parentClassReflection->getName();
242+
return $declaringClassName;
252243
}
253244

254245
$objectType = $call instanceof MethodCall
@@ -262,9 +253,9 @@ private function resolveClassName(StaticCall|MethodCall $call): ?string
262253
return $objectType->getClassName();
263254
}
264255

265-
private function resolveClassReflection(Node $node): ?ClassReflection
256+
private function resolveClassReflection(StaticCall $staticCall): ?ClassReflection
266257
{
267-
$scope = $node->getAttribute(AttributeKey::SCOPE);
258+
$scope = $staticCall->getAttribute(AttributeKey::SCOPE);
268259
if (! $scope instanceof Scope) {
269260
return null;
270261
}

0 commit comments

Comments
 (0)