Merge pull request #7608 from uranusjr/global-cleanup

Delay TempDirectory.delete resolution to cleanup
This commit is contained in:
Christopher Hunt 2020-01-22 18:25:05 +08:00 committed by GitHub
commit f1cd4cb48e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 26 additions and 8 deletions

View File

@ -107,13 +107,10 @@ class TempDirectory(object):
): ):
super(TempDirectory, self).__init__() super(TempDirectory, self).__init__()
if path is None and delete is None: # If we were given an explicit directory, resolve delete option now.
# If we were not given an explicit directory, and we were not given # Otherwise we wait until cleanup and see what tempdir_registry says.
# an explicit delete option, then we'll default to deleting unless if path is not None and delete is None:
# the tempdir_registry says otherwise. delete = False
delete = True
if _tempdir_registry:
delete = _tempdir_registry.get_delete(kind)
if path is None: if path is None:
path = self._create(kind) path = self._create(kind)
@ -145,7 +142,14 @@ class TempDirectory(object):
def __exit__(self, exc, value, tb): def __exit__(self, exc, value, tb):
# type: (Any, Any, Any) -> None # type: (Any, Any, Any) -> None
if self.delete: if self.delete is not None:
delete = self.delete
elif _tempdir_registry:
delete = _tempdir_registry.get_delete(self.kind)
else:
delete = True
if delete:
self.cleanup() self.cleanup()
def _create(self, kind): def _create(self, kind):

View File

@ -234,3 +234,17 @@ def test_tempdir_registry(kind, delete, exists):
path = d.path path = d.path
assert os.path.exists(path) assert os.path.exists(path)
assert os.path.exists(path) == exists assert os.path.exists(path) == exists
@pytest.mark.parametrize("should_delete", [True, False])
def test_tempdir_registry_lazy(should_delete):
"""
Test the registry entry can be updated after a temp dir is created,
to change whether a kind should be deleted or not.
"""
with tempdir_registry() as registry:
with TempDirectory(delete=None, kind="test-for-lazy") as d:
path = d.path
registry.set_delete("test-for-lazy", should_delete)
assert os.path.exists(path)
assert os.path.exists(path) == (not should_delete)