django - pytest-django:使用 create_user 创建的用户始终经过身份验证
问题描述
我正在尝试编写一个夹具来从自定义用户模型生成 Django 用户。奇怪的是,新创建的用户结果默认经过身份验证,而我希望它是匿名的。我究竟做错了什么?
夹具:
import pytest
@pytest.fixture
def create_user(db, django_user_model):
def make_user(**kwargs):
return django_user_model.objects.create_user(**kwargs)
return make_user
测试夹具:
@pytest.mark.django_db
def test_fixture_create_user(create_user):
user = create_user(email='foo@bar.com', password='bar')
assert user.is_authenticated is True # <-- this should be False but it's True
assert user.is_anonymous is True # <-- this fails
测试以这种方式失败:
E assert False is True
E + where False = <CustomUser: foo@bar.com>.is_anonymous
自定义用户模型:
class CustomUser(AbstractUser):
username = None
email = models.EmailField(_('email address'), unique=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
objects = CustomUserManager()
自定义用户管理器:
class CustomUserManager(BaseUserManager):
"""
Custom user model manager where email is the unique identifiers
for authentication instead of usernames.
"""
def create_user(self, email, password, **extra_fields):
"""
Create and save a User with the given email and password.
"""
if not email:
raise ValueError(_('The Email must be set'))
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save()
return user
解决方案
没有错,伙计。的is_authenticated
属性AbstractUser
被硬编码为True
。Django 的中间件正在做所有的事情并request.user
作为AnonymousUser
类实例返回,该is_authenticated
属性返回False
推荐阅读
- pdf - 使用 Ghostscript,如何在合并的 PDF 文件上添加页码
- sql - 需要从稀疏填充的表中估算缺失数据
- python - 在将字符串转换为列表后,如何从我的 nltk 令牌中删除 '\n' 或防止它首先出现?
- python - 使用排序文件绘制 X 轴与原始文件中相应的 Y 值
- python - for 循环中的变量未在另一个循环中显示
- python - 如何在“文本标记”中动态更改字体大小?
- javascript - 如何在悬停时更改 html 元素文本
- android - Android 通知不会显示在设备上
- neo4j - Neo4j:大规模查询性能问题,即使有索引
- perforce - 如何防止 Perforce 将相对符号链接转换为绝对符号链接?