mirror of
https://github.com/python/cpython.git
synced 2025-08-12 04:49:01 +00:00
Merged revisions 72167 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk ........ r72167 | walter.doerwald | 2009-05-01 19:35:37 +0200 (Fr, 01 Mai 2009) | 5 lines Make test.test_support.EnvironmentVarGuard behave like a dictionary. All changes are mirrored to the underlying os.environ dict, but rolled back on exit from the with block. ........
This commit is contained in:
parent
33841c3489
commit
155374d95d
10 changed files with 79 additions and 68 deletions
|
@ -384,8 +384,13 @@ The :mod:`test.support` module defines the following classes:
|
||||||
.. class:: EnvironmentVarGuard()
|
.. class:: EnvironmentVarGuard()
|
||||||
|
|
||||||
Class used to temporarily set or unset environment variables. Instances can be
|
Class used to temporarily set or unset environment variables. Instances can be
|
||||||
used as a context manager.
|
used as a context manager and have a complete dictionary interface for
|
||||||
|
querying/modifying the underlying ``os.environ``. After exit from the context
|
||||||
|
manager all changes to environment variables done through this instance will
|
||||||
|
be rolled back.
|
||||||
|
|
||||||
|
.. versionchanged:: 2.7
|
||||||
|
Added dictionary interface.
|
||||||
|
|
||||||
.. method:: EnvironmentVarGuard.set(envvar, value)
|
.. method:: EnvironmentVarGuard.set(envvar, value)
|
||||||
|
|
||||||
|
@ -396,6 +401,7 @@ The :mod:`test.support` module defines the following classes:
|
||||||
|
|
||||||
Temporarily unset the environment variable ``envvar``.
|
Temporarily unset the environment variable ``envvar``.
|
||||||
|
|
||||||
|
|
||||||
.. class:: WarningsRecorder()
|
.. class:: WarningsRecorder()
|
||||||
|
|
||||||
Class used to record warnings for unit tests. See documentation of
|
Class used to record warnings for unit tests. See documentation of
|
||||||
|
|
|
@ -13,6 +13,7 @@ import shutil
|
||||||
import warnings
|
import warnings
|
||||||
import unittest
|
import unittest
|
||||||
import importlib
|
import importlib
|
||||||
|
import collections
|
||||||
|
|
||||||
__all__ = ["Error", "TestFailed", "ResourceDenied", "import_module",
|
__all__ = ["Error", "TestFailed", "ResourceDenied", "import_module",
|
||||||
"verbose", "use_resources", "max_memuse", "record_original_stdout",
|
"verbose", "use_resources", "max_memuse", "record_original_stdout",
|
||||||
|
@ -510,26 +511,45 @@ class CleanImport(object):
|
||||||
sys.modules.update(self.original_modules)
|
sys.modules.update(self.original_modules)
|
||||||
|
|
||||||
|
|
||||||
class EnvironmentVarGuard(object):
|
class EnvironmentVarGuard(collections.MutableMapping):
|
||||||
|
|
||||||
"""Class to help protect the environment variable properly. Can be used as
|
"""Class to help protect the environment variable properly. Can be used as
|
||||||
a context manager."""
|
a context manager."""
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
|
self._environ = os.environ
|
||||||
self._changed = {}
|
self._changed = {}
|
||||||
|
|
||||||
def set(self, envvar, value):
|
def __getitem__(self, envvar):
|
||||||
|
return self._environ[envvar]
|
||||||
|
|
||||||
|
def __setitem__(self, envvar, value):
|
||||||
# Remember the initial value on the first access
|
# Remember the initial value on the first access
|
||||||
if envvar not in self._changed:
|
if envvar not in self._changed:
|
||||||
self._changed[envvar] = os.environ.get(envvar)
|
self._changed[envvar] = self._environ.get(envvar)
|
||||||
os.environ[envvar] = value
|
self._environ[envvar] = value
|
||||||
|
|
||||||
|
def __delitem__(self, envvar):
|
||||||
|
# Remember the initial value on the first access
|
||||||
|
if envvar not in self._changed:
|
||||||
|
self._changed[envvar] = self._environ.get(envvar)
|
||||||
|
if envvar in self._environ:
|
||||||
|
del self._environ[envvar]
|
||||||
|
|
||||||
|
def keys(self):
|
||||||
|
return self._environ.keys()
|
||||||
|
|
||||||
|
def __iter__(self):
|
||||||
|
return iter(self._environ)
|
||||||
|
|
||||||
|
def __len__(self):
|
||||||
|
return len(self._environ)
|
||||||
|
|
||||||
|
def set(self, envvar, value):
|
||||||
|
self[envvar] = value
|
||||||
|
|
||||||
def unset(self, envvar):
|
def unset(self, envvar):
|
||||||
# Remember the initial value on the first access
|
del self[envvar]
|
||||||
if envvar not in self._changed:
|
|
||||||
self._changed[envvar] = os.environ.get(envvar)
|
|
||||||
if envvar in os.environ:
|
|
||||||
del os.environ[envvar]
|
|
||||||
|
|
||||||
def __enter__(self):
|
def __enter__(self):
|
||||||
return self
|
return self
|
||||||
|
@ -537,10 +557,11 @@ class EnvironmentVarGuard(object):
|
||||||
def __exit__(self, *ignore_exc):
|
def __exit__(self, *ignore_exc):
|
||||||
for (k, v) in self._changed.items():
|
for (k, v) in self._changed.items():
|
||||||
if v is None:
|
if v is None:
|
||||||
if k in os.environ:
|
if k in self._environ:
|
||||||
del os.environ[k]
|
del self._environ[k]
|
||||||
else:
|
else:
|
||||||
os.environ[k] = v
|
self._environ[k] = v
|
||||||
|
|
||||||
|
|
||||||
class TransientResource(object):
|
class TransientResource(object):
|
||||||
|
|
||||||
|
|
|
@ -1,7 +1,7 @@
|
||||||
# test_getopt.py
|
# test_getopt.py
|
||||||
# David Goodger <dgoodger@bigfoot.com> 2000-08-19
|
# David Goodger <dgoodger@bigfoot.com> 2000-08-19
|
||||||
|
|
||||||
from test.support import verbose, run_doctest, run_unittest
|
from test.support import verbose, run_doctest, run_unittest, EnvironmentVarGuard
|
||||||
import unittest
|
import unittest
|
||||||
|
|
||||||
import getopt
|
import getopt
|
||||||
|
@ -11,15 +11,13 @@ sentinel = object()
|
||||||
|
|
||||||
class GetoptTests(unittest.TestCase):
|
class GetoptTests(unittest.TestCase):
|
||||||
def setUp(self):
|
def setUp(self):
|
||||||
self.old_posixly_correct = os.environ.get("POSIXLY_CORRECT", sentinel)
|
self.env = EnvironmentVarGuard()
|
||||||
if self.old_posixly_correct is not sentinel:
|
if "POSIXLY_CORRECT" in self.env:
|
||||||
del os.environ["POSIXLY_CORRECT"]
|
del self.env["POSIXLY_CORRECT"]
|
||||||
|
|
||||||
def tearDown(self):
|
def tearDown(self):
|
||||||
if self.old_posixly_correct is sentinel:
|
self.env.__exit__()
|
||||||
os.environ.pop("POSIXLY_CORRECT", None)
|
del self.env
|
||||||
else:
|
|
||||||
os.environ["POSIXLY_CORRECT"] = self.old_posixly_correct
|
|
||||||
|
|
||||||
def assertError(self, *args, **kwargs):
|
def assertError(self, *args, **kwargs):
|
||||||
self.assertRaises(getopt.GetoptError, *args, **kwargs)
|
self.assertRaises(getopt.GetoptError, *args, **kwargs)
|
||||||
|
@ -135,7 +133,7 @@ class GetoptTests(unittest.TestCase):
|
||||||
self.assertEqual(args, ['arg1', '-b', '1', '--alpha', '--beta=2'])
|
self.assertEqual(args, ['arg1', '-b', '1', '--alpha', '--beta=2'])
|
||||||
|
|
||||||
# Posix style via POSIXLY_CORRECT
|
# Posix style via POSIXLY_CORRECT
|
||||||
os.environ["POSIXLY_CORRECT"] = "1"
|
self.env["POSIXLY_CORRECT"] = "1"
|
||||||
opts, args = getopt.gnu_getopt(cmdline, 'ab:', ['alpha', 'beta='])
|
opts, args = getopt.gnu_getopt(cmdline, 'ab:', ['alpha', 'beta='])
|
||||||
self.assertEqual(opts, [('-a', '')])
|
self.assertEqual(opts, [('-a', '')])
|
||||||
self.assertEqual(args, ['arg1', '-b', '1', '--alpha', '--beta=2'])
|
self.assertEqual(args, ['arg1', '-b', '1', '--alpha', '--beta=2'])
|
||||||
|
|
|
@ -58,10 +58,6 @@ LOCALEDIR = os.path.join('xx', 'LC_MESSAGES')
|
||||||
MOFILE = os.path.join(LOCALEDIR, 'gettext.mo')
|
MOFILE = os.path.join(LOCALEDIR, 'gettext.mo')
|
||||||
UMOFILE = os.path.join(LOCALEDIR, 'ugettext.mo')
|
UMOFILE = os.path.join(LOCALEDIR, 'ugettext.mo')
|
||||||
MMOFILE = os.path.join(LOCALEDIR, 'metadata.mo')
|
MMOFILE = os.path.join(LOCALEDIR, 'metadata.mo')
|
||||||
try:
|
|
||||||
LANG = os.environ['LANGUAGE']
|
|
||||||
except:
|
|
||||||
LANG = 'en'
|
|
||||||
|
|
||||||
|
|
||||||
class GettextBaseTest(unittest.TestCase):
|
class GettextBaseTest(unittest.TestCase):
|
||||||
|
@ -77,10 +73,12 @@ class GettextBaseTest(unittest.TestCase):
|
||||||
fp = open(MMOFILE, 'wb')
|
fp = open(MMOFILE, 'wb')
|
||||||
fp.write(base64.decodestring(MMO_DATA))
|
fp.write(base64.decodestring(MMO_DATA))
|
||||||
fp.close()
|
fp.close()
|
||||||
os.environ['LANGUAGE'] = 'xx'
|
self.env = support.EnvironmentVarGuard()
|
||||||
|
self.env['LANGUAGE'] = 'xx'
|
||||||
|
|
||||||
def tearDown(self):
|
def tearDown(self):
|
||||||
os.environ['LANGUAGE'] = LANG
|
self.env.__exit__()
|
||||||
|
del self.env
|
||||||
shutil.rmtree(os.path.split(LOCALEDIR)[0])
|
shutil.rmtree(os.path.split(LOCALEDIR)[0])
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -141,12 +141,11 @@ class TestNtpath(unittest.TestCase):
|
||||||
tester("ntpath.normpath('//machine/share//a/b')", r'\\machine\share\a\b')
|
tester("ntpath.normpath('//machine/share//a/b')", r'\\machine\share\a\b')
|
||||||
|
|
||||||
def test_expandvars(self):
|
def test_expandvars(self):
|
||||||
oldenv = os.environ.copy()
|
with support.EnvironmentVarGuard() as env:
|
||||||
try:
|
env.clear()
|
||||||
os.environ.clear()
|
env["foo"] = "bar"
|
||||||
os.environ["foo"] = "bar"
|
env["{foo"] = "baz1"
|
||||||
os.environ["{foo"] = "baz1"
|
env["{foo}"] = "baz2"
|
||||||
os.environ["{foo}"] = "baz2"
|
|
||||||
tester('ntpath.expandvars("foo")', "foo")
|
tester('ntpath.expandvars("foo")', "foo")
|
||||||
tester('ntpath.expandvars("$foo bar")', "bar bar")
|
tester('ntpath.expandvars("$foo bar")', "bar bar")
|
||||||
tester('ntpath.expandvars("${foo}bar")', "barbar")
|
tester('ntpath.expandvars("${foo}bar")', "barbar")
|
||||||
|
@ -166,9 +165,6 @@ class TestNtpath(unittest.TestCase):
|
||||||
tester('ntpath.expandvars("%?bar%")', "%?bar%")
|
tester('ntpath.expandvars("%?bar%")', "%?bar%")
|
||||||
tester('ntpath.expandvars("%foo%%bar")', "bar%bar")
|
tester('ntpath.expandvars("%foo%%bar")', "bar%bar")
|
||||||
tester('ntpath.expandvars("\'%foo%\'%bar")', "\'%foo%\'%bar")
|
tester('ntpath.expandvars("\'%foo%\'%bar")', "\'%foo%\'%bar")
|
||||||
finally:
|
|
||||||
os.environ.clear()
|
|
||||||
os.environ.update(oldenv)
|
|
||||||
|
|
||||||
def test_abspath(self):
|
def test_abspath(self):
|
||||||
# ntpath.abspath() can only be used on a system with the "nt" module
|
# ntpath.abspath() can only be used on a system with the "nt" module
|
||||||
|
|
|
@ -1449,7 +1449,7 @@ class TestHelp(BaseTest):
|
||||||
# screws things up for other tests when it's part of the Python
|
# screws things up for other tests when it's part of the Python
|
||||||
# test suite.
|
# test suite.
|
||||||
with support.EnvironmentVarGuard() as env:
|
with support.EnvironmentVarGuard() as env:
|
||||||
env.set('COLUMNS', str(columns))
|
env['COLUMNS'] = str(columns)
|
||||||
return InterceptingOptionParser(option_list=options)
|
return InterceptingOptionParser(option_list=options)
|
||||||
|
|
||||||
def assertHelpEquals(self, expected_output):
|
def assertHelpEquals(self, expected_output):
|
||||||
|
@ -1474,7 +1474,7 @@ class TestHelp(BaseTest):
|
||||||
|
|
||||||
def test_help_title_formatter(self):
|
def test_help_title_formatter(self):
|
||||||
with support.EnvironmentVarGuard() as env:
|
with support.EnvironmentVarGuard() as env:
|
||||||
env.set("COLUMNS", "80")
|
env["COLUMNS"] = "80"
|
||||||
self.parser.formatter = TitledHelpFormatter()
|
self.parser.formatter = TitledHelpFormatter()
|
||||||
self.assertHelpEquals(_expected_help_title_formatter)
|
self.assertHelpEquals(_expected_help_title_formatter)
|
||||||
|
|
||||||
|
|
|
@ -420,18 +420,17 @@ class PosixPathTest(unittest.TestCase):
|
||||||
self.assert_(isinstance(posixpath.expanduser(b"~foo/"), bytes))
|
self.assert_(isinstance(posixpath.expanduser(b"~foo/"), bytes))
|
||||||
|
|
||||||
with support.EnvironmentVarGuard() as env:
|
with support.EnvironmentVarGuard() as env:
|
||||||
env.set('HOME', '/')
|
env['HOME'] = '/'
|
||||||
self.assertEqual(posixpath.expanduser("~"), "/")
|
self.assertEqual(posixpath.expanduser("~"), "/")
|
||||||
|
|
||||||
self.assertRaises(TypeError, posixpath.expanduser)
|
self.assertRaises(TypeError, posixpath.expanduser)
|
||||||
|
|
||||||
def test_expandvars(self):
|
def test_expandvars(self):
|
||||||
oldenv = os.environ.copy()
|
with support.EnvironmentVarGuard() as env:
|
||||||
try:
|
env.clear()
|
||||||
os.environ.clear()
|
env["foo"] = "bar"
|
||||||
os.environ["foo"] = "bar"
|
env["{foo"] = "baz1"
|
||||||
os.environ["{foo"] = "baz1"
|
env["{foo}"] = "baz2"
|
||||||
os.environ["{foo}"] = "baz2"
|
|
||||||
self.assertEqual(posixpath.expandvars("foo"), "foo")
|
self.assertEqual(posixpath.expandvars("foo"), "foo")
|
||||||
self.assertEqual(posixpath.expandvars("$foo bar"), "bar bar")
|
self.assertEqual(posixpath.expandvars("$foo bar"), "bar bar")
|
||||||
self.assertEqual(posixpath.expandvars("${foo}bar"), "barbar")
|
self.assertEqual(posixpath.expandvars("${foo}bar"), "barbar")
|
||||||
|
@ -457,10 +456,6 @@ class PosixPathTest(unittest.TestCase):
|
||||||
self.assertEqual(posixpath.expandvars(b"${{foo}}"), b"baz1}")
|
self.assertEqual(posixpath.expandvars(b"${{foo}}"), b"baz1}")
|
||||||
self.assertEqual(posixpath.expandvars(b"$foo$foo"), b"barbar")
|
self.assertEqual(posixpath.expandvars(b"$foo$foo"), b"barbar")
|
||||||
self.assertEqual(posixpath.expandvars(b"$bar$bar"), b"$bar$bar")
|
self.assertEqual(posixpath.expandvars(b"$bar$bar"), b"$bar$bar")
|
||||||
finally:
|
|
||||||
os.environ.clear()
|
|
||||||
os.environ.update(oldenv)
|
|
||||||
|
|
||||||
self.assertRaises(TypeError, posixpath.expandvars)
|
self.assertRaises(TypeError, posixpath.expandvars)
|
||||||
|
|
||||||
def test_normpath(self):
|
def test_normpath(self):
|
||||||
|
|
|
@ -144,9 +144,9 @@ class TclTest(unittest.TestCase):
|
||||||
import sys
|
import sys
|
||||||
if sys.platform.startswith(('win', 'darwin', 'cygwin')):
|
if sys.platform.startswith(('win', 'darwin', 'cygwin')):
|
||||||
return # no failure possible on windows?
|
return # no failure possible on windows?
|
||||||
|
with support.EnvironmentVarGuard() as env:
|
||||||
if 'DISPLAY' in os.environ:
|
if 'DISPLAY' in os.environ:
|
||||||
old_display = os.environ['DISPLAY']
|
del env['DISPLAY']
|
||||||
del os.environ['DISPLAY']
|
|
||||||
# on some platforms, deleting environment variables
|
# on some platforms, deleting environment variables
|
||||||
# doesn't actually carry through to the process level
|
# doesn't actually carry through to the process level
|
||||||
# because they don't support unsetenv
|
# because they don't support unsetenv
|
||||||
|
@ -154,13 +154,10 @@ class TclTest(unittest.TestCase):
|
||||||
display = os.popen('echo $DISPLAY').read().strip()
|
display = os.popen('echo $DISPLAY').read().strip()
|
||||||
if display:
|
if display:
|
||||||
return
|
return
|
||||||
try:
|
|
||||||
tcl = Tcl()
|
tcl = Tcl()
|
||||||
self.assertRaises(TclError, tcl.winfo_geometry)
|
self.assertRaises(TclError, tcl.winfo_geometry)
|
||||||
self.assertRaises(TclError, tcl.loadtk)
|
self.assertRaises(TclError, tcl.loadtk)
|
||||||
finally:
|
|
||||||
if old_display is not None:
|
|
||||||
os.environ['DISPLAY'] = old_display
|
|
||||||
|
|
||||||
def test_main():
|
def test_main():
|
||||||
support.run_unittest(TclTest, TkinterTest)
|
support.run_unittest(TclTest, TkinterTest)
|
||||||
|
|
|
@ -153,7 +153,7 @@ class test__candidate_tempdir_list(TC):
|
||||||
for envname in 'TMPDIR', 'TEMP', 'TMP':
|
for envname in 'TMPDIR', 'TEMP', 'TMP':
|
||||||
dirname = os.getenv(envname)
|
dirname = os.getenv(envname)
|
||||||
if not dirname:
|
if not dirname:
|
||||||
env.set(envname, os.path.abspath(envname))
|
env[envname] = os.path.abspath(envname)
|
||||||
|
|
||||||
cand = tempfile._candidate_tempdir_list()
|
cand = tempfile._candidate_tempdir_list()
|
||||||
|
|
||||||
|
|
|
@ -572,7 +572,7 @@ class CGIHandlerTestCase(unittest.TestCase):
|
||||||
|
|
||||||
def test_cgi_get(self):
|
def test_cgi_get(self):
|
||||||
with support.EnvironmentVarGuard() as env:
|
with support.EnvironmentVarGuard() as env:
|
||||||
env.set('REQUEST_METHOD', 'GET')
|
env['REQUEST_METHOD'] = 'GET'
|
||||||
# if the method is GET and no request_text is given, it runs handle_get
|
# if the method is GET and no request_text is given, it runs handle_get
|
||||||
# get sysout output
|
# get sysout output
|
||||||
tmp = sys.stdout
|
tmp = sys.stdout
|
||||||
|
@ -613,7 +613,7 @@ class CGIHandlerTestCase(unittest.TestCase):
|
||||||
sys.stdout = open(support.TESTFN, "w")
|
sys.stdout = open(support.TESTFN, "w")
|
||||||
|
|
||||||
with support.EnvironmentVarGuard() as env:
|
with support.EnvironmentVarGuard() as env:
|
||||||
env.set('CONTENT_LENGTH', str(len(data)))
|
env['CONTENT_LENGTH'] = str(len(data))
|
||||||
self.cgi.handle_request()
|
self.cgi.handle_request()
|
||||||
|
|
||||||
sys.stdin.close()
|
sys.stdin.close()
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue