python - pytest-mock 如何修补嵌套函数

标签 python pytest pytest-mock

我有以下代码:

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

我将 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

但是当我在 py.test 中运行时出现错误:

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

我想测试 mocker.patch functions\methods,它们在测试模块中不可见,并且嵌套在该函数中,有什么方法可以测试吗?

最佳答案

作为@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

你的 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

关于python - pytest-mock 如何修补嵌套函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61932936/

相关文章:

python - MAP (PySpark) 返回的元组列表(或迭代器)

python - 模拟类实例而不调用 `__init__`并模拟它们各自的属性

python - 如何解决 pytest 中的弃用警告

python - pytest mocker fixture mock 模块来自定义的位置而不是使用的位置

python-3.x - pytest - 在构造函数中模拟构造函数

Python pytest mock 失败,函数调用断言为 "assert None"

Python-C 集成 : Ctypes, CFFI 或创建二进制模块

python - Django 在数据库中保存带有额外字符的表单字符串 (u'string')

python - 如何修改 pythons argparse 中位置参数的元变量?

python - 从 pip 转移到诗歌,现在 pytest-cov 不会收集覆盖率数据