Browse Source

Use os.replace instead of os.remove; remove a "no cover"

tags/nilmdb-2.0.0
Jim Paris 4 years ago
parent
commit
ba915bb290
2 changed files with 14 additions and 10 deletions
  1. +2
    -10
      nilmdb/utils/atomic.py
  2. +12
    -0
      tests/test_misc.py

+ 2
- 10
nilmdb/utils/atomic.py View File

@@ -4,8 +4,7 @@ import os

def replace_file(filename, content):
"""Attempt to atomically and durably replace the filename with the
given contents. This is intended to be 'pretty good on most
OSes', but not necessarily bulletproof."""
given contents"""

newfilename = filename + b".new"

@@ -16,11 +15,4 @@ def replace_file(filename, content):
os.fsync(f.fileno())

# Move new file over old one
try:
os.rename(newfilename, filename)
except OSError: # pragma: no cover
# Some OSes might not support renaming over an existing file.
# This is definitely NOT atomic!
os.remove(filename)
os.rename(newfilename, filename)

os.replace(newfilename, filename)

+ 12
- 0
tests/test_misc.py View File

@@ -32,3 +32,15 @@ class TestMisc(object):
return None
with assert_raises(TypeError):
nilmdb.utils.lock.exclusive_lock(FakeFile())

def test_replace_file(self):
fn = b"tests/misc-testdb/file"
try:
os.mkdir(os.path.dirname(fn))
except FileExistsError:
pass
with open(fn, "wb") as f:
f.write(b"hello, world")
nilmdb.utils.atomic.replace_file(fn, b"goodbye, world")
with open(fn, "rb") as f:
eq_(f.read(), b"goodbye, world")

Loading…
Cancel
Save