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
28 changes: 26 additions & 2 deletions src/DocblockSpecials.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,13 @@ final class DocblockSpecials
'usesDefaultClass' => true,
];

/**
* Matches every tag PHPUnit 11 reads from a docblock (the keys of DocblockMetadataHandler::ATTRIBUTES) by its
* first letters, in any case.
*/
private const TAGS = '/@(?:after|backup|before|covers|dataProvider|depends|doesNotPerformAssertions|exclude|group'
. '|large|medium|postCondition|preCondition|preserveGlobalState|requires|run|small|test|ticket|uses)/i';

/**
* The tags PHPUnit 11 accepts. A malformed tag is ignored by PHPUnit, so it is not here.
*
Expand All @@ -50,7 +57,7 @@ public static function of(Node $node): array
}

/**
* Every tag, malformed or not.
* Every tag, malformed or not, of a docblock that may hold a tag PHPUnit 11 reads.
*
* @return array<string, list<array{int, string}>> tag => [[file line, value]]
*/
Expand All @@ -77,13 +84,30 @@ public static function malformed(Node $node): array
return $malformed;
}

/**
* Whether the docblock of the node may hold a tag PHPUnit 11 reads. Without one, of(), all() and malformed() find
* nothing.
*/
public static function mayHoldTags(Node $node): bool
{
$docblock = $node->getDocComment();

return $docblock !== null && self::docblockMayHoldTags($docblock);
}

private static function docblockMayHoldTags(Doc $docblock): bool
{
// Psalm's DocblockParser removes every \r before it reads a tag
return \preg_match(self::TAGS, \str_replace("\r", '', $docblock->getText())) === 1;
}

