-
Notifications
You must be signed in to change notification settings - Fork 77
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* Ignore local aws config. * Ignore local aws config. * Temporarily override env vars. * remove cli override. * Pr feedback. * Revert change.
- Loading branch information
Showing
3 changed files
with
82 additions
and
23 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
import os | ||
|
||
from truss.util.env_vars import override_env_vars | ||
|
||
|
||
def test_override_env_vars(): | ||
os.environ["API_KEY"] = "original_key" | ||
|
||
with override_env_vars({"API_KEY": "new_key", "DEBUG": "true"}): | ||
assert os.environ["API_KEY"] == "new_key" | ||
assert os.environ["DEBUG"] == "true" | ||
|
||
assert os.environ["API_KEY"] == "original_key" | ||
assert "DEBUG" not in os.environ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
import os | ||
from typing import Dict, Optional | ||
|
||
|
||
class override_env_vars: | ||
"""A context manager for temporarily overwriting environment variables. | ||
Usage: | ||
with override_env_vars({'API_KEY': 'test_key', 'DEBUG': 'true'}): | ||
# Environment variables are modified here | ||
... | ||
# Original environment is restored here | ||
""" | ||
|
||
def __init__(self, env_vars: Dict[str, str]): | ||
""" | ||
Args: | ||
env_vars: Dictionary of environment variables to set | ||
""" | ||
self.env_vars = env_vars | ||
self.original_vars: Dict[str, Optional[str]] = {} | ||
|
||
def __enter__(self): | ||
for key in self.env_vars: | ||
self.original_vars[key] = os.environ.get(key) | ||
|
||
for key, value in self.env_vars.items(): | ||
os.environ[key] = value | ||
|
||
return self | ||
|
||
def __exit__(self, exc_type, exc_val, exc_tb): | ||
# Restore original environment | ||
for key, value in self.original_vars.items(): | ||
if value is None: | ||
# Variable didn't exist originally | ||
if key in os.environ: | ||
del os.environ[key] | ||
else: | ||
# Restore original value | ||
os.environ[key] = value |