How do I assert equal two pydantic models with mock attributes in pytest?

  pydantic, pytest, pytest-mock, python-3.x

lets say I have the following assert statement with the pydantic models:

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,
    )
]

Now all other attributes except est_time are equal. i,e:

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),
    )
]

But the above assertion fails because the objects returned with mock.ANY in est_time attribute do not have the same reference id nor its attributes from the actual result.

I want to mock est_time, because it is not part of the test scope as well it being difficult / cumbersome to calculate each time. (the calculation is based on the current time.)

This is what I did eventually, but I am looking for a "cleaner / more pythonic way" to achieve the same result:

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()

Many thanks in advance

Source: Python-3x Questions

LEAVE A COMMENT