如何测试is_active = False的用户对象?

时间:2019-10-11 02:21:04

标签: python django

此处,使用 is_active = False 属性实例化User对象。我正在使用具有相同用户凭据的 AuthenticationForm 来测试登录,但是没有得到预期的响应。

将数据传递给表单时: form.is_valid()返回False。

https://docs.djangoproject.com/en/2.2/topics/auth/default/#django.contrib.auth.forms.AuthenticationForm 在文档中说:

  

默认情况下,AuthenticationForm拒绝is_active标志设置为False的用户。

如何将User.is_active设置为False,又如何输入条件块,以便根据上述属性状态返回适当的闪存消息?

def sign_in(request):
    import pdb; pdb.set_trace()
    form = AuthenticationForm()
    if request.method == 'POST':
        form = AuthenticationForm(data=request.POST)
        if form.is_valid():
            if form.user_cache is not None:
                user = form.user_cache
                if user.is_active:
                    login(request, user)
                    return HttpResponseRedirect(
                        reverse('home')  # TODO: go to profile
                    )
                else:
                    messages.error(
                        request,
                        "That user account has been disabled."
                    )
            else:
                messages.error(
                    request,
                    "Username or password is incorrect."
                )
    return render(request, 'accounts/sign_in.html', {'form': form})
class UserAccountSignIn(TestCase):

    @classmethod
    def setUpTestData(cls):
        cls.inactive_user = {
            'username': 'non_user',
            'password': 'secret',
            'is_active': False
        }
        User.objects.create_user(**cls.inactive_user)

    def test_inactive_user_login_fail(self):
        self.client.login(**self.inactive_user)
        response = self.client.post(reverse('accounts:sign_in'), self.inactive_user)
        self.assertContains(response, "That user account has been disabled.")

https://github.com/django/django/blob/master/django/contrib/auth/forms.py#L213

实际结果:ValidationError("This account is inactive.")

预期结果:闪烁的消息:"That user account has been disabled."

0 个答案:

没有答案