From 9990d0ee36715ec13d293ed7741ce7a9022dcbff Mon Sep 17 00:00:00 2001 From: Ikki Nishihara Date: Fri, 20 Nov 2026 05:29:51 +0900 Subject: [PATCH] Fail when a snapshot cannot be written (#2048) Co-authored-by: haranishi <223786623+haranishi@users.noreply.github.com> Co-authored-by: Punyapal Shah --- src/Repositories/Snapshot.php | 5 ++- tests/.snapshots/success.txt | 5 ++- .../Features/Expect/SnapshotWriteFailure.php | 31 +++++++++++++++++++ 3 files changed, 39 insertions(+), 2 deletions(-) create mode 100644 tests/Features/Expect/SnapshotWriteFailure.php diff --git a/src/Repositories/Snapshot.php b/src/Repositories/Snapshot.php index 1c0371b4..c537a906 100644 --- a/src/Repositories/Snapshot.php +++ b/src/Repositories/Snapshot.php @@ -5,6 +5,7 @@ declare(strict_types=1); namespace Pest\Repositories; use Pest\Exceptions\ShouldNotHappen; +use RuntimeException; /** * @internal @@ -48,7 +49,9 @@ final readonly class Snapshot @mkdir($directory, 0755, true); } - file_put_contents($this->filename, $contents); + if (@file_put_contents($this->filename, $contents) !== strlen($contents)) { + throw new RuntimeException(sprintf('Unable to write snapshot at [%s].', $this->path())); + } return $this; } diff --git a/tests/.snapshots/success.txt b/tests/.snapshots/success.txt index 98066c4a..fce430b7 100644 --- a/tests/.snapshots/success.txt +++ b/tests/.snapshots/success.txt @@ -401,6 +401,9 @@ ✓ it works with nested properties ✓ it works with higher order tests + PASS Tests\Features\Expect\SnapshotWriteFailure + ✓ reports a missing snapshot that cannot be written + PASS Tests\Features\Expect\each ✓ an exception is thrown if the the type is not iterable ✓ it expects on each item @@ -2523,4 +2526,4 @@ ✓ pass with dataset with ('my-datas-set-value') ✓ within describe → pass with dataset with ('my-datas-set-value') - Tests: 2 deprecated, 4 warnings, 5 incomplete, 2 notices, 40 todos, 38 skipped, 1831 passed (4152 assertions) \ No newline at end of file + Tests: 2 deprecated, 4 warnings, 5 incomplete, 2 notices, 40 todos, 38 skipped, 1832 passed (4156 assertions) \ No newline at end of file diff --git a/tests/Features/Expect/SnapshotWriteFailure.php b/tests/Features/Expect/SnapshotWriteFailure.php new file mode 100644 index 00000000..a1ed4e90 --- /dev/null +++ b/tests/Features/Expect/SnapshotWriteFailure.php @@ -0,0 +1,31 @@ +write($directory, 'An existing file.'); + $project->write($testFile, <<<'PHP' + toMatchSnapshot(); + }); + PHP); + + $run = $project->pest($testFile, '--update-snapshots'); + + expect($run->exitCode)->toBe(2, $run->describe()) + ->and(str_replace('\\', '/', $run->output))->toContain("Unable to write snapshot at [$directory/stores_a_snapshot.snap].") + ->not->toContain('Snapshot created at') + ->and(file_get_contents($project->path($directory)))->toBe('An existing file.'); +})->group('integration');