我正在尝试修补fun_1
字典中的worker_functions
函数,我似乎在苦苦挣扎:
import sys
from worker_functions import (
fun_1,
fun_2,
fun_3,
)
FUNCTION_MAP = {
'run_1': fun_1,
'run_2': fun_2,
'run_3': fun_3,
}
def main():
command = sys.argv[1]
tag = sys.argv[2]
action = FUNCTION_MAP[command]
action(tag)
我尝试过模仿cli.fun_1
和cli.main.action
以及cli.action
,但这会导致失败。
from mock import patch
from cli import main
def make_test_args(tup):
sample_args = ['cli.py']
sample_args.extend(tup)
return sample_args
def test_fun_1_command():
test_args = make_test_args(['run_1', 'fake_tag'])
with patch('sys.argv', test_args),\
patch('cli.fun_1') as mock_action:
main()
mock_action.assert_called_once()
我似乎错过了什么吗?
答案 0 :(得分:1)
您需要修补FUNCTION_MAP
字典本身的引用。使用patch.dict()
callable执行此操作:
from unittest.mock import patch, MagicMock
mock_action = MagicMock()
with patch('sys.argv', test_args),\
patch.dict('cli.FUNCTION_MAP', {'run_1': mock_action}):
# ...
那是因为FUNCTION_MAP
字典是查找函数引用的位置。