diff --git a/Lib/test/support/__init__.py b/Lib/test/support/__init__.py index 6658ece735cfe9..46796e788743cd 100644 --- a/Lib/test/support/__init__.py +++ b/Lib/test/support/__init__.py @@ -960,10 +960,12 @@ def temp_dir(path=None, quiet=False): warnings.warn(f'tests may fail, unable to create ' f'temporary directory {path!r}: {exc}', RuntimeWarning, stacklevel=3) + if dir_created: + pid = os.getpid() try: yield path finally: - if dir_created: + if dir_created and pid == os.getpid(): rmtree(path) @contextlib.contextmanager diff --git a/Lib/test/test_regrtest.py b/Lib/test/test_regrtest.py index 0bd62985d9c21d..908ab2c7506cfc 100644 --- a/Lib/test/test_regrtest.py +++ b/Lib/test/test_regrtest.py @@ -821,5 +821,20 @@ def test_crashed(self): randomize=True) +class TempCwdTestCase(unittest.TestCase): + @unittest.skipUnless(hasattr(os, "fork"), "test requires os.fork") + def test_forked_child(self): + import sys + with support.temp_cwd() as cwd: + pid = os.fork() + if pid != 0: + # parent + os.waitpid(pid, 0) + self.assertTrue(os.path.isdir(cwd), "directory was removed "+cwd) + if pid == 0: + # terminate the child in order to not confuse the test runner + os._exit(0) + + if __name__ == '__main__': unittest.main()