Debian Codegraph @

tests/test_formatters.py

raw
1 """Tests for the Formatters."""
2
3 from math import pi
4
5 try:
6 import numpy
7 except:
8 numpy = None
9 import pytest
10
11 from IPython import get_ipython
12 from traitlets.config import Config
13 from IPython.core.formatters import (
14 PlainTextFormatter,
15 HTMLFormatter,
16 PDFFormatter,
17 _mod_name_key,
18 DisplayFormatter,
19 JSONFormatter,
20 )
21 from IPython.utils.io import capture_output
22
23
24 class A(object):
25 def __repr__(self):
26 return "A()"
27
28
29 class B(A):
30 def __repr__(self):
31 return "B()"
32
33
34 class C:
35 pass
36
37
38 class BadRepr(object):
39 def __repr__(self):
40 raise ValueError("bad repr")
41
42
43 class BadPretty(object):
44 _repr_pretty_ = None
45
46
47 class GoodPretty(object):
48 def _repr_pretty_(self, pp, cycle):
49 pp.text("foo")
50
51 def __repr__(self):
52 return "GoodPretty()"
53
54
55 def foo_printer(obj, pp, cycle):
56 pp.text("foo")
57
58
59 def test_display_formatter_active_types_config():
60 from IPython.terminal.interactiveshell import TerminalInteractiveShell
61 from IPython.core.history import HistoryManager
62 from traitlets.config import Config
63
64 # Clear HistoryManager instances to bypass singleton limit before creating new shell
65 prev_instances = HistoryManager._instances.copy()
66 HistoryManager._instances.clear()
67
68 try:
69 c = Config()
70 c.DisplayFormatter.active_types = ["text/plain", "image/png"]
71 # Disable history
72 c.HistoryManager.enabled = False
73
74 ip = TerminalInteractiveShell(config=c)
75
76 active_types = ip.display_formatter.active_types
77 assert "text/plain" in active_types
78 assert "image/png" in active_types
79
80 # Ensure only the expected types are active
81 assert set(active_types) == {"text/plain", "image/png"}
82
83 finally:
84 # Clean up the new instance and restore previous state
85 HistoryManager._instances.clear()
86 HistoryManager._instances.update(prev_instances)
87
88
89 def test_pretty():
90 f = PlainTextFormatter()
91 f.for_type(A, foo_printer)
92 assert f(A()) == "foo"
93 assert f(B()) == "B()"
94 assert f(GoodPretty()) == "foo"
95 # Just don't raise an exception for the following:
96 f(BadPretty())
97
98 f.pprint = False
99 assert f(A()) == "A()"
100 assert f(B()) == "B()"
101 assert f(GoodPretty()) == "GoodPretty()"
102
103
104 def test_deferred():
105 f = PlainTextFormatter()
106
107
108 def test_precision():
109 """test various values for float_precision."""
110 f = PlainTextFormatter()
111 assert f(pi) == repr(pi)
112 f.float_precision = 0
113 if numpy:
114 po = numpy.get_printoptions()
115 assert po["precision"] == 0
116 assert f(pi) == "3"
117 f.float_precision = 2
118 if numpy:
119 po = numpy.get_printoptions()
120 assert po["precision"] == 2
121 assert f(pi) == "3.14"
122 f.float_precision = "%g"
123 if numpy:
124 po = numpy.get_printoptions()
125 assert po["precision"] == 2
126 assert f(pi) == "3.14159"
127 f.float_precision = "%e"
128 assert f(pi) == "3.141593e+00"
129 f.float_precision = ""
130 if numpy:
131 po = numpy.get_printoptions()
132 assert po["precision"] == 8
133 assert f(pi) == repr(pi)
134
135
136 def test_bad_precision():
137 """test various invalid values for float_precision."""
138 f = PlainTextFormatter()
139
140 def set_fp(p):
141 f.float_precision = p
142
143 pytest.raises(ValueError, set_fp, "%")
144 pytest.raises(ValueError, set_fp, "%.3f%i")
145 pytest.raises(ValueError, set_fp, "foo")
146 pytest.raises(ValueError, set_fp, -1)
147
148
149 def test_for_type():
150 f = PlainTextFormatter()
151
152 # initial return, None
153 assert f.for_type(C, foo_printer) is None
154 # no func queries
155 assert f.for_type(C) is foo_printer
156 # shouldn't change anything
157 assert f.for_type(C) is foo_printer
158 # None should do the same
159 assert f.for_type(C, None) is foo_printer
160 assert f.for_type(C, None) is foo_printer
161
162
163 def test_for_type_string():
164 f = PlainTextFormatter()
165
166 type_str = "%s.%s" % (C.__module__, "C")
167
168 # initial return, None
169 assert f.for_type(type_str, foo_printer) is None
170 # no func queries
171 assert f.for_type(type_str) is foo_printer
172 assert _mod_name_key(C) in f.deferred_printers
173 assert f.for_type(C) is foo_printer
174 assert _mod_name_key(C) not in f.deferred_printers
175 assert C in f.type_printers
176
177
178 def test_for_type_by_name():
179 f = PlainTextFormatter()
180
181 mod = C.__module__
182
183 # initial return, None
184 assert f.for_type_by_name(mod, "C", foo_printer) is None
185 # no func queries
186 assert f.for_type_by_name(mod, "C") is foo_printer
187 # shouldn't change anything
188 assert f.for_type_by_name(mod, "C") is foo_printer
189 # None should do the same
190 assert f.for_type_by_name(mod, "C", None) is foo_printer
191 assert f.for_type_by_name(mod, "C", None) is foo_printer
192
193
194 def test_lookup():
195 f = PlainTextFormatter()
196
197 f.for_type(C, foo_printer)
198 assert f.lookup(C()) is foo_printer
199 with pytest.raises(KeyError):
200 f.lookup(A())
201
202
203 def test_lookup_string():
204 f = PlainTextFormatter()
205 type_str = "%s.%s" % (C.__module__, "C")
206
207 f.for_type(type_str, foo_printer)
208 assert f.lookup(C()) is foo_printer
209 # should move from deferred to imported dict
210 assert _mod_name_key(C) not in f.deferred_printers
211 assert C in f.type_printers
212
213
214 def test_lookup_by_type():
215 f = PlainTextFormatter()
216 f.for_type(C, foo_printer)
217 assert f.lookup_by_type(C) is foo_printer
218 with pytest.raises(KeyError):
219 f.lookup_by_type(A)
220
221
222 def test_lookup_by_type_string():
223 f = PlainTextFormatter()
224 type_str = "%s.%s" % (C.__module__, "C")
225 f.for_type(type_str, foo_printer)
226
227 # verify insertion
228 assert _mod_name_key(C) in f.deferred_printers
229 assert C not in f.type_printers
230
231 assert f.lookup_by_type(type_str) is foo_printer
232 # lookup by string doesn't cause import
233 assert _mod_name_key(C) in f.deferred_printers
234 assert C not in f.type_printers
235
236 assert f.lookup_by_type(C) is foo_printer
237 # should move from deferred to imported dict
238 assert _mod_name_key(C) not in f.deferred_printers
239 assert C in f.type_printers
240
241
242 def test_in_formatter():
243 f = PlainTextFormatter()
244 f.for_type(C, foo_printer)
245 type_str = "%s.%s" % (C.__module__, "C")
246 assert C in f
247 assert type_str in f
248
249
250 def test_string_in_formatter():
251 f = PlainTextFormatter()
252 type_str = "%s.%s" % (C.__module__, "C")
253 f.for_type(type_str, foo_printer)
254 assert type_str in f
255 assert C in f
256
257
258 def test_pop():
259 f = PlainTextFormatter()
260 f.for_type(C, foo_printer)
261 assert f.lookup_by_type(C) is foo_printer
262 assert f.pop(C, None) is foo_printer
263 f.for_type(C, foo_printer)
264 assert f.pop(C) is foo_printer
265 with pytest.raises(KeyError):
266 f.lookup_by_type(C)
267 with pytest.raises(KeyError):
268 f.pop(C)
269 with pytest.raises(KeyError):
270 f.pop(A)
271 assert f.pop(A, None) is None
272
273
274 def test_pop_string():
275 f = PlainTextFormatter()
276 type_str = "%s.%s" % (C.__module__, "C")
277
278 with pytest.raises(KeyError):
279 f.pop(type_str)
280
281 f.for_type(type_str, foo_printer)
282 f.pop(type_str)
283 with pytest.raises(KeyError):
284 f.lookup_by_type(C)
285 with pytest.raises(KeyError):
286 f.pop(type_str)
287
288 f.for_type(C, foo_printer)
289 assert f.pop(type_str, None) is foo_printer
290 with pytest.raises(KeyError):
291 f.lookup_by_type(C)
292 with pytest.raises(KeyError):
293 f.pop(type_str)
294 assert f.pop(type_str, None) is None
295
296
297 def test_error_method():
298 f = HTMLFormatter()
299
300 class BadHTML(object):
301 def _repr_html_(self):
302 raise ValueError("Bad HTML")
303
304 bad = BadHTML()
305 with capture_output() as captured:
306 result = f(bad)
307 assert result is None
308 assert "Traceback" in captured.stdout
309 assert "Bad HTML" in captured.stdout
310 assert "_repr_html_" in captured.stdout
311
312
313 def test_nowarn_notimplemented():
314 f = HTMLFormatter()
315
316 class HTMLNotImplemented(object):
317 def _repr_html_(self):
318 raise NotImplementedError
319
320 h = HTMLNotImplemented()
321 with capture_output() as captured:
322 result = f(h)
323 assert result is None
324 assert "" == captured.stderr
325 assert "" == captured.stdout
326
327
328 def test_warn_error_for_type():
329 f = HTMLFormatter()
330 f.for_type(int, lambda i: name_error)
331 with capture_output() as captured:
332 result = f(5)
333 assert result is None
334 assert "Traceback" in captured.stdout
335 assert "NameError" in captured.stdout
336 assert "name_error" in captured.stdout
337
338
339 def test_error_pretty_method():
340 f = PlainTextFormatter()
341
342 class BadPretty(object):
343 def _repr_pretty_(self):
344 return "hello"
345
346 bad = BadPretty()
347 with capture_output() as captured:
348 result = f(bad)
349 assert result is None
350 assert "Traceback" in captured.stdout
351 assert "_repr_pretty_" in captured.stdout
352 assert "given" in captured.stdout
353 assert "argument" in captured.stdout
354
355
356 def test_bad_repr_traceback():
357 f = PlainTextFormatter()
358 bad = BadRepr()
359 with capture_output() as captured:
360 result = f(bad)
361 # catches error, returns None
362 assert result is None
363 assert "Traceback" in captured.stdout
364 assert "__repr__" in captured.stdout
365 assert "ValueError" in captured.stdout
366
367
368 class MakePDF(object):
369 def _repr_pdf_(self):
370 return "PDF"
371
372
373 def test_pdf_formatter():
374 pdf = MakePDF()
375 f = PDFFormatter()
376 assert f(pdf) == "PDF"
377
378
379 def test_print_method_bound():
380 f = HTMLFormatter()
381
382 class MyHTML(object):
383 def _repr_html_(self):
384 return "hello"
385
386 with capture_output() as captured:
387 result = f(MyHTML)
388 assert result is None
389 assert "FormatterWarning" not in captured.stderr
390
391 with capture_output() as captured:
392 result = f(MyHTML())
393 assert result == "hello"
394 assert captured.stderr == ""
395
396
397 def test_print_method_weird():
398 class TextMagicHat(object):
399 def __getattr__(self, key):
400 return key
401
402 f = HTMLFormatter()
403
404 text_hat = TextMagicHat()
405 assert text_hat._repr_html_ == "_repr_html_"
406 with capture_output() as captured:
407 result = f(text_hat)
408
409 assert result is None
410 assert "FormatterWarning" not in captured.stderr
411
412 class CallableMagicHat(object):
413 def __getattr__(self, key):
414 return lambda: key
415
416 call_hat = CallableMagicHat()
417 with capture_output() as captured:
418 result = f(call_hat)
419
420 assert result is None
421
422 class BadReprArgs(object):
423 def _repr_html_(self, extra, args):
424 return "html"
425
426 bad = BadReprArgs()
427 with capture_output() as captured:
428 result = f(bad)
429
430 assert result is None
431 assert "FormatterWarning" not in captured.stderr
432
433
434 def test_format_config():
435 """config objects don't pretend to support fancy reprs with lazy attrs"""
436 f = HTMLFormatter()
437 cfg = Config()
438 with capture_output() as captured:
439 result = f(cfg)
440 assert result is None
441 assert captured.stderr == ""
442
443 with capture_output() as captured:
444 result = f(Config)
445 assert result is None
446 assert captured.stderr == ""
447
448
449 def test_pretty_max_seq_length():
450 f = PlainTextFormatter(max_seq_length=1)
451 lis = list(range(3))
452 text = f(lis)
453 assert text == "[0, ...]"
454 f.max_seq_length = 0
455 text = f(lis)
456 assert text == "[0, 1, 2]"
457 text = f(list(range(1024)))
458 lines = text.splitlines()
459 assert len(lines) == 1024
460
461
462 def test_ipython_display_formatter():
463 """Objects with _ipython_display_ defined bypass other formatters"""
464 f = get_ipython().display_formatter
465 catcher = []
466
467 class SelfDisplaying(object):
468 def _ipython_display_(self):
469 catcher.append(self)
470
471 class NotSelfDisplaying(object):
472 def __repr__(self):
473 return "NotSelfDisplaying"
474
475 def _ipython_display_(self):
476 raise NotImplementedError
477
478 save_enabled = f.ipython_display_formatter.enabled
479 f.ipython_display_formatter.enabled = True
480
481 yes = SelfDisplaying()
482 no = NotSelfDisplaying()
483
484 d, md = f.format(no)
485 assert d == {"text/plain": repr(no)}
486 assert md == {}
487 assert catcher == []
488
489 d, md = f.format(yes)
490 assert d == {}
491 assert md == {}
492 assert catcher == [yes]
493
494 f.ipython_display_formatter.enabled = save_enabled
495
496
497 def test_repr_mime():
498 class HasReprMime(object):
499 def _repr_mimebundle_(self, include=None, exclude=None):
500 return {
501 "application/json+test.v2": {"x": "y"},
502 "plain/text": "<HasReprMime>",
503 "image/png": "i-overwrite",
504 }
505
506 def _repr_png_(self):
507 return "should-be-overwritten"
508
509 def _repr_html_(self):
510 return "<b>hi!</b>"
511
512 f = get_ipython().display_formatter
513 html_f = f.formatters["text/html"]
514 save_enabled = html_f.enabled
515 html_f.enabled = True
516 obj = HasReprMime()
517 d, md = f.format(obj)
518 html_f.enabled = save_enabled
519
520 assert sorted(d) == [
521 "application/json+test.v2",
522 "image/png",
523 "plain/text",
524 "text/html",
525 "text/plain",
526 ]
527 assert md == {}
528
529 d, md = f.format(obj, include={"image/png"})
530 assert list(d.keys()) == [
531 "image/png"
532 ], "Include should filter out even things from repr_mimebundle"
533
534 assert d["image/png"] == "i-overwrite", "_repr_mimebundle_ take precedence"
535
536
537 def test_pass_correct_include_exclude():
538 class Tester(object):
539 def __init__(self, include=None, exclude=None):
540 self.include = include
541 self.exclude = exclude
542
543 def _repr_mimebundle_(self, include, exclude, **kwargs):
544 if include and (include != self.include):
545 raise ValueError("include got modified: display() may be broken.")
546 if exclude and (exclude != self.exclude):
547 raise ValueError("exclude got modified: display() may be broken.")
548
549 return None
550
551 include = {"a", "b", "c"}
552 exclude = {"c", "e", "f"}
553
554 f = get_ipython().display_formatter
555 f.format(Tester(include=include, exclude=exclude), include=include, exclude=exclude)
556 f.format(Tester(exclude=exclude), exclude=exclude)
557 f.format(Tester(include=include), include=include)
558
559
560 def test_repr_mime_meta():
561 class HasReprMimeMeta(object):
562 def _repr_mimebundle_(self, include=None, exclude=None):
563 data = {
564 "image/png": "base64-image-data",
565 }
566 metadata = {
567 "image/png": {
568 "width": 5,
569 "height": 10,
570 }
571 }
572 return (data, metadata)
573
574 f = get_ipython().display_formatter
575 obj = HasReprMimeMeta()
576 d, md = f.format(obj)
577 assert sorted(d) == ["image/png", "text/plain"]
578 assert md == {
579 "image/png": {
580 "width": 5,
581 "height": 10,
582 }
583 }
584
585
586 def test_repr_mime_failure():
587 class BadReprMime(object):
588 def _repr_mimebundle_(self, include=None, exclude=None):
589 raise RuntimeError
590
591 f = get_ipython().display_formatter
592 obj = BadReprMime()
593 d, md = f.format(obj)
594 assert "text/plain" in d
595
596
597 def test_custom_repr_namedtuple_partialmethod():
598 from functools import partialmethod
599 from typing import NamedTuple
600
601 class Foo(NamedTuple):
602 ...
603
604 Foo.__repr__ = partialmethod(lambda obj: "Hello World")
605 foo = Foo()
606
607 f = PlainTextFormatter()
608 assert f.pprint
609 assert f(foo) == "Hello World"