HOME BLOG

Archive for June, 2025

How to patch in a fixture with Pytest

Posted on: June 5th, 2025 by Olu No Comments

Hi Folks,

In this post I cover a tip to help you write automated tests easily in Python. Specifically I talk about a simple way to apply a patch to multiple test cases without having to manually specify it in each test case. I will assume you’re using the Pytest as your testing framework.

A way to do this is to do the patching in a fixtures.

For example, you can add code as follows to your conftest.py, or wherever you define your fixture:

import pytest
from unittest.mock import patch


@pytest.fixture(autouse=True)
def no_delay():
    with patch('ConstantsModule.ConstantsClass.DELAY_TIME', 10):
        yield

This way, when you want to apply the mock in a test case, all you have to do is add no_delay as an argument to the function.

That’s all for now. Till next time, happy testing.

 

Reference

python – py.test patch on fixture – Stack Overflow. https://stackoverflow.com/questions/50048080/py-test-patch-on-fixture