Pretty print an object to a string
(obj: object, monkeypatch: pytest.MonkeyPatch)
| 13 | |
| 14 | |
| 15 | def print_obj(obj: object, monkeypatch: pytest.MonkeyPatch) -> str: |
| 16 | """Pretty print an object to a string""" |
| 17 | |
| 18 | # monkeypatch pydantic model printing so that model fields |
| 19 | # are always printed in the same order so we can reliably |
| 20 | # use this for snapshot tests |
| 21 | original_repr = pydantic.BaseModel.__repr_args__ |
| 22 | |
| 23 | def __repr_args__(self: pydantic.BaseModel) -> ReprArgs: |
| 24 | return sorted(original_repr(self), key=lambda arg: arg[0] or arg) |
| 25 | |
| 26 | with monkeypatch.context() as m: |
| 27 | m.setattr(pydantic.BaseModel, "__repr_args__", __repr_args__) |
| 28 | |
| 29 | string = rich_print_str(obj) |
| 30 | |
| 31 | # Pydantic v1 and v2 have different implementations of __repr__ and print out |
| 32 | # generics differently, so we strip out generic type parameters to ensure |
| 33 | # consistent snapshot tests across both versions |
| 34 | return re.sub(r"([A-Za-z_]\w*)\[[^\[\]]+\](?=\()", r"\1", string) |