codyc4321
codyc4321

Reputation: 9682

Mock requests.json after getting response in Python

I have test:

class MyTests(TestCase):

    def setUp(self):
        self.myclient = MyClient()

    @mock.patch('the_file.requests.json')
    def test_myfunc(self, mock_item):
        mock_item.return_value = [
                    {'itemId': 1},
                    {'itemId': 2},
        ]
        item_ids = self.myclient.get_item_ids()
        self.assertEqual(item_ids, [1, 2])

in the file I have

import requests

class MyClient(object):

    def get_product_info(self):
            response = requests.get(PRODUCT_INFO_URL)
            return response.json()

My goal is to mock get_product_info() to return the return_value data in the test. I have tried mocking requests.json and requests.get.json, both error out on no attribute, I've mocked the_file.MyClient.get_product_info which doesn't cause error but doesn't work, it returns the real data.

How can I mock this get_product_info which uses requests library?

Upvotes: 1

Views: 1862

Answers (1)

Don Kirkby
Don Kirkby

Reputation: 56230

You should be able to just patch get_product_info().

from unittest.mock import patch


class MyClient(object):
    def get_product_info(self):
        return 'x'

with patch('__main__.MyClient.get_product_info', return_value='z'):
    client = MyClient()
    info = client.get_product_info()
    print('Info is {}'.format(info))
    # >> Info is z

Just switch __main__ to the name of your module. You might also find patch.object useful.

Upvotes: 1

Related Questions