File tree Expand file tree Collapse file tree 2 files changed +49
-0
lines changed
Expand file tree Collapse file tree 2 files changed +49
-0
lines changed Original file line number Diff line number Diff line change 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
Original file line number Diff line number Diff line change 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 ]
You can’t perform that action at this time.
0 commit comments