Search code examples
pythondjangounit-testingdjango-unittest

How can I test function with request.is_ajax() and request.method=='POST' in Django using unittest?


I have next function

    def edit_resolution_text_view(self, request):
        if request.method == 'POST' and request.is_ajax():
            resolution = request.POST.get('resolution')
            donation_id = request.POST.get('donation')
            result = Donation.objects.filter(pk=donation_id).\
                update(resolution_note=resolution)
            if not result:
                return JsonResponse({'message': 'Error'})
            return JsonResponse({'resolution': resolution})
        return JsonResponse({'message': 'Error'})

How can to test it using unittest

This function located in Django modelAdmin.

I define instance as self.donation_admin = DonationAdmin(model=Donation, admin_site=AdminSite()) and call function as self.donation_admin.edit_resolution_text_view(...)


Solution

  • The easiest way would be to use the Client from unittest and call the enpoint that resolves to you function. The is_ajax() method just checks that the HTTP_X_REQUESTED_WITH': 'XMLHttpRequest' header is in the request. So you can add it to the test request.

    class TestEditResulutionTextView(unittest.TestCase):
    
        def test_get(self):
            response = self.client.get('/url_to_my_view/', **{'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'})
            self.assertEqual(response.json(), {'message': 'Error'})
    
        def test_post(self):
            expected_resolution = # put here what you are expecting
            response = self.client.post('/url_to_my_view/', **{'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'})
            self.assertEqual(response.json(), {'resolution': expected_resolution})