Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
110 changes: 93 additions & 17 deletions src/Rules/PHPUnit/DataProviderDataRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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]) {
Expand All @@ -85,39 +100,100 @@ 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<array{ReflectionMethod, bool}> $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);
if ($args === null) {
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;
}

/**
Expand Down
29 changes: 29 additions & 0 deletions src/Rules/PHPUnit/DataProviderHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<array{Closure, Expr|null}>
*/
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<PhpDocTagNode>
*/
Expand Down
5 changes: 5 additions & 0 deletions src/Rules/PHPUnit/PHPUnitVersion.php
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
116 changes: 115 additions & 1 deletion tests/Rules/PHPUnit/DataProviderDataRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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<Rule<Node>> $rules */
$rules = [
Expand Down Expand Up @@ -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<array{int|null, int|null}>
*/
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
Expand Down
23 changes: 23 additions & 0 deletions tests/Rules/PHPUnit/data/data-provider-closure-trait-user.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php // lint >= 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;
}
15 changes: 15 additions & 0 deletions tests/Rules/PHPUnit/data/data-provider-closure-trait.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php // lint >= 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
{
}
}
Loading