fix: normalize snapshot paths for files outside tests directory

This commit is contained in:
Clément Birklé
2025-03-19 15:59:45 +01:00
parent ed70c9dc2b
commit 490f321a0d
2 changed files with 15 additions and 1 deletions

View File

@ -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, '.'));

View File

@ -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']),
);