简体   繁体   English

在Django测试中以非活动用户身份登录

[英]Logging in as an inactive user in a Django test

I have a Participant model that contains a django.contrib.auth.model.User with it's is_active property to False . 我有一个包含django.contrib.auth.model.UserParticipant模型,它的is_active属性为False That prevents these users from logging themselves in. An admin user has to do that for them, using some custom code I've written that uses django.contrib.auth.authenticate() . 这样可以防止这些用户登录。管理员用户必须使用我编写的一些自定义代码django.contrib.auth.authenticate()使用django.contrib.auth.authenticate()为他们执行此操作。

I need to be able to authenticate these users in my tests, 我需要能够在测试中对这些用户进行身份验证,

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)

Does anyone have an idea how to authenticate this inactive user? 有谁知道如何认证这个不活跃的用户?

I was able to solve this by setting the user to active right before doing the login: 我可以通过在登录之前将用户设置为活动状态来解决此问题:

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM