Search code examples
pythonjsondjangounit-testingdjango-unittest

Writing a Django unit test for a function with a HttpResponse


I'm writing a unit test to check to see if the telecasts key is in the JSON data returned in this function (in my views.py):

def my_function(request, date1='', date2='', date3='', date4=''):
    ::some other functions...::
    return HttpResponse(data, content_type='application/json')

As you see, the JSON I want to check is sent via a HttpResponse as the variable data

This JSON data, when received on the front-end, is structured like:

{"records": [ {"program": "WWE ENTERTAINMENT", "telecasts": 201,...}, {..} ]

So this is how I'm trying to write the unit test, but I'm getting an error when I run it:

    def my_test(self):
    """Data returned has telecasts key"""

    request = self.client.get(
        '/apps/myapp/2014-08-01/2015-06-10/2016-01-13/2016-03-23/',
        {dictionary of optional parameters}
    )

    force_authenticate(request, user=self.user)

    response = my_function(
        request,
        '2014-08-01',
        '2015-06-10',
        '2016-01-13',
        '2016-03-23'
    )

    telecasts_check = response['records'][0]['telecasts']
    self.assertRaises(KeyError, lambda: telecasts_check)

Solution

  • self.client.get makes the request and returns the response so it is totally unnecessary to call myfunction directly to get the response down below.

    Another thing is, HttpResponse has a property named content which can be a bytestring or an iterator that stores the response content.

    In your case, you can convert that to a dictionary using json.loads and access any values just like you already are doing:

    import json
    
    def my_test(self):
        ...
        response = self.client.get(...)
        result = json.loads(response.content)
        telecasts_check = result['records'][0]['telecasts']
        ...