Django TestCase对象没有属性'login'

问题描述 投票:0回答:1

我已经使用硒来测试我的登录方法,并且可以正常工作。然后,我尝试测试网站的其他部分。因此,我需要在测试中创建一个用户。为此,我使用了客户端而不是请求工厂(因为存在中间件类)。但是,我得到了错误:

AttributeError: 'ProjectListTestCase' object has no attribute 'login'

我有一个自定义的身份验证后端,允许使用电子邮件地址代替用户名:

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'phonenumber_field',
'rest_framework',

# 3rd party apps
'crispy_forms',

# Local apps 
'accounts',
...

我尝试了控制台中的代码:

>>> the_client = Client()
>>> the_client.login(email='[email protected]', password='testingPassword')
True

这是我的test_views.py中的代码:

from django.core.urlresolvers import reverse
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.test import TestCase
from django.test import RequestFactory

from model_mommy import mommy
from selenium import webdriver

from project_profile.models import Project
from user_profile.models import UserProfile

class ProjectListTestCase(TestCase):
    def setUp(self):

        # login the user
        login = self.client.login(email='[email protected]', password='testingPassword')
        print ('Login successful? ', self.login)          # Just to see what's going on

        response = self.client.get(reverse('development:list_view_developmentproject') )
        print('response: ', self.response)                # Just to see what's going on


    def test_user_login(self):           
        self.assertEqual(self.response.status_code, 200)

为什么在运行测试时出现错误,但是在控制台中使用相同的代码运行正常?

django django-testing
1个回答
0
投票

正如@Iain Shelvington提到的in this comment,您还没有assigned变量loginself您应该这样做,

class ProjectListTestCase(TestCase):
    def setUp(self):
        # login the user
        self.login = self.client.login(email='[email protected]', password='testingPassword')
        print('Login successful? ', self.login)  # Just to see what's going on

        self.response = self.client.get(reverse('development:list_view_developmentproject'))
        print('response: ', self.response)  # Just to see what's going on

    def test_user_login(self):
        self.assertEqual(self.response.status_code, 200)
© www.soinside.com 2019 - 2024. All rights reserved.