首页 > 解决方案 > 如何在 pytest 中断言两个具有模拟属性的 pydantic 模型相等?

问题描述

假设我对 pydantic 模型有以下断言语句:

assert my_schedule == [
    Class.construct(
        student_id=student1.student1.id,
        property=Property.A,
        est_time=mock.ANY,
    ),
    Class.construct(
        student_id=student1.student1.id,
        property=Property.B,
        est_time=mock.ANY,
    )
]

现在除了 est_time 之外的所有其他属性都是相等的。IE:

my_schedule = [
    Class(
        student_id=student1.id,
        property=Property.A,
        est_time=datetime(2020,1,3),
    ),
    Class(
        student_id=student1.id,
        property=Property.B,
        est_time=datetime(2020,1,4),
    )
]

但是上面的断言失败了,因为在 est_time 属性中使用 mock.ANY 返回的对象没有相同的引用 id,也没有来自实际结果的属性。

我想模拟 est_time,因为它不是测试范围的一部分,而且每次计算都很困难/麻烦。(计算基于当前时间。)

这就是我最终所做的,但我正在寻找一种“更清洁/更 Pythonic 的方式”来实现相同的结果:

expected_list = [
    Class.construct(
        student_id=student1.student1.id,
        property=Property.A,
        est_time=mock.ANY,
    ),
    Class.construct(
        student_id=student1.student1.id,
        property=Property.B,
        est_time=mock.ANY,
    )
]

for result, expected in zip(my_schedules, expected_list):
    assert result.dict() == expected.dict()

提前谢谢了

标签: python-3.xpytestpydanticpytest-mock

解决方案


您可以覆盖Class中的方法eq

 def __eq__(self, other):
        if other.__class__ is self.__class__:
            return self.dict() == other.dict()
        return NotImplemented

然后在测试中断言将是assert expected_list == my_schedule


推荐阅读