使用Pytest测试django中的模型属性

eaf3rand  于 2023-08-08  发布在  Go
关注(0)|答案(1)|浏览(122)

我想使用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%

piok6c0g

piok6c0g1#

修正了我的问题,通过改变代码测试一点点
网址:models.py

@property
def age(self):
    days_in_year = 365.2425
    age = int((date.today() - self.birthdate).days / days_in_year)
    return age

字符串
test_models.py:

assert travel_friend.age is not None
    days_in_year = 365.2425
    assert travel_friend.age == int((date.today() - travel_friend.birthdate).days / days_in_year)


template.html:

{% for friend in travel_friends %}
  <li>{{ friend.name }} 
    {% if friend.age >= 18 %}(18+)
    {% else %}({{ friend.age }})
    {% endif %}
  </li>
{% endfor %}


不需要在属性中获取'18+',最好在模板中获取

相关问题