我想测试我的视图在处理后是否返回正确的 json。这是我的看法:
@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')
这工作正常。这是我尝试过的测试:
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 返回空字符串。
谢谢你。