我想使用pytest[pytest-django]测试django中模型属性的输出。
网址:models.py
class TravelFriend(models.Model):
user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name="travel_friends")
name = models.CharField(max_length=100)
birthdate = models.DateField()
def __str__(self):
return self.name
@property
def age(self):
days_in_year = 365.2425
age = int((date.today() - self.birthdate).days / days_in_year)
if age >= 18:
return "18+"
else:
return age
字符串
基本上,该属性返回以年为单位的年龄,或者如果年龄大于18,则返回字符串'18+'
test_models.py:
class TestTravelFriend:
def test_travelfriend(self):
"""The family member is connected to a user and have valid attributes"""
travel_friend = TravelFriendFactory()
assert travel_friend is not None
assert str(travel_friend) == travel_friend.name
assert travel_friend.user is not None
assert travel_friend.name is not None
assert travel_friend.birthdate is not None
assert travel_friend.age is not None
型
网址:factories.py
class TravelFriendFactory(factory.django.DjangoModelFactory):
class Meta:
model = "accounts.TravelFriend"
user = factory.SubFactory("accounts.tests.factories.CustomUserFactory")
birthdate = factory.Faker(
"date_of_birth",
maximum_age=25,
)
型
我想测试属性的输出是否正确但是如果我在测试中放入一个if语句,就像这样
year = -int(travel_friend.birthdate.year - date.today().year)
if year < 18:
assert travel_friend.age == year
else:
assert travel_friend.age == "18+"
型
但是为了100%的覆盖率,我需要测试最后一部分代码,我认为这是不正确的(测试测试,真的吗?!?)..任何想法如何正确地测试属性?我查过pytest.mark.parametrize没有成功
我需要测试属性,而不需要在test_models.py上添加更多测试
---------- coverage: platform darwin, python 3.11.4-final-0 ----------
Name Stmts Miss Cover Missing
-------------------------------------------------------------
accounts/forms.py 26 6 77% 29-36
accounts/models.py 44 1 98% 59
accounts/tests/test_models.py 28 1 96% 48
-------------------------------------------------------------
TOTAL 187 8 96%
型
1条答案
按热度按时间piok6c0g1#
修正了我的问题,通过改变代码测试一点点
网址:models.py
字符串
test_models.py:
型
template.html:
型
不需要在属性中获取'18+',最好在模板中获取