Show More
@@ -1,511 +1,515 b'' | |||
|
1 | 1 | # Copyright (c) IPython Development Team. |
|
2 | 2 | # Distributed under the terms of the Modified BSD License. |
|
3 | 3 | |
|
4 | 4 | import json |
|
5 | 5 | import os |
|
6 | 6 | import warnings |
|
7 | 7 | |
|
8 | 8 | from unittest import mock |
|
9 | 9 | |
|
10 | 10 | import pytest |
|
11 | 11 | |
|
12 | 12 | from IPython import display |
|
13 | 13 | from IPython.core.getipython import get_ipython |
|
14 | 14 | from IPython.utils.io import capture_output |
|
15 | 15 | from IPython.utils.tempdir import NamedFileInTemporaryDirectory |
|
16 | 16 | from IPython import paths as ipath |
|
17 | 17 | from IPython.testing.tools import AssertNotPrints |
|
18 | 18 | |
|
19 | 19 | import IPython.testing.decorators as dec |
|
20 | 20 | |
|
21 | 21 | def test_image_size(): |
|
22 | 22 | """Simple test for display.Image(args, width=x,height=y)""" |
|
23 | 23 | thisurl = 'http://www.google.fr/images/srpr/logo3w.png' |
|
24 | 24 | img = display.Image(url=thisurl, width=200, height=200) |
|
25 | 25 | assert '<img src="%s" width="200" height="200"/>' % (thisurl) == img._repr_html_() |
|
26 | 26 | img = display.Image(url=thisurl, metadata={'width':200, 'height':200}) |
|
27 | 27 | assert '<img src="%s" width="200" height="200"/>' % (thisurl) == img._repr_html_() |
|
28 | 28 | img = display.Image(url=thisurl, width=200) |
|
29 | 29 | assert '<img src="%s" width="200"/>' % (thisurl) == img._repr_html_() |
|
30 | 30 | img = display.Image(url=thisurl) |
|
31 | 31 | assert '<img src="%s"/>' % (thisurl) == img._repr_html_() |
|
32 | 32 | img = display.Image(url=thisurl, unconfined=True) |
|
33 | 33 | assert '<img src="%s" class="unconfined"/>' % (thisurl) == img._repr_html_() |
|
34 | 34 | |
|
35 | 35 | |
|
36 | 36 | def test_image_mimes(): |
|
37 | 37 | fmt = get_ipython().display_formatter.format |
|
38 | 38 | for format in display.Image._ACCEPTABLE_EMBEDDINGS: |
|
39 | 39 | mime = display.Image._MIMETYPES[format] |
|
40 | 40 | img = display.Image(b'garbage', format=format) |
|
41 | 41 | data, metadata = fmt(img) |
|
42 | 42 | assert sorted(data) == sorted([mime, "text/plain"]) |
|
43 | 43 | |
|
44 | 44 | |
|
45 | 45 | def test_geojson(): |
|
46 | 46 | |
|
47 | 47 | gj = display.GeoJSON(data={ |
|
48 | 48 | "type": "Feature", |
|
49 | 49 | "geometry": { |
|
50 | 50 | "type": "Point", |
|
51 | 51 | "coordinates": [-81.327, 296.038] |
|
52 | 52 | }, |
|
53 | 53 | "properties": { |
|
54 | 54 | "name": "Inca City" |
|
55 | 55 | } |
|
56 | 56 | }, |
|
57 | 57 | url_template="http://s3-eu-west-1.amazonaws.com/whereonmars.cartodb.net/{basemap_id}/{z}/{x}/{y}.png", |
|
58 | 58 | layer_options={ |
|
59 | 59 | "basemap_id": "celestia_mars-shaded-16k_global", |
|
60 | 60 | "attribution": "Celestia/praesepe", |
|
61 | 61 | "minZoom": 0, |
|
62 | 62 | "maxZoom": 18, |
|
63 | 63 | }, |
|
64 | 64 | ) |
|
65 | 65 | assert "<IPython.core.display.GeoJSON object>" == str(gj) |
|
66 | 66 | |
|
67 | 67 | |
|
68 | 68 | def test_retina_png(): |
|
69 | 69 | here = os.path.dirname(__file__) |
|
70 | 70 | img = display.Image(os.path.join(here, "2x2.png"), retina=True) |
|
71 | 71 | assert img.height == 1 |
|
72 | 72 | assert img.width == 1 |
|
73 | 73 | data, md = img._repr_png_() |
|
74 | 74 | assert md["width"] == 1 |
|
75 | 75 | assert md["height"] == 1 |
|
76 | 76 | |
|
77 | 77 | |
|
78 | 78 | def test_embed_svg_url(): |
|
79 | 79 | import gzip |
|
80 | 80 | from io import BytesIO |
|
81 | 81 | svg_data = b'<svg><circle x="0" y="0" r="1"/></svg>' |
|
82 | 82 | url = 'http://test.com/circle.svg' |
|
83 | 83 | |
|
84 | 84 | gzip_svg = BytesIO() |
|
85 | 85 | with gzip.open(gzip_svg, 'wb') as fp: |
|
86 | 86 | fp.write(svg_data) |
|
87 | 87 | gzip_svg = gzip_svg.getvalue() |
|
88 | 88 | |
|
89 | 89 | def mocked_urlopen(*args, **kwargs): |
|
90 | 90 | class MockResponse: |
|
91 | 91 | def __init__(self, svg): |
|
92 | 92 | self._svg_data = svg |
|
93 | 93 | self.headers = {'content-type': 'image/svg+xml'} |
|
94 | 94 | |
|
95 | 95 | def read(self): |
|
96 | 96 | return self._svg_data |
|
97 | 97 | |
|
98 | 98 | if args[0] == url: |
|
99 | 99 | return MockResponse(svg_data) |
|
100 | 100 | elif args[0] == url + "z": |
|
101 | 101 | ret = MockResponse(gzip_svg) |
|
102 | 102 | ret.headers["content-encoding"] = "gzip" |
|
103 | 103 | return ret |
|
104 | 104 | return MockResponse(None) |
|
105 | 105 | |
|
106 | 106 | with mock.patch('urllib.request.urlopen', side_effect=mocked_urlopen): |
|
107 | 107 | svg = display.SVG(url=url) |
|
108 | 108 | assert svg._repr_svg_().startswith("<svg") is True |
|
109 | 109 | svg = display.SVG(url=url + "z") |
|
110 | 110 | assert svg._repr_svg_().startswith("<svg") is True |
|
111 | 111 | |
|
112 | 112 | |
|
113 | 113 | def test_retina_jpeg(): |
|
114 | 114 | here = os.path.dirname(__file__) |
|
115 | 115 | img = display.Image(os.path.join(here, "2x2.jpg"), retina=True) |
|
116 | 116 | assert img.height == 1 |
|
117 | 117 | assert img.width == 1 |
|
118 | 118 | data, md = img._repr_jpeg_() |
|
119 | 119 | assert md["width"] == 1 |
|
120 | 120 | assert md["height"] == 1 |
|
121 | 121 | |
|
122 | 122 | |
|
123 | 123 | def test_base64image(): |
|
124 | 124 | display.Image("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAACnej3aAAAAAWJLR0QAiAUdSAAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB94BCRQnOqNu0b4AAAAKSURBVAjXY2AAAAACAAHiIbwzAAAAAElFTkSuQmCC") |
|
125 | 125 | |
|
126 | 126 | def test_image_filename_defaults(): |
|
127 | 127 | '''test format constraint, and validity of jpeg and png''' |
|
128 | 128 | tpath = ipath.get_ipython_package_dir() |
|
129 | 129 | pytest.raises( |
|
130 | 130 | ValueError, |
|
131 | 131 | display.Image, |
|
132 | 132 | filename=os.path.join(tpath, "testing/tests/badformat.zip"), |
|
133 | 133 | embed=True, |
|
134 | 134 | ) |
|
135 | 135 | pytest.raises(ValueError, display.Image) |
|
136 | 136 | pytest.raises( |
|
137 | 137 | ValueError, |
|
138 | 138 | display.Image, |
|
139 | 139 | data="this is not an image", |
|
140 | 140 | format="badformat", |
|
141 | 141 | embed=True, |
|
142 | 142 | ) |
|
143 | 143 | # check boths paths to allow packages to test at build and install time |
|
144 | 144 | imgfile = os.path.join(tpath, 'core/tests/2x2.png') |
|
145 | 145 | img = display.Image(filename=imgfile) |
|
146 | 146 | assert "png" == img.format |
|
147 | 147 | assert img._repr_png_() is not None |
|
148 | 148 | img = display.Image( |
|
149 | 149 | filename=os.path.join(tpath, "testing/tests/logo.jpg"), embed=False |
|
150 | 150 | ) |
|
151 | 151 | assert "jpeg" == img.format |
|
152 | 152 | assert img._repr_jpeg_() is None |
|
153 | 153 | |
|
154 | 154 | def _get_inline_config(): |
|
155 | 155 | from matplotlib_inline.config import InlineBackend |
|
156 | 156 | return InlineBackend.instance() |
|
157 | 157 | |
|
158 | 158 | |
|
159 | 159 | @dec.skip_without("ipykernel") |
|
160 | 160 | @dec.skip_without("matplotlib") |
|
161 | 161 | def test_set_matplotlib_close(): |
|
162 | 162 | cfg = _get_inline_config() |
|
163 | 163 | cfg.close_figures = False |
|
164 | display.set_matplotlib_close() | |
|
164 | with pytest.deprecated_call(): | |
|
165 | display.set_matplotlib_close() | |
|
165 | 166 | assert cfg.close_figures |
|
166 | display.set_matplotlib_close(False) | |
|
167 | with pytest.deprecated_call(): | |
|
168 | display.set_matplotlib_close(False) | |
|
167 | 169 | assert not cfg.close_figures |
|
168 | 170 | |
|
169 | 171 | _fmt_mime_map = { |
|
170 | 172 | 'png': 'image/png', |
|
171 | 173 | 'jpeg': 'image/jpeg', |
|
172 | 174 | 'pdf': 'application/pdf', |
|
173 | 175 | 'retina': 'image/png', |
|
174 | 176 | 'svg': 'image/svg+xml', |
|
175 | 177 | } |
|
176 | 178 | |
|
177 | 179 | @dec.skip_without('matplotlib') |
|
178 | 180 | def test_set_matplotlib_formats(): |
|
179 | 181 | from matplotlib.figure import Figure |
|
180 | 182 | formatters = get_ipython().display_formatter.formatters |
|
181 | 183 | for formats in [ |
|
182 | 184 | ('png',), |
|
183 | 185 | ('pdf', 'svg'), |
|
184 | 186 | ('jpeg', 'retina', 'png'), |
|
185 | 187 | (), |
|
186 | 188 | ]: |
|
187 | 189 | active_mimes = {_fmt_mime_map[fmt] for fmt in formats} |
|
188 | display.set_matplotlib_formats(*formats) | |
|
190 | with pytest.deprecated_call(): | |
|
191 | display.set_matplotlib_formats(*formats) | |
|
189 | 192 | for mime, f in formatters.items(): |
|
190 | 193 | if mime in active_mimes: |
|
191 | 194 | assert Figure in f |
|
192 | 195 | else: |
|
193 | 196 | assert Figure not in f |
|
194 | 197 | |
|
195 | 198 | |
|
196 | 199 | @dec.skip_without("ipykernel") |
|
197 | 200 | @dec.skip_without("matplotlib") |
|
198 | 201 | def test_set_matplotlib_formats_kwargs(): |
|
199 | 202 | from matplotlib.figure import Figure |
|
200 | 203 | ip = get_ipython() |
|
201 | 204 | cfg = _get_inline_config() |
|
202 | 205 | cfg.print_figure_kwargs.update(dict(foo='bar')) |
|
203 | 206 | kwargs = dict(dpi=150) |
|
204 | display.set_matplotlib_formats('png', **kwargs) | |
|
205 | formatter = ip.display_formatter.formatters['image/png'] | |
|
207 | with pytest.deprecated_call(): | |
|
208 | display.set_matplotlib_formats("png", **kwargs) | |
|
209 | formatter = ip.display_formatter.formatters["image/png"] | |
|
206 | 210 | f = formatter.lookup_by_type(Figure) |
|
207 | 211 | formatter_kwargs = f.keywords |
|
208 | 212 | expected = kwargs |
|
209 | 213 | expected["base64"] = True |
|
210 | 214 | expected["fmt"] = "png" |
|
211 | 215 | expected.update(cfg.print_figure_kwargs) |
|
212 | 216 | assert formatter_kwargs == expected |
|
213 | 217 | |
|
214 | 218 | def test_display_available(): |
|
215 | 219 | """ |
|
216 | 220 | Test that display is available without import |
|
217 | 221 | |
|
218 | 222 | We don't really care if it's in builtin or anything else, but it should |
|
219 | 223 | always be available. |
|
220 | 224 | """ |
|
221 | 225 | ip = get_ipython() |
|
222 | 226 | with AssertNotPrints('NameError'): |
|
223 | 227 | ip.run_cell('display') |
|
224 | 228 | try: |
|
225 | 229 | ip.run_cell('del display') |
|
226 | 230 | except NameError: |
|
227 | 231 | pass # it's ok, it might be in builtins |
|
228 | 232 | # even if deleted it should be back |
|
229 | 233 | with AssertNotPrints('NameError'): |
|
230 | 234 | ip.run_cell('display') |
|
231 | 235 | |
|
232 | 236 | def test_textdisplayobj_pretty_repr(): |
|
233 | 237 | p = display.Pretty("This is a simple test") |
|
234 | 238 | assert repr(p) == "<IPython.core.display.Pretty object>" |
|
235 | 239 | assert p.data == "This is a simple test" |
|
236 | 240 | |
|
237 | 241 | p._show_mem_addr = True |
|
238 | 242 | assert repr(p) == object.__repr__(p) |
|
239 | 243 | |
|
240 | 244 | |
|
241 | 245 | def test_displayobject_repr(): |
|
242 | 246 | h = display.HTML("<br />") |
|
243 | 247 | assert repr(h) == "<IPython.core.display.HTML object>" |
|
244 | 248 | h._show_mem_addr = True |
|
245 | 249 | assert repr(h) == object.__repr__(h) |
|
246 | 250 | h._show_mem_addr = False |
|
247 | 251 | assert repr(h) == "<IPython.core.display.HTML object>" |
|
248 | 252 | |
|
249 | 253 | j = display.Javascript("") |
|
250 | 254 | assert repr(j) == "<IPython.core.display.Javascript object>" |
|
251 | 255 | j._show_mem_addr = True |
|
252 | 256 | assert repr(j) == object.__repr__(j) |
|
253 | 257 | j._show_mem_addr = False |
|
254 | 258 | assert repr(j) == "<IPython.core.display.Javascript object>" |
|
255 | 259 | |
|
256 | 260 | @mock.patch('warnings.warn') |
|
257 | 261 | def test_encourage_iframe_over_html(m_warn): |
|
258 | 262 | display.HTML() |
|
259 | 263 | m_warn.assert_not_called() |
|
260 | 264 | |
|
261 | 265 | display.HTML('<br />') |
|
262 | 266 | m_warn.assert_not_called() |
|
263 | 267 | |
|
264 | 268 | display.HTML('<html><p>Lots of content here</p><iframe src="http://a.com"></iframe>') |
|
265 | 269 | m_warn.assert_not_called() |
|
266 | 270 | |
|
267 | 271 | display.HTML('<iframe src="http://a.com"></iframe>') |
|
268 | 272 | m_warn.assert_called_with('Consider using IPython.display.IFrame instead') |
|
269 | 273 | |
|
270 | 274 | m_warn.reset_mock() |
|
271 | 275 | display.HTML('<IFRAME SRC="http://a.com"></IFRAME>') |
|
272 | 276 | m_warn.assert_called_with('Consider using IPython.display.IFrame instead') |
|
273 | 277 | |
|
274 | 278 | def test_progress(): |
|
275 | 279 | p = display.ProgressBar(10) |
|
276 | 280 | assert "0/10" in repr(p) |
|
277 | 281 | p.html_width = "100%" |
|
278 | 282 | p.progress = 5 |
|
279 | 283 | assert ( |
|
280 | 284 | p._repr_html_() == "<progress style='width:100%' max='10' value='5'></progress>" |
|
281 | 285 | ) |
|
282 | 286 | |
|
283 | 287 | |
|
284 | 288 | def test_progress_iter(): |
|
285 | 289 | with capture_output(display=False) as captured: |
|
286 | 290 | for i in display.ProgressBar(5): |
|
287 | 291 | out = captured.stdout |
|
288 | 292 | assert "{0}/5".format(i) in out |
|
289 | 293 | out = captured.stdout |
|
290 | 294 | assert "5/5" in out |
|
291 | 295 | |
|
292 | 296 | |
|
293 | 297 | def test_json(): |
|
294 | 298 | d = {'a': 5} |
|
295 | 299 | lis = [d] |
|
296 | 300 | metadata = [ |
|
297 | 301 | {'expanded': False, 'root': 'root'}, |
|
298 | 302 | {'expanded': True, 'root': 'root'}, |
|
299 | 303 | {'expanded': False, 'root': 'custom'}, |
|
300 | 304 | {'expanded': True, 'root': 'custom'}, |
|
301 | 305 | ] |
|
302 | 306 | json_objs = [ |
|
303 | 307 | display.JSON(d), |
|
304 | 308 | display.JSON(d, expanded=True), |
|
305 | 309 | display.JSON(d, root='custom'), |
|
306 | 310 | display.JSON(d, expanded=True, root='custom'), |
|
307 | 311 | ] |
|
308 | 312 | for j, md in zip(json_objs, metadata): |
|
309 | 313 | assert j._repr_json_() == (d, md) |
|
310 | 314 | |
|
311 | 315 | with warnings.catch_warnings(record=True) as w: |
|
312 | 316 | warnings.simplefilter("always") |
|
313 | 317 | j = display.JSON(json.dumps(d)) |
|
314 | 318 | assert len(w) == 1 |
|
315 | 319 | assert j._repr_json_() == (d, metadata[0]) |
|
316 | 320 | |
|
317 | 321 | json_objs = [ |
|
318 | 322 | display.JSON(lis), |
|
319 | 323 | display.JSON(lis, expanded=True), |
|
320 | 324 | display.JSON(lis, root='custom'), |
|
321 | 325 | display.JSON(lis, expanded=True, root='custom'), |
|
322 | 326 | ] |
|
323 | 327 | for j, md in zip(json_objs, metadata): |
|
324 | 328 | assert j._repr_json_() == (lis, md) |
|
325 | 329 | |
|
326 | 330 | with warnings.catch_warnings(record=True) as w: |
|
327 | 331 | warnings.simplefilter("always") |
|
328 | 332 | j = display.JSON(json.dumps(lis)) |
|
329 | 333 | assert len(w) == 1 |
|
330 | 334 | assert j._repr_json_() == (lis, metadata[0]) |
|
331 | 335 | |
|
332 | 336 | |
|
333 | 337 | def test_video_embedding(): |
|
334 | 338 | """use a tempfile, with dummy-data, to ensure that video embedding doesn't crash""" |
|
335 | 339 | v = display.Video("http://ignored") |
|
336 | 340 | assert not v.embed |
|
337 | 341 | html = v._repr_html_() |
|
338 | 342 | assert 'src="data:' not in html |
|
339 | 343 | assert 'src="http://ignored"' in html |
|
340 | 344 | |
|
341 | 345 | with pytest.raises(ValueError): |
|
342 | 346 | v = display.Video(b'abc') |
|
343 | 347 | |
|
344 | 348 | with NamedFileInTemporaryDirectory('test.mp4') as f: |
|
345 | 349 | f.write(b'abc') |
|
346 | 350 | f.close() |
|
347 | 351 | |
|
348 | 352 | v = display.Video(f.name) |
|
349 | 353 | assert not v.embed |
|
350 | 354 | html = v._repr_html_() |
|
351 | 355 | assert 'src="data:' not in html |
|
352 | 356 | |
|
353 | 357 | v = display.Video(f.name, embed=True) |
|
354 | 358 | html = v._repr_html_() |
|
355 | 359 | assert 'src="data:video/mp4;base64,YWJj"' in html |
|
356 | 360 | |
|
357 | 361 | v = display.Video(f.name, embed=True, mimetype='video/other') |
|
358 | 362 | html = v._repr_html_() |
|
359 | 363 | assert 'src="data:video/other;base64,YWJj"' in html |
|
360 | 364 | |
|
361 | 365 | v = display.Video(b'abc', embed=True, mimetype='video/mp4') |
|
362 | 366 | html = v._repr_html_() |
|
363 | 367 | assert 'src="data:video/mp4;base64,YWJj"' in html |
|
364 | 368 | |
|
365 | 369 | v = display.Video(u'YWJj', embed=True, mimetype='video/xyz') |
|
366 | 370 | html = v._repr_html_() |
|
367 | 371 | assert 'src="data:video/xyz;base64,YWJj"' in html |
|
368 | 372 | |
|
369 | 373 | def test_html_metadata(): |
|
370 | 374 | s = "<h1>Test</h1>" |
|
371 | 375 | h = display.HTML(s, metadata={"isolated": True}) |
|
372 | 376 | assert h._repr_html_() == (s, {"isolated": True}) |
|
373 | 377 | |
|
374 | 378 | |
|
375 | 379 | def test_display_id(): |
|
376 | 380 | ip = get_ipython() |
|
377 | 381 | with mock.patch.object(ip.display_pub, 'publish') as pub: |
|
378 | 382 | handle = display.display('x') |
|
379 | 383 | assert handle is None |
|
380 | 384 | handle = display.display('y', display_id='secret') |
|
381 | 385 | assert isinstance(handle, display.DisplayHandle) |
|
382 | 386 | handle2 = display.display('z', display_id=True) |
|
383 | 387 | assert isinstance(handle2, display.DisplayHandle) |
|
384 | 388 | assert handle.display_id != handle2.display_id |
|
385 | 389 | |
|
386 | 390 | assert pub.call_count == 3 |
|
387 | 391 | args, kwargs = pub.call_args_list[0] |
|
388 | 392 | assert args == () |
|
389 | 393 | assert kwargs == { |
|
390 | 394 | 'data': { |
|
391 | 395 | 'text/plain': repr('x') |
|
392 | 396 | }, |
|
393 | 397 | 'metadata': {}, |
|
394 | 398 | } |
|
395 | 399 | args, kwargs = pub.call_args_list[1] |
|
396 | 400 | assert args == () |
|
397 | 401 | assert kwargs == { |
|
398 | 402 | 'data': { |
|
399 | 403 | 'text/plain': repr('y') |
|
400 | 404 | }, |
|
401 | 405 | 'metadata': {}, |
|
402 | 406 | 'transient': { |
|
403 | 407 | 'display_id': handle.display_id, |
|
404 | 408 | }, |
|
405 | 409 | } |
|
406 | 410 | args, kwargs = pub.call_args_list[2] |
|
407 | 411 | assert args == () |
|
408 | 412 | assert kwargs == { |
|
409 | 413 | 'data': { |
|
410 | 414 | 'text/plain': repr('z') |
|
411 | 415 | }, |
|
412 | 416 | 'metadata': {}, |
|
413 | 417 | 'transient': { |
|
414 | 418 | 'display_id': handle2.display_id, |
|
415 | 419 | }, |
|
416 | 420 | } |
|
417 | 421 | |
|
418 | 422 | |
|
419 | 423 | def test_update_display(): |
|
420 | 424 | ip = get_ipython() |
|
421 | 425 | with mock.patch.object(ip.display_pub, 'publish') as pub: |
|
422 | 426 | with pytest.raises(TypeError): |
|
423 | 427 | display.update_display('x') |
|
424 | 428 | display.update_display('x', display_id='1') |
|
425 | 429 | display.update_display('y', display_id='2') |
|
426 | 430 | args, kwargs = pub.call_args_list[0] |
|
427 | 431 | assert args == () |
|
428 | 432 | assert kwargs == { |
|
429 | 433 | 'data': { |
|
430 | 434 | 'text/plain': repr('x') |
|
431 | 435 | }, |
|
432 | 436 | 'metadata': {}, |
|
433 | 437 | 'transient': { |
|
434 | 438 | 'display_id': '1', |
|
435 | 439 | }, |
|
436 | 440 | 'update': True, |
|
437 | 441 | } |
|
438 | 442 | args, kwargs = pub.call_args_list[1] |
|
439 | 443 | assert args == () |
|
440 | 444 | assert kwargs == { |
|
441 | 445 | 'data': { |
|
442 | 446 | 'text/plain': repr('y') |
|
443 | 447 | }, |
|
444 | 448 | 'metadata': {}, |
|
445 | 449 | 'transient': { |
|
446 | 450 | 'display_id': '2', |
|
447 | 451 | }, |
|
448 | 452 | 'update': True, |
|
449 | 453 | } |
|
450 | 454 | |
|
451 | 455 | |
|
452 | 456 | def test_display_handle(): |
|
453 | 457 | ip = get_ipython() |
|
454 | 458 | handle = display.DisplayHandle() |
|
455 | 459 | assert isinstance(handle.display_id, str) |
|
456 | 460 | handle = display.DisplayHandle("my-id") |
|
457 | 461 | assert handle.display_id == "my-id" |
|
458 | 462 | with mock.patch.object(ip.display_pub, "publish") as pub: |
|
459 | 463 | handle.display("x") |
|
460 | 464 | handle.update("y") |
|
461 | 465 | |
|
462 | 466 | args, kwargs = pub.call_args_list[0] |
|
463 | 467 | assert args == () |
|
464 | 468 | assert kwargs == { |
|
465 | 469 | 'data': { |
|
466 | 470 | 'text/plain': repr('x') |
|
467 | 471 | }, |
|
468 | 472 | 'metadata': {}, |
|
469 | 473 | 'transient': { |
|
470 | 474 | 'display_id': handle.display_id, |
|
471 | 475 | } |
|
472 | 476 | } |
|
473 | 477 | args, kwargs = pub.call_args_list[1] |
|
474 | 478 | assert args == () |
|
475 | 479 | assert kwargs == { |
|
476 | 480 | 'data': { |
|
477 | 481 | 'text/plain': repr('y') |
|
478 | 482 | }, |
|
479 | 483 | 'metadata': {}, |
|
480 | 484 | 'transient': { |
|
481 | 485 | 'display_id': handle.display_id, |
|
482 | 486 | }, |
|
483 | 487 | 'update': True, |
|
484 | 488 | } |
|
485 | 489 | |
|
486 | 490 | |
|
487 | 491 | def test_image_alt_tag(): |
|
488 | 492 | """Simple test for display.Image(args, alt=x,)""" |
|
489 | 493 | thisurl = "http://example.com/image.png" |
|
490 | 494 | img = display.Image(url=thisurl, alt="an image") |
|
491 | 495 | assert '<img src="%s" alt="an image"/>' % (thisurl) == img._repr_html_() |
|
492 | 496 | img = display.Image(url=thisurl, unconfined=True, alt="an image") |
|
493 | 497 | assert ( |
|
494 | 498 | '<img src="%s" class="unconfined" alt="an image"/>' % (thisurl) |
|
495 | 499 | == img._repr_html_() |
|
496 | 500 | ) |
|
497 | 501 | img = display.Image(url=thisurl, alt='>"& <') |
|
498 | 502 | assert '<img src="%s" alt=">"& <"/>' % (thisurl) == img._repr_html_() |
|
499 | 503 | |
|
500 | 504 | img = display.Image(url=thisurl, metadata={"alt": "an image"}) |
|
501 | 505 | assert img.alt == "an image" |
|
502 | 506 | here = os.path.dirname(__file__) |
|
503 | 507 | img = display.Image(os.path.join(here, "2x2.png"), alt="an image") |
|
504 | 508 | assert img.alt == "an image" |
|
505 | 509 | _, md = img._repr_png_() |
|
506 | 510 | assert md["alt"] == "an image" |
|
507 | 511 | |
|
508 | 512 | |
|
509 | 513 | def test_image_bad_filename_raises_proper_exception(): |
|
510 | 514 | with pytest.raises(FileNotFoundError): |
|
511 | 515 | display.Image("/this/file/does/not/exist/")._repr_png_() |
@@ -1,274 +1,274 b'' | |||
|
1 | 1 | """Tests for pylab tools module. |
|
2 | 2 | """ |
|
3 | 3 | |
|
4 | 4 | # Copyright (c) IPython Development Team. |
|
5 | 5 | # Distributed under the terms of the Modified BSD License. |
|
6 | 6 | |
|
7 | 7 | |
|
8 | 8 | from binascii import a2b_base64 |
|
9 | 9 | from io import BytesIO |
|
10 | 10 | |
|
11 | 11 | import pytest |
|
12 | 12 | |
|
13 | 13 | matplotlib = pytest.importorskip("matplotlib") |
|
14 | 14 | matplotlib.use('Agg') |
|
15 | 15 | from matplotlib.figure import Figure |
|
16 | 16 | |
|
17 | 17 | from matplotlib import pyplot as plt |
|
18 | 18 | from matplotlib_inline import backend_inline |
|
19 | 19 | import numpy as np |
|
20 | 20 | |
|
21 | 21 | from IPython.core.getipython import get_ipython |
|
22 | 22 | from IPython.core.interactiveshell import InteractiveShell |
|
23 | 23 | from IPython.core.display import _PNG, _JPEG |
|
24 | 24 | from .. import pylabtools as pt |
|
25 | 25 | |
|
26 | 26 | from IPython.testing import decorators as dec |
|
27 | 27 | |
|
28 | 28 | |
|
29 | 29 | def test_figure_to_svg(): |
|
30 | 30 | # simple empty-figure test |
|
31 | 31 | fig = plt.figure() |
|
32 | 32 | assert pt.print_figure(fig, "svg") is None |
|
33 | 33 | |
|
34 | 34 | plt.close('all') |
|
35 | 35 | |
|
36 | 36 | # simple check for at least svg-looking output |
|
37 | 37 | fig = plt.figure() |
|
38 | 38 | ax = fig.add_subplot(1,1,1) |
|
39 | 39 | ax.plot([1,2,3]) |
|
40 | 40 | plt.draw() |
|
41 | 41 | svg = pt.print_figure(fig, "svg")[:100].lower() |
|
42 | 42 | assert "doctype svg" in svg |
|
43 | 43 | |
|
44 | 44 | |
|
45 | 45 | def _check_pil_jpeg_bytes(): |
|
46 | 46 | """Skip if PIL can't write JPEGs to BytesIO objects""" |
|
47 | 47 | # PIL's JPEG plugin can't write to BytesIO objects |
|
48 | 48 | # Pillow fixes this |
|
49 | 49 | from PIL import Image |
|
50 | 50 | buf = BytesIO() |
|
51 | 51 | img = Image.new("RGB", (4,4)) |
|
52 | 52 | try: |
|
53 | 53 | img.save(buf, 'jpeg') |
|
54 | 54 | except Exception as e: |
|
55 | 55 | ename = e.__class__.__name__ |
|
56 | 56 | raise pytest.skip("PIL can't write JPEG to BytesIO: %s: %s" % (ename, e)) from e |
|
57 | 57 | |
|
58 | 58 | @dec.skip_without("PIL.Image") |
|
59 | 59 | def test_figure_to_jpeg(): |
|
60 | 60 | _check_pil_jpeg_bytes() |
|
61 | 61 | # simple check for at least jpeg-looking output |
|
62 | 62 | fig = plt.figure() |
|
63 | 63 | ax = fig.add_subplot(1,1,1) |
|
64 | 64 | ax.plot([1,2,3]) |
|
65 | 65 | plt.draw() |
|
66 | 66 | jpeg = pt.print_figure(fig, 'jpeg', pil_kwargs={'optimize': 50})[:100].lower() |
|
67 | 67 | assert jpeg.startswith(_JPEG) |
|
68 | 68 | |
|
69 | 69 | def test_retina_figure(): |
|
70 | 70 | # simple empty-figure test |
|
71 | 71 | fig = plt.figure() |
|
72 | 72 | assert pt.retina_figure(fig) == None |
|
73 | 73 | plt.close('all') |
|
74 | 74 | |
|
75 | 75 | fig = plt.figure() |
|
76 | 76 | ax = fig.add_subplot(1,1,1) |
|
77 | 77 | ax.plot([1,2,3]) |
|
78 | 78 | plt.draw() |
|
79 | 79 | png, md = pt.retina_figure(fig) |
|
80 | 80 | assert png.startswith(_PNG) |
|
81 | 81 | assert "width" in md |
|
82 | 82 | assert "height" in md |
|
83 | 83 | |
|
84 | 84 | |
|
85 | 85 | _fmt_mime_map = { |
|
86 | 86 | 'png': 'image/png', |
|
87 | 87 | 'jpeg': 'image/jpeg', |
|
88 | 88 | 'pdf': 'application/pdf', |
|
89 | 89 | 'retina': 'image/png', |
|
90 | 90 | 'svg': 'image/svg+xml', |
|
91 | 91 | } |
|
92 | 92 | |
|
93 | 93 | def test_select_figure_formats_str(): |
|
94 | 94 | ip = get_ipython() |
|
95 | 95 | for fmt, active_mime in _fmt_mime_map.items(): |
|
96 | 96 | pt.select_figure_formats(ip, fmt) |
|
97 | 97 | for mime, f in ip.display_formatter.formatters.items(): |
|
98 | 98 | if mime == active_mime: |
|
99 | 99 | assert Figure in f |
|
100 | 100 | else: |
|
101 | 101 | assert Figure not in f |
|
102 | 102 | |
|
103 | 103 | def test_select_figure_formats_kwargs(): |
|
104 | 104 | ip = get_ipython() |
|
105 |
kwargs = dict( |
|
|
106 |
pt.select_figure_formats(ip, |
|
|
107 |
formatter = ip.display_formatter.formatters[ |
|
|
105 | kwargs = dict(bbox_inches="tight") | |
|
106 | pt.select_figure_formats(ip, "png", **kwargs) | |
|
107 | formatter = ip.display_formatter.formatters["image/png"] | |
|
108 | 108 | f = formatter.lookup_by_type(Figure) |
|
109 | 109 | cell = f.keywords |
|
110 | 110 | expected = kwargs |
|
111 | 111 | expected["base64"] = True |
|
112 | 112 | expected["fmt"] = "png" |
|
113 | 113 | assert cell == expected |
|
114 | 114 | |
|
115 | 115 | # check that the formatter doesn't raise |
|
116 | 116 | fig = plt.figure() |
|
117 | 117 | ax = fig.add_subplot(1,1,1) |
|
118 | 118 | ax.plot([1,2,3]) |
|
119 | 119 | plt.draw() |
|
120 | 120 | formatter.enabled = True |
|
121 | 121 | png = formatter(fig) |
|
122 | 122 | assert isinstance(png, str) |
|
123 | 123 | png_bytes = a2b_base64(png) |
|
124 | 124 | assert png_bytes.startswith(_PNG) |
|
125 | 125 | |
|
126 | 126 | def test_select_figure_formats_set(): |
|
127 | 127 | ip = get_ipython() |
|
128 | 128 | for fmts in [ |
|
129 | 129 | {'png', 'svg'}, |
|
130 | 130 | ['png'], |
|
131 | 131 | ('jpeg', 'pdf', 'retina'), |
|
132 | 132 | {'svg'}, |
|
133 | 133 | ]: |
|
134 | 134 | active_mimes = {_fmt_mime_map[fmt] for fmt in fmts} |
|
135 | 135 | pt.select_figure_formats(ip, fmts) |
|
136 | 136 | for mime, f in ip.display_formatter.formatters.items(): |
|
137 | 137 | if mime in active_mimes: |
|
138 | 138 | assert Figure in f |
|
139 | 139 | else: |
|
140 | 140 | assert Figure not in f |
|
141 | 141 | |
|
142 | 142 | def test_select_figure_formats_bad(): |
|
143 | 143 | ip = get_ipython() |
|
144 | 144 | with pytest.raises(ValueError): |
|
145 | 145 | pt.select_figure_formats(ip, 'foo') |
|
146 | 146 | with pytest.raises(ValueError): |
|
147 | 147 | pt.select_figure_formats(ip, {'png', 'foo'}) |
|
148 | 148 | with pytest.raises(ValueError): |
|
149 | 149 | pt.select_figure_formats(ip, ['retina', 'pdf', 'bar', 'bad']) |
|
150 | 150 | |
|
151 | 151 | def test_import_pylab(): |
|
152 | 152 | ns = {} |
|
153 | 153 | pt.import_pylab(ns, import_all=False) |
|
154 | 154 | assert "plt" in ns |
|
155 | 155 | assert ns["np"] == np |
|
156 | 156 | |
|
157 | 157 | |
|
158 | 158 | from traitlets.config import Config |
|
159 | 159 | |
|
160 | 160 | |
|
161 | 161 | class TestPylabSwitch(object): |
|
162 | 162 | class Shell(InteractiveShell): |
|
163 | 163 | def init_history(self): |
|
164 | 164 | """Sets up the command history, and starts regular autosaves.""" |
|
165 | 165 | self.config.HistoryManager.hist_file = ":memory:" |
|
166 | 166 | super().init_history() |
|
167 | 167 | |
|
168 | 168 | def enable_gui(self, gui): |
|
169 | 169 | pass |
|
170 | 170 | |
|
171 | 171 | def setup(self): |
|
172 | 172 | import matplotlib |
|
173 | 173 | def act_mpl(backend): |
|
174 | 174 | matplotlib.rcParams['backend'] = backend |
|
175 | 175 | |
|
176 | 176 | # Save rcParams since they get modified |
|
177 | 177 | self._saved_rcParams = matplotlib.rcParams |
|
178 | 178 | self._saved_rcParamsOrig = matplotlib.rcParamsOrig |
|
179 | 179 | matplotlib.rcParams = dict(backend='Qt4Agg') |
|
180 | 180 | matplotlib.rcParamsOrig = dict(backend='Qt4Agg') |
|
181 | 181 | |
|
182 | 182 | # Mock out functions |
|
183 | 183 | self._save_am = pt.activate_matplotlib |
|
184 | 184 | pt.activate_matplotlib = act_mpl |
|
185 | 185 | self._save_ip = pt.import_pylab |
|
186 | 186 | pt.import_pylab = lambda *a,**kw:None |
|
187 | 187 | self._save_cis = backend_inline.configure_inline_support |
|
188 | 188 | backend_inline.configure_inline_support = lambda *a, **kw: None |
|
189 | 189 | |
|
190 | 190 | def teardown(self): |
|
191 | 191 | pt.activate_matplotlib = self._save_am |
|
192 | 192 | pt.import_pylab = self._save_ip |
|
193 | 193 | backend_inline.configure_inline_support = self._save_cis |
|
194 | 194 | import matplotlib |
|
195 | 195 | matplotlib.rcParams = self._saved_rcParams |
|
196 | 196 | matplotlib.rcParamsOrig = self._saved_rcParamsOrig |
|
197 | 197 | |
|
198 | 198 | def test_qt(self): |
|
199 | 199 | |
|
200 | 200 | s = self.Shell() |
|
201 | 201 | gui, backend = s.enable_matplotlib(None) |
|
202 | 202 | assert gui == "qt" |
|
203 | 203 | assert s.pylab_gui_select == "qt" |
|
204 | 204 | |
|
205 | 205 | gui, backend = s.enable_matplotlib("inline") |
|
206 | 206 | assert gui == "inline" |
|
207 | 207 | assert s.pylab_gui_select == "qt" |
|
208 | 208 | |
|
209 | 209 | gui, backend = s.enable_matplotlib("qt") |
|
210 | 210 | assert gui == "qt" |
|
211 | 211 | assert s.pylab_gui_select == "qt" |
|
212 | 212 | |
|
213 | 213 | gui, backend = s.enable_matplotlib("inline") |
|
214 | 214 | assert gui == "inline" |
|
215 | 215 | assert s.pylab_gui_select == "qt" |
|
216 | 216 | |
|
217 | 217 | gui, backend = s.enable_matplotlib() |
|
218 | 218 | assert gui == "qt" |
|
219 | 219 | assert s.pylab_gui_select == "qt" |
|
220 | 220 | |
|
221 | 221 | def test_inline(self): |
|
222 | 222 | s = self.Shell() |
|
223 | 223 | gui, backend = s.enable_matplotlib("inline") |
|
224 | 224 | assert gui == "inline" |
|
225 | 225 | assert s.pylab_gui_select == None |
|
226 | 226 | |
|
227 | 227 | gui, backend = s.enable_matplotlib("inline") |
|
228 | 228 | assert gui == "inline" |
|
229 | 229 | assert s.pylab_gui_select == None |
|
230 | 230 | |
|
231 | 231 | gui, backend = s.enable_matplotlib("qt") |
|
232 | 232 | assert gui == "qt" |
|
233 | 233 | assert s.pylab_gui_select == "qt" |
|
234 | 234 | |
|
235 | 235 | def test_inline_twice(self): |
|
236 | 236 | "Using '%matplotlib inline' twice should not reset formatters" |
|
237 | 237 | |
|
238 | 238 | ip = self.Shell() |
|
239 | 239 | gui, backend = ip.enable_matplotlib("inline") |
|
240 | 240 | assert gui == "inline" |
|
241 | 241 | |
|
242 | 242 | fmts = {'png'} |
|
243 | 243 | active_mimes = {_fmt_mime_map[fmt] for fmt in fmts} |
|
244 | 244 | pt.select_figure_formats(ip, fmts) |
|
245 | 245 | |
|
246 | 246 | gui, backend = ip.enable_matplotlib("inline") |
|
247 | 247 | assert gui == "inline" |
|
248 | 248 | |
|
249 | 249 | for mime, f in ip.display_formatter.formatters.items(): |
|
250 | 250 | if mime in active_mimes: |
|
251 | 251 | assert Figure in f |
|
252 | 252 | else: |
|
253 | 253 | assert Figure not in f |
|
254 | 254 | |
|
255 | 255 | def test_qt_gtk(self): |
|
256 | 256 | s = self.Shell() |
|
257 | 257 | gui, backend = s.enable_matplotlib("qt") |
|
258 | 258 | assert gui == "qt" |
|
259 | 259 | assert s.pylab_gui_select == "qt" |
|
260 | 260 | |
|
261 | 261 | gui, backend = s.enable_matplotlib("gtk") |
|
262 | 262 | assert gui == "qt" |
|
263 | 263 | assert s.pylab_gui_select == "qt" |
|
264 | 264 | |
|
265 | 265 | |
|
266 | 266 | def test_no_gui_backends(): |
|
267 | 267 | for k in ['agg', 'svg', 'pdf', 'ps']: |
|
268 | 268 | assert k not in pt.backend2gui |
|
269 | 269 | |
|
270 | 270 | |
|
271 | 271 | def test_figure_no_canvas(): |
|
272 | 272 | fig = Figure() |
|
273 | 273 | fig.canvas = None |
|
274 | 274 | pt.print_figure(fig) |
@@ -1,8 +1,20 b'' | |||
|
1 | 1 | coverage: |
|
2 | 2 | status: |
|
3 | 3 | patch: off |
|
4 | 4 | project: |
|
5 | 5 | default: |
|
6 | 6 | target: auto |
|
7 | 7 | codecov: |
|
8 | 8 | require_ci_to_pass: false |
|
9 | ||
|
10 | ignore: | |
|
11 | - IPython/kernel/* | |
|
12 | - IPython/consoleapp.py | |
|
13 | - IPython/core/inputsplitter.py | |
|
14 | - IPython/lib/inputhook*.py | |
|
15 | - IPython/lib/kernel.py | |
|
16 | - IPython/utils/jsonutil.py | |
|
17 | - IPython/utils/localinterfaces.py | |
|
18 | - IPython/utils/log.py | |
|
19 | - IPython/utils/signatures.py | |
|
20 | - IPython/utils/traitlets.py |
@@ -1,43 +1,47 b'' | |||
|
1 | 1 | [pytest] |
|
2 | 2 | addopts = --durations=10 |
|
3 | 3 | -p IPython.testing.plugin.pytest_ipdoctest --ipdoctest-modules |
|
4 | 4 | --ignore=docs |
|
5 | 5 | --ignore=examples |
|
6 | 6 | --ignore=htmlcov |
|
7 | 7 | --ignore=ipython_kernel |
|
8 | 8 | --ignore=ipython_parallel |
|
9 | 9 | --ignore=results |
|
10 | 10 | --ignore=tmp |
|
11 | 11 | --ignore=tools |
|
12 | 12 | --ignore=traitlets |
|
13 | 13 | --ignore=IPython/core/tests/daft_extension |
|
14 | 14 | --ignore=IPython/sphinxext |
|
15 | 15 | --ignore=IPython/terminal/pt_inputhooks |
|
16 | 16 | --ignore=IPython/__main__.py |
|
17 | 17 | --ignore=IPython/config.py |
|
18 | 18 | --ignore=IPython/frontend.py |
|
19 | 19 | --ignore=IPython/html.py |
|
20 | 20 | --ignore=IPython/nbconvert.py |
|
21 | 21 | --ignore=IPython/nbformat.py |
|
22 | 22 | --ignore=IPython/parallel.py |
|
23 | 23 | --ignore=IPython/qt.py |
|
24 | 24 | --ignore=IPython/external/qt_for_kernel.py |
|
25 | 25 | --ignore=IPython/html/widgets/widget_link.py |
|
26 | 26 | --ignore=IPython/html/widgets/widget_output.py |
|
27 | --ignore=IPython/lib/inputhookglut.py | |
|
28 | --ignore=IPython/lib/inputhookgtk.py | |
|
29 | --ignore=IPython/lib/inputhookgtk3.py | |
|
30 | --ignore=IPython/lib/inputhookgtk4.py | |
|
31 | --ignore=IPython/lib/inputhookpyglet.py | |
|
32 | --ignore=IPython/lib/inputhookqt4.py | |
|
33 | --ignore=IPython/lib/inputhookwx.py | |
|
34 | 27 | --ignore=IPython/terminal/console.py |
|
35 | 28 | --ignore=IPython/terminal/ptshell.py |
|
36 | 29 | --ignore=IPython/utils/_process_cli.py |
|
37 | 30 | --ignore=IPython/utils/_process_posix.py |
|
38 | 31 | --ignore=IPython/utils/_process_win32.py |
|
39 | 32 | --ignore=IPython/utils/_process_win32_controller.py |
|
40 | 33 | --ignore=IPython/utils/daemonize.py |
|
41 | 34 | --ignore=IPython/utils/eventful.py |
|
35 | ||
|
36 | --ignore=IPython/kernel | |
|
37 | --ignore=IPython/consoleapp.py | |
|
38 | --ignore=IPython/core/inputsplitter.py | |
|
39 | --ignore-glob=IPython/lib/inputhook*.py | |
|
40 | --ignore=IPython/lib/kernel.py | |
|
41 | --ignore=IPython/utils/jsonutil.py | |
|
42 | --ignore=IPython/utils/localinterfaces.py | |
|
43 | --ignore=IPython/utils/log.py | |
|
44 | --ignore=IPython/utils/signatures.py | |
|
45 | --ignore=IPython/utils/traitlets.py | |
|
42 | 46 | doctest_optionflags = NORMALIZE_WHITESPACE ELLIPSIS |
|
43 | 47 | ipdoctest_optionflags = NORMALIZE_WHITESPACE ELLIPSIS |
General Comments 0
You need to be logged in to leave comments.
Login now