class ExtractedArchiveFiles(object): """ Context manager class giving temporary access to a directory containing data from a (recursively) extracted archive. """ def __init__(self, archive_file, archive_ext=DEFAULT_ARCHIVE_EXT): self.archive = open_archive(archive_file) def __enter__(self): self._tempdir = TemporaryDir() path = self._tempdir.__enter__() self.archive.extract(path) def __exit__(self, exc_type, exc_value, traceback): self._tempdir.__exit__(exc_type, exc_value, traceback)
def test_temporary_dir(): with TemporaryDir() as tempdir: with open(os.path.join(tempdir, 'foobar.txt'), 'wt') as fp: fp.write('Hello, world!\n') with open(os.path.join(tempdir, 'foobar.txt'), 'rt') as fp: assert fp.read() == 'Hello, world!\n' assert not os.path.exists(os.path.join(tempdir, 'foobar.txt')) assert not os.path.exists(tempdir)
def test_disallow_reuse(): tempdir = TemporaryDir() with tempdir: pass with pytest.raises(RuntimeError): with tempdir: pass tempfile = TemporaryFile() with tempfile: pass with pytest.raises(RuntimeError): with tempfile: pass
def __enter__(self): self._tempdir = TemporaryDir() path = self._tempdir.__enter__() self.archive.extract(path)