【发布时间】:2023-01-03 00:57:15
【问题描述】:
我试图了解补丁,但我似乎没有这样做。
目前我正在尝试在测试函数中修补一个 api 调用:
# function being tested
def tested function():
response = call_to_api()
status = response["status"]
if status == "something":
# some more logic to test
在 test_ 文件中,我尝试执行以下操作:
@patch("import_from_same_file.call_to_api")
def test_tested_function(my_mock):
my_mock.return_value = {"status":"COMPLETE"}
到目前为止,我所能实现的只是 Got error: list indices must be integers or slices, not str 错误,不知道它实际上来自哪里。请帮忙,已经花了很多时间在这上面。
我还尝试提供一个对象作为模拟的返回值。
class Response():
status = "COMPLETE"
虽然没有运气。显然我遗漏了一些关于补丁如何工作的信息。
【问题讨论】:
-
"import_from_same_file.call_to_api"绝对正确吗?将breakpoint放入tested_function以查看您得到的响应。你需要模拟call_to_api,从它被调用的地方,而不是它被定义的地方
标签: python mocking pytest patch