diff --git a/src/Rules/PHPUnit/DataProviderDataRule.php b/src/Rules/PHPUnit/DataProviderDataRule.php index 81e0fbe..d2b52af 100644 --- a/src/Rules/PHPUnit/DataProviderDataRule.php +++ b/src/Rules/PHPUnit/DataProviderDataRule.php @@ -3,9 +3,11 @@ namespace PHPStan\Rules\PHPUnit; use PhpParser\Node; +use PHPStan\Analyser\NodeCallbackInvoker; use PHPStan\Analyser\Scope; use PHPStan\BetterReflection\Reflection\ReflectionMethod; use PHPStan\Node\Expr\TypeExpr; +use PHPStan\Reflection\ClassReflection; use PHPStan\Rules\MultipleNodeTypesRule; use PHPStan\Type\ObjectType; use PHPStan\Type\Type; @@ -57,20 +59,33 @@ public function processNode(Node $node, Scope $scope): array return []; } - if ($scope->getFunction() === null) { + $classReflection = $scope->getClassReflection(); + if ($classReflection === null) { return []; } - if ($scope->isInAnonymousFunction()) { + + $method = $scope->getFunction(); + if ($method === null) { + $testMethodWithProviderClosure = $this->findTestMethodWithDataProviderClosure($node, $scope, $classReflection); + if ($testMethodWithProviderClosure === null) { + return []; + } + + [$testMethod, $validateArgumentCount] = $testMethodWithProviderClosure; + $this->checkDataProviderData( + $node, + $scope, + $classReflection, + [[$testMethod, !$validateArgumentCount && !$testMethod->isVariadic()]], + ); + return []; } - - $classReflection = $scope->getClassReflection(); - if ($classReflection === null) { + if ($scope->isInAnonymousFunction()) { return []; } $testWithProviderMethods = []; - $method = $scope->getFunction(); $testMethods = $this->testMethodsHelper->getTestMethods($classReflection, $scope); foreach ($testMethods as $testMethod) { foreach ($this->dataProviderHelper->getDataProviderMethods($scope, $testMethod, $classReflection) as [, $providerMethodName]) { @@ -85,15 +100,36 @@ public function processNode(Node $node, Scope $scope): array return []; } + $maxNumberOfParameters = $this->getMaxNumberOfParameters($testWithProviderMethods); + + $testMethodsToCheck = []; + foreach ($testWithProviderMethods as $testWithProviderMethod) { + $testMethodsToCheck[] = [ + $testWithProviderMethod, + !$testWithProviderMethod->isVariadic() + && $testWithProviderMethod->getNumberOfParameters() !== $maxNumberOfParameters, + ]; + } + + $this->checkDataProviderData($node, $scope, $classReflection, $testMethodsToCheck); + + return []; + } + + /** + * @param Node\Stmt\Return_|Node\Expr\Yield_|Node\Expr\YieldFrom $node + * @param Scope&NodeCallbackInvoker $scope + * @param list $testMethods test methods with a flag whether to trim arguments to the number of parameters + */ + private function checkDataProviderData(Node $node, Scope $scope, ClassReflection $classReflection, array $testMethods): void + { $arraysTypes = $this->buildArrayTypesFromNode($node, $scope); if ($arraysTypes === []) { - return []; + return; } - $maxNumberOfParameters = $this->getMaxNumberOfParameters($testWithProviderMethods); - - foreach ($testWithProviderMethods as $testWithProviderMethod) { - $numberOfParameters = $testWithProviderMethod->getNumberOfParameters(); + foreach ($testMethods as [$testMethod, $trimArgs]) { + $numberOfParameters = $testMethod->getNumberOfParameters(); foreach ($arraysTypes as [$startLine, $arraysType]) { $args = $this->arrayItemsToArgs($arraysType, $numberOfParameters); @@ -101,23 +137,63 @@ public function processNode(Node $node, Scope $scope): array continue; } - if ( - !$testWithProviderMethod->isVariadic() - && $numberOfParameters !== $maxNumberOfParameters - ) { + if ($trimArgs) { $args = array_slice($args, 0, $numberOfParameters); } $scope->invokeNodeCallback(new Node\Expr\MethodCall( new TypeExpr(new ObjectType($classReflection->getName())), - $testWithProviderMethod->getName(), + $testMethod->getName(), $args, ['startLine' => $startLine], )); } } + } - return []; + /** + * Finds the test method whose #[DataProviderClosure] attribute contains the closure + * the given node is directly declared in. + * + * @return array{ReflectionMethod, bool}|null test method and whether the argument count should be validated + */ + private function findTestMethodWithDataProviderClosure(Node $node, Scope $scope, ClassReflection $classReflection): ?array + { + if (!$scope->isInAnonymousFunction()) { + return null; + } + + // test methods declared in traits are not considered by TestMethodsHelper. + // line numbers of a trait would also be compared with closures of the using class file. + if ($scope->isInTrait()) { + return null; + } + + // skip closures nested within the data provider closure + $parentScope = $scope->getParentScope(); + if ($parentScope === null || $parentScope->isInAnonymousFunction()) { + return null; + } + + $nodeStartPos = $node->getStartFilePos(); + $testMethods = $this->testMethodsHelper->getTestMethods($classReflection, $scope); + foreach ($testMethods as $testMethod) { + foreach ($this->dataProviderHelper->getDataProviderClosures($testMethod) as [$closure, $validateArgumentCount]) { + if ( + $nodeStartPos < $closure->getStartFilePos() + || $nodeStartPos > $closure->getEndFilePos() + ) { + continue; + } + + return [ + $testMethod, + $validateArgumentCount === null || !$scope->getType($validateArgumentCount)->isFalse()->yes(), + ]; + } + } + + return null; } /** diff --git a/src/Rules/PHPUnit/DataProviderHelper.php b/src/Rules/PHPUnit/DataProviderHelper.php index a2d90bf..3e498c9 100644 --- a/src/Rules/PHPUnit/DataProviderHelper.php +++ b/src/Rules/PHPUnit/DataProviderHelper.php @@ -6,7 +6,9 @@ use PhpParser\Modifiers; use PhpParser\Node; use PhpParser\Node\Attribute; +use PhpParser\Node\Expr; use PhpParser\Node\Expr\ClassConstFetch; +use PhpParser\Node\Expr\Closure; use PhpParser\Node\Name; use PhpParser\Node\Scalar\String_; use PhpParser\Node\Stmt\ClassLike; @@ -75,6 +77,33 @@ public function getDataProviderMethods( yield from $this->yieldDataProviderAttributes($testMethod, $classReflection); } + /** + * Returns closures defined via the #[DataProviderClosure] attribute (PHPUnit 13.4+) + * together with the expression of its `validateArgumentCount` argument, if given. + * + * @return iterable + */ + public function getDataProviderClosures(ReflectionMethod $testMethod): iterable + { + if (!$this->PHPUnitVersion->supportsDataProviderClosureAttribute()->yes()) { + return; + } + + foreach ($testMethod->getAttributesByName('PHPUnit\Framework\Attributes\DataProviderClosure') as $attr) { + $args = $attr->getArgumentsExpressions(); + + $closure = $args[0] ?? $args['closure'] ?? null; + if (!$closure instanceof Closure) { + continue; + } + + yield [ + $closure, + $args[1] ?? $args['validateArgumentCount'] ?? null, + ]; + } + } + /** * @return array */ diff --git a/src/Rules/PHPUnit/PHPUnitVersion.php b/src/Rules/PHPUnit/PHPUnitVersion.php index 0b6522b..39c798a 100644 --- a/src/Rules/PHPUnit/PHPUnitVersion.php +++ b/src/Rules/PHPUnit/PHPUnitVersion.php @@ -42,6 +42,11 @@ public function supportsDataProviderAttribute(): TrinaryLogic return TrinaryLogic::createFromBoolean($this->majorVersion >= 10); } + public function supportsDataProviderClosureAttribute(): TrinaryLogic + { + return $this->minVersion(13, 4); + } + public function supportsTestAttribute(): TrinaryLogic { if ($this->majorVersion === null) { diff --git a/tests/Rules/PHPUnit/DataProviderDataRuleTest.php b/tests/Rules/PHPUnit/DataProviderDataRuleTest.php index 4f88814..b5df224 100644 --- a/tests/Rules/PHPUnit/DataProviderDataRuleTest.php +++ b/tests/Rules/PHPUnit/DataProviderDataRuleTest.php @@ -19,10 +19,12 @@ class DataProviderDataRuleTest extends RuleTestCase { private ?int $phpunitVersion; + private ?int $phpunitMinorVersion = 0; + protected function getRule(): Rule { $reflectionProvider = $this->createReflectionProvider(); - $phpunitVersion = new PHPUnitVersion($this->phpunitVersion, 0); + $phpunitVersion = new PHPUnitVersion($this->phpunitVersion, $this->phpunitMinorVersion); /** @var list> $rules */ $rules = [ @@ -298,6 +300,118 @@ public function testTrimmingArgs(): void ]); } + public function testDataProviderClosure(): void + { + $this->phpunitVersion = 13; + $this->phpunitMinorVersion = 4; + + $this->analyse([__DIR__ . '/data/data-provider-closure.php'], [ + [ + 'Parameter #2 $b of method DataProviderClosureTest\DataTest::testAdd() expects int, string given.', + 13, + ], + [ + 'Parameter #3 $expected of method DataProviderClosureTest\DataTest::testAdd() expects int, false given.', + 15, + ], + [ + 'Parameter #3 $expected of method DataProviderClosureTest\DataTest::testNamedDataSets() expects int, string given.', + 25, + ], + [ + 'Parameter #1 $a of method DataProviderClosureTest\DataTest::testGenerator() expects int, string given.', + 34, + ], + [ + 'Parameter #2 $b of method DataProviderClosureTest\DataTest::testGenerator() expects int, true given.', + 37, + ], + [ + 'Parameter #2 $b of method DataProviderClosureTest\DataTest::testVariables() expects int, string given.', + 50, + ], + [ + 'Parameter #2 $b of method DataProviderClosureTest\DataTest::testNamedArgument() expects int, string given.', + 57, + ], + [ + 'Method DataProviderClosureTest\DataTest::testWithArgumentCountValidation() invoked with 3 parameters, 2 required.', + 71, + ], + [ + 'Parameter #1 $a of method DataProviderClosureTest\DataTest::testWithoutArgumentCountValidationTypeError() expects int, string given.', + 78, + ], + [ + 'Parameter #2 $b of method DataProviderClosureTest\DataTest::testWithoutArgumentCountValidationTypeError() expects int, string given.', + 78, + ], + [ + 'Parameter #2 $b of method DataProviderClosureTest\DataTest::testRepeated() expects int, string given.', + 99, + ], + [ + 'Parameter #2 $b of method DataProviderClosureTest\DataTest::testSingleLine() expects int, string given.', + 105, + ], + [ + 'Parameter #3 ...$rest of method DataProviderClosureTest\DataTest::testVariadicWithoutArgumentCountValidation() expects int, string given.', + 111, + ], + [ + 'Method DataProviderClosureTest\DataTest::testConstantWithArgumentCountValidation() invoked with 3 parameters, 2 required.', + 129, + ], + [ + 'Method DataProviderClosureTest\DataTest::testSameLine() invoked with 3 parameters, 2 required.', + 135, + ], + [ + 'Method DataProviderClosureTest\DataTest::testUnknownBoolArgumentCountValidation() invoked with 3 parameters, 2 required.', + 142, + ], + [ + 'Method DataProviderClosureTest\DataTest::testFalsyArgumentCountValidation() invoked with 3 parameters, 2 required.', + 150, + ], + ]); + } + + public function testDataProviderClosureInTrait(): void + { + $this->phpunitVersion = 13; + $this->phpunitMinorVersion = 4; + + // closures of test methods declared in traits are not checked, + // and must not be mixed up with closures on the same lines in the class using the trait + $this->analyse([ + __DIR__ . '/data/data-provider-closure-trait-user.php', + __DIR__ . '/data/data-provider-closure-trait.php', + ], []); + } + + /** + * @return iterable + */ + static public function provideUnsupportedDataProviderClosurePHPUnitVersions(): iterable + { + yield [null, null]; + yield [12, 5]; + yield [13, 3]; + } + + /** + * @dataProvider provideUnsupportedDataProviderClosurePHPUnitVersions + */ + #[DataProvider('provideUnsupportedDataProviderClosurePHPUnitVersions')] + public function testDataProviderClosureUnsupportedPHPUnitVersion(?int $major, ?int $minor): void + { + $this->phpunitVersion = $major; + $this->phpunitMinorVersion = $minor; + + $this->analyse([__DIR__ . '/data/data-provider-closure.php'], []); + } + static public function provideNamedArgumentPHPUnitVersions(): iterable { yield [null]; // unknown phpunit version diff --git a/tests/Rules/PHPUnit/data/data-provider-closure-trait-user.php b/tests/Rules/PHPUnit/data/data-provider-closure-trait-user.php new file mode 100644 index 0000000..01139c1 --- /dev/null +++ b/tests/Rules/PHPUnit/data/data-provider-closure-trait-user.php @@ -0,0 +1,23 @@ += 8.5 + +namespace DataProviderClosureTraitTest; + +use PHPUnit\Framework\Attributes\DataProviderClosure; +use PHPUnit\Framework\TestCase; + +final class TraitUserTest extends TestCase +{ + #[DataProviderClosure(static function (): array { + return [[1, 2]]; + })] + public function testOwn(int $a, int $b): void + { + } + + #[DataProviderClosure('notAClosure')] + public function testNotAClosure(int $a): void + { + } + + use ProviderTrait; +} diff --git a/tests/Rules/PHPUnit/data/data-provider-closure-trait.php b/tests/Rules/PHPUnit/data/data-provider-closure-trait.php new file mode 100644 index 0000000..5db98e5 --- /dev/null +++ b/tests/Rules/PHPUnit/data/data-provider-closure-trait.php @@ -0,0 +1,15 @@ += 8.5 + +namespace DataProviderClosureTraitTest; + +use PHPUnit\Framework\Attributes\DataProviderClosure; + +trait ProviderTrait +{ + #[DataProviderClosure(static function (): array { + return [[1, 'fromTrait']]; + })] + public function testInTrait(int $a, int $b): void + { + } +} diff --git a/tests/Rules/PHPUnit/data/data-provider-closure.php b/tests/Rules/PHPUnit/data/data-provider-closure.php new file mode 100644 index 0000000..c1ad48d --- /dev/null +++ b/tests/Rules/PHPUnit/data/data-provider-closure.php @@ -0,0 +1,162 @@ += 8.5 + +namespace DataProviderClosureTest; + +use PHPUnit\Framework\Attributes\DataProviderClosure; +use PHPUnit\Framework\TestCase; + +final class DataTest extends TestCase +{ + #[DataProviderClosure(static function (): array { + return [ + [0, 0, 0], + [0, '1', 1], + [1, 0, 1], + [1, 1, false], + ]; + })] + public function testAdd(int $a, int $b, int $expected): void + { + } + + #[DataProviderClosure(static function (): array { + return [ + 'zeros' => [0, 0, 0], + 'one plus one' => [1, 1, '2'], + ]; + })] + public function testNamedDataSets(int $a, int $b, int $expected): void + { + } + + #[DataProviderClosure(static function (): iterable { + yield [0, 0]; + yield ['0', 0]; + yield from [ + [1, 1], + [1, true], + ]; + })] + public function testGenerator(int $a, int $b): void + { + } + + #[DataProviderClosure(static function (): array { + $data = [[1, 2], [3, 4]]; + if (rand(0, 1)) { + $data = [[1, 'foo']]; + } + + return $data; + })] + public function testVariables(int $a, int $b): void + { + } + + #[DataProviderClosure(closure: static function (): array { + return [[1, 'foo']]; + })] + public function testNamedArgument(int $a, int $b): void + { + } + + #[DataProviderClosure(static function (): array { + return [[1, 2, 3]]; + }, validateArgumentCount: false)] + public function testWithoutArgumentCountValidation(int $a, int $b): void + { + } + + #[DataProviderClosure(static function (): array { + return [[1, 2, 3]]; + })] + public function testWithArgumentCountValidation(int $a, int $b): void + { + } + + #[DataProviderClosure(static function (): array { + return [['foo', 'bar']]; + }, false)] + public function testWithoutArgumentCountValidationTypeError(int $a, int $b): void + { + } + + #[DataProviderClosure(static function (): array { + $fn = static function (): array { + return [['not', 'a', 'data', 'set']]; + }; + + return [[1, 2]]; + })] + public function testNestedClosure(int $a, int $b): void + { + } + + #[DataProviderClosure(static function (): array { + return [[1, 2]]; + })] + #[DataProviderClosure(static function (): array { + return [[1, 'two']]; + })] + public function testRepeated(int $a, int $b): void + { + } + + #[DataProviderClosure(static function (): array { return [[1, 'foo']]; })] + public function testSingleLine(int $a, int $b): void + { + } + + #[DataProviderClosure(static function (): array { + return [[1, 2, 'three']]; + }, validateArgumentCount: false)] + public function testVariadicWithoutArgumentCountValidation(int $a, int ...$rest): void + { + } + + const NO_VALIDATION = false; + + const WITH_VALIDATION = true; + + #[DataProviderClosure(static function (): array { + return [[1, 2, 3]]; + }, self::NO_VALIDATION)] + public function testConstantWithoutArgumentCountValidation(int $a, int $b): void + { + } + + #[DataProviderClosure(static function (): array { + return [[1, 2, 3]]; + }, validateArgumentCount: self::WITH_VALIDATION)] + public function testConstantWithArgumentCountValidation(int $a, int $b): void + { + } + + #[DataProviderClosure(static function (): array { return [[1, 2, 3]]; }), DataProviderClosure(static function (): array { return [[1, 2, 3]]; }, false)] + public function testSameLine(int $a, int $b): void + { + } + + // a value not known to be false at analysis time keeps the argument count validation enabled + #[DataProviderClosure(static function (): array { + return [[1, 2, 3]]; + }, validateArgumentCount: ZEND_DEBUG_BUILD)] + public function testUnknownBoolArgumentCountValidation(int $a, int $b): void + { + } + + // only false disables the argument count validation, other falsy values do not + #[DataProviderClosure(static function (): array { + return [[1, 2, 3]]; + }, validateArgumentCount: null)] + public function testFalsyArgumentCountValidation(int $a, int $b): void + { + } + + #[DataProviderClosure(static function (): array { + return [['foo']]; + })] + public function notATest(int $a): void + { + } +}