-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathtestutil.py
39 lines (31 loc) · 1.14 KB
/
testutil.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
"""Context manager for environment variables.
Taken from https://gist.github.com/sidprak/a3571943bcf6df0565c09471ab2f90b8
Usage:
>>> os.environ['MYVAR'] = 'oldvalue'
>>> with EnvironmentVariable('MYVAR', 'myvalue'):
... print os.getenv('MYVAR')
myvalue
>>> print os.getenv('MYVAR')
oldvalue
"""
import os
class EnvironmentVariable(object):
"""Context manager for creating a temporary environment variable.
:param key: Environment variable name.
:param value: Value to set in environment variable.
"""
def __init__(self, key, value):
self.key = key
self.new_value = value
def __enter__(self):
"""Sets the environment variable and saves the old value."""
self.old_value = os.environ.get(self.key)
os.environ[self.key] = self.new_value
return self
def __exit__(self, *args):
"""Sets the environment variable back to the way it was before."""
# Check against None explicitly so we restore empty strings too
if self.old_value is not None:
os.environ[self.key] = self.old_value
else:
del os.environ[self.key]