Skip to content

prefer-monkeypatch-for-process-state-in-test

Test mutates process-wide state without a restoring test scope.

Why

The working directory and Python import registries are shared by every test in the process. A direct mutation can survive an assertion or setup failure, making later tests depend on execution order.

Fix

Use pytest's monkeypatch.chdir, monkeypatch.syspath_prepend, monkeypatch.setitem, or monkeypatch.delitem so teardown restores the previous state even when the test fails. A deliberate manual restoration may remain when it is enclosed by a matching try/finally.

Examples

Before — flagged Test installs a module without guaranteed restoration
tests/test_plugin.py
import sys
def test_plugin(fake_plugin):
sys.modules["optional_plugin"] = fake_plugin
After — preferred Pytest restores the module registry after the test
tests/test_plugin.py
import sys
def test_plugin(monkeypatch, fake_plugin):
monkeypatch.setitem(sys.modules, "optional_plugin", fake_plugin)