python-3.x - 如何在 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()
提前谢谢了
解决方案
您可以覆盖Class中的方法eq
def __eq__(self, other):
if other.__class__ is self.__class__:
return self.dict() == other.dict()
return NotImplemented
然后在测试中断言将是assert expected_list == my_schedule
推荐阅读
- xml - 使用单个 XSLT 生成不同的输出文件
- sql - 查找表中每个实体的最大 N 值的最有效 SQL 查询是什么
- laravel - 在 Laravel 中执行 CRUD 的单个函数
- php - php file_put_content 到 aws S3
- dart - Angular Dart:如果用户未登录,则将用户重定向到登录页面
- angular - 如何在角度 6 中单击从一个组件到另一个组件的按钮时获取复选框的选中值
- arduino - 功能音和IRremote
- chart.js - ChartJS X 轴上的日期不显示任何图表
- c++ - 使用贪心算法没有得到所需的背包问题输出
- reactjs - 如何在反应中将值从父功能组件传递给子类组件