Created
June 2, 2023 09:45
-
-
Save jonashaag/5e425703e0f60069e647974d175336e9 to your computer and use it in GitHub Desktop.
Run a pytest test in a fork
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def run_test_in_fork(func, *args, **kwargs): | |
"""Run a pytest test in a fork of the pytest process. | |
Useful to check behaviour of some code when run in a forked process. | |
The test outcome will be reported normally in the pytest parent. | |
""" | |
if not hasattr(os, "fork"): | |
pytest.skip("os.fork not available") | |
error_in_child = multiprocessing.Value("b") | |
child_pid = os.fork() | |
if child_pid: | |
# We are the parent | |
os.waitpid(child_pid, 0) | |
assert not error_in_child.value | |
else: | |
# We are the child | |
try: | |
func(*args, **kwargs) | |
except Exception: | |
error_in_child.value = True | |
raise | |
# Stop running other tests of this test suite in the child | |
pytest.exit("Stop tests in child") | |
def test_something_in_fork(): | |
run_test_in_fork(_test_something_in_fork_inner) | |
def _test_something_in_fork_inner(): | |
assert 1 + 1 == 2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment