Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Unittests Client Login: fails in test suite, but not in Shell

I'm running a basic test of my home view. While logging the client in from the shell works, the same line of code fails to log the client in when using the test suite.

What is the correct way to log the client in when using the Django test suite?

Or

Any idea why the client is not logging in with my current method?

Shell test:

import unittest
from django.test.client import Client
from django.test.utils import setup_test_environment
setup_test_environment()

client = Client()
login = client.login(username='agconti', password='password')

# login --> evals to True

Django test suite:

#### View Tests ####
import unittest
from django.test.client import Client
from shopping_cart.models import Store, Order, Item, Transaction

class Home_ViewTest(unittest.TestCase):
    def setUp(self):
        self.client = Client()
        # login user
        login = self.client.login(username='agconti', password='password')
        # Check login
        self.assertEqual(login, True)

    def test_details(self):
        # get the home view
        response = self.client.get('/')      
        self.assertEqual(response.status_code, 200)

        # Check that the rendered context is not none 
        self.assertTrue(response.context['stores'] != None)

# self.assertEqual(login, True) --> login evals to False, raises the assertion
like image 542
agconti Avatar asked Sep 02 '13 17:09

agconti


1 Answers

A test user should be created. Something like:

  def setUp(self):
    self.client = Client()
    self.username = 'agconti'
    self.email = '[email protected]'
    self.password = 'test'        
    self.test_user = User.objects.create_user(self.username, self.email, self.password)
    login = self.client.login(username=self.username, password=self.password)
    self.assertEqual(login, True)

In your shell test the user is probably already present in your db, whereas in your unittest there might not be a user...

like image 91
dm03514 Avatar answered Oct 23 '22 00:10

dm03514