django - pytest-django:使用 create_user 创建的用户始终经过身份验证

标签 django pytest django-authentication django-users pytest-django

我正在尝试编写一个 fixture 来从自定义用户模型生成 Django 用户。奇怪的是,新创建的用户结果默认经过身份验证,而我希望它是匿名的。我做错了什么?

fixture :

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

测试 fixture :

@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

最佳答案

没有什么不对,伙计。 AbstractUseris_authenticated 属性 is hardcoded to be True . Django 的中间件正在发挥所有的作用,并返回 request.user 作为 AnonymousUser 类实例,其中 is_authenticated 属性返回 False

关于django - pytest-django:使用 create_user 创建的用户始终经过身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61595777/

相关文章:

python - 什么时候假设破折号 m 用法并避免 __init__?

django - 无法为 Django 的重置密码流程创建集成测试

Django:如何处理 Ajax 请求不同 View 中的缓存?

python - 在注册中验证电子邮件不会在 Django 中引发validationError?

python - 具有大对象的 Memcached(NetworkX 图)

Python 修补类 - 方法 return_value 返回 MagicMock

python - 如何在django-sphinx下自动重建Sphinx索引?

python - 在测试序列中的测试之间保存数据的模式

django - 如何不使用 Django 的管理员登录 View ?

python - 尝试扩展 django.contrib.auth.views.login 时出错