I have a class in foo.py
that I wish to test:
import requests
class Foo:
def fooMethod(self, url):
response = requests.get(url)
return response
I want to replace the requests
call to simulate the response.
Here is my test file in 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
I want to check that the mocked_requests_get
function is called only once.
The interpreter gives an error on the spy = mocker.spy ...
line:
'Foo' object has no attribute 'test_foo.mocked_requests_get'
This is understandable - but I can't work out a way to get to the object instance that references that function. Can anyone help please?