Debian Codegraph @

tests/test_display_2.py

raw
1 # Copyright (c) IPython Development Team.
2 # Distributed under the terms of the Modified BSD License.
3
4 import json
5 import os
6 import warnings
7
8 from unittest import mock
9
10 import pytest
11
12 from IPython import display
13 from IPython.core.getipython import get_ipython
14 from IPython.utils.io import capture_output
15 from IPython.utils.tempdir import NamedFileInTemporaryDirectory
16 from IPython import paths as ipath
17 from IPython.testing.tools import AssertNotPrints
18
19 import IPython.testing.decorators as dec
20
21
22 def test_image_size():
23 """Simple test for display.Image(args, width=x,height=y)"""
24 thisurl = "http://www.google.fr/images/srpr/logo3w.png"
25 img = display.Image(url=thisurl, width=200, height=200)
26 assert '<img src="%s" width="200" height="200"/>' % (thisurl) == img._repr_html_()
27 img = display.Image(url=thisurl, metadata={"width": 200, "height": 200})
28 assert '<img src="%s" width="200" height="200"/>' % (thisurl) == img._repr_html_()
29 img = display.Image(url=thisurl, width=200)
30 assert '<img src="%s" width="200"/>' % (thisurl) == img._repr_html_()
31 img = display.Image(url=thisurl)
32 assert '<img src="%s"/>' % (thisurl) == img._repr_html_()
33 img = display.Image(url=thisurl, unconfined=True)
34 assert '<img src="%s" class="unconfined"/>' % (thisurl) == img._repr_html_()
35
36
37 def test_image_mimes():
38 fmt = get_ipython().display_formatter.format
39 for format in display.Image._ACCEPTABLE_EMBEDDINGS:
40 mime = display.Image._MIMETYPES[format]
41 img = display.Image(b"garbage", format=format)
42 data, metadata = fmt(img)
43 assert sorted(data) == sorted([mime, "text/plain"])
44
45
46 def test_geojson():
47 gj = display.GeoJSON(
48 data={
49 "type": "Feature",
50 "geometry": {"type": "Point", "coordinates": [-81.327, 296.038]},
51 "properties": {"name": "Inca City"},
52 },
53 url_template="http://s3-eu-west-1.amazonaws.com/whereonmars.cartodb.net/{basemap_id}/{z}/{x}/{y}.png",
54 layer_options={
55 "basemap_id": "celestia_mars-shaded-16k_global",
56 "attribution": "Celestia/praesepe",
57 "minZoom": 0,
58 "maxZoom": 18,
59 },
60 )
61 assert "<IPython.core.display.GeoJSON object>" == str(gj)
62
63
64 def test_retina_png():
65 here = os.path.dirname(__file__)
66 img = display.Image(os.path.join(here, "2x2.png"), retina=True)
67 assert img.height == 1
68 assert img.width == 1
69 data, md = img._repr_png_()
70 assert md["width"] == 1
71 assert md["height"] == 1
72
73
74 def test_embed_svg_url():
75 import gzip
76 from io import BytesIO
77
78 svg_data = b'<svg><circle x="0" y="0" r="1"/></svg>'
79 url = "http://test.com/circle.svg"
80
81 gzip_svg = BytesIO()
82 with gzip.open(gzip_svg, "wb") as fp:
83 fp.write(svg_data)
84 gzip_svg = gzip_svg.getvalue()
85
86 def mocked_urlopen(*args, **kwargs):
87 class MockResponse:
88 def __init__(self, svg):
89 self._svg_data = svg
90 self.headers = {"content-type": "image/svg+xml"}
91
92 def read(self):
93 return self._svg_data
94
95 if args[0] == url:
96 return MockResponse(svg_data)
97 elif args[0] == url + "z":
98 ret = MockResponse(gzip_svg)
99 ret.headers["content-encoding"] = "gzip"
100 return ret
101 return MockResponse(None)
102
103 with mock.patch("urllib.request.urlopen", side_effect=mocked_urlopen):
104 svg = display.SVG(url=url)
105 assert svg._repr_svg_().startswith("<svg") is True
106 svg = display.SVG(url=url + "z")
107 assert svg._repr_svg_().startswith("<svg") is True
108
109
110 def test_retina_jpeg():
111 here = os.path.dirname(__file__)
112 img = display.Image(os.path.join(here, "2x2.jpg"), retina=True)
113 assert img.height == 1
114 assert img.width == 1
115 data, md = img._repr_jpeg_()
116 assert md["width"] == 1
117 assert md["height"] == 1
118
119
120 def test_base64image():
121 display.Image(
122 "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAACnej3aAAAAAWJLR0QAiAUdSAAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB94BCRQnOqNu0b4AAAAKSURBVAjXY2AAAAACAAHiIbwzAAAAAElFTkSuQmCC"
123 )
124
125
126 def test_image_filename_defaults():
127 """test format constraint, and validity of jpeg and png"""
128 tpath = ipath.get_ipython_package_dir()
129 pytest.raises(
130 ValueError,
131 display.Image,
132 filename=os.path.join(tpath, "testing/tests/badformat.zip"),
133 embed=True,
134 )
135 pytest.raises(ValueError, display.Image)
136 pytest.raises(
137 ValueError,
138 display.Image,
139 data="this is not an image",
140 format="badformat",
141 embed=True,
142 )
143
144
145 def _get_inline_config():
146 from matplotlib_inline.config import InlineBackend
147
148 return InlineBackend.instance()
149
150
151 @dec.skip_without("matplotlib")
152 def test_set_matplotlib_close():
153 from matplotlib_inline.backend_inline import set_matplotlib_close
154
155 cfg = _get_inline_config()
156 cfg.close_figures = False
157
158 set_matplotlib_close()
159 assert cfg.close_figures
160 set_matplotlib_close(False)
161 assert not cfg.close_figures
162
163
164 _fmt_mime_map = {
165 "png": "image/png",
166 "jpeg": "image/jpeg",
167 "pdf": "application/pdf",
168 "retina": "image/png",
169 "svg": "image/svg+xml",
170 }
171
172
173 @dec.skip_without("matplotlib")
174 def test_set_matplotlib_formats():
175 from matplotlib.figure import Figure
176 from matplotlib_inline.backend_inline import set_matplotlib_formats
177
178 formatters = get_ipython().display_formatter.formatters
179 for formats in [
180 ("png",),
181 ("pdf", "svg"),
182 ("jpeg", "retina", "png"),
183 (),
184 ]:
185 active_mimes = {_fmt_mime_map[fmt] for fmt in formats}
186 set_matplotlib_formats(*formats)
187 for mime, f in formatters.items():
188 if mime in active_mimes:
189 assert Figure in f
190 else:
191 assert Figure not in f
192
193
194 @dec.skip_without("matplotlib")
195 def test_set_matplotlib_formats_kwargs():
196 from matplotlib.figure import Figure
197 from matplotlib_inline.backend_inline import set_matplotlib_formats
198
199 ip = get_ipython()
200 cfg = _get_inline_config()
201 cfg.print_figure_kwargs.update(dict(foo="bar"))
202 kwargs = dict(dpi=150)
203 try:
204 set_matplotlib_formats("png", **kwargs)
205 formatter = ip.display_formatter.formatters["image/png"]
206 f = formatter.lookup_by_type(Figure)
207 formatter_kwargs = f.keywords
208 expected = kwargs
209 expected["base64"] = True
210 expected["fmt"] = "png"
211 expected.update(cfg.print_figure_kwargs)
212 assert formatter_kwargs == expected
213 finally:
214 cfg.print_figure_kwargs.clear()
215
216
217 @dec.skip_without("matplotlib")
218 def test_matplotlib_positioning():
219 _ip = get_ipython()
220
221 prev_active_types = _ip.display_formatter.active_types.copy()
222 prev_execution_count = _ip.execution_count
223 prev_user_ns_underscore = _ip.user_ns.get("_", None)
224
225 _ip.history_manager.reset()
226 _ip.display_formatter.active_types = ["text/plain", "image/png"]
227
228 _ip.run_cell("import matplotlib")
229 prev_mpl_backend = _ip.run_cell("matplotlib.get_backend()").result
230
231 try:
232 _ip.run_line_magic("matplotlib", "inline")
233 _ip.execution_count = 1
234 _ip.run_cell("'no plot here'", store_history=True)
235
236 # Cell 2: No manual flush
237 _ip.run_cell(
238 "import matplotlib.pyplot as plt;plt.plot([0, 1])", store_history=True
239 )
240
241 _ip.run_cell("'no plot here'", store_history=True)
242
243 # Cell 4: Manual flush
244 _ip.run_cell("plt.plot([1, 0])\nplt.show()", store_history=True)
245
246 _ip.run_cell("'no plot here'", store_history=True)
247
248 outputs = _ip.history_manager.outputs
249
250 # Only cells 2 and 4 should have plots
251 for cell_num in [1, 3, 5]:
252 assert not any(
253 "image/png" in out.bundle for out in outputs.get(cell_num, [])
254 ), f"Cell {cell_num} should not have plot"
255
256 cell_2_has_plot = any("image/png" in out.bundle for out in outputs.get(2, []))
257 cell_4_has_plot = any("image/png" in out.bundle for out in outputs.get(4, []))
258
259 assert cell_2_has_plot, "Cell 2 should have plot (auto-flush)"
260 assert cell_4_has_plot, "Cell 4 should have plot (manual flush)"
261
262 finally:
263 _ip.run_cell("plt.close('all')")
264 _ip.run_line_magic("matplotlib", prev_mpl_backend)
265 _ip.history_manager.reset()
266 _ip.display_formatter.active_types = prev_active_types
267 _ip.displayhook.flush()
268
269 _ip.execution_count = prev_execution_count
270 if prev_user_ns_underscore is not None:
271 _ip.user_ns["_"] = prev_user_ns_underscore
272 elif "_" in _ip.user_ns:
273 del _ip.user_ns["_"]
274
275
276 def test_display_available():
277 """
278 Test that display is available without import
279
280 We don't really care if it's in builtin or anything else, but it should
281 always be available.
282 """
283 ip = get_ipython()
284 with AssertNotPrints("NameError"):
285 ip.run_cell("display")
286 try:
287 ip.run_cell("del display")
288 except NameError:
289 pass # it's ok, it might be in builtins
290 # even if deleted it should be back
291 with AssertNotPrints("NameError"):
292 ip.run_cell("display")
293
294
295 def test_textdisplayobj_pretty_repr():
296 p = display.Pretty("This is a simple test")
297 assert repr(p) == "<IPython.core.display.Pretty object>"
298 assert p.data == "This is a simple test"
299
300 p._show_mem_addr = True
301 assert repr(p) == object.__repr__(p)
302
303
304 def test_displayobject_repr():
305 h = display.HTML("<br />")
306 assert repr(h) == "<IPython.core.display.HTML object>"
307 h._show_mem_addr = True
308 assert repr(h) == object.__repr__(h)
309 h._show_mem_addr = False
310 assert repr(h) == "<IPython.core.display.HTML object>"
311
312 j = display.Javascript("")
313 assert repr(j) == "<IPython.core.display.Javascript object>"
314 j._show_mem_addr = True
315 assert repr(j) == object.__repr__(j)
316 j._show_mem_addr = False
317 assert repr(j) == "<IPython.core.display.Javascript object>"
318
319
320 @mock.patch("warnings.warn")
321 def test_encourage_iframe_over_html(m_warn):
322 display.HTML()
323 m_warn.assert_not_called()
324
325 display.HTML("<br />")
326 m_warn.assert_not_called()
327
328 display.HTML(
329 '<html><p>Lots of content here</p><iframe src="http://a.com"></iframe>'
330 )
331 m_warn.assert_not_called()
332
333 display.HTML('<iframe src="http://a.com"></iframe>')
334 m_warn.assert_called_with("Consider using IPython.display.IFrame instead")
335
336 m_warn.reset_mock()
337 display.HTML('<IFRAME SRC="http://a.com"></IFRAME>')
338 m_warn.assert_called_with("Consider using IPython.display.IFrame instead")
339
340
341 def test_progress():
342 p = display.ProgressBar(10)
343 assert "0/10" in repr(p)
344 p.html_width = "100%"
345 p.progress = 5
346 assert (
347 p._repr_html_() == "<progress style='width:100%' max='10' value='5'></progress>"
348 )
349
350
351 def test_progress_iter():
352 with capture_output(display=False) as captured:
353 for i in display.ProgressBar(5):
354 out = captured.stdout
355 assert "{0}/5".format(i) in out
356 out = captured.stdout
357 assert "5/5" in out
358
359
360 def test_json():
361 d = {"a": 5}
362 lis = [d]
363 metadata = [
364 {"expanded": False, "root": "root"},
365 {"expanded": True, "root": "root"},
366 {"expanded": False, "root": "custom"},
367 {"expanded": True, "root": "custom"},
368 ]
369 json_objs = [
370 display.JSON(d),
371 display.JSON(d, expanded=True),
372 display.JSON(d, root="custom"),
373 display.JSON(d, expanded=True, root="custom"),
374 ]
375 for j, md in zip(json_objs, metadata):
376 assert j._repr_json_() == (d, md)
377
378 with warnings.catch_warnings(record=True) as w:
379 warnings.simplefilter("always")
380 j = display.JSON(json.dumps(d))
381 assert len(w) == 1
382 assert j._repr_json_() == (d, metadata[0])
383
384 json_objs = [
385 display.JSON(lis),
386 display.JSON(lis, expanded=True),
387 display.JSON(lis, root="custom"),
388 display.JSON(lis, expanded=True, root="custom"),
389 ]
390 for j, md in zip(json_objs, metadata):
391 assert j._repr_json_() == (lis, md)
392
393 with warnings.catch_warnings(record=True) as w:
394 warnings.simplefilter("always")
395 j = display.JSON(json.dumps(lis))
396 assert len(w) == 1
397 assert j._repr_json_() == (lis, metadata[0])
398
399
400 def test_video_embedding():
401 """use a tempfile, with dummy-data, to ensure that video embedding doesn't crash"""
402 v = display.Video("http://ignored")
403 assert not v.embed
404 html = v._repr_html_()
405 assert 'src="data:' not in html
406 assert 'src="http://ignored"' in html
407
408 with pytest.raises(ValueError):
409 v = display.Video(b"abc")
410
411 with NamedFileInTemporaryDirectory("test.mp4", "wb") as f:
412 f.write(b"abc")
413 f.close()
414
415 v = display.Video(f.name)
416 assert not v.embed
417 html = v._repr_html_()
418 assert 'src="data:' not in html
419
420 v = display.Video(f.name, embed=True)
421 html = v._repr_html_()
422 assert 'src="data:video/mp4;base64,YWJj"' in html
423
424 v = display.Video(f.name, embed=True, mimetype="video/other")
425 html = v._repr_html_()
426 assert 'src="data:video/other;base64,YWJj"' in html
427
428 v = display.Video(b"abc", embed=True, mimetype="video/mp4")
429 html = v._repr_html_()
430 assert 'src="data:video/mp4;base64,YWJj"' in html
431
432 v = display.Video("YWJj", embed=True, mimetype="video/xyz")
433 html = v._repr_html_()
434 assert 'src="data:video/xyz;base64,YWJj"' in html
435
436
437 def test_html_metadata():
438 s = "<h1>Test</h1>"
439 h = display.HTML(s, metadata={"isolated": True})
440 assert h._repr_html_() == (s, {"isolated": True})
441
442
443 def test_display_id():
444 ip = get_ipython()
445 with mock.patch.object(ip.display_pub, "publish") as pub:
446 handle = display.display("x")
447 assert handle is None
448 handle = display.display("y", display_id="secret")
449 assert isinstance(handle, display.DisplayHandle)
450 handle2 = display.display("z", display_id=True)
451 assert isinstance(handle2, display.DisplayHandle)
452 assert handle.display_id != handle2.display_id
453
454 assert pub.call_count == 3
455 args, kwargs = pub.call_args_list[0]
456 assert args == ()
457 assert kwargs == {
458 "data": {"text/plain": repr("x")},
459 "metadata": {},
460 }
461 args, kwargs = pub.call_args_list[1]
462 assert args == ()
463 assert kwargs == {
464 "data": {"text/plain": repr("y")},
465 "metadata": {},
466 "transient": {
467 "display_id": handle.display_id,
468 },
469 }
470 args, kwargs = pub.call_args_list[2]
471 assert args == ()
472 assert kwargs == {
473 "data": {"text/plain": repr("z")},
474 "metadata": {},
475 "transient": {
476 "display_id": handle2.display_id,
477 },
478 }
479
480
481 def test_update_display():
482 ip = get_ipython()
483 with mock.patch.object(ip.display_pub, "publish") as pub:
484 with pytest.raises(TypeError):
485 display.update_display("x")
486 display.update_display("x", display_id="1")
487 display.update_display("y", display_id="2")
488 args, kwargs = pub.call_args_list[0]
489 assert args == ()
490 assert kwargs == {
491 "data": {"text/plain": repr("x")},
492 "metadata": {},
493 "transient": {
494 "display_id": "1",
495 },
496 "update": True,
497 }
498 args, kwargs = pub.call_args_list[1]
499 assert args == ()
500 assert kwargs == {
501 "data": {"text/plain": repr("y")},
502 "metadata": {},
503 "transient": {
504 "display_id": "2",
505 },
506 "update": True,
507 }
508
509
510 def test_display_handle():
511 ip = get_ipython()
512 handle = display.DisplayHandle()
513 assert isinstance(handle.display_id, str)
514 handle = display.DisplayHandle("my-id")
515 assert handle.display_id == "my-id"
516 with mock.patch.object(ip.display_pub, "publish") as pub:
517 handle.display("x")
518 handle.update("y")
519
520 args, kwargs = pub.call_args_list[0]
521 assert args == ()
522 assert kwargs == {
523 "data": {"text/plain": repr("x")},
524 "metadata": {},
525 "transient": {
526 "display_id": handle.display_id,
527 },
528 }
529 args, kwargs = pub.call_args_list[1]
530 assert args == ()
531 assert kwargs == {
532 "data": {"text/plain": repr("y")},
533 "metadata": {},
534 "transient": {
535 "display_id": handle.display_id,
536 },
537 "update": True,
538 }
539
540
541 def test_image_alt_tag():
542 """Simple test for display.Image(args, alt=x,)"""
543 thisurl = "http://example.com/image.png"
544 img = display.Image(url=thisurl, alt="an image")
545 assert '<img src="%s" alt="an image"/>' % (thisurl) == img._repr_html_()
546 img = display.Image(url=thisurl, unconfined=True, alt="an image")
547 assert (
548 '<img src="%s" class="unconfined" alt="an image"/>' % (thisurl)
549 == img._repr_html_()
550 )
551 img = display.Image(url=thisurl, alt='>"& <')
552 assert '<img src="%s" alt="&gt;&quot;&amp; &lt;"/>' % (thisurl) == img._repr_html_()
553
554 img = display.Image(url=thisurl, metadata={"alt": "an image"})
555 assert img.alt == "an image"
556 here = os.path.dirname(__file__)
557 img = display.Image(os.path.join(here, "2x2.png"), alt="an image")
558 assert img.alt == "an image"
559 _, md = img._repr_png_()
560 assert md["alt"] == "an image"
561
562
563 def test_image_bad_filename_raises_proper_exception():
564 with pytest.raises(FileNotFoundError):
565 display.Image("/this/file/does/not/exist/")._repr_png_()