summaryrefslogtreecommitdiffstats
path: root/Lib/test/test_support.py
diff options
context:
space:
mode:
Diffstat (limited to 'Lib/test/test_support.py')
-rw-r--r--Lib/test/test_support.py27
1 files changed, 27 insertions, 0 deletions
diff --git a/Lib/test/test_support.py b/Lib/test/test_support.py
index 75563cb..b578bcd 100644
--- a/Lib/test/test_support.py
+++ b/Lib/test/test_support.py
@@ -669,6 +669,33 @@ TESTFN = "{}_{}_tmp".format(TESTFN, os.getpid())
SAVEDCWD = os.getcwd()
@contextlib.contextmanager
+def change_cwd(path, quiet=False):
+ """Return a context manager that changes the current working directory.
+
+ Arguments:
+
+ path: the directory to use as the temporary current working directory.
+
+ quiet: if False (the default), the context manager raises an exception
+ on error. Otherwise, it issues only a warning and keeps the current
+ working directory the same.
+
+ """
+ saved_dir = os.getcwd()
+ try:
+ os.chdir(path)
+ except OSError:
+ if not quiet:
+ raise
+ warnings.warn('tests may fail, unable to change CWD to: ' + path,
+ RuntimeWarning, stacklevel=3)
+ try:
+ yield os.getcwd()
+ finally:
+ os.chdir(saved_dir)
+
+
+@contextlib.contextmanager
def temp_cwd(name='tempcwd', quiet=False):
"""
Context manager that creates a temporary directory and set it as CWD.