Search code examples
pythonpython-3.xfunctionpytest

Mocking function within a function pytest?


def func1():
    return 5
    
def func2(param1, param2):
    
    var1 = func1()
    return param1 + param2 + var1

I want to use pytest to test the second function by mocking the first, but I am not sure how to do this.

@pytest.fixture(autouse=True)
def patch_func1(self):
    with mock.patch(
        "func1",
        return_value= 5,
    ) as self.mock_func1:
        yield

I think it can be done with a dependency injection and fixture as above but that would mean changing func1 which I would prefer not to do.


Solution

  • You don't need to change anything.

    You can use mocker fixture with pytest (requires installation of pytest-mock). don't worry about the mocker argument, it will magically work.

    def test_func2(mocker):
        mocked_value = 4
        first = 1
        second = 2
        func1_mock = mocker.patch("func1")
        func1_mock.return_value = mocked_value
        actual_value = func2(first, second)
        assert actual_value == first + second + mocked_value