diff options
author | Filipe Laíns <lains@riseup.net> | 2021-10-19 22:19:27 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-10-19 22:19:27 (GMT) |
commit | 3592980f9122ab0d9ed93711347742d110b749c2 (patch) | |
tree | e1e3a4894a60187a5152c2a8c3ae648987f5f75b /Lib/test/test_contextlib.py | |
parent | ad6d162e518963711d24c80f1b7d6079bd437584 (diff) | |
download | cpython-3592980f9122ab0d9ed93711347742d110b749c2.zip cpython-3592980f9122ab0d9ed93711347742d110b749c2.tar.gz cpython-3592980f9122ab0d9ed93711347742d110b749c2.tar.bz2 |
bpo-25625: add contextlib.chdir (GH-28271)
Added non parallel-safe :func:`~contextlib.chdir` context manager to change
the current working directory and then restore it on exit. Simple wrapper
around :func:`~os.chdir`.
Signed-off-by: Filipe Laíns <lains@riseup.net>
Co-authored-by: Łukasz Langa <lukasz@langa.pl>
Diffstat (limited to 'Lib/test/test_contextlib.py')
-rw-r--r-- | Lib/test/test_contextlib.py | 43 |
1 files changed, 43 insertions, 0 deletions
diff --git a/Lib/test/test_contextlib.py b/Lib/test/test_contextlib.py index 7982d9d..bc8e4e4 100644 --- a/Lib/test/test_contextlib.py +++ b/Lib/test/test_contextlib.py @@ -1,6 +1,7 @@ """Unit tests for contextlib.py, and other context managers.""" import io +import os import sys import tempfile import threading @@ -1114,5 +1115,47 @@ class TestSuppress(unittest.TestCase): 1/0 self.assertTrue(outer_continued) + +class TestChdir(unittest.TestCase): + def test_simple(self): + old_cwd = os.getcwd() + target = os.path.join(os.path.dirname(__file__), 'data') + self.assertNotEqual(old_cwd, target) + + with chdir(target): + self.assertEqual(os.getcwd(), target) + self.assertEqual(os.getcwd(), old_cwd) + + def test_reentrant(self): + old_cwd = os.getcwd() + target1 = os.path.join(os.path.dirname(__file__), 'data') + target2 = os.path.join(os.path.dirname(__file__), 'ziptestdata') + self.assertNotIn(old_cwd, (target1, target2)) + chdir1, chdir2 = chdir(target1), chdir(target2) + + with chdir1: + self.assertEqual(os.getcwd(), target1) + with chdir2: + self.assertEqual(os.getcwd(), target2) + with chdir1: + self.assertEqual(os.getcwd(), target1) + self.assertEqual(os.getcwd(), target2) + self.assertEqual(os.getcwd(), target1) + self.assertEqual(os.getcwd(), old_cwd) + + def test_exception(self): + old_cwd = os.getcwd() + target = os.path.join(os.path.dirname(__file__), 'data') + self.assertNotEqual(old_cwd, target) + + try: + with chdir(target): + self.assertEqual(os.getcwd(), target) + raise RuntimeError("boom") + except RuntimeError as re: + self.assertEqual(str(re), "boom") + self.assertEqual(os.getcwd(), old_cwd) + + if __name__ == "__main__": unittest.main() |