Skip to content

Commit

Permalink
Add linting rule against using useless parent calls in unit tests
Browse files Browse the repository at this point in the history
  • Loading branch information
caendesilva committed Sep 8, 2024
1 parent 330f089 commit 40e3dfe
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
22 changes: 22 additions & 0 deletions monorepo/HydeStan/HydeStan.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ final class HydeStan
private const TEST_FILE_ANALYSERS = [
NoFixMeAnalyser::class,
NoUsingAssertEqualsForScalarTypesTestAnalyser::class,
NoParentSetUpTearDownInUnitTestCaseAnalyser::class,
];

private const LINE_ANALYSERS = [
Expand Down Expand Up @@ -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.");
}
}
}
}
9 changes: 6 additions & 3 deletions monorepo/HydeStan/includes/helpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down

0 comments on commit 40e3dfe

Please sign in to comment.