Skip to content
Snippets Groups Projects
Commit 1b188328 authored by Alan De Smet's avatar Alan De Smet
Browse files

Fix ExclusiveLockFile; better doctest for AtomicCreateIfMissing

ExclusiveLockFile unconditionally closed the file on object deletion,
which threw an exception if you don't have an open file.
parent ecd617b7
No related merge requests found
......@@ -111,7 +111,8 @@ class ExclusiveLockFile:
self.unlock()
def __del__(self):
self.file.close()
if self.file is not None:
self.file.close()
def samefile(f1, f2):
""" Do do file objects correspond to the same file on disk?
......@@ -193,7 +194,6 @@ def file_matches_filename(file, filename):
class AtomicCreateIfMissing:
""" Context manager to atomically create a file
>>> from exclusivelockfile import AtomicCreateIfMissing
>>> from tempfile import mkdtemp
>>> tmpdir = mkdtemp()
......@@ -201,18 +201,23 @@ class AtomicCreateIfMissing:
>>> #
>>> with AtomicCreateIfMissing(filename) as f:
... if f is None:
... raise Exception("This won't happen, as filename doens't exist yet")
"""
"""
... f.write("this is the body of a test file\n")
... with open(filename) as input:
... print(input.read()) # prints nothing; file is still empty
... raise Exception("This won't happen, as filename doesn't exist yet")
... _ = f.write("this is the body of the test file")
... try:
... open(filename)
... raise Exception("This won't happen; file doesn't exist yet")
... except FileNotFoundError:
... pass
>>> # This file now exists
>>> with open(filename) as f: print(f.read())
this is the body of a test file
this is the body of the test file
>>> # Retrying will fail, returning None as the file
>>> with AtomicCreateIfMissing(filename) as f:
... if f is None:
... return
... raise Exception("This won't happen, as the file already exists and AtomicCreateIfMissing returned None above")
... if f is not None:
... raise Exception("This won't happen, as the file already exists and AtomicCreateIfMissing returned None above")
>>> import os
>>> os.unlink(filename)
>>> os.rmdir(tmpdir)
"""
def __init__(self, filename, partial_suffix=".part"):
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment