Skip to content

Commit

Permalink
added testing class Temp_Env_Vars
Browse files Browse the repository at this point in the history
  • Loading branch information
DinisCruz committed Jun 7, 2024
1 parent b8125e7 commit 477dad6
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
20 changes: 20 additions & 0 deletions osbot_utils/testing/Temp_Env_Vars.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import os

from osbot_utils.base_classes.Type_Safe import Type_Safe


class Temp_Env_Vars(Type_Safe):
env_vars : dict
original_env_vars: dict

def __enter__(self):
for key, value in self.env_vars.items():
self.original_env_vars[key] = os.environ.get(key) # Backup original environment variables and set new ones
os.environ[key] = value

def __exit__(self, exc_type, exc_value, traceback):
for key in self.env_vars: # Restore original environment variables
if self.original_env_vars[key] is None:
del os.environ[key]
else:
os.environ[key] = self.original_env_vars[key]
35 changes: 35 additions & 0 deletions tests/testing/test_Temp_Env_Vars.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import os
from unittest import TestCase

from osbot_utils.testing.Temp_Env_Vars import Temp_Env_Vars
from osbot_utils.utils.Env import get_env


class test_Temp_Env_Vars(TestCase):

def test__enter__leave__(self):
env_vars = {'var_1': 'value-1', 'var_2': 'value-2'}

assert get_env('var_1') is None # Ensure the environment variables are not set initially
assert get_env('var_2') is None


with Temp_Env_Vars(env_vars=env_vars): # Use Temp_Env_Vars context manager to set the environment variables
assert get_env('var_1') == 'value-1' # Check that the environment variables are set within the context
assert get_env('var_2') == 'value-2'

assert get_env('var_1') is None # Ensure the environment variables are restored to their original state
assert get_env('var_2') is None

os.environ['var_1'] = 'original-value-1' # Check behavior when some variables are initially set
assert get_env('var_1') == 'original-value-1'
assert get_env('var_2') is None

with Temp_Env_Vars(env_vars=env_vars):
assert get_env('var_1') == 'value-1'
assert get_env('var_2') == 'value-2'

assert get_env('var_1') == 'original-value-1' # Ensure the environment variables are restored to their original state
assert get_env('var_2') is None

del os.environ['var_1'] # Clean up

0 comments on commit 477dad6

Please sign in to comment.