How do I mock a method that uses requests.get with the WITH keyword in my class?

88 Views Asked by At

I am having trouble understanding how mocking works when the get responses involve using the with keyword. Here is an example I am following for my class `Album' and I have been successful when I am mocking a url as seen below:

def find_album_by_id(id):
    url = f'https://jsonplaceholder.typicode.com/albums/{id}'
    response = requests.get(url)
    if response.status_code == 200:
        return response.json()['title']
    else:
        return None

Here the test

class TestAlbum(unittest.TestCase):

    @patch('album.requests')
    def test_find_album_by_id_success(self, mock_requests):
        # mock the response
        mock_response = MagicMock()
        mock_response.status_code = 200
        mock_response.json.return_value = {
            'userId': 1,
            'id': 1,
            'title': 'hello',
        }

        # specify the return value of the get() method
        mock_requests.get.return_value = mock_response

        # call the find_album_by_id and test if the title is 'hello'
        self.assertEqual(find_album_by_id(1), 'hello')

However, I am trying to understand how this would work with the with keyword involved in the code logic which I am using in my project. This is how I changed the method

def find_album_by_id(id):
    url = f'https://jsonplaceholder.typicode.com/albums/{id}'
    with requests.get(url) as response:
        pipelines = response.json()
    if response.status_code == 200:
        return pipelines['title']
    else:
        return None

Here is my current test:

   @patch('album.requests.get') 
    def test_find_album_by_id_success(self, mock_requests):
        mock_response = MagicMock()
        mock_response.status_code = 200
        mock_response.pipelines.response.json = {
            'userId': 1,
            'id': 1,
            'title': 'hello',
        }
       
        mock_requests.return_value.json.return_value = mock_response
      
        self.assertEqual(find_album_by_id(1), 'hello')

Thanks

I have tried debugging the test and it just never receives the status code of 200 so I am not sure I am mocking response correctly at all? From my understanding the mock_response is supposed to have that status code of 200 but breakline indicates that response is just a MagicMock with nothing in it.

0

There are 0 best solutions below