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
11 changes: 11 additions & 0 deletions src/Hooks/ProviderReturnTypeHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,17 @@ public static function afterStatementAnalysis(AfterFunctionLikeAnalysisEvent $ev
unset(self::$inferredTypes[$storage]);

$codebase = $event->getCodebase();
$declaring_class = $storage->defining_fqcln;
// Only a test case reads the types, and walking the body of every static helper of the project is costly.
// A trait method is always walked: its storage is shared by the classes using it, any of them can be a test.
if (
$declaring_class !== null
&& !$codebase->classlikes->traitExists($declaring_class)
&& !$codebase->classExtends($declaring_class, 'PHPUnit\Framework\TestCase')
) {
return null;
}

$statements = $method->stmts ?? [];

$finder = new NodeFinder();
Expand Down
57 changes: 57 additions & 0 deletions tests/acceptance/ProviderReturnTypes.feature
Original file line number Diff line number Diff line change
Expand Up @@ -985,3 +985,60 @@ Feature: Data provider return types
| Type | Message | Line |
| InvalidArgument | Argument 1 of NS\MyTestCase::testSomething expects int, 'x' provided by NS\MyTestCase::provide():(array{one: list{'x'}}) | 17 |
And I see no other errors

Scenario: A trait provider is checked when a test method also uses the trait in an anonymous class
Given I have the following code
"""
use PHPUnit\Framework\Attributes\DataProvider;

trait Provides
{
/** @psalm-pure */
public static function provide(): array {
return ['one' => ['x']];
}
}

final class MyTestCase extends TestCase
{
use Provides;

#[DataProvider('provide')]
public function testSomething(int $i): void {
$this->assertSame(1, $i);
new class {
use Provides;
};
}
}
"""
When I run Psalm
Then I see these errors
| Type | Message | Line |
| InvalidArgument | Argument 1 of NS\MyTestCase::testSomething expects int, 'x' provided by NS\Provides::provide():(array{one: list{'x'}}) | 19 |
And I see no other errors

Scenario: A provider that rebinds its scope with a docblock is still checked
Given I have the following code
"""
use PHPUnit\Framework\Attributes\DataProvider;

final class MyTestCase extends TestCase
{
/** @psalm-pure */
public static function provide(): array {
/** @psalm-scope-this \stdClass */
return ['one' => ['x']];
}

#[DataProvider('provide')]
public function testSomething(int $i): void {
$this->assertSame(1, $i);
}
}
"""
When I run Psalm
Then I see these errors
| Type | Message | Line |
| InvalidArgument | Argument 1 of NS\MyTestCase::testSomething expects int, 'x' provided by NS\MyTestCase::provide():(array{one: list{'x'}}) | 15 |
And I see no other errors