I want to test that my view returns correct json after processes. here is my view:
@login_required
@require_POST
def xxx_view(request):
if 'post_id' in request.POST:
post_id = request.POST['post_id']
post = Post.objects.get(id=post_id)
post.order = 2
post.save()
json_dump = simplejson.dumps({'new_title': post.order,})
return HttpResponse(json_dump, mimetype='application/json')
else:
return HttpResponse('oups')
this works correctly. Here is what i ve tried for testing:
from django.test import TestCase
from django.test.client import Client
from django.utils import simplejson
from app.models import *
c = Client()
class CustomTests(TestCase):
def test_xxx(self):
json_data = simplejson.dumps({'post_id': 1,})
response = client.post('/content/vote/', json_data,
content_type='application/json',
HTTP_X_REQUESTED_WITH='XMLHttpRequest')
self.assertEqual(response.status_code, 302) # this is OK.
self.assertEqual(response.content, 2) # but this fails.
response.content returns empty string.
Thank you.
It looks like your login_required
decorator is redirecting your unauthenticated user. Make sure you create a test user and log that user in using test client login
method
https://docs.djangoproject.com/en/dev/topics/testing/overview/#django.test.client.Client.login