osueboy
osueboy

Reputation: 143

Django Unit Testing Assert error

this is on Django 1.6

def test_perfil_password_validates_new_passwords(self):
    self.client.login(username='[email protected]', password='test')
    resp = self.client.post('/perfil/password/',
                            json.dumps({'oldpassword': 'test',
                                        'newPassword1': 'wrong',
                                        'newPassword2': 'nuevo'}
                                       ),
                            'text/json',
                            HTTP_X_REQUESTED_WITH='XMLHttpRequest')
    self.assertEqual(resp.status_code, 400)

THIS WORKS and this is the output:

Creating test database for alias 'default'... .
---------------------------------------------------------------------- 
Ran 1 test in 0.273s

OK

Now if i add this extra assert

self.assertContains(resp, '"error":')

Creating test database for alias 'default'... F
====================================================================== 
FAIL: test_perfil_password_validates_new_passwords (users.tests.PerfilLoggedTestCase)
----------------------------------------------------------------------  
Traceback (most recent call last):   File "/.../src/users/tests.py", 
line 141, in test_perfil_password_validates_new_passwords
    self.assertContains(resp, '"error":')   
File "/usr/local/lib/python2.7/dist-packages/django/test/testcases.py", line 327, 
in assertContains
    " (expected %d)" % (response.status_code, status_code)) 
AssertionError: Couldn't retrieve content: Response code was 400 (expected 200)

---------------------------------------------------------------------- 
Ran 1 test in 0.241s

FAILED (failures=1)

I have no clue why this expects 200, or why does it give me an assertionError I can even print the content, so it's there. What am I missing?

Upvotes: 4

Views: 2417

Answers (1)

mjgpy3
mjgpy3

Reputation: 8937

Looking at the docs, it appears that the assert takes the expected status code, which is defaulted to 200:

TestCase.assertContains(response, text, count=None, status_code=200, msg_prefix='', html=False)

I'm going to go out on a limb and say, your assert should look like:

self.assertContains(resp, '"error":', status_code=400)

Upvotes: 6

Related Questions