Pytest: 3.7.1 unittest.mock decorators won't work for pytest fixture

Created on 3 Aug 2018  路  5Comments  路  Source: pytest-dev/pytest

Hi, some of my unittests failed after I upgrade to pytest 3.7.1. I checked them and found it has something to do with using mock decorator with pytest fixtures.

Example:

import unittest.mock as mock

import pytest

config = {
    'mykey': '1'
}


@pytest.fixture(scope='function')
@mock.patch.dict(config, {'mykey': 0})
def my_fixture():
    print("value of mykey now: {}".format(config['mykey']))


def test_foobar(my_fixture):
    print('bla bla bla')

With pytest 3.6.3, it works fine and output is like:

============================= test session starts ==============================
platform darwin -- Python 3.5.0, pytest-3.6.3, py-1.5.4, pluggy-0.6.0
rootdir: /Users/zhangyan/foobar/tests, inifile:
plugins: falcon-0.4.0collected 1 item
test_fixture.py value of mykey now: 0
.bla bla bla

Can see that the value of mykey has been mocked.

But with pytest 3.7.1, the output is:

============================= test session starts ==============================
platform darwin -- Python 3.5.0, pytest-3.7.1, py-1.5.4, pluggy-0.7.1
rootdir: /Users/zhangyan/foobar/tests, inifile:
plugins: falcon-0.4.0collected 1 item
test_fixture.py value of mykey now: 1
.bla bla bla

Can see from the output that, the mock didn't make any effect.
Please correct me if my usage is incorrect, thanks!

bug regression

Most helpful comment

Hi @njsmith,

Yeah we already have quite a number of bug fixes on master, so I was planning to start a release later today. 馃憤

All 5 comments

@fabregaszy this is a regression, i believe it relates to #3754

my suspicion is that getting the real function at that place is just unwrapping the mock decorator as well

a suggestion for a quick fix is to use monkeypatch in the fixture

my suspicion is that getting the real function at that place is just unwrapping the mock decorator as well

Yes I think that's the problem, get_real_func unwraps everything until it gets to the original function. I will take a look ASAP.

Any chance of a point release soon? This is also breaking pytest-trio's test suite (which tries to combine @pytest.fixture with @async_generator): https://github.com/python-trio/pytest-trio/pull/50#issuecomment-413124393

(And I've confirmed that using pytest master does resolve the issue we're seeing with 3.7.1.)

Hi @njsmith,

Yeah we already have quite a number of bug fixes on master, so I was planning to start a release later today. 馃憤

Was this page helpful?
0 / 5 - 0 ratings