3

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?

Dipas
  • 294
  • 2
  • 9
  • 21
  • Does this answer your question? [How to access a function inside a function?](https://stackoverflow.com/questions/17395338/how-to-access-a-function-inside-a-function) – quamrana May 21 '20 at 11:09
  • I think no, because my main function doesn't return a function. It has only nested function which is used for calculations inside main function – Dipas May 21 '20 at 11:17
  • 1
    Actually, if you read the answers to the question mentioned by @quamrana, you will find that the local function is created anew each time `my_func` is called - so you cannot patch it, as it doesn't exist at patch time. You can only patch the outer function (e.g. `my_func`). – MrBean Bremen May 21 '20 at 15:15

1 Answers1

-2

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
donmoy
  • 61
  • 5