Skip to content

Commit 53630f7

Browse files
committed
Add environment context manager, document it and test it
1 parent 28b804c commit 53630f7

File tree

3 files changed

+49
-0
lines changed

3 files changed

+49
-0
lines changed

README.md

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,18 @@ Then, for each remote it pushes the tags and the commits.
5252

5353
This section describes generic tools that could not be put in a specific category, but tend to be useful.
5454

55+
## Environment
56+
57+
To temporarily set an environment use:
58+
59+
```python
60+
from dmu.generic import utilities as gut
61+
62+
with gut.environment(mapping = {'VAR' : '1234', 'VOR' : 'abcd'}):
63+
var = os.environ['VAR']
64+
vor = os.environ['VOR']
65+
```
66+
5567
## Typing
5668

5769
### Pandas types

src/dmu/generic/utilities.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,25 @@ def default_encoder(x):
8383
return json_string
8484
# ---------------------------------
8585
@contextmanager
86+
def environment(mapping : dict[str,str]):
87+
'''
88+
Parameters
89+
---------------
90+
mapping: Dictionary holding environment that will be set
91+
'''
92+
old_mapping = { key : os.environ.get(key) for key in mapping }
93+
94+
try:
95+
os.environ.update(mapping)
96+
yield
97+
finally:
98+
for key, val in old_mapping.items():
99+
if val is None:
100+
os.environ.pop(key, None)
101+
else:
102+
os.environ[key] = val
103+
# ---------------------------------
104+
@contextmanager
86105
def enforce_schema_validation(value : bool):
87106
'''
88107
Parameters

tests/generic/test_generic_utilities.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
'''
22
Module with tests for functions in generic/utilities.py
33
'''
4+
import os
45
from time import sleep
56
from pathlib import Path
67

@@ -11,6 +12,23 @@
1112

1213
log=LogStore.add_logger('dmu:test_generic_utilities')
1314
# ----------------------
15+
def test_environment_context():
16+
'''
17+
This function tests the environment context manager
18+
'''
19+
with gut.environment(mapping = {}):
20+
pass
21+
22+
with gut.environment(mapping = {'VAR' : '1234'}):
23+
assert os.environ['VAR'] == '1234'
24+
25+
with gut.environment(mapping = {'VAR' : '1234', 'VOR' : 'abcd'}):
26+
assert os.environ['VAR'] == '1234'
27+
assert os.environ['VOR'] == 'abcd'
28+
29+
with pytest.raises(KeyError):
30+
os.environ['VAR']
31+
# ----------------------
1432
@pytest.fixture(scope='session', autouse=True)
1533
def initialize():
1634
'''

0 commit comments

Comments
 (0)