Skip to content

Commit 6d45a51

Browse files
authored
[PHPUnit60] Cache containsAssertCall() per node in AddDoesNotPerformAssertionToNonAssertingTestRector (#829)
1 parent 9545637 commit 6d45a51

3 files changed

Lines changed: 145 additions & 28 deletions

File tree

‎.github/workflows/code_analysis.yaml‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,10 @@ jobs:
5252
name: 'Bench framework test cases'
5353
run: php bench/does_not_perform_assertion_framework_test_case_bench.php
5454

55+
-
56+
name: 'Bench cache'
57+
run: php bench/does_not_perform_assertion_cache_bench.php
58+
5559
name: ${{ matrix.actions.name }}
5660
runs-on: ubuntu-latest
5761
timeout-minutes: 10
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\Class_;
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+
$classes = [];
97+
foreach ($testFilePaths as $testFilePath) {
98+
$stmts = $testingParser->parseFileToDecoratedNodes($testFilePath);
99+
$classes = [...$classes, ...$betterNodeFinder->findInstanceOf($stmts, Class_::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 ($classes as $class) {
113+
if ($rector->refactor($class) instanceof Class_) {
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, changed: %d%s', count($classes), $changedCount, PHP_EOL);
125+
printf('CPU: %.4f s (%.3f ms/class)%s', $cpu, $cpu / count($classes) * 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: 10 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -20,14 +20,15 @@
2020
use Rector\NodeTypeResolver\NodeTypeResolver;
2121
use Rector\PhpParser\AstResolver;
2222
use Rector\PhpParser\Node\BetterNodeFinder;
23-
use Rector\PhpParser\Printer\BetterStandardPrinter;
2423
use Rector\PHPUnit\Enum\PHPUnitClassName;
2524
use Rector\StaticTypeMapper\ValueObject\Type\FullyQualifiedObjectType;
2625

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

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

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

5955
public function __construct(
6056
private readonly AstResolver $astResolver,
61-
private readonly BetterStandardPrinter $betterStandardPrinter,
6257
private readonly BetterNodeFinder $betterNodeFinder,
6358
private readonly NodeNameResolver $nodeNameResolver,
6459
private readonly NodeTypeResolver $nodeTypeResolver,
@@ -81,25 +76,22 @@ public function containsAssertCall(ClassMethod $classMethod): bool
8176
return false;
8277
}
8378

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

9385
// A. try "->assert" shallow search first for performance
9486
$hasDirectAssertOrMockCall = $this->hasDirectAssertOrMockCall($classMethod);
9587
if ($hasDirectAssertOrMockCall) {
96-
$this->containsAssertCallByClassMethod[$cacheHash] = true;
88+
$classMethod->setAttribute(self::CONTAINS_ASSERT_CALL_ATTRIBUTE, true);
9789
return true;
9890
}
9991

10092
// B. look for nested calls
10193
$hasNestedAssertOrMockCall = $this->hasNestedAssertCall($classMethod);
102-
$this->containsAssertCallByClassMethod[$cacheHash] = $hasNestedAssertOrMockCall;
94+
$classMethod->setAttribute(self::CONTAINS_ASSERT_CALL_ATTRIBUTE, $hasNestedAssertOrMockCall);
10395

10496
return $hasNestedAssertOrMockCall;
10597
} finally {
@@ -249,16 +241,6 @@ private function isDeclaredInFrameworkTestCase(string $className, string $method
249241
return in_array($declaringClassName, PHPUnitClassName::FRAMEWORK_TEST_CASES, true);
250242
}
251243

252-
private function resolveOwnClassName(ClassMethod $classMethod): string
253-
{
254-
$classReflection = $this->resolveClassReflection($classMethod);
255-
if (! $classReflection instanceof ClassReflection) {
256-
return '';
257-
}
258-
259-
return $classReflection->getName();
260-
}
261-
262244
private function resolveClassName(StaticCall|MethodCall $call): ?string
263245
{
264246
if ($call instanceof StaticCall && $this->nodeNameResolver->isName($call->class, ObjectReference::PARENT)) {
@@ -282,9 +264,9 @@ private function resolveClassName(StaticCall|MethodCall $call): ?string
282264
return $objectType->getClassName();
283265
}
284266

285-
private function resolveClassReflection(Node $node): ?ClassReflection
267+
private function resolveClassReflection(StaticCall $staticCall): ?ClassReflection
286268
{
287-
$scope = $node->getAttribute(AttributeKey::SCOPE);
269+
$scope = $staticCall->getAttribute(AttributeKey::SCOPE);
288270
if (! $scope instanceof Scope) {
289271
return null;
290272
}

0 commit comments

Comments
 (0)