0

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

divide_by_zero
  • 997
  • 1
  • 8
  • 20
  • 1
    With the code in your last sample, you'd need to `@patch('module_xyz.head')` (replacing 'module_xyz' with the name of the module where you define `MyClient`). The 'from...' style import means that when `MyClient` refers to `head`, `head` is a name in module_xyz's namespace. So that namespace is where you patch it. – slothrop Aug 01 '23 at 19:26

0 Answers0