首页 > 解决方案 > 如何在 django 中测试自定义身份验证后端

问题描述

我编写了一个自定义身份验证后端,我在我的视图中使用它来证明它正在工作,但是我想测试它以防万一它在未来因任何原因而中断,我会知道的。我认为问题可能是因为我在测试中没有请求,所以没有将请求传递给 authenticate 方法。如果这是问题所在,那么如何将有效请求传递给 authenticate 方法并对其进行测试以使测试通过。换句话说,有人可以给我看一个通过下面的身份验证后端的测试吗

后端.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 != the user.email that was generated 。谢谢你的帮助。

标签: djangoauthenticationdjango-authenticationdjango-testingdjango-tests

解决方案


尝试:

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

推荐阅读