Similar to this question, I'm having problems testing a view with Django's unit testing framework. My view is very simple: it processes a form, adds an object to the database, and returns a JSONResponse. The test is equally simple, but I keep getting "First argument is not valid JSON: ''. The code actually works in my application; it just doesn't seem to work when unit testing. Any help is appreciated.
EDIT: Traceback
======================================================================
ERROR: tearDownClass (zoning_intake.tests.AddActionTypeTest)
Traceback (most recent call last): File "C:\Virtual\Django18\lib\site-packages\django\test\testcases.py", line 96 2, in tearDownClass cls._rollback_atomics(cls.cls_atomics) AttributeError: type object 'AddActionTypeTest' has no attribute 'cls_atomics'
====================================================================== FAIL: test_post_add_action_type_succeeds (zoning_intake.tests.AddActionTypeTest)
Traceback (most recent call last): File "C:\Hg\sdcgis\zoning_intake\tests.py", line 26, in test_post_add_action_t ype_succeeds self.assertJSONEqual(response.content,{'result':'Success', 'msg':'Success'})
File "C:\Virtual\Django18\lib\site-packages\django\test\testcases.py", line 68 9, in assertJSONEqual self.fail("First argument is not valid JSON: %r" % raw) AssertionError: First argument is not valid JSON: ''
Ran 1 test in 10.757s
FAILED (failures=1, errors=1) Preserving test database for alias 'default'... Preserving test database for alias 'other'...
My view:
form = ActionTypeForm(request.POST)
if form.is_valid():
action = form.cleaned_data['action']
new_type = CaseRequestActionType(action=action)
new_type.save()
return JsonResponse({'result':'Success', 'msg':'Success'})
else:
return JsonResponse({'result':'Fail', 'msg':'An unknown error occurred'})
My test:
class AddActionTypeTest(TestCase):
if django.VERSION[:2] >= (1, 7):
# Django 1.7 requires an explicit setup() when running tests in PTVS
@classmethod
def setUpClass(cls):
django.setup()
def test_post_add_action_type_fails(self):
response = self.client.post(reverse('zoning:add_action_type'))
self.assertEqual(response.status_code, 302)
self.assertJSONEqual(force_text(response.content), {'result':'Fail', 'msg':'An unknown error occurred'})