Search code examples
pythonjsondjangotravis-cijsonresponse

Django JsonResponse returning content-type text/html instead of application/json


I've hit a dead end with a django web-project I'm working on and I can't seem to find any answers. I'm trying to test a view as simple as this:

def list(request):
    return JsonResponse( {"foo": "bar"} )

It seems to run all well. If I open the site on my browser and check the Page-Info it says "Type: application/json".

However, when I run following test on a travis ci:

def setUpTestData(cls):
    cls.client = Client()
    #A few lines of setting up test-data

def test_content_type(self):
    response = self.client.get('/api/list')
    self.assertEqual(response['content-type'], 'application/json')

I get following Failure:

FAIL: test_content_type (researchlibrary.api.tests.test_list.ListTests)
----------------------------------------------------------------------
Traceback (most recent call last):
   File "/home/travis/build/FUB-HCC/ACE-Research-Library/researchlibrary/api/tests/test_list.py", line 25, in test_content_type
    self.assertEqual(response['content-type'], 'application/json')
AssertionError: 'text/html' != 'application/json'
- text/html
+ application/json

The urls are all fine. The test recieves the correct page, just the type appears to be text/html instead of application/json and I have no clue why that is.

Anybody got any ideas as to why this could be?

EDIT: changing self.client.get('/api/list') to self.client.get('/api/list/') solved the problem.


Solution

  • It appears that

    self.client.get('/api/list')
    

    led to an error-page (hence the text/html content_type).

    EDIT: Not an error-page, but an http-redirect, according to LudwikTrammer.

    Changing

    self.client.get('/api/list') 
    

    to

    self.client.get('/api/list/') 
    

    solved the issue.