Skip to content

Commit 8cc192d

Browse files
committed
Add temp_env util function to temporarily set env variables with a context manager
1 parent 3bc6cff commit 8cc192d

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

tests/client/test_utils.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import os
2+
3+
from tests.client.utils import temp_env
4+
5+
6+
def test_util_temp_env():
7+
"""
8+
Verify that temp_env correctly injects and cleans up environment variables.
9+
"""
10+
env = os.environ.copy()
11+
new_env_var = {'some_var': '1'}
12+
13+
with temp_env(**new_env_var):
14+
# Assert that the difference of the two environs is the new variable.
15+
assert set(env.items()) ^ set(os.environ.items()) == set(new_env_var.items())
16+
17+
# key should now not exist in the current imported os.environ.
18+
assert list(new_env_var.keys())[0] not in os.environ
19+
20+
import importlib
21+
importlib.reload(os)
22+
23+
# key should still not exist even when reloading the os module.
24+
assert list(new_env_var.keys())[0] not in os.environ

tests/client/utils.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import contextlib
2+
import os
3+
4+
5+
@contextlib.contextmanager
6+
def temp_env(**environment_variables):
7+
"""
8+
Context manager that sets temporal environment variables within the scope.
9+
10+
Example:
11+
with temp_env(some_key='value'):
12+
import os
13+
'some_key' in os.environ
14+
# True
15+
'some_key' in os.environ
16+
# False
17+
"""
18+
try:
19+
for k, v in environment_variables.items():
20+
os.environ[k] = str(v)
21+
yield
22+
finally:
23+
for k, v in environment_variables.items():
24+
os.unsetenv(k)
25+
del os.environ[k]

0 commit comments

Comments
 (0)