Django TestCase对象没有属性“session”

2024-05-01 01:56:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Django学习测试。我需要先创建用户和登录,然后才能测试任何东西。我试过以下方法。。。在

class ProjectTest(TestCase):
    def setUp(self):
        self.email = 'test@test.com'
        self.password = 'test'
        self.new_user = AppUser.objects.create_superuser(email=self.email, password=self.password)

        new_user = authenticate(username=self.email,
                                    password=self.password)

        login(request, new_user)
        self.assertEqual(login, True)

    def tearDown(self):
        self.new_user.delete()

这给了我一个错误:AttributeError:“str”对象没有属性“session”

我也尝试过:

^{pr2}$

但它说我没有登录名。在

正确的方法是什么?在


Tags: django方法用户testselfnewemaildef
2条回答

您不需要在用户上调用login,而是在测试客户机的实例上调用它。在

self.client.login(username=self.email, password=self.password)
class ProjectTest(TestCase):

    def test_login_feature(self):
        user = User.objects.create_user(username='joe', password='pass')
        self.client.login(username='joe', password='pass')
        # client now authenticated and can access 
        # restricted views. 

所以这就是你要做的。创建一个用户并使用self.client.login您可以在documentation中阅读有关如何使用它的更多信息

相关问题 更多 >