Siddhu
Siddhu

Reputation: 916

Testing TastyPie APIs using Django Test Client always results in empty HTTP 200 responses

I've got a simple Django-TastyPie API defined (it is a basic class that derives from ModelResource; I'm using the 0.9.11, the latest stable version). The class UserProfileListResource gets a list of users formatted in JSON (therefore, the content type is application/json). I've not reproduced the code because it works fine when testing it manually.

I have it registered in urls.py as follows:

v1_api = Api(api_name='v1')
v1_api.register(UserProfileListResource())

urlpatterns += patterns('',
    (r'^api/', include(v1_api.urls)))

And it works fine when I test it manually using a browser.

However, when I write a simple test case using django.test.client.Client to send the request out, I receive an HTTP 200 response with empty response content and the wrong content-type (text/html instead of application/json).

I introduced a few logging statements into my API code, and I realise that my API code is not being executed at all.

From what I could see, there have been other people who were successful. Is there something obvious I am missing? I'm stuck! :-(

Please find below my test code; my test class inherits from django.utils.unittest.TestCase (I have also tried django.test.testcases.TestCase; but no joy):

admin_user_profile = self._create_user_profile()

browser_client = Client()
response = browser_client.get(self.LIST_USERS_URL)
self.assertTrue(HttpResponse.status_code, response.status_code)

logging.debug(response._headers) #prints {'content-type': ('Content-Type', 'text/html; charset=utf-8'), 'location': ('Location', 'http://testserver/api/v1/users/?username=user&api_key=1681f96d50ba54b410c91365a678ec07b6375efc')}
logging.debug(response.content) #prints empty string

Upvotes: 0

Views: 1691

Answers (1)

Siddhu
Siddhu

Reputation: 916

I've figured out what I was doing wrong. I was inheriting from django.test.testcases.TestCase instead of django.test.TestCase (unittests.TestCase just doesn't work). When I changed that, it's all started to work.

I hope this helps somebody else fighting with the same problem.

Upvotes: 2

Related Questions