jeudi 19 mars 2020

Both decorating a test function with mock and using a mock through pytest.fixture

I am writing a test function using pytest and mock. Surprisingly, I am having difficulties in both using a @mock.patch() decorator and using a mock through a fixture.

Example code

import pytest
import unittest.mock as mock

import source_module

@pytest.fixture
def mock_some_function_by_fixture():
    with mock.patch.object(source_module, "some_function") as fixture_mock:
        yield fixture_mock


@mock.patch.object(source_module, "some_other_function_to_be_mocked")
def test_my_big_function(mock_some_function_by_fixture):
    _ = source_module.my_big_function()

    mock_function_by_fixture.assert_called()

In this case, it seems I cannot both mock by decorator and by fixture.

I can tell from print output in the source of some_function, that it does not get mocked and the assert_called() fails.

After a bit of fiddling around, it seems that if there are N decorator mocks then first N mocks by fixture get replaced by those decorators. If there are more fixture mocks, then they work as expected.

Am I doing something wrong here, or can this be solved so I can use both decorators and fixtures without them replacing each other?

Aucun commentaire:

Enregistrer un commentaire