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

时间:2020-05-04 15:25:14

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

我正在尝试编写一种夹具,以根据自定义用户模型生成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()

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

1 个答案:

答案 0 :(得分:2)

没错,队友。 is_authenticated is hardcoded to be TrueAbstractUser属性。 Django的中间件正在发挥所有作用,并将request.user作为AnonymousUser类实例返回,其中is_authenticated属性返回False