Debian Codegraph @

hypothesis-python/tests/cover/test_pretty.py

raw
1 # This file is part of Hypothesis, which may be found at
2 # https://github.com/HypothesisWorks/hypothesis/
3 #
4 # Copyright the Hypothesis Authors.
5 # Individual contributors are listed in AUTHORS.rst and the git log.
6 #
7 # This Source Code Form is subject to the terms of the Mozilla Public License,
8 # v. 2.0. If a copy of the MPL was not distributed with this file, You can
9 # obtain one at https://mozilla.org/MPL/2.0/.
10
11 """This file originates in the IPython project and is made use of under the
12 following licensing terms:
13
14 The IPython licensing terms
15 IPython is licensed under the terms of the Modified BSD License (also known as
16 New or Revised or 3-Clause BSD), as follows:
17
18 Copyright (c) 2008-2014, IPython Development Team
19 Copyright (c) 2001-2007, Fernando Perez <[email protected]>
20 Copyright (c) 2001, Janko Hauser <[email protected]>
21 Copyright (c) 2001, Nathaniel Gray <[email protected]>
22 All rights reserved.
23
24 Redistribution and use in source and binary forms, with or without
25 modification, are permitted provided that the following conditions are met:
26
27 Redistributions of source code must retain the above copyright notice, this
28 list of conditions and the following disclaimer.
29
30 Redistributions in binary form must reproduce the above copyright notice, this
31 list of conditions and the following disclaimer in the documentation and/or
32 other materials provided with the distribution.
33
34 Neither the name of the IPython Development Team nor the names of its
35 contributors may be used to endorse or promote products derived from this
36 software without specific prior written permission.
37
38 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
39 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
40 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
41 DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
42 ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
43 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
44 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
45 ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
46 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
47 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
48 """
49
50 import io
51 import re
52 import struct
53 import warnings
54 from collections import Counter, OrderedDict, defaultdict, deque
55 from dataclasses import dataclass, field
56 from enum import Enum, Flag
57 from functools import partial
58
59 import pytest
60
61 from hypothesis import given, strategies as st
62 from hypothesis.control import current_build_context
63 from hypothesis.internal.compat import PYPY
64 from hypothesis.internal.conjecture.floats import float_to_lex
65 from hypothesis.internal.floats import SIGNALING_NAN
66 from hypothesis.vendor import pretty
67
68
69 class MyList:
70 def __init__(self, content):
71 self.content = content
72
73 def _repr_pretty_(self, p, cycle):
74 if cycle:
75 p.text("MyList(...)")
76 else:
77 with p.group(3, "MyList(", ")"):
78 for i, child in enumerate(self.content):
79 if i:
80 p.text(",")
81 p.breakable()
82 else:
83 p.breakable("")
84 p.pretty(child)
85
86
87 class MyDict(dict):
88 def _repr_pretty_(self, p, cycle):
89 p.text("MyDict(...)")
90
91
92 class MyObj:
93 def somemethod(self):
94 pass
95
96
97 class Dummy1:
98 def _repr_pretty_(self, p, cycle):
99 p.text("Dummy1(...)")
100
101
102 class Dummy2:
103 _repr_pretty_ = None
104
105 def __repr__(self):
106 return "Dummy2()"
107
108
109 class NoModule:
110 pass
111
112
113 NoModule.__module__ = None
114
115
116 class Breaking:
117 def _repr_pretty_(self, p, cycle):
118 with p.group(4, "TG: ", ":"):
119 p.text("Breaking(")
120 p.break_()
121 p.text(")")
122
123
124 class BreakingRepr:
125 def __repr__(self):
126 return "Breaking(\n)"
127
128
129 class BreakingReprParent:
130 def _repr_pretty_(self, p, cycle):
131 with p.group(4, "TG: ", ":"):
132 p.pretty(BreakingRepr())
133
134
135 class BadRepr:
136 def __repr__(self):
137 return 1 / 0
138
139
140 def test_list():
141 assert pretty.pretty([]) == "[]"
142 assert pretty.pretty([1]) == "[1]"
143
144
145 def test_dict():
146 assert pretty.pretty({}) == "{}"
147 assert pretty.pretty({1: 1}) == "{1: 1}"
148 assert pretty.pretty({1: 1, 0: 0}) == "{1: 1, 0: 0}"
149
150 # Check that pretty-printing doesn't trigger a BytesWarning under `python -bb`
151 with warnings.catch_warnings():
152 warnings.simplefilter("ignore", BytesWarning)
153 x = {"": 0, b"": 0}
154 assert pretty.pretty(x) == "{'': 0, b'': 0}"
155
156
157 def test_tuple():
158 assert pretty.pretty(()) == "()"
159 assert pretty.pretty((1,)) == "(1,)"
160 assert pretty.pretty((1, 2)) == "(1, 2)"
161
162
163 class ReprDict(dict):
164 def __repr__(self):
165 return "hi"
166
167
168 def test_dict_with_custom_repr():
169 assert pretty.pretty(ReprDict()) == "hi"
170
171
172 class ReprList(list):
173 def __repr__(self):
174 return "bye"
175
176
177 class ReprSet(set):
178 def __repr__(self):
179 return "cat"
180
181
182 def test_set_with_custom_repr():
183 assert pretty.pretty(ReprSet()) == "cat"
184
185
186 def test_list_with_custom_repr():
187 assert pretty.pretty(ReprList()) == "bye"
188
189
190 def test_indentation():
191 """Test correct indentation in groups."""
192 count = 40
193 gotoutput = pretty.pretty(MyList(range(count)))
194 expectedoutput = "MyList(\n" + ",\n".join(f" {i}" for i in range(count)) + ")"
195
196 assert gotoutput == expectedoutput
197
198
199 def test_dispatch():
200 """Test correct dispatching: The _repr_pretty_ method for MyDict must be
201 found before the registered printer for dict."""
202 gotoutput = pretty.pretty(MyDict())
203 expectedoutput = "MyDict(...)"
204
205 assert gotoutput == expectedoutput
206
207
208 def test_callability_checking():
209 """Test that the _repr_pretty_ method is tested for callability and skipped
210 if not."""
211 gotoutput = pretty.pretty(Dummy2())
212 expectedoutput = "Dummy2()"
213
214 assert gotoutput == expectedoutput
215
216
217 def test_sets():
218 """Test that set and frozenset use Python 3 formatting."""
219 objects = [
220 set(),
221 frozenset(),
222 {1},
223 frozenset([1]),
224 {1, 2},
225 frozenset([1, 2]),
226 {-1, -2, -3},
227 ]
228 expected = [
229 "set()",
230 "frozenset()",
231 "{1}",
232 "frozenset({1})",
233 "{1, 2}",
234 "frozenset({1, 2})",
235 "{-3, -2, -1}",
236 ]
237 for obj, expected_output in zip(objects, expected, strict=True):
238 got_output = pretty.pretty(obj)
239 assert got_output == expected_output
240
241
242 def test_unsortable_set():
243 xs = {1, 2, 3, "foo", "bar", "baz", object()}
244 p = pretty.pretty(xs)
245 for x in xs:
246 assert pretty.pretty(x) in p
247
248
249 def test_unsortable_dict():
250 xs = {k: 1 for k in [1, 2, 3, "foo", "bar", "baz", object()]}
251 p = pretty.pretty(xs)
252 for x in xs:
253 assert pretty.pretty(x) in p
254
255
256 def test_pprint_nomod():
257 """Test that pprint works for classes with no __module__."""
258 output = pretty.pretty(NoModule)
259 assert output == "NoModule"
260
261
262 def test_pprint_break():
263 """Test that p.break_ produces expected output."""
264 output = pretty.pretty(Breaking())
265 expected = "TG: Breaking(\n ):"
266 assert output == expected
267
268
269 def test_pprint_break_repr():
270 """Test that p.break_ is used in repr."""
271 output = pretty.pretty(BreakingReprParent())
272 expected = "TG: Breaking(\n ):"
273 assert output == expected
274
275
276 def test_bad_repr():
277 """Don't catch bad repr errors."""
278 with pytest.raises(ZeroDivisionError):
279 pretty.pretty(BadRepr())
280
281
282 class BadException(Exception):
283 def __str__(self):
284 return -1 # noqa
285
286
287 class ReallyBadRepr:
288 __module__ = 1
289
290 @property
291 def __class__(self):
292 raise ValueError("I am horrible")
293
294 def __repr__(self):
295 raise BadException
296
297
298 def test_really_bad_repr():
299 with pytest.raises(BadException):
300 pretty.pretty(ReallyBadRepr())
301
302
303 class SA:
304 pass
305
306
307 class SB(SA):
308 pass
309
310
311 try:
312 super(SA).__self__
313
314 def test_super_repr():
315 output = pretty.pretty(super(SA))
316 assert "SA" in output
317
318 sb = SB()
319 output = pretty.pretty(super(SA, sb))
320 assert "SA" in output
321
322 except AttributeError:
323
324 def test_super_repr():
325 pretty.pretty(super(SA))
326 sb = SB()
327 pretty.pretty(super(SA, sb))
328
329
330 def test_long_list():
331 lis = list(range(10000))
332 p = pretty.pretty(lis)
333 last2 = p.rsplit("\n", 2)[-2:]
334 assert last2 == [" 999,", " ...]"]
335
336
337 def test_long_set():
338 s = set(range(10000))
339 p = pretty.pretty(s)
340 last2 = p.rsplit("\n", 2)[-2:]
341 assert last2 == [" 999,", " ...}"]
342
343
344 def test_long_tuple():
345 tup = tuple(range(10000))
346 p = pretty.pretty(tup)
347 last2 = p.rsplit("\n", 2)[-2:]
348 assert last2 == [" 999,", " ...)"]
349
350
351 def test_long_dict():
352 d = {n: n for n in range(10000)}
353 p = pretty.pretty(d)
354 last2 = p.rsplit("\n", 2)[-2:]
355 assert last2 == [" 999: 999,", " ...}"]
356
357
358 def test_unbound_method():
359 assert pretty.pretty(MyObj.somemethod) == "somemethod"
360
361
362 class MetaClass(type):
363 def __new__(metacls, name):
364 return type.__new__(metacls, name, (object,), {"name": name})
365
366 def __repr__(cls):
367 return f"[CUSTOM REPR FOR CLASS {cls.name}]"
368
369
370 ClassWithMeta = MetaClass("ClassWithMeta")
371
372
373 def test_metaclass_repr():
374 output = pretty.pretty(ClassWithMeta)
375 assert output == "[CUSTOM REPR FOR CLASS ClassWithMeta]"
376
377
378 def test_unicode_repr():
379 u = "üniçodé"
380
381 class C:
382 def __repr__(self):
383 return u
384
385 c = C()
386 p = pretty.pretty(c)
387 assert p == u
388 p = pretty.pretty([c])
389 assert p == f"[{u}]"
390
391
392 def test_basic_class():
393 def type_pprint_wrapper(obj, p, cycle):
394 if obj is MyObj:
395 type_pprint_wrapper.called = True
396 return pretty._type_pprint(obj, p, cycle)
397
398 type_pprint_wrapper.called = False
399
400 printer = pretty.RepresentationPrinter()
401 printer.type_pprinters[type] = type_pprint_wrapper
402 printer.pretty(MyObj)
403 output = printer.getvalue()
404
405 assert output == f"{__name__}.MyObj"
406 assert type_pprint_wrapper.called
407
408
409 def test_collections_defaultdict():
410 # Create defaultdicts with cycles
411 a = defaultdict()
412 a.default_factory = a
413 b = defaultdict(list)
414 b["key"] = b
415
416 # Dictionary order cannot be relied on, test against single keys.
417 cases = [
418 (defaultdict(list), "defaultdict(list, {})"),
419 (
420 defaultdict(list, {"key": "-" * 50}),
421 "defaultdict(list,\n"
422 " {'key': '-----------------------------------------"
423 "---------'})",
424 ),
425 (a, "defaultdict(defaultdict(...), {})"),
426 (b, "defaultdict(list, {'key': defaultdict(...)})"),
427 ]
428 for obj, expected in cases:
429 assert pretty.pretty(obj) == expected
430
431
432 @pytest.mark.skipif(PYPY, reason="slightly different on PyPy3")
433 def test_collections_ordereddict():
434 # Create OrderedDict with cycle
435 a = OrderedDict()
436 a["key"] = a
437
438 cases = [
439 (OrderedDict(), "OrderedDict()"),
440 (
441 OrderedDict((i, i) for i in range(1000, 1010)),
442 "OrderedDict([(1000, 1000),\n"
443 " (1001, 1001),\n"
444 " (1002, 1002),\n"
445 " (1003, 1003),\n"
446 " (1004, 1004),\n"
447 " (1005, 1005),\n"
448 " (1006, 1006),\n"
449 " (1007, 1007),\n"
450 " (1008, 1008),\n"
451 " (1009, 1009)])",
452 ),
453 (a, "OrderedDict([('key', OrderedDict(...))])"),
454 ]
455 for obj, expected in cases:
456 assert pretty.pretty(obj) == expected
457
458
459 def test_collections_deque():
460 # Create deque with cycle
461 a = deque()
462 a.append(a)
463
464 cases = [
465 (deque(), "deque([])"),
466 (deque([1, 2, 3]), "deque([1, 2, 3])"),
467 (
468 deque(i for i in range(1000, 1020)),
469 "deque([1000,\n"
470 " 1001,\n"
471 " 1002,\n"
472 " 1003,\n"
473 " 1004,\n"
474 " 1005,\n"
475 " 1006,\n"
476 " 1007,\n"
477 " 1008,\n"
478 " 1009,\n"
479 " 1010,\n"
480 " 1011,\n"
481 " 1012,\n"
482 " 1013,\n"
483 " 1014,\n"
484 " 1015,\n"
485 " 1016,\n"
486 " 1017,\n"
487 " 1018,\n"
488 " 1019])",
489 ),
490 (a, "deque([deque(...)])"),
491 ]
492 for obj, expected in cases:
493 assert pretty.pretty(obj) == expected
494
495
496 def test_collections_counter():
497 class MyCounter(Counter):
498 pass
499
500 cases = [
501 (Counter(), "Counter()"),
502 (Counter(a=1), "Counter({'a': 1})"),
503 (MyCounter(a=1), "MyCounter({'a': 1})"),
504 ]
505 for obj, expected in cases:
506 assert pretty.pretty(obj) == expected
507
508
509 def test_cyclic_list():
510 x = []
511 x.append(x)
512 assert pretty.pretty(x) == "[[...]]"
513
514
515 def test_cyclic_dequeue():
516 x = deque()
517 x.append(x)
518 assert pretty.pretty(x) == "deque([deque(...)])"
519
520
521 class HashItAnyway:
522 def __init__(self, value):
523 self.value = value
524
525 def __hash__(self):
526 return 0
527
528 def __eq__(self, other):
529 return isinstance(other, HashItAnyway) and self.value == other.value
530
531 def __ne__(self, other):
532 return not self.__eq__(other)
533
534 def _repr_pretty_(self, pretty, cycle):
535 pretty.pretty(self.value)
536
537
538 def test_cyclic_counter():
539 c = Counter()
540 k = HashItAnyway(c)
541 c[k] = 1
542 assert pretty.pretty(c) == "Counter({Counter(...): 1})"
543
544
545 def test_cyclic_dict():
546 x = {}
547 k = HashItAnyway(x)
548 x[k] = x
549 assert pretty.pretty(x) == "{{...}: {...}}"
550
551
552 def test_cyclic_set():
553 x = set()
554 x.add(HashItAnyway(x))
555 assert pretty.pretty(x) == "{{...}}"
556
557
558 class BigList(list):
559 def _repr_pretty_(self, printer, cycle):
560 if cycle:
561 return "[...]"
562 else:
563 with printer.group(open="[", close="]"), printer.indent(5):
564 for v in self:
565 printer.pretty(v)
566 printer.breakable(",")
567
568
569 def test_print_with_indent():
570 pretty.pretty(BigList([1, 2, 3]))
571
572
573 class MyException(Exception):
574 pass
575
576
577 def test_exception():
578 assert pretty.pretty(ValueError("hi")) == "ValueError('hi')"
579 assert pretty.pretty(ValueError("hi", "there")) == "ValueError('hi', 'there')"
580 assert "test_pretty." in pretty.pretty(MyException())
581
582
583 def test_re_evals():
584 for r in [
585 re.compile(r"hi"),
586 re.compile(r"b\nc", re.MULTILINE),
587 re.compile(rb"hi", 0),
588 re.compile("foo", re.MULTILINE | re.UNICODE),
589 ]:
590 r2 = eval(pretty.pretty(r), globals())
591 assert r.pattern == r2.pattern
592 assert r.flags == r2.flags
593
594
595 def test_print_builtin_function():
596 assert pretty.pretty(abs) == "abs"
597
598
599 def test_pretty_function():
600 assert pretty.pretty(test_pretty_function) == "test_pretty_function"
601
602
603 def test_breakable_at_group_boundary():
604 assert "\n" in pretty.pretty([[], "0" * 80])
605
606
607 @pytest.mark.parametrize(
608 "obj, rep",
609 [
610 (float("nan"), "nan"),
611 (-float("nan"), "-nan"),
612 (SIGNALING_NAN, "struct.unpack('d', struct.pack('Q', 0x7ff8000000000001))[0]"),
613 (-SIGNALING_NAN, "struct.unpack('d', struct.pack('Q', 0xfff8000000000001))[0]"),
614 ],
615 )
616 def test_nan_reprs(obj, rep):
617 assert pretty.pretty(obj) == rep
618 assert float_to_lex(obj) == float_to_lex(
619 eval(rep, {"struct": struct, "nan": float("nan")})
620 )
621
622
623 def _repr_call(*args, **kwargs):
624 p = pretty.RepresentationPrinter()
625 p.repr_call(*args, **kwargs)
626 return p.getvalue()
627
628
629 @pytest.mark.parametrize("func_name", ["f", "lambda: ...", "lambda *args: ..."])
630 def test_repr_call(func_name):
631 fn = f"({func_name})" if func_name.startswith(("lambda:", "lambda ")) else func_name
632 aas = "a" * 100
633 assert _repr_call(func_name, (1, 2), {}) == f"{fn}(1, 2)"
634 assert _repr_call(func_name, (aas,), {}) == f"{fn}(\n {aas!r},\n)"
635 assert _repr_call(func_name, (), {"a": 1, "b": 2}) == f"{fn}(a=1, b=2)"
636 assert _repr_call(func_name, (), {"x": aas}) == f"{fn}(\n x={aas!r},\n)"
637
638
639 class AnEnum(Enum):
640 SOME_MEMBER = 1
641
642
643 class Options(Flag):
644 A = 1
645 B = 2
646 C = 4
647
648
649 class EvilReprOptions(Flag):
650 A = 1
651 B = 2
652
653 def __repr__(self):
654 return "can't parse this nonsense"
655
656
657 class LyingReprOptions(Flag):
658 A = 1
659 B = 2
660
661 def __repr__(self):
662 return "LyingReprOptions.A|B|C"
663
664
665 @pytest.mark.parametrize(
666 "rep",
667 [
668 "AnEnum.SOME_MEMBER",
669 "Options.A",
670 "Options.A | Options.B",
671 "Options.A | Options.B | Options.C",
672 "Options(0)",
673 "EvilReprOptions.A",
674 "LyingReprOptions.A",
675 "EvilReprOptions.A | EvilReprOptions.B",
676 "LyingReprOptions.A | LyingReprOptions.B",
677 ],
678 )
679 def test_pretty_prints_enums_as_code(rep):
680 assert pretty.pretty(eval(rep)) == rep
681
682
683 class Obj:
684 def _repr_pretty_(self, p, cycle):
685 """Exercise the IPython callback interface."""
686 assert not cycle
687 with p.indent(2):
688 p.text("abc,")
689 p.breakable(" ")
690 p.break_()
691 p.begin_group(8, "<")
692 p.end_group(8, ">")
693
694
695 def test_supports_ipython_callback():
696 assert pretty.pretty(Obj()) == "abc, \n <>"
697
698
699 def test_pretty_partial_with_cycle():
700 ls = []
701 p = partial(bool, ls)
702 assert pretty.pretty(p) == "functools.partial(bool, [])"
703 ls.append(p)
704 assert pretty.pretty(p) == "functools.partial(bool, [functools.partial(bool, ...)])"
705
706
707 class InvalidSyntaxRepr:
708 def __init__(self, val=None) -> None:
709 self.val = val
710
711 def __repr__(self):
712 return "invalid syntax"
713
714
715 class ValidSyntaxRepr:
716 def __init__(self, val=None) -> None:
717 self.val = val
718
719 def __repr__(self):
720 return "ValidSyntaxRepr(...)"
721
722
723 @given(st.data())
724 def test_pprint_with_call_or_repr_as_call(data):
725 # mapped pprint repr only triggers for failing examples - which makes an
726 # end to end test given hypothesis difficult. fake our way around it.
727 current_build_context().is_final = True
728
729 x = data.draw(st.none().map(InvalidSyntaxRepr))
730 p = pretty.RepresentationPrinter(context=current_build_context())
731 p.pretty(x)
732 assert p.getvalue() == "InvalidSyntaxRepr(None)"
733
734
735 @given(st.just(InvalidSyntaxRepr()).map(ValidSyntaxRepr))
736 def test_pprint_with_call_or_repr_as_repr(x):
737 p = pretty.RepresentationPrinter(context=current_build_context())
738 p.pretty(x)
739 assert p.getvalue() == "ValidSyntaxRepr(...)"
740
741
742 @given(st.data())
743 def test_pprint_map_with_cycle(data):
744 current_build_context().is_final = True
745 x = data.draw(st.just(ValidSyntaxRepr()).map(lambda x: x))
746
747 p = pretty.RepresentationPrinter(context=current_build_context())
748 p.pretty(x)
749 assert p.getvalue() == "ValidSyntaxRepr(...)"
750
751
752 def test_pprint_large_integers():
753 p = pretty.RepresentationPrinter()
754 p.pretty(1234567890)
755 assert p.getvalue() == "1_234_567_890"
756
757
758 def test_pprint_extremely_large_integers():
759 x = 10**5000 # repr fails with ddos error
760 p = pretty.RepresentationPrinter()
761 p.pretty(x)
762 got = p.getvalue()
763 assert got == f"{x:#_x}" # hexadecimal with underscores
764 assert eval(got) == x
765
766
767 class ReprDetector:
768 def _repr_pretty_(self, p, cycle):
769 """Exercise the IPython callback interface."""
770 p.text("GOOD")
771
772 def __repr__(self):
773 return "BAD"
774
775
776 @dataclass
777 class SomeDataClass:
778 x: object
779
780
781 def test_pretty_prints_data_classes():
782 assert pretty.pretty(SomeDataClass(ReprDetector())) == "SomeDataClass(x=GOOD)"
783
784
785 def test_handles_cycles_in_dataclass():
786 x = SomeDataClass(x=1)
787 x.x = x
788
789 assert pretty.pretty(x) == "SomeDataClass(x=SomeDataClass(...))"
790
791
792 @dataclass
793 class DataClassWithNoInitField:
794 x: int
795 y: int = field(init=False)
796
797
798 def test_does_not_include_no_init_fields_in_dataclass_printing():
799 record = DataClassWithNoInitField(x=1)
800 assert pretty.pretty(record) == "DataClassWithNoInitField(x=1)"
801 record.y = 1
802 assert pretty.pretty(record) == "DataClassWithNoInitField(x=1)"
803
804
805 class Namespace:
806 @dataclass
807 class DC:
808 x: int
809
810 class E(Enum):
811 A = 1
812
813
814 NAMESPACED_VALUES = [
815 Namespace.DC(x=1),
816 Namespace.E.A,
817 ]
818
819
820 @pytest.mark.parametrize("obj", NAMESPACED_VALUES, ids=map(repr, NAMESPACED_VALUES))
821 def test_includes_namespace_classes_in_pretty(obj):
822 assert pretty.pretty(obj).startswith("Namespace.")
823
824
825 class Banana:
826 def _repr_pretty_(self, p, cycle):
827 p.text("I am a banana")
828
829
830 @dataclass
831 class InheritsPretty(Banana):
832 x: int
833 y: int
834
835
836 def test_uses_defined_pretty_printing_method():
837 assert pretty.pretty(InheritsPretty(x=1, y=2)) == pretty.pretty(Banana())
838
839
840 def test_prefers_singleton_printing_to_repr_pretty():
841 out = io.StringIO()
842 printer = pretty.RepresentationPrinter(out)
843 banana = Banana()
844 printer.singleton_pprinters[id(banana)] = lambda obj, p, cycle: p.text(
845 "Actually a fish"
846 )
847 printer.pretty(banana)
848 assert "Actually a fish" in out.getvalue()
849
850
851 def test_tuple_pprinter_cycle():
852 # Test that _tuple_pprinter handles cycles correctly
853 from hypothesis.vendor.pretty import _tuple_pprinter
854
855 t = (1, 2, 3)
856 arg_labels = {"arg[0]": (0, 1), "arg[1]": (1, 2), "arg[2]": (2, 3)}
857 pprinter = _tuple_pprinter(arg_labels)
858
859 out = io.StringIO()
860 p = pretty.RepresentationPrinter(out)
861 # Simulate a cycle by adding the tuple's id to the stack
862 p.stack.append(id(t))
863 pprinter(t, p, cycle=True)
864 p.flush()
865 assert out.getvalue() == "(...)"
866
867
868 def test_fixeddict_pprinter_cycle():
869 # Test that _fixeddict_pprinter handles cycles correctly
870 from hypothesis.vendor.pretty import _fixeddict_pprinter
871
872 d = {"a": 1, "b": 2}
873 mapping = {"a": None, "b": None} # dummy mapping for key ordering
874 arg_labels = {"a": (0, 1), "b": (1, 2)}
875 pprinter = _fixeddict_pprinter(arg_labels, mapping)
876
877 out = io.StringIO()
878 p = pretty.RepresentationPrinter(out)
879 # Simulate a cycle by adding the dict's id to the stack
880 p.stack.append(id(d))
881 pprinter(d, p, cycle=True)
882 p.flush()
883 assert out.getvalue() == "{...}"
884
885
886 def test_get_slice_comment_skips_already_commented():
887 # Test that _get_slice_comment returns None for already-commented slices
888 from hypothesis.vendor.pretty import _get_slice_comment
889
890 out = io.StringIO()
891 p = pretty.RepresentationPrinter(out)
892 p.slice_comments = {(0, 5): "or any other generated value"}
893 # Mark the slice as already commented
894 p._commented_slices.add((0, 5))
895
896 arg_labels = {"arg[0]": (0, 5)}
897 # Should return None because slice is already in _commented_slices
898 result = _get_slice_comment(p, arg_labels, "arg[0]")
899 assert result is None