0

I'm writing Django unit test for Login form. Below is my sample code.

from unittest import TestCase
from django.contrib.auth.models import User


class TestSuite(TestCase):
    def setUp(self):
        self.credentials = {
            'username': 'testuser',
            'password': 'secret'}
        User.objects.create_user(**self.credentials)

    def test_login(self):
        # send login data
        response = self.client.post('/accounts/login', self.credentials, follow=True)
        # should be logged in now
        self.assertTrue(response.context['user'].is_active)

But when I'm executing from my console it's throwing the below error.

Traceback

System check identified no issues (0 silenced).
E
======================================================================
ERROR: test_login (accounts.tests.test_form.TestSuite)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Django\webapplication\accounts\tests\test_form.py", line 15, in test_login
    response = self.client.post('/accounts/login', self.credentials, follow=True)
AttributeError: 'TestSuite' object has no attribute 'client'

----------------------------------------------------------------------
Ran 1 test in 0.502s
eroot163pi
  • 1,791
  • 1
  • 11
  • 23
Amlanjyoti
  • 85
  • 2
  • 8

2 Answers2

4

The problem is that python unittest module has not client in it; You should use django.test.

Simply change your first line as:

from django.test import TestCase

Read more about different test classes available to use.

Pedram Parsian
  • 3,750
  • 3
  • 19
  • 34
  • Thank you its working..but one more question I've..the line self.assertTrue(response.context['user'].is_active) is giving the error like AssertionError: False is not true... when I'm printing print(response.context['user']) its giving AnonymousUser....Can you plz clarify me on this? – Amlanjyoti Dec 17 '19 at 09:28
  • @Amlanjyoti Testing the "login" in this way is a bit strange. I think you're looking for `login` or probably `force_login` method; Check them in the docs for more information. – Pedram Parsian Dec 17 '19 at 18:17
0

You need django.test TestCase, instead of unittest's.

dev.ink
  • 380
  • 5
  • 21