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

View File

@ -234,3 +234,17 @@ def test_tempdir_registry(kind, delete, exists):
path = d.path
assert os.path.exists(path)
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)