The monkeypatch fixture lets you change parts of your code during tests without changing the real code. It helps test tricky parts safely.
monkeypatch fixture in PyTest
def test_example(monkeypatch): monkeypatch.setattr(target, "name", new_value) monkeypatch.setenv("VAR_NAME", "value") monkeypatch.delattr(target, "name", raising=False)
monkeypatch is a special argument you add to your test function.
You can change attributes, environment variables, or delete attributes safely.
module.func with fake_func during the test.def test_replace_function(monkeypatch): def fake_func(): return "fake" monkeypatch.setattr("module.func", fake_func) assert module.func() == "fake"
API_KEY just for the test.def test_change_env(monkeypatch): monkeypatch.setenv("API_KEY", "12345") assert os.getenv("API_KEY") == "12345"
def test_remove_attribute(monkeypatch): monkeypatch.delattr("module.Class.attr", raising=False) assert not hasattr(module.Class, "attr")
This test uses monkeypatch to set and delete an environment variable API_KEY. It checks that get_api_key() returns the right value depending on the environment.
import os def get_api_key(): return os.getenv("API_KEY", "no-key") def test_api_key(monkeypatch): monkeypatch.setenv("API_KEY", "test123") assert get_api_key() == "test123" monkeypatch.delenv("API_KEY", raising=False) assert get_api_key() == "no-key"
Always use monkeypatch inside tests to avoid changing real code or environment.
Changes made by monkeypatch last only during the test and are undone automatically.
Use raising=False to avoid errors if the attribute or env variable does not exist.
monkeypatch helps change code or environment safely during tests.
It is useful to replace functions, set environment variables, or remove attributes temporarily.
Changes are only for the test and do not affect other tests or real code.