From 490f321a0dc5750ac391e38ccd66dc96bbad4683 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cl=C3=A9ment=20Birkl=C3=A9?= Date: Wed, 19 Mar 2025 15:59:45 +0100 Subject: [PATCH] fix: normalize snapshot paths for files outside tests directory --- src/Repositories/SnapshotRepository.php | 15 ++++++++++++++- src/TestSuite.php | 1 + 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/src/Repositories/SnapshotRepository.php b/src/Repositories/SnapshotRepository.php index 171fd88f..9a33a5c5 100644 --- a/src/Repositories/SnapshotRepository.php +++ b/src/Repositories/SnapshotRepository.php @@ -19,6 +19,7 @@ final class SnapshotRepository * Creates a snapshot repository instance. */ public function __construct( + readonly private string $rootPath, readonly private string $testsPath, readonly private string $snapshotsPath, ) {} @@ -103,7 +104,19 @@ final class SnapshotRepository */ private function getSnapshotFilename(): string { - $relativePath = str_replace($this->testsPath, '', TestSuite::getInstance()->getFilename()); + $testFile = TestSuite::getInstance()->getFilename(); + + if (str_starts_with($testFile, $this->testsPath)) { + // if the test file is in the tests directory + $startPath = $this->testsPath; + } else { + // if the test file is in the app, src, etc. directory + $startPath = $this->rootPath; + } + + // relative path: we use substr() and not str_replace() to remove the start path + // for instance, if the $startPath is /app/ and the $testFile is /app/app/tests/Unit/ExampleTest.php, we should only remove the first /app/ from the path + $relativePath = substr($testFile, strlen($startPath)); // remove extension from filename $relativePath = substr($relativePath, 0, (int) strrpos($relativePath, '.')); diff --git a/src/TestSuite.php b/src/TestSuite.php index ca35a040..e96a6ba9 100644 --- a/src/TestSuite.php +++ b/src/TestSuite.php @@ -78,6 +78,7 @@ final class TestSuite $this->afterAll = new AfterAllRepository; $this->rootPath = (string) realpath($rootPath); $this->snapshots = new SnapshotRepository( + $this->rootPath, implode(DIRECTORY_SEPARATOR, [$this->rootPath, $this->testPath]), implode(DIRECTORY_SEPARATOR, ['.pest', 'snapshots']), );