Debian Codegraph @

testing/io/test_saferepr.py

raw
1 # mypy: allow-untyped-defs
2 from __future__ import annotations
3
4 from _pytest._io.saferepr import DEFAULT_REPR_MAX_SIZE
5 from _pytest._io.saferepr import SafeRepr
6 from _pytest._io.saferepr import saferepr
7 from _pytest._io.saferepr import saferepr_unlimited
8 import pytest
9
10
11 def test_simple_repr():
12 assert saferepr(1) == "1"
13 assert saferepr(None) == "None"
14
15
16 def test_maxsize():
17 s = saferepr("x" * 50, maxsize=25)
18 assert len(s) == 25
19 expected = repr("x" * 10 + "..." + "x" * 10)
20 assert s == expected
21
22
23 def test_no_maxsize():
24 text = "x" * DEFAULT_REPR_MAX_SIZE * 10
25 s = saferepr(text, maxsize=None)
26 expected = repr(text)
27 assert s == expected
28
29
30 def test_maxsize_error_on_instance():
31 class A:
32 def __repr__(self):
33 raise ValueError("...")
34
35 s = saferepr(("*" * 50, A()), maxsize=25)
36 assert len(s) == 25
37 assert s[0] == "(" and s[-1] == ")"
38
39
40 def test_exceptions() -> None:
41 class BrokenRepr:
42 def __init__(self, ex):
43 self.ex = ex
44
45 def __repr__(self):
46 raise self.ex
47
48 class BrokenReprException(Exception):
49 __str__ = None # type: ignore[assignment]
50 __repr__ = None # type: ignore[assignment]
51
52 assert "Exception" in saferepr(BrokenRepr(Exception("broken")))
53 s = saferepr(BrokenReprException("really broken"))
54 assert "TypeError" in s
55 assert "TypeError" in saferepr(BrokenRepr("string"))
56
57 none = None
58 try:
59 none() # type: ignore[misc]
60 except BaseException as exc:
61 exp_exc = repr(exc)
62 obj = BrokenRepr(BrokenReprException("omg even worse"))
63 s2 = saferepr(obj)
64 assert s2 == (
65 f"<[unpresentable exception ({exp_exc!s}) raised in repr()] BrokenRepr object at 0x{id(obj):x}>"
66 )
67
68
69 def test_baseexception():
70 """Test saferepr() with BaseExceptions, which includes pytest outcomes."""
71
72 class RaisingOnStrRepr(BaseException):
73 def __init__(self, exc_types):
74 self.exc_types = exc_types
75
76 def raise_exc(self, *args):
77 try:
78 self.exc_type = self.exc_types.pop(0)
79 except IndexError:
80 pass
81 if hasattr(self.exc_type, "__call__"):
82 raise self.exc_type(*args)
83 raise self.exc_type
84
85 def __str__(self): # noqa: PLE0307
86 self.raise_exc("__str__")
87
88 def __repr__(self):
89 self.raise_exc("__repr__")
90
91 class BrokenObj:
92 def __init__(self, exc):
93 self.exc = exc
94
95 def __repr__(self):
96 raise self.exc
97
98 __str__ = __repr__
99
100 baseexc_str = BaseException("__str__")
101 obj = BrokenObj(RaisingOnStrRepr([BaseException]))
102 assert saferepr(obj) == (
103 f"<[unpresentable exception ({baseexc_str!r}) "
104 f"raised in repr()] BrokenObj object at 0x{id(obj):x}>"
105 )
106 obj = BrokenObj(RaisingOnStrRepr([RaisingOnStrRepr([BaseException])]))
107 assert saferepr(obj) == (
108 f"<[{baseexc_str!r} raised in repr()] BrokenObj object at 0x{id(obj):x}>"
109 )
110
111 with pytest.raises(KeyboardInterrupt):
112 saferepr(BrokenObj(KeyboardInterrupt()))
113
114 with pytest.raises(SystemExit):
115 saferepr(BrokenObj(SystemExit()))
116
117 with pytest.raises(KeyboardInterrupt):
118 saferepr(BrokenObj(RaisingOnStrRepr([KeyboardInterrupt])))
119
120 with pytest.raises(SystemExit):
121 saferepr(BrokenObj(RaisingOnStrRepr([SystemExit])))
122
123 with pytest.raises(KeyboardInterrupt):
124 print(saferepr(BrokenObj(RaisingOnStrRepr([BaseException, KeyboardInterrupt]))))
125
126 with pytest.raises(SystemExit):
127 saferepr(BrokenObj(RaisingOnStrRepr([BaseException, SystemExit])))
128
129
130 def test_buggy_builtin_repr():
131 # Simulate a case where a repr for a builtin raises.
132 # reprlib dispatches by type name, so use "int".
133
134 class int:
135 def __repr__(self):
136 raise ValueError("Buggy repr!")
137
138 assert "Buggy" in saferepr(int())
139
140
141 def test_big_repr():
142 from _pytest._io.saferepr import SafeRepr
143
144 assert len(saferepr(range(1000))) <= len("[" + SafeRepr(0).maxlist * "1000" + "]")
145
146
147 def test_repr_on_newstyle() -> None:
148 class Function:
149 def __repr__(self):
150 return f"<{self.name}>" # type: ignore[attr-defined]
151
152 assert saferepr(Function())
153
154
155 def test_unicode():
156 val = "£€"
157 reprval = "'£€'"
158 assert saferepr(val) == reprval
159
160
161 def test_broken_getattribute():
162 """saferepr() can create proper representations of classes with
163 broken __getattribute__ (#7145)
164 """
165
166 class SomeClass:
167 def __getattribute__(self, attr):
168 raise RuntimeError
169
170 def __repr__(self):
171 raise RuntimeError
172
173 assert saferepr(SomeClass()).startswith(
174 "<[RuntimeError() raised in repr()] SomeClass object at 0x"
175 )
176
177
178 def test_saferepr_unlimited():
179 dict5 = {f"v{i}": i for i in range(5)}
180 assert saferepr_unlimited(dict5) == "{'v0': 0, 'v1': 1, 'v2': 2, 'v3': 3, 'v4': 4}"
181
182 dict_long = {f"v{i}": i for i in range(1_000)}
183 r = saferepr_unlimited(dict_long)
184 assert "..." not in r
185 assert "\n" not in r
186
187
188 def test_saferepr_unlimited_exc():
189 class A:
190 def __repr__(self):
191 raise ValueError(42)
192
193 assert saferepr_unlimited(A()).startswith(
194 "<[ValueError(42) raised in repr()] A object at 0x"
195 )
196
197
198 def test_saferepr_dict_preserves_insertion_order() -> None:
199 d = {
200 "b": 2,
201 "a": 1,
202 "d": 4,
203 "e": 5,
204 "c": 3,
205 }
206 s = SafeRepr(maxsize=None)
207 s.maxdict = 10
208 assert s.repr(d) == "{'b': 2, 'a': 1, 'd': 4, 'e': 5, 'c': 3}"
209
210
211 def test_saferepr_dict_truncation_preserves_insertion_order() -> None:
212 d = {
213 "b": 2,
214 "a": 1,
215 "d": 4,
216 "e": 5,
217 "c": 3,
218 }
219 s = SafeRepr(maxsize=None)
220 s.maxdict = 1
221 assert s.repr(d) == "{'b': 2, ...}"
222
223
224 def test_saferepr_dict_fillvalue_when_level_is_zero() -> None:
225 s = SafeRepr(maxsize=None)
226 assert s.repr_dict({"a": 1}, level=0) == "{...}"
227
228
229 def test_saferepr_dict_empty() -> None:
230 s = SafeRepr(maxsize=None)
231 assert s.repr_dict({}, level=1) == "{}"