微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在Django中测试自定义身份验证后端

如何解决如何在Django中测试自定义身份验证后端

我写了一个自定义的身份验证后端,我在我的观点中使用它来证明它可以正常工作,但是我想对其进行测试,以防万一将来由于某种原因而中断。我认为问题可能是因为我在测试中没有请求,所以没有请求传递到authenticate方法中。如果这是问题所在,那么如何将有效请求传递到authenticate方法中并对其进行测试,以便测试通过。换句话说,有人可以告诉我一个通过以下身份验证后端的测试

backends.py

class EmailBackend(BaseBackend):

    def authenticate(self,request,email=None,password=None):
        try:
            user = User.objects.filter(email=email).first()
            if user.check_password(password):
                return user
            else:
                return None
        except User.DoesNotExist:
            return None

    def get_user(self,user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None

test_backends.py

class TestUserBackend(TestCase):

    def test_authenticate(self):
        user = UserFactory()
        authenticated_user = authenticate(email=user.email,password=user.password)
        self.assertEqual(authenticated_user,user)

UserFactory()来自工厂男孩。我还检查了user.password是否被散列,以及是否也被散列的user.password相同。 但是我不断得到None!=生成的user.email。 感谢您的帮助。

解决方法

试试:

 self.c = APIClient()
 authenticated_user = authenticate(self.c.request,email=user.email,password=user.password)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。