-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy pathtest_pretty.py
546 lines (413 loc) · 13.7 KB
/
test_pretty.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
import collections
import io
import sys
from array import array
from collections import UserDict, defaultdict
from dataclasses import dataclass, field
from typing import List, NamedTuple
import attr
import pytest
from rich.console import Console
from rich.measure import Measurement
from rich.pretty import Node, Pretty, _ipy_display_hook, install, pprint, pretty_repr
from rich.text import Text
skip_py36 = pytest.mark.skipif(
sys.version_info.minor == 6 and sys.version_info.major == 3,
reason="rendered differently on py3.6",
)
skip_py37 = pytest.mark.skipif(
sys.version_info.minor == 7 and sys.version_info.major == 3,
reason="rendered differently on py3.7",
)
skip_py38 = pytest.mark.skipif(
sys.version_info.minor == 8 and sys.version_info.major == 3,
reason="rendered differently on py3.8",
)
skip_py39 = pytest.mark.skipif(
sys.version_info.minor == 9 and sys.version_info.major == 3,
reason="rendered differently on py3.9",
)
skip_py310 = pytest.mark.skipif(
sys.version_info.minor == 10 and sys.version_info.major == 3,
reason="rendered differently on py3.10",
)
def test_install():
console = Console(file=io.StringIO())
dh = sys.displayhook
install(console)
sys.displayhook("foo")
assert console.file.getvalue() == "'foo'\n"
assert sys.displayhook is not dh
def test_ipy_display_hook__repr_html():
console = Console(file=io.StringIO(), force_jupyter=True)
class Thing:
def _repr_html_(self):
return "hello"
console.begin_capture()
_ipy_display_hook(Thing(), console=console)
# Rendering delegated to notebook because _repr_html_ method exists
assert console.end_capture() == ""
def test_ipy_display_hook__multiple_special_reprs():
"""
The case where there are multiple IPython special _repr_*_
methods on the object, and one of them returns None but another
one does not.
"""
console = Console(file=io.StringIO(), force_jupyter=True)
class Thing:
def _repr_latex_(self):
return None
def _repr_html_(self):
return "hello"
console.begin_capture()
_ipy_display_hook(Thing(), console=console)
assert console.end_capture() == ""
def test_ipy_display_hook__no_special_repr_methods():
console = Console(file=io.StringIO(), force_jupyter=True)
class Thing:
def __repr__(self) -> str:
return "hello"
console.begin_capture()
_ipy_display_hook(Thing(), console=console)
# No IPython special repr methods, so printed by Rich
assert console.end_capture() == "hello\n"
def test_ipy_display_hook__special_repr_raises_exception():
"""
When an IPython special repr method raises an exception,
we treat it as if it doesn't exist and look for the next.
"""
console = Console(file=io.StringIO(), force_jupyter=True)
class Thing:
def _repr_markdown_(self):
raise Exception()
def _repr_latex_(self):
return None
def _repr_html_(self):
return "hello"
console.begin_capture()
_ipy_display_hook(Thing(), console=console)
assert console.end_capture() == ""
def test_ipy_display_hook__console_renderables_on_newline():
console = Console(file=io.StringIO(), force_jupyter=True)
console.begin_capture()
_ipy_display_hook(Text("hello"), console=console)
assert console.end_capture() == "\nhello\n"
def test_pretty():
test = {
"foo": [1, 2, 3, (4, 5, {6}, 7, 8, {9}), {}],
"bar": {"egg": "baz", "words": ["Hello World"] * 10},
False: "foo",
True: "",
"text": ("Hello World", "foo bar baz egg"),
}
result = pretty_repr(test, max_width=80)
print(result)
expected = "{\n 'foo': [1, 2, 3, (4, 5, {6}, 7, 8, {9}), {}],\n 'bar': {\n 'egg': 'baz',\n 'words': [\n 'Hello World',\n 'Hello World',\n 'Hello World',\n 'Hello World',\n 'Hello World',\n 'Hello World',\n 'Hello World',\n 'Hello World',\n 'Hello World',\n 'Hello World'\n ]\n },\n False: 'foo',\n True: '',\n 'text': ('Hello World', 'foo bar baz egg')\n}"
print(expected)
assert result == expected
@dataclass
class ExampleDataclass:
foo: int
bar: str
ignore: int = field(repr=False)
baz: List[str] = field(default_factory=list)
last: int = field(default=1, repr=False)
def test_pretty_dataclass():
dc = ExampleDataclass(1000, "Hello, World", 999, ["foo", "bar", "baz"])
result = pretty_repr(dc, max_width=80)
print(repr(result))
assert (
result
== "ExampleDataclass(foo=1000, bar='Hello, World', baz=['foo', 'bar', 'baz'])"
)
result = pretty_repr(dc, max_width=16)
print(repr(result))
assert (
result
== "ExampleDataclass(\n foo=1000,\n bar='Hello, World',\n baz=[\n 'foo',\n 'bar',\n 'baz'\n ]\n)"
)
dc.bar = dc
result = pretty_repr(dc, max_width=80)
print(repr(result))
assert result == "ExampleDataclass(foo=1000, bar=..., baz=['foo', 'bar', 'baz'])"
class StockKeepingUnit(NamedTuple):
name: str
description: str
price: float
category: str
reviews: List[str]
def test_pretty_namedtuple():
console = Console(color_system=None)
console.begin_capture()
example_namedtuple = StockKeepingUnit(
"Sparkling British Spring Water",
"Carbonated spring water",
0.9,
"water",
["its amazing!", "its terrible!"],
)
result = pretty_repr(example_namedtuple)
print(result)
assert (
result
== """StockKeepingUnit(
name='Sparkling British Spring Water',
description='Carbonated spring water',
price=0.9,
category='water',
reviews=['its amazing!', 'its terrible!']
)"""
)
def test_pretty_namedtuple_length_one_no_trailing_comma():
instance = collections.namedtuple("Thing", ["name"])(name="Bob")
assert pretty_repr(instance) == "Thing(name='Bob')"
def test_pretty_namedtuple_empty():
instance = collections.namedtuple("Thing", [])()
assert pretty_repr(instance) == "Thing()"
def test_pretty_namedtuple_custom_repr():
class Thing(NamedTuple):
def __repr__(self):
return "XX"
assert pretty_repr(Thing()) == "XX"
def test_pretty_namedtuple_fields_invalid_type():
class LooksLikeANamedTupleButIsnt(tuple):
_fields = "blah"
instance = LooksLikeANamedTupleButIsnt()
result = pretty_repr(instance)
assert result == "()" # Treated as tuple
def test_pretty_namedtuple_max_depth():
instance = {"unit": StockKeepingUnit("a", "b", 1.0, "c", ["d", "e"])}
result = pretty_repr(instance, max_depth=1)
assert result == "{'unit': ...}"
def test_small_width():
test = ["Hello world! 12345"]
result = pretty_repr(test, max_width=10)
expected = "[\n 'Hello world! 12345'\n]"
assert result == expected
@skip_py36
def test_broken_repr():
class BrokenRepr:
def __repr__(self):
1 / 0
test = [BrokenRepr()]
result = pretty_repr(test)
expected = "[<repr-error 'division by zero'>]"
assert result == expected
@skip_py36
def test_broken_getattr():
class BrokenAttr:
def __getattr__(self, name):
1 / 0
def __repr__(self):
return "BrokenAttr()"
test = BrokenAttr()
result = pretty_repr(test)
assert result == "BrokenAttr()"
def test_recursive():
test = []
test.append(test)
result = pretty_repr(test)
expected = "[...]"
assert result == expected
def test_max_depth():
d = {}
d["foo"] = {"fob": {"a": [1, 2, 3], "b": {"z": "x", "y": ["a", "b", "c"]}}}
assert pretty_repr(d, max_depth=0) == "..."
assert pretty_repr(d, max_depth=1) == "{'foo': ...}"
assert pretty_repr(d, max_depth=2) == "{'foo': {'fob': ...}}"
assert pretty_repr(d, max_depth=3) == "{'foo': {'fob': {'a': ..., 'b': ...}}}"
assert (
pretty_repr(d, max_width=100, max_depth=4)
== "{'foo': {'fob': {'a': [1, 2, 3], 'b': {'z': 'x', 'y': ...}}}}"
)
assert (
pretty_repr(d, max_width=100, max_depth=5)
== "{'foo': {'fob': {'a': [1, 2, 3], 'b': {'z': 'x', 'y': ['a', 'b', 'c']}}}}"
)
assert (
pretty_repr(d, max_width=100, max_depth=None)
== "{'foo': {'fob': {'a': [1, 2, 3], 'b': {'z': 'x', 'y': ['a', 'b', 'c']}}}}"
)
def test_max_depth_rich_repr():
class Foo:
def __init__(self, foo):
self.foo = foo
def __rich_repr__(self):
yield "foo", self.foo
class Bar:
def __init__(self, bar):
self.bar = bar
def __rich_repr__(self):
yield "bar", self.bar
assert (
pretty_repr(Foo(foo=Bar(bar=Foo(foo=[]))), max_depth=2)
== "Foo(foo=Bar(bar=...))"
)
def test_max_depth_attrs():
@attr.define
class Foo:
foo = attr.field()
@attr.define
class Bar:
bar = attr.field()
assert (
pretty_repr(Foo(foo=Bar(bar=Foo(foo=[]))), max_depth=2)
== "Foo(foo=Bar(bar=...))"
)
def test_max_depth_dataclass():
@dataclass
class Foo:
foo: object
@dataclass
class Bar:
bar: object
assert (
pretty_repr(Foo(foo=Bar(bar=Foo(foo=[]))), max_depth=2)
== "Foo(foo=Bar(bar=...))"
)
def test_defaultdict():
test_dict = defaultdict(int, {"foo": 2})
result = pretty_repr(test_dict)
assert result == "defaultdict(<class 'int'>, {'foo': 2})"
def test_array():
test_array = array("I", [1, 2, 3])
result = pretty_repr(test_array)
assert result == "array('I', [1, 2, 3])"
def test_tuple_of_one():
assert pretty_repr((1,)) == "(1,)"
def test_node():
node = Node("abc")
assert pretty_repr(node) == "abc: "
def test_indent_lines():
console = Console(width=100, color_system=None)
console.begin_capture()
console.print(Pretty([100, 200], indent_guides=True), width=8)
expected = """\
[
│ 100,
│ 200
]
"""
result = console.end_capture()
print(repr(result))
print(result)
assert result == expected
def test_pprint():
console = Console(color_system=None)
console.begin_capture()
pprint(1, console=console)
assert console.end_capture() == "1\n"
def test_pprint_max_values():
console = Console(color_system=None)
console.begin_capture()
pprint([1, 2, 3, 4, 5, 6, 7, 8, 9, 0], console=console, max_length=2)
assert console.end_capture() == "[1, 2, ... +8]\n"
def test_pprint_max_items():
console = Console(color_system=None)
console.begin_capture()
pprint({"foo": 1, "bar": 2, "egg": 3}, console=console, max_length=2)
assert console.end_capture() == """{'foo': 1, 'bar': 2, ... +1}\n"""
def test_pprint_max_string():
console = Console(color_system=None)
console.begin_capture()
pprint(["Hello" * 20], console=console, max_string=8)
assert console.end_capture() == """['HelloHel'+92]\n"""
def test_tuples():
console = Console(color_system=None)
console.begin_capture()
pprint((1,), console=console)
pprint((1,), expand_all=True, console=console)
pprint(((1,),), expand_all=True, console=console)
result = console.end_capture()
print(repr(result))
expected = "(1,)\n(\n│ 1,\n)\n(\n│ (\n│ │ 1,\n│ ),\n)\n"
print(result)
print("--")
print(expected)
assert result == expected
def test_newline():
console = Console(color_system=None)
console.begin_capture()
console.print(Pretty((1,), insert_line=True, expand_all=True))
result = console.end_capture()
expected = "\n(\n 1,\n)\n"
assert result == expected
def test_empty_repr():
class Foo:
def __repr__(self):
return ""
assert pretty_repr(Foo()) == ""
def test_attrs():
@attr.define
class Point:
x: int
y: int
foo: str = attr.field(repr=str.upper)
z: int = 0
result = pretty_repr(Point(1, 2, foo="bar"))
print(repr(result))
expected = "Point(x=1, y=2, foo=BAR, z=0)"
assert result == expected
def test_attrs_empty():
@attr.define
class Nada:
pass
result = pretty_repr(Nada())
print(repr(result))
expected = "Nada()"
assert result == expected
@skip_py36
@skip_py310
def test_attrs_broken():
@attr.define
class Foo:
bar: int
foo = Foo(1)
del foo.bar
result = pretty_repr(foo)
print(repr(result))
expected = "Foo(bar=AttributeError('bar'))"
assert result == expected
@skip_py36
@skip_py37
@skip_py38
@skip_py39
def test_attrs_broken_310():
@attr.define
class Foo:
bar: int
foo = Foo(1)
del foo.bar
result = pretty_repr(foo)
print(repr(result))
expected = "Foo(bar=AttributeError(\"'Foo' object has no attribute 'bar'\"))"
assert result == expected
def test_user_dict():
class D1(UserDict):
pass
class D2(UserDict):
def __repr__(self):
return "FOO"
d1 = D1({"foo": "bar"})
d2 = D2({"foo": "bar"})
result = pretty_repr(d1, expand_all=True)
print(repr(result))
assert result == "{\n 'foo': 'bar'\n}"
result = pretty_repr(d2, expand_all=True)
print(repr(result))
assert result == "FOO"
def test_lying_attribute():
"""Test getattr doesn't break rich repr protocol"""
class Foo:
def __getattr__(self, attr):
return "foo"
foo = Foo()
result = pretty_repr(foo)
assert "Foo" in result
def test_measure_pretty():
"""Test measure respects expand_all"""
# https://github.com/Textualize/rich/issues/1998
console = Console()
pretty = Pretty(["alpha", "beta", "delta", "gamma"], expand_all=True)
measurement = console.measure(pretty)
assert measurement == Measurement(12, 12)