2

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 has GET attribute and should contains a dictionary {'sessionid': 'blah'}

How do I do that using the mock package?

2 Answers 2

2

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')
2
  • When I call request.GET.get('sessionid') it returns {'sessionid': 'blah'}, expected result should return 'blah'
    – James Lin
    Aug 18, 2014 at 22:12
  • OK I have worked it out based on your answer mock_request.GET.get.return_value = 'blah'
    – James Lin
    Aug 18, 2014 at 22:15
0

Why don't you use the built-in test client, which supports mock sessions already?

def test_dowork(self):
    session = self.client.session
    session = ['sessionid'] = 'blah'
    session.save()
    response = self.client.get('/dowork/')
    self.assertEqual(...)
1
  • Hi the sessionid is a query param that comes from the callback from our credit card gateway.
    – James Lin
    Aug 18, 2014 at 22:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.