From 40e3dfe7b4f9ebfc7cd318156b58d97c10bd9a09 Mon Sep 17 00:00:00 2001 From: Caen De Silva Date: Sun, 8 Sep 2024 20:26:19 +0200 Subject: [PATCH] Add linting rule against using useless parent calls in unit tests --- monorepo/HydeStan/HydeStan.php | 22 ++++++++++++++++++++++ monorepo/HydeStan/includes/helpers.php | 9 ++++++--- 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/monorepo/HydeStan/HydeStan.php b/monorepo/HydeStan/HydeStan.php index 05aa7eafe55..ea49692f419 100644 --- a/monorepo/HydeStan/HydeStan.php +++ b/monorepo/HydeStan/HydeStan.php @@ -20,6 +20,7 @@ final class HydeStan private const TEST_FILE_ANALYSERS = [ NoFixMeAnalyser::class, NoUsingAssertEqualsForScalarTypesTestAnalyser::class, + NoParentSetUpTearDownInUnitTestCaseAnalyser::class, ]; private const LINE_ANALYSERS = [ @@ -382,3 +383,24 @@ public function run(string $file, int $lineNumber, string $line): void } } } + +class NoParentSetUpTearDownInUnitTestCaseAnalyser extends FileAnalyser +{ + public function run(string $file, string $contents): void + { + if (! str_contains($contents, 'extends UnitTestCase')) { + return; + } + + $methods = ['setUp', 'tearDown']; + + foreach ($methods as $method) { + AnalysisStatisticsContainer::analysedExpression(); + if (str_contains($contents, "parent::$method()")) { + $lineNumber = substr_count(substr($contents, 0, strpos($contents, $method)), "\n") + 1; + $this->fail(sprintf("Found '%s' method in UnitTestCase at %s", "parent::$method()", fileLink($file, $lineNumber, false))); + HydeStan::addActionsMessage('error', $file, $lineNumber, "HydeStan: UnnecessaryParent{$method}MethodError", "{$method} method in UnitTestCase performs no operation and should be removed."); + } + } + } +} diff --git a/monorepo/HydeStan/includes/helpers.php b/monorepo/HydeStan/includes/helpers.php index f3a9c8dcb31..7e542f683d3 100644 --- a/monorepo/HydeStan/includes/helpers.php +++ b/monorepo/HydeStan/includes/helpers.php @@ -51,11 +51,14 @@ function check_str_contains_any(array $searches, string $line): bool return $strContainsAny; } -function fileLink(string $file, ?int $line = null): string +function fileLink(string $file, ?int $line = null, bool $substr = true): string { $path = (realpath(__DIR__.'/../../packages/framework/'.$file) ?: $file).($line ? ':'.$line : ''); - $trim = strlen(getcwd()) + 2; - $path = substr($path, $trim); + + if ($substr) { + $trim = strlen(getcwd()) + 2; + $path = substr($path, $trim); + } return str_replace('\\', '/', $path); }