Skip to main content

python-unittest-patch-context-manager

Instead of using a patch as a decorator:

decorator.py
from unittest.mock import patch 
 
@patch('something.from.the.environment', 42)
test_it_works():
    ...

You can use it as a context manager:

context_manager.py
test_it_works():
    with patch('something.from.the.environment', 42):
        ...

And if you want to apply the same patch to every test in a module, you can use that context manager in a fixture so you don’t have to repeat it in each test:

fixture.py
from pytest import fixture
 
@fixture(autouse=True, scope="module")
def apply_to_every_test():
    with patch('something.from.the.environment', 42):
        yield
 
test_happy_path():
    # patch applied
    ...
 
test_sad_path():
    # patch applied again
    ...

Source: py.test patch on fixture - Stack Overflow