【发布时间】:2021-02-26 13:55:58
【问题描述】:
我想测试 foo.py 的一门课程:
import requests
class Foo:
def fooMethod(self, url):
response = requests.get(url)
return response
我想替换requests调用来模拟响应。
这是我在test_foo.py中的测试文件:
from foo import Foo
def mocked_requests_get(*args, **kwargs):
class MockResponse:
def __init__(self, text, code):
self.text = text
self.code = code
if args[0] == "http://localhost":
return MockResponse("Test response", 200)
return MockResponse(None, 404)
class TestFoo:
def test_foo(self, mocker):
a = Foo()
mocker.patch ('foo.requests.get', mocked_requests_get)
spy = mocker.spy (a, 'test_foo.mocked_requests_get')
response = a.fooMethod("http://localhost")
assert response.text == "Test response"
assert spy.call_count == 1
我想检查mocked_requests_get 函数是否只被调用过一次。
解释器在spy = mocker.spy ... 行给出错误:
'Foo' object has no attribute 'test_foo.mocked_requests_get'
这是可以理解的 - 但我无法找到一种方法来获取引用该函数的对象实例。有人可以帮忙吗?
【问题讨论】:
标签: python pytest pytest-mock