pytest-forked

1.6.0 · active · verified Thu Apr 09

pytest-forked is a pytest plugin that runs tests in isolated forked subprocesses, preventing global state pollution and ensuring test independence. As of version 1.6.0, it supports modern Python (3.7+) and pytest versions, offering a crucial tool for test isolation. It generally follows pytest's release cadence for compatibility updates.

Warnings

Install

Quickstart

pytest-forked is typically activated via command-line arguments or `pytest.ini` configuration, not by direct Python imports. This example demonstrates how tests benefit from isolation when `--forked` is used, preventing global state changes in one test from affecting another.

# test_isolation.py
import pytest

# A module-level variable to simulate global state
_global_resource_id = 0

def setup_module():
    global _global_resource_id
    _global_resource_id = 100 # This setup runs once per module

def test_isolated_resource_access():
    # Each forked test process gets its own copy of the global state
    # if it's set up before the fork, or a fresh state if set up within the test.
    assert _global_resource_id == 100

    # Simulate modifying a global resource
    global _global_resource_id
    _global_resource_id += 1
    assert _global_resource_id == 101

def test_another_isolated_resource_access():
    # This test, when forked, should start with the original _global_resource_id from setup_module,
    # not affected by modifications in test_isolated_resource_access.
    assert _global_resource_id == 100

# To run these tests with forked isolation:
# 1. Save the code above as test_isolation.py
# 2. Run from your terminal:
#    pytest --forked test_isolation.py

view raw JSON →