简体   繁体   English

pytest-mock 如何修补嵌套的 function

[英]pytest-mock how to patch nested function

I have the following code:我有以下代码:

my_module.py我的模块.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 中使用 pytest 和 pytest-mock 和 mocker 作为夹具

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:但是当我在 py.test 中运行时出现错误:

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?有没有什么方法可以修改 mocker.patch 函数\方法,这些函数在测试模块中不可见,并且嵌套在该函数中,我想测试?

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作为@MrBean Bremen 的后续行动,我认为解决方法是在 my_func 之外定义 nested_func 并在 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你的 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM