Skip to content

Commit

Permalink
Assert all errors has proper identifier (#190)
Browse files Browse the repository at this point in the history
  • Loading branch information
janedbal committed Dec 12, 2023
1 parent deaf0c6 commit 23089fe
Showing 1 changed file with 35 additions and 7 deletions.
42 changes: 35 additions & 7 deletions tests/RuleTestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,14 @@
namespace ShipMonk\PHPStan;

use LogicException;
use PHPStan\Analyser\Error;
use PHPStan\Rules\Rule;
use PHPStan\Testing\RuleTestCase as OriginalRuleTestCase;
use function explode;
use function file_get_contents;
use function implode;
use function preg_match_all;
use function sprintf;
use function trim;

/**
Expand All @@ -19,12 +22,35 @@ abstract class RuleTestCase extends OriginalRuleTestCase

protected function analyseFile(string $file): void
{
$file = $this->getFileHelper()->normalizePath($file);
$this->analyse([$file], $this->parseExpectedErrors($file));
$actualErrors = $this->processActualErrors($this->gatherAnalyserErrors([$file]));
$expectedErrors = $this->parseExpectedErrors($file);

self::assertSame(
implode("\n", $expectedErrors) . "\n",
implode("\n", $actualErrors) . "\n",
);
}

/**
* @return list<array{0: string, 1: int}>
* @param list<Error> $actualErrors
* @return list<string>
*/
private function processActualErrors(array $actualErrors): array
{
$resultToAssert = [];

foreach ($actualErrors as $error) {
$resultToAssert[] = $this->formatErrorForAssert($error->getMessage(), $error->getLine());

self::assertNotNull($error->getIdentifier(), "Missing error identifier for error: {$error->getMessage()}");
self::assertStringStartsWith('shipmonk.', $error->getIdentifier());
}

return $resultToAssert;
}

/**
* @return list<string>
*/
private function parseExpectedErrors(string $file): array
{
Expand Down Expand Up @@ -52,14 +78,16 @@ private function parseExpectedErrors(string $file): array
}

foreach ($matches[1] as $error) {
$expectedErrors[] = [
trim($error),
$line + 1,
];
$expectedErrors[] = $this->formatErrorForAssert(trim($error), $line + 1);
}
}

return $expectedErrors;
}

private function formatErrorForAssert(string $message, ?int $line): string
{
return sprintf('%02d: %s', $line ?? -1, $message);
}

}

0 comments on commit 23089fe

Please sign in to comment.