Search code examples
pythondjangounit-testingmockingpython-mock

Python mock to create a fake object return a dictionary when any of its attributes are used


for example I have a method in Django which reuses the request object:

def dowork(request):
    # the sessionid is a query param of the callback from payment gateway
    print request.GET.get('sessionid')

When I write unittest, I need to create a fake request object, which should have GET attribute and should contain a dictionary {'sessionid': 'blah'}

How do I do that using the mock package?


Solution

  • Do this by creating a mock, and setting its attributes like any other python object.

    The only caveat is that mocks are specialized so that their attributes are automatically padded with mocks, which makes this very easy. You don't need to explicitly create each attribute as a mock object.

    For example,

    import mock
    mock_request = mock.Mock()
    
    mock_request.GET.get.return_value = {'sessionid': 'blah'}
    
    x = mock_request.GET.get('sessionid')
    
    assert x == {'sessionid': 'blah'}
    mock_request.GET.get.assert_called_once_with('sessionid')