问题描述
我写了一个自定义的身份验证后端,我在我的观点中使用它来证明它可以正常工作,但是我想对其进行测试,以防万一将来由于某种原因而中断。我认为问题可能是因为我在测试中没有请求,所以没有请求传递到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)