/**
* @return list<array{string, int, string, string|null}> [tag, file line, value, what is wrong with the tag]
*/
private static function parse(Node $node): array
{
$docblock = $node->getDocComment();
if (!$docblock) {
if ($docblock === null || !self::docblockMayHoldTags($docblock)) {
return [];
}

Expand Down
14 changes: 13 additions & 1 deletion src/Hooks/DocblockMetadataHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,20 @@ public static function afterStatementAnalysis(AfterClassLikeAnalysisEvent $event

// Inherited methods are reported with the class that declares them. A trait docblock or method is reported
// once for every class using it, at the same location with the same message, which Psalm deduplicates.
$methods_with_metadata = [];
foreach ($class_storage->declaring_method_ids as $declaring_method_id) {
$declaring_class = $codebase->classlike_storage_provider->get($declaring_method_id->fq_class_name);
$declaring_class_name = $declaring_method_id->fq_class_name;
if (!\array_key_exists($declaring_class_name, $methods_with_metadata)) {
$methods_with_metadata[$declaring_class_name] = TestCaseHandler::methodsWithMetadata(
$codebase->classlike_storage_provider->get($declaring_class_name),
);
}
$with_metadata = $methods_with_metadata[$declaring_class_name];
if ($with_metadata !== null && !isset($with_metadata[$declaring_method_id->method_name])) {
continue;
}

$declaring_class = $codebase->classlike_storage_provider->get($declaring_class_name);
$declaring_class_node = match (true) {
\strtolower($declaring_class->name) === \strtolower($class_storage->name) => $class_node,
$declaring_class->is_trait => $codebase->classlikes->getTraitNode($declaring_class->name),
Expand Down
66 changes: 58 additions & 8 deletions src/Hooks/TestCaseHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -341,15 +341,23 @@ public static function afterClassLikeVisit(AfterClassLikeVisitEvent $event)
$class_storage->sealed_methods = false;
}

$metadata = (array) ($class_storage->custom_metadata[__NAMESPACE__] ?? []);
$before = self::getBeforeMethods($class_storage, $class_node, $aliases);
if ($before !== []) {
$class_storage->custom_metadata[__NAMESPACE__] = ['before' => $before];
$metadata['before'] = $before;
}

$file_path = $statements_source->getFilePath();
$file_storage = $codebase->file_storage_provider->get($file_path);

$with_metadata = [];
foreach ($class_node->getMethods() as $method) {
// any attribute: at analysis, the aliases also hold the imports written after the class
if ($method->attrGroups === [] && !DocblockSpecials::mayHoldTags($method)) {
continue;
}
$with_metadata[$method->name->toLowerString()] = true;

$providers = self::getDataProviders($method, $aliases, $aliases, $class_storage);
foreach ($providers as $provider) {
if ($provider['class'] === null) {
Expand Down Expand Up @@ -379,6 +387,10 @@ public static function afterClassLikeVisit(AfterClassLikeVisitEvent $event)
'depends' => self::getDependencyTargets($method, $aliases, $class_storage) !== [],
];
}

// a stub and the file it refines are visited into the same storage, the set covers both
$metadata['with_metadata'] = $with_metadata + (array) ($metadata['with_metadata'] ?? []);
$class_storage->custom_metadata[__NAMESPACE__] = $metadata;
}

#[\Override]
Expand Down Expand Up @@ -432,17 +444,29 @@ public static function afterStatementAnalysis(AfterClassLikeAnalysisEvent $event
);
}

$methods_with_metadata = [];
foreach ($class_storage->declaring_method_ids as $method_name_lc => $declaring_method_id) {
$method_name = $codebase->getCasedMethodId($class_storage->name . '::' . $method_name_lc);
$method_storage = $codebase->methods->getStorage($declaring_method_id);
[$declaring_method_class, $declaring_method_name] = \explode('::', (string) $declaring_method_id);
$declaring_class_storage = $codebase->classlike_storage_provider->get($declaring_method_class);
$declaring_method_class = $declaring_method_id->fq_class_name;
$declaring_method_name = $declaring_method_id->method_name;
if (!\array_key_exists($declaring_method_class, $methods_with_metadata)) {
$methods_with_metadata[$declaring_method_class] = self::methodsWithMetadata(
$codebase->classlike_storage_provider->get($declaring_method_class),
);
}
$with_metadata = $methods_with_metadata[$declaring_method_class];

$declaring_class_node = $class_node;
if ($declaring_class_storage->is_trait) {
$declaring_class_node = $codebase->classlikes->getTraitNode($declaring_class_storage->name);
// PHPUnit runs the methods the test case names test*, a trait alias included. Of the others it only reads
// the metadata of their declaration.
if (
$with_metadata !== null
&& !isset($with_metadata[$declaring_method_name])
&& !\str_starts_with($method_name_lc, 'test')
) {
continue;
}

$method_storage = $codebase->methods->getStorage($declaring_method_id);
$declaring_class_storage = $codebase->classlike_storage_provider->get($declaring_method_class);
if (!$method_storage->location) {
continue;
}
Expand All @@ -461,6 +485,10 @@ public static function afterStatementAnalysis(AfterClassLikeAnalysisEvent $event
continue;
}

$declaring_class_node = $declaring_class_storage->is_trait
? $codebase->classlikes->getTraitNode($declaring_class_storage->name)
: $class_node;

$stmt_method = $declaring_class_node->getMethod($declaring_method_name);

if (!$stmt_method) {
Expand Down Expand Up @@ -499,6 +527,8 @@ public static function afterStatementAnalysis(AfterClassLikeAnalysisEvent $event
continue;
}

$method_name = $codebase->getCasedMethodId($class_storage->name . '::' . $method_name_lc);

$dependency_values = self::countDependencyValues(
$codebase,
$stmt_method,
Expand Down Expand Up @@ -1739,6 +1769,26 @@ public static function isPublicMethod(
return $visibility === ClassLikeAnalyzer::VISIBILITY_PUBLIC;
}

/**
* An upper bound of the methods the class-like declares with PHPUnit metadata, as afterClassLikeVisit() found
* them: a method outside it has no attribute and no docblock tag PHPUnit 11 reads. The methods in it and the ones
* a test case names test* still go through every check. Null when unknown: the storage was cached by an older
* version of the plugin.
*
* @return array<lowercase-string, true>|null
*
* @psalm-mutation-free
*
* @internal
*/
public static function methodsWithMetadata(ClassLikeStorage $storage): ?array
{
$metadata = (array) ($storage->custom_metadata[__NAMESPACE__] ?? []);

/** @var array<lowercase-string, true>|null */
return $metadata['with_metadata'] ?? null;
}

/**
* PHPUnit's ParserChain ignores docblock annotations on a class or method that has any PHPUnit attribute.
*
Expand Down
23 changes: 23 additions & 0 deletions tests/acceptance/AnnotationParsing.feature
Original file line number Diff line number Diff line change
Expand Up @@ -648,3 +648,26 @@ final class MyTestCase extends TestCase
| Type | Message | Line |
| InvalidPhpUnitAnnotation | Annotation "@covers" has no value | 14 |
And I see no other errors

Scenario: Malformed annotation on a trait method that is not a test is reported
Given I have the following code
"""
trait HelperTrait
{
/**
* @group
*/
public function helper(): void {
}
}

final class MyTestCase extends TestCase
{
use HelperTrait;
}
"""
When I run Psalm
Then I see these errors
| Type | Message | Line |
| InvalidPhpUnitAnnotation | Annotation "@group" has no value | 8 |
And I see no other errors
130 changes: 130 additions & 0 deletions tests/acceptance/DataProviders.feature
Original file line number Diff line number Diff line change
Expand Up @@ -1400,3 +1400,133 @@ Feature: Data providers
"""
When I run Psalm
Then I see no errors

Scenario: A trait test imported as protected is checked under the public name it is also imported with
Given I have the following code
"""
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Test;

trait HelperTrait
{
#[Test]
#[DataProvider('provide')]
public function check(int $int): void {
$this->assertSame(1, $int);
}
}

final class MyTestCase extends TestCase
{
use HelperTrait {
check as protected;
check as public verify;
}

/**
* @return iterable<int, array{string}>
* @psalm-pure
*/
public static function provide(): iterable {
yield ['a'];
}
}
"""
When I run Psalm
Then I see these errors
| Type | Message |
| InvalidArgument | Argument 1 of NS\HelperTrait::check expects int, string provided by NS\MyTestCase::provide():(iterable[pure]<int, list{string}>) |
And I see no other errors

Scenario: Invalid implementation of an abstract data provider of an inherited @test method is reported
Given I have the following code
"""
abstract class BaseTestCase extends TestCase {
/**
* @return iterable<int,array<int,int>>
* @psalm-pure
*/
abstract public function provide();

/**
* @test
* @dataProvider provide
*/
public function check(int $int): void {
$this->assertSame(1, $int);
}
}

final class MyTestCase extends BaseTestCase {
/**
* @return iterable<int,array<int,int>>
* @psalm-pure
*/
#[\Override]
public function provide() {
yield [1];
}
}
"""
When I run Psalm
Then I see these errors
| Type | Message |
| InvalidDataProvider | Data provider method NS\MyTestCase::provide must be static |
And I see no other errors

Scenario: Invalid implementation of an abstract data provider of an inherited #[Test] method is reported when only the file of the subclass is analysed
Given I have the following code in "BaseTestCase.php"
"""
<?php
namespace NS;

use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;

abstract class BaseTestCase extends TestCase {
/**
* @return iterable<int,array<int,int>>
* @psalm-pure
*/
abstract public function provide();

#[Test]
#[DataProvider('provide')]
public function check(int $int): void {
$this->assertSame(1, $int);
}
}
"""
And I have the following code in "test.php"
"""
<?php
namespace NS;

final class MyTestCase extends BaseTestCase {
/**
* @return iterable<int,array<int,int>>
* @psalm-pure
*/
#[\Override]
public function provide() {
yield [1];
}
}
"""
And I have the following code in "autoload.php"
"""
<?php
spl_autoload_register(function(string $class) {
if ($class === 'NS\\BaseTestCase') {
/** @psalm-suppress UnresolvableInclude */
include __DIR__ . '/BaseTestCase.php';
}
});
"""
And the config uses the autoloader "autoload.php"
When I run Psalm on "test.php"
Then I see these errors
| Type | Message |
| InvalidDataProvider | Data provider method NS\MyTestCase::provide must be static |
And I see no other errors
Loading