【发布时间】:2020-05-13 12:15:09
【问题描述】:
当从函数列表调用函数时,我试图模拟一个函数。
以下工作:
# demo_module.py
import demo_module_b
def run_me():
run_me_too()
# demo_module_b
def run_me_too():
pass
# test.py
from demo_module import run_me
from demo_module_b import run_me_too
@patch('demo_module_b.run_me_too')
def test_run_me_with_patch(mock_run_me_too):
run_me()
assert mock_run_me_too.called # PASSES
以下失败:
# demo_module.py
import demo_module_b
PROCESS = [
demo_module_b.run_me_too,
]
def run_me():
PROCESSES[0]()
# demo_module_b
def run_me_too():
pass
# test.py
from demo_module import run_me
from demo_module_b import run_me_too
@patch('demo_module_b.run_me_too')
def test_run_me_with_patch(mock_run_me_too):
run_me()
assert mock_run_me_too.called # FAILS
有没有办法让它工作而无需模拟列表?
编辑 1
这也失败了(并且直接导入失败了两个测试):
# demo_module.py
from demo_module_b import run_me_too
processes = [
run_me_too,
]
def run_me():
processes[0]() # FAILS IN TEST
run_me_too() # ALSO FAILS IN TEST
【问题讨论】:
-
这就是你应该如何定义
PROCESSES:PROCESS = [run_me_too]而不是PROCESS = [demo_module_b.run_me_too] -
谢谢我试过这个,它也失败了。以上编辑
标签: python python-3.x pytest python-mock