如何使用pytest测试保存Django模型方法? 用户模型工厂

问题描述

我有什么

我已经覆盖了save模型的User方法,以便能够使用大写的首字母更改姓氏和名字。

用户模型

from django.contrib.auth.models import AbstractBaseUser

class User(AbstractBaseUser):
    name = models.CharField(
        verbose_name=_("Name"),max_length=30,)
    last_name = models.CharField(
        verbose_name=_("Last Name"),max_length=50,)
    # ...other fields

    def save(self,*args: Any,**kwargs: Any) -> None:
        """Always have the name and last_name first letter in uppercase"""
        for field_name in ["name","last_name"]:
            val = getattr(self,field_name,False)
            if val:
                setattr(
                    self,string.capwords(val.lower()),)
        super(User,self).save(*args,**kwargs)

我正在使用pytestfactory_boy来测试我的模型。首先,我创建了一个工厂来创建用户:

工厂

from factory import DjangoModelFactory,Faker

class UserFactory(DjangoModelFactory):
    """Define User Factory"""

    name = Faker("first_name",locale="es")
    last_names = Faker("last_name",locale="es")
    # ...other fields

    class Meta:
        model = get_user_model()

我将工厂放置在fixture中的conftest.py中,以供所有测试使用:

from app_name.users.tests.factories import UserFactory

@pytest.fixture
def user() -> User:
    """Create user for testing."""
    return UserFactory()

问题

我想测试我的保存方法,但是当我尝试在测试中访问用户的namelast_name字段时,第一个字母已大写。我想在应用save方法之前获取原始数据以执行测试。

import pytest

pytestmark = pytest.mark.django_db


def test_save(user: User):
    print(user.names) # -> comes with the changes applied to the save method
    print(user.last_names) # -> comes with the changes applied to the save method

解决方法

在应用save方法之前,您不需要获取原始数据。实际上,您已经在测试它!因为工厂保存了对象,所以您只需检查它是否已正确编辑名称即可。

类似这样的东西:

>>> name = user.name
>>> expected_name = string.capwords(name.lower())
>>> assert name == expected_name,"name is not correct"

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...