Skip to content

Commit

Permalink
bpo-30028: make test.support.temp_cwd() fork-safe
Browse files Browse the repository at this point in the history
Improve the context manager test.support.temp_cwd() to not remove the temporary
directory, if a forked child terminates.
  • Loading branch information
Anselm Kruis committed Apr 9, 2017
1 parent 45d22c2 commit 22e032a
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
4 changes: 3 additions & 1 deletion Lib/test/support/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
15 changes: 15 additions & 0 deletions Lib/test/test_regrtest.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()

0 comments on commit 22e032a

Please sign in to comment.