Debian Codegraph @

tests/lib/utils.py

raw
1 from __future__ import annotations
2
3 import io
4 import re
5 import inspect
6 from typing import Any, Iterable
7 from typing_extensions import TypeAlias
8
9 import rich
10 import pytest
11 import pydantic
12 import rich.pretty
13 import rich.console
14
15 ReprArgs: TypeAlias = "Iterable[tuple[str | None, Any]]"
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:
51 frame = inspect.currentframe()
52 assert frame is not None
53
54 for i in range(stacklevel):
55 frame = frame.f_back
56 assert frame is not None, f"no {i}th frame"
57
58 return frame.f_code.co_name
59
60
61 def clear_locals(string: str, *, stacklevel: int) -> str:
62 caller = get_caller_name(stacklevel=stacklevel + 1)
63 return string.replace(f"{caller}.<locals>.", "")
64
65
66 def rich_print_str(obj: object) -> str:
67 """Like `rich.print()` but returns the string instead"""
68
69 buf = io.StringIO()
70 console = rich.console.Console(
71 file=buf,
72 width=120,
73 force_terminal=False,
74 color_system=None,
75 record=True,
76 )
77
78 # Use Rich's pretty printer for nice multi-line formatting
79 rich.pretty.install(console)
80 console.print(obj, overflow="fold", width=120)
81
82 result = buf.getvalue()
83 # Strip out [~...] patterns to exclude generic content from snapshots
84 result = re.sub(r"\[~[^\]]*\]", "", result)
85 result = result.replace("[TypeVar]", "")
86 return result