Pretty print an object to a string
(obj: object)
| 16 | |
| 17 | |
| 18 | def print_obj(obj: object) -> str: |
| 19 | """Pretty print an object to a string""" |
| 20 | |
| 21 | # monkeypatch pydantic model printing so that model fields |
| 22 | # are always printed in the same order so we can reliably |
| 23 | # use this for snapshot tests |
| 24 | original_repr = pydantic.BaseModel.__repr_args__ |
| 25 | |
| 26 | def __repr_args__(self: pydantic.BaseModel) -> ReprArgs: |
| 27 | return sorted(original_repr(self), key=lambda arg: arg[0] or arg) |
| 28 | |
| 29 | def __repr_name__(self: pydantic.BaseModel) -> str: |
| 30 | # Drop generic parameters from the name |
| 31 | # e.g. `GenericModel[Location]` -> `GenericModel` |
| 32 | return self.__class__.__name__.split("[", maxsplit=1)[0] |
| 33 | |
| 34 | with pytest.MonkeyPatch.context() as m: |
| 35 | m.setattr(pydantic.BaseModel, "__repr_args__", __repr_args__) |
| 36 | m.setattr(pydantic.BaseModel, "__repr_name__", __repr_name__) |
| 37 | |
| 38 | string = rich_print_str(obj) |
| 39 | |
| 40 | # we remove all `fn_name.<locals>.` occurrences |
| 41 | # so that we can share the same snapshots between |
| 42 | # pydantic v1 and pydantic v2 as their output for |
| 43 | # generic models differs, e.g. |
| 44 | # |
| 45 | # v2: `GenericModel[test_generic_model.<locals>.Location]` |
| 46 | # v1: `GenericModel[Location]` |
| 47 | return clear_locals(string, stacklevel=2) |
| 48 | |
| 49 | |
| 50 | def get_caller_name(*, stacklevel: int = 1) -> str: |