6

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
4

1 回答 1

23

应该创建一个测试用户。就像是:

  def setUp(self):
    self.client = Client()
    self.username = 'agconti'
    self.email = 'test@test.com'
    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)

在您的 shell 测试中,用户可能已经存在于您的数据库中,而在您的单元测试中可能没有用户...

于 2013-09-02T17:38:01.930 回答