Search code examples
pythondjangomockingdjango-testing

Django : How can I mock request.session of view?


I'm using mocking to test views.

tests.py

@patch('orders.views.OrderView.generate_merchant_uid')
def test_expected_price_is_registered_on_GET_request(self, mock_generate_merchant_uid):
    self.client.get(reverse('orders:order'))

views.py

class OrderView(LoginRequiredMixin, View):

    def generate_merchant_uid(self):
        merchant_uid = "blah_blah_blah"
        return merchant_uid

    def get(self, request, *args, **kwargs):
        merchant_uid = self.generate_merchant_uid()
        request.session['merchant_uid'] = merchant_uid
        return HttpResponse('a')

It occurs errors:

TypeError: <MagicMock name='generate_merchant_uid()' id='4431843456'> is not JSON serializable

It occurs error because I mocked generate_merchant_uid and it returns MagicMock and View trying to store this MagicMock in the request.session.

I think what I have to do is to mock request.session.

But have no idea how I can do that.

Need advices. Thanks.


Solution

  • The problem is not about mocking the session itself. You forgot to set what your mocked function should return. By default it returns a Mock object and it is trying to store it request session and converting it to JSON, there is where you got the error, Mock instance is not JSON serializable.

    @patch('orders.views.OrderView.generate_merchant_uid')
    def test_expected_price_is_registered_on_GET_request(self, mock_generate_merchant_uid):
    
        mock_generate_merchant_uid.return_value = //here goes your mocked value
    
        self.client.get(reverse('orders:order'))
    

    For example:

    mock_generate_merchant_uid.return_value = "blah_blah_blah"