Search code examples
pythonpytest

Mocking a nested function call with pytest


If I have a function, A1, that is being tested, and that function imports and calls function B1, which itself calls B2 from the same file, how do I mock function B2?

If I mock with mocker.patch('B.B2', return_value=return_value), the mocked function doesn't get called. If I mock with 'A.B2', 'A.B1.B2', 'A.B.B2', or anything like that, I get errors because those don't exist. I understand if I wanted to mock B1 in this situation, I would mock 'A.B1' because of how it's being imported and where it's being used, but I can't find a way to mock B2 which is being called inside B1.

File layout is as follows, to give a visual.

File B

def B2():
    # does a thing, should be mocked

def B1():
    B2()

File A

from B import B1

def A1():
    B1()

Test File

def test_a1():
    from A import A1
    A1()

Solution

  • It might not be obvious but you should patch functions based on where there were used and not where they were defined. So in your case you could achieve it by following way:

    from A import A1
    from unittest import mock
    
    def test_a1():
        with mock.patch('B.B2', return_value="some random val") as mock_b2:
            A1()
            mock_b2​