【发布时间】:2021-10-26 14:02:39
【问题描述】:
我面临以下情况。
我有以下源码
#file:[src/my_module.py]
def order_names(unordered_input: List) -> str:
# function that orders a list of names
...
if(is_ID(unordered_input[i])):
id = unordered_input[i]
name = get_name_by_id(id)
...
def get_name_by_id(id) -> str:
# function that returns a name, based on an ID, through a Rest API call
return make_some_network_call(id)
我想测试函数order_names,我想模拟对get_name_by_id(id)的调用。
假设get_name_by_id(id)会被各种ids多次调用,是否可以创建一个根据输入返回值的mock?
例如:
#file:[test/test_my_module.py]
from unittest import mock
from my_module import order_names
@mock.patch("src.my_module.get_name_by_id", return_value={"3": "Mark", "4": "Kate", "5":"Alfred"})
def test_order_names():
ordered_names = order_names(["3", "4", "Suzan", "5"])
assert ordered_names == "Alfred, Kate, Mark, Suzan"
上述测试代码是要实现的行为类型的示例,因为get_name_by_id() 不是dict 返回类型。
干杯!
【问题讨论】:
-
get_name_by_id应该返回一个名称;嘲笑它以返回dict将无济于事。我认为您真正想要模拟的是make_some_network_call,以便get_name_by_id继续按原样工作。 -
@chepner 没错。我提供的补丁代码只是期望结果的一个例子。让我详细说明一下,因为我可以看到这会造成混乱。
-
我也会后退一点;可能有理由完全修补
get_name_by_id而不是修补它使用的东西。 -
@chepner 你能详细说明一下吗?我相信这就是我想要实现的目标。
标签: python python-3.x python-unittest python-mock