[英]pytest-mock how to patch nested function
我有以下代碼:
我的模塊.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
我在 test_my_module.py 中使用 pytest 和 pytest-mock 和 mocker 作為夾具
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 函數\方法,這些函數在測試模塊中不可見,並且嵌套在該函數中,我想測試?
作為@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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.