我有一门课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'
这是可以理解的 - 但我无法找到一种方法来获取引用该函数的对象实例。有人可以帮忙吗?