@Patch decorator is not compatible with pytest fixture @Patch decorator is not compatible with pytest fixture python python

@Patch decorator is not compatible with pytest fixture


When using pytest fixture with mock.patch, test parameter order is crucial.

If you place a fixture parameter before a mocked one:

from unittest import mock@mock.patch('my.module.my.class')def test_my_code(my_fixture, mocked_class):

then the mock object will be in my_fixture and mocked_class will be search as a fixture:

fixture 'mocked_class' not found

But, if you reverse the order, placing the fixture parameter at the end:

from unittest import mock@mock.patch('my.module.my.class')def test_my_code(mocked_class, my_fixture):

then all will be fine.


As of Python3.3, the mock module has been pulled into the unittest library. There is also a backport (for previous versions of Python) available as the standalone library mock.

Combining these 2 libraries within the same test-suite yields the above-mentioned error:

E       fixture 'fixture_name' not found

Within your test-suite's virtual environment, run pip uninstall mock, and make sure you aren't using the backported library alongside the core unittest library. When you re-run your tests after uninstalling, you would see ImportErrors if this were the case.

Replace all instances of this import with from unittest.mock import <stuff>.


If you have multiple patches to be applied, order they are injected is important:

# from question@pytest.fixture(scope="module")def brands():    return 1# notice the order@patch('my.module.my.class1')@patch('my.module.my.class2')def test_list_instance_elb_tg(mocked_class2, mocked_class1, brands):    pass