Skip to content

Commit bc1f308

Browse files
committed
Do not truncate file on failed flush
- fixes #548
1 parent 651c62b commit bc1f308

File tree

3 files changed

+24
-2
lines changed

3 files changed

+24
-2
lines changed

Diff for: CHANGES.md

+2
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ The released versions correspond to PyPi releases.
44
## Version 4.2.0 (as yet unreleased)
55

66
#### Fixes
7+
* do not truncate file on failed flush
8+
(see [#548](../../issues/548))
79
* suppress deprecation warnings while collecting modules
810
(see [#542](../../issues/542))
911
* add support for `os.truncate` and `os.ftruncate`

Diff for: pyfakefs/fake_filesystem.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -384,11 +384,11 @@ def _set_initial_contents(self, contents):
384384
changed = self._byte_contents != contents
385385
st_size = len(contents)
386386

387-
if self._byte_contents:
388-
self.size = 0
389387
current_size = self.st_size or 0
390388
self.filesystem.change_disk_usage(
391389
st_size - current_size, self.name, self.st_dev)
390+
if self._byte_contents:
391+
self.size = 0
392392
self._byte_contents = contents
393393
self.st_size = st_size
394394
self.epoch += 1

Diff for: pyfakefs/tests/fake_open_test.py

+20
Original file line numberDiff line numberDiff line change
@@ -918,6 +918,26 @@ def test_write_devnull(self):
918918
with self.open(self.os.devnull) as f:
919919
self.assertEqual('', f.read())
920920

921+
def test_failed_flush_does_not_truncate_file(self):
922+
# regression test for #548
923+
self.skip_real_fs() # cannot set fs size in real fs
924+
self.filesystem.set_disk_usage(100)
925+
self.os.makedirs("foo")
926+
file_path = self.os.path.join('foo', 'bar.txt')
927+
with self.open(file_path, 'wb') as f:
928+
f.write(b'a' * 50)
929+
f.flush()
930+
with self.open(file_path, "rb") as r:
931+
x = r.read()
932+
self.assertTrue(x.startswith(b'a' * 50))
933+
with self.assertRaises(OSError):
934+
f.write(b'b' * 200)
935+
f.flush()
936+
with self.open(file_path, "rb") as r:
937+
x = r.read()
938+
self.assertTrue(x.startswith(b'a' * 50))
939+
f.truncate(50)
940+
921941

922942
class RealFileOpenTest(FakeFileOpenTest):
923943
def use_real_fs(self):

0 commit comments

Comments
 (0)