【问题标题】:Pytest mock / patch of an api callapi 调用的 Pytest 模拟/补丁
【发布时间】: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


【解决方案1】:

在没有看到调用堆栈的情况下,很难准确地说出哪里出了问题,但以下一般模式有效。

foo.py

def foo():
    pass


def bar():
    result = foo()
    return result["status"]

test_foo.py作为

import mock

from foo import bar


@mock.patch("foo.foo", return_value={"status": "PASSED"})
def test_add(mock_foo):
    assert bar() == "PASSED"

这种通用模式适用于同一目录中的pytest test_foo.py

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-30
    • 2020-10-29
    • 1970-01-01
    • 1970-01-01
    • 2015-06-18
    相关资源
    最近更新 更多