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

时间:2015-01-07 21:03:11

标签: python django django-authentication django-testing django-1.7

我的Participant模型包含django.contrib.auth.model.Useris_active属性为False。这会阻止这些用户自行登录。管理员用户必须使用我编写的使用django.contrib.auth.authenticate()的自定义代码为他们执行此操作。

我需要能够在我的测试中对这些用户进行身份验证,

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)

有没有人知道如何验证此非活动用户?

1 个答案:

答案 0 :(得分:0)

我能够通过在登录前将用户设置为活动来解决此问题:

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