在Django-tes中以非活动用户身份登录

2024-03-28 10:54:50 发布

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

我有一个Participant模型,它包含一个django.contrib.auth.model.User,它的is_active属性是False。阻止这些用户自己登录。管理员用户必须使用我编写的一些使用^{}的自定义代码为他们做这件事。在

我需要在测试中验证这些用户的身份

class ParticipantFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Participant

    user = factory.SubFactory(InactiveUserFactory)
    first_location = factory.SubFactory(LocationFactory)
    location = factory.SubFactory(LocationFactory)
    study_id = FuzzyText(prefix='7')


class BasicTest(TestCase):
    def setUp(self):            
        self.u = User.objects.create_user(
            'test_user', 'test@example.com', 'test_pass')
        self.u.is_active = False
        self.u.save()
        self.participant = ParticipantFactory(user=self.u)

        # This works but has no effect on the tests
        auth = authenticate(username=self.u.username, password='test_pass')
        assert(auth is not None)

        # This fails because the user is inactive
        # login = self.client.login(username=self.u.username,
        #                          password='test_pass')
        # assert(login is True)

有人知道如何认证这个不活跃的用户吗?在


Tags: django用户testselfauthmodelisfactory
1条回答
网友
1楼 · 发布于 2024-03-28 10:54:50

我可以在登录之前将用户设置为活动状态来解决此问题:

class BasicTest(TestCase):
    def setUp(self):
        u = InactiveUserFactory()
        u.set_password('test_pass')
        u.save()
        self.participant = ParticipantFactory(user=u)
        self.u = self.participant.user

        self.u.is_active = True
        self.u.save()
        login = self.client.login(username=self.u.username,
                                  password='test_pass')
        assert(login is True)

        self.u.is_active = False
        self.u.save()

相关问题 更多 >