vendredi 26 août 2016

Pytest works with old mock, but not unittest.mock

I'm porting some code from Python 2 to 3, and py.test isn't playing well with the patch decorator from unittest.mock. When I use the patch decorator to pass a mock into the arguments of a test function, py.test instead interprets that argument to be a fixture, and is unable to set up the test.

Here's a contrived example that hopefully illuminates the problem:

@patch('my_module.my_func')
def test_my_func(mock_func):
    mock_func()
    mock_func.assert_called_once_with()

After running py.test, the error message would look like:

E       fixture 'my_func' not found
>       available fixtures: cache, capfd, capsys, doctest_namespace, monkeypatch, pytestconfig, record_xml_property, recwarn, tmpdir, tmpdir_factory
>       use 'pytest --fixtures [testpath]' for help on them.

This is the only scenario under which this failure occurs. If I explicitly call the test (i.e. run test_my_func()), no error. If I patch my_func using either of the other patching techniques, no error. If I import patch from mock instead of unittest.mock, no error.

It's only while running my tests using py.test, using unittest.mock, and patching using the decorator when this occurs.

I'm running Python 3.4.5.

Aucun commentaire:

Enregistrer un commentaire