django - 如何在 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 。谢谢你的帮助。
解决方案
尝试:
self.c = APIClient()
authenticated_user = authenticate(self.c.request, email=user.email, password=user.password)
推荐阅读
- php - 如何在 Outlook 365 中将 imap_open() 用于组
- sql-server - 部署 DACPAC 是否需要将数据库注册为 DAC?
- sql - 在 SQL 中使用联接时出现重复记录 - 图像数据
- python-sphinx - 用重组文本+ sphinx替换另一个文档中的字段属性
- java - 队列反向实现 - 代码不起作用
- c# - C# 中有数学伽玛函数吗?
- neo4j - 具有多重关系的 Cypher 性能
- c# - System.Net.TcpListener 在 Android/UWP 上不起作用
- php - 在php中将4个不同的文件插入1个SQL表行
- php - 带有准备好的语句的 Openssl_Encryption