pytest-mock how to patch nested function

Viewed 2278

I have the following code:

my_module.py

def my_func(number):
    def nested_func(value):
        '''
        Doing some calculation
        '''
        return result
    output = []
    for i in range(number):
        res = nested_func(i)
        output.append(res)
    return output

I'm using pytest with pytest-mock and mocker as a fixture in test_my_module.py

test_my_module.py

def test_my_module(mocker):
    expected_res = [1, 1, 1]
    mocker.patch('nested_func', return_value=1)

    from my_module import my_func
    assert my_func(3) == expected_res

But when I run in py.test I got an error:

TypeError: Need a valid target to patch. You supplied: 'nested_func'

Is there any way to mocker.patch functions\methods, which are not visible in testing module and located as nested in that functions, I want to test?

1 Answers

As a follow up to @MrBean Bremen, I think a work around is to define nested_func outside of my_func and call it within my_func

def nested_func(value):
   result = value + 2
   return result
def my_func(number):
   output = []
   for i in range(number):
       res = nested_func(i)
       output.append(res)
   return output

Your test_my_module

from my_module import my_func
def test_my_module(mocker):
    expected_res = [1, 1, 1]
    mocker.patch('my_module.nested_func', return_value=1)

    assert my_func(3) == expected_res
Related