tests: Always cleanup when exiting modify_env context manager

Previously, an exception would leave the environment changed.
This commit is contained in:
François Freitag 2020-11-15 10:25:36 +01:00
parent 5a42348fd7
commit 5eb74d5c8e
No known key found for this signature in database
GPG Key ID: 0CD53670BCA9253D

View File

@ -54,9 +54,11 @@ def modify_env(**env):
original_env = os.environ.copy() original_env = os.environ.copy()
for k, v in env.items(): for k, v in env.items():
os.environ[k] = v os.environ[k] = v
yield try:
for k in env: yield
try: finally:
os.environ[k] = original_env[k] for k in env:
except KeyError: try:
os.unsetenv(k) os.environ[k] = original_env[k]
except KeyError:
os.unsetenv(k)