Search code examples
pythonpython-3.xmockingpython-unittestmagicmock

MagicMock the response to get data in python 3.x


I have below two functions which I am trying to write unittest case using magicMock.

import json
from unittest import mock
from unittest.mock import MagicMock
def get_response(m, time):
    response = get_data(m, time)
    return response

def my_method():
    m = ''
    time = "2019-08-30"
    resp = get_response(m, time)
    if resp.status_code = 200:
        data = json.loads(resp.text)

I am trying to write unittest case to get the response code and text using MagicMock:

ok_response_mock = MagicMock()
type(ok_response_mock).status_code = mock.PropertyMock(return_value=200)
ok_response_mock.text.return_value = "{'blah':'blah'}"

get_response = MagicMock()
get_response.return_value = ok_response_mock

But I am not getting this worked. The above method is not able to mock the resp.text.


Solution

  • You can mock get_response with a Mock object that returns a Mock object that has a status_code attribute of 200 and a text attribute of your mock JSON content:

    import json
    from unittest.mock import Mock
    
    def my_method():
        m = ''
        time = "2019-08-30"
        resp = get_response(m, time)
        if resp.status_code == 200:
            print(json.loads(resp.text))
    
    get_response = Mock(return_value=Mock(status_code=200, text='{"blah": "blah"}'))
    
    my_method()
    

    This outputs:

    {'blah': 'blah'}
    

    Since the default return value of a Mock object is a Mock object, you can also configure the return_value attribute of the Mock object like this, and it will work just as well:

    get_response = Mock()
    get_response.return_value.status_code = 200
    get_response.return_value.text = '{"blah": "blah"}'