I have the following client class:
import requests
class MyClient:
def stuff(self):
req = requests.head("my_url")
some_bool = check_requests(req) #true if proper response from requests.head
return some_bool
I am testing this client class using the following test:
import requests
from unittest.mock import MagicMock, patch
@patch('requests.head')
def test_myclient_stuff(mock_head):
my_client = MyClient()
response = mock_resp()
mock_head.return_value = response
my_client.stuff()
mock_head.assert_called_with("my_url")
def mock_resp():
response = MagicMock(spec=requests.Response)
response.status_code = 200
response.request = MagicMock(spec=requests.PreparedRequest)
response.headers = {}
return response
All of the above is working correctly and as expected. However, I am shuffling some of the imports around to the Client as follows:
from requests import head
class MyClient:
def stuff(self):
req = head("my_url")
some_bool = check_requests(req) #true if proper response from requests.head
return some_bool
I have tried adjusting the test to use either @patch('requests.head')
or from request import head
with @patch('head')
and neither work. @patch('head')
is invalid because it is not a correct reference to requests.head
. With @patch('requests.head')
, it is not actually mocking and trying to connect to actually connect to "my_url". How do I adjust the test to work with from requests import head
as opposed to import requests
and using requests.head