Merge branch 'flv0-savefile_open-flush'

This commit is contained in:
Florian Bruhin 2016-07-27 10:11:51 +02:00
commit b98d970393
3 changed files with 17 additions and 7 deletions

View File

@ -152,8 +152,8 @@ Contributors, sorted by the number of commits in descending order:
* Raphael Pierzina * Raphael Pierzina
* Joel Torstensson * Joel Torstensson
* Jan Verbeek * Jan Verbeek
* Tarcisio Fedrizzi
* Patric Schmitz * Patric Schmitz
* Tarcisio Fedrizzi
* Claude * Claude
* Corentin Julé * Corentin Julé
* meles5 * meles5

View File

@ -209,20 +209,19 @@ def savefile_open(filename, binary=False, encoding='utf-8'):
f = QSaveFile(filename) f = QSaveFile(filename)
cancelled = False cancelled = False
try: try:
ok = f.open(QIODevice.WriteOnly) open_ok = f.open(QIODevice.WriteOnly)
if not ok: if not open_ok:
raise QtOSError(f) raise QtOSError(f)
if binary: if binary:
new_f = PyQIODevice(f) new_f = PyQIODevice(f)
else: else:
new_f = io.TextIOWrapper(PyQIODevice(f), encoding=encoding) new_f = io.TextIOWrapper(PyQIODevice(f), encoding=encoding)
yield new_f yield new_f
new_f.flush()
except: except:
f.cancelWriting() f.cancelWriting()
cancelled = True cancelled = True
raise raise
else:
new_f.flush()
finally: finally:
commit_ok = f.commit() commit_ok = f.commit()
if not commit_ok and not cancelled: if not commit_ok and not cancelled:

View File

@ -481,16 +481,27 @@ class TestSavefileOpen:
assert str(excinfo.value) in errors assert str(excinfo.value) in errors
assert tmpdir.listdir() == [filename] assert tmpdir.listdir() == [filename]
def test_failing_flush(self, tmpdir):
"""Test with the file being closed before flushing."""
filename = tmpdir / 'foo'
with pytest.raises(ValueError) as excinfo:
with qtutils.savefile_open(str(filename), binary=True) as f:
f.write(b'Hello')
f.dev.commit() # provoke failing flush
assert str(excinfo.value) == "IO operation on closed device!"
assert tmpdir.listdir() == [filename]
def test_failing_commit(self, tmpdir): def test_failing_commit(self, tmpdir):
"""Test with the file being closed before committing.""" """Test with the file being closed before committing."""
filename = tmpdir / 'foo' filename = tmpdir / 'foo'
with pytest.raises(OSError) as excinfo: with pytest.raises(OSError) as excinfo:
with qtutils.savefile_open(str(filename), binary=True) as f: with qtutils.savefile_open(str(filename), binary=True) as f:
f.write(b'Hello') f.write(b'Hello')
f.dev.commit() # provoke failing "real" commit f.dev.cancelWriting() # provoke failing commit
assert str(excinfo.value) == "Commit failed!" assert str(excinfo.value) == "Commit failed!"
assert tmpdir.listdir() == [filename] assert tmpdir.listdir() == []
def test_line_endings(self, tmpdir): def test_line_endings(self, tmpdir):
"""Make sure line endings are translated correctly. """Make sure line endings are translated correctly.