Instead of using a patch as a decorator:
from unittest.mock import patch
@patch('something.from.the.environment', 42)
test_it_works():
...
You can use it as a context manager:
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:
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
...