diff options
author | Brett Cannon <bcannon@gmail.com> | 2007-01-04 00:23:49 (GMT) |
---|---|---|
committer | Brett Cannon <bcannon@gmail.com> | 2007-01-04 00:23:49 (GMT) |
commit | 92d54d5e9c52da3eb71b4a5aa940d0f2b6aed254 (patch) | |
tree | 76c26b8b036b4b06c0140c01e24f1a5a334afdd4 /Lib | |
parent | 5399910eba1ef3580aebf49482b1367f14fa6c48 (diff) | |
download | cpython-92d54d5e9c52da3eb71b4a5aa940d0f2b6aed254.zip cpython-92d54d5e9c52da3eb71b4a5aa940d0f2b6aed254.tar.gz cpython-92d54d5e9c52da3eb71b4a5aa940d0f2b6aed254.tar.bz2 |
Add EnvironmentVarGuard to test.test_support. Provides a context manager to
temporarily set or unset environment variables.
Diffstat (limited to 'Lib')
-rw-r--r-- | Lib/test/test_support.py | 34 |
1 files changed, 33 insertions, 1 deletions
diff --git a/Lib/test/test_support.py b/Lib/test/test_support.py index 4939410..fa02eac 100644 --- a/Lib/test/test_support.py +++ b/Lib/test/test_support.py @@ -279,7 +279,39 @@ def guard_warnings_filter(): yield finally: warnings.filters = original_filters - + +class EnvironmentVarGuard(object): + + """Class to help protect the environment variable properly. Can be used as + a context manager.""" + + def __init__(self): + from os import environ + self._environ = environ + self._unset = set() + self._reset = dict() + + def set(self, envvar, value): + if envvar not in self._environ: + self._unset.add(envvar) + else: + self._reset[envvar] = self._environ[envvar] + self._environ[envvar] = value + + def unset(self, envvar): + if envvar in self._environ: + self._reset[envvar] = self._environ[envvar] + del self._environ[envvar] + + def __enter__(self): + return self + + def __exit__(self, *ignore_exc): + for envvar, value in self._reset.iteritems(): + self._environ[envvar] = value + for unset in self._unset: + del self._environ[unset] + #======================================================================= # Decorator for running a function in a different locale, correctly resetting |