##// END OF EJS Templates
Merge pull request #12617 from Carreau/skip-ipykernel
Matthias Bussonnier -
r26085:887e93ef merge
parent child Browse files
Show More
@@ -1,455 +1,459 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 nose.tools as nt
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 nt.assert_equal(u'<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 nt.assert_equal(u'<img src="%s" width="200" height="200"/>' % (thisurl), img._repr_html_())
28 28 img = display.Image(url=thisurl, width=200)
29 29 nt.assert_equal(u'<img src="%s" width="200"/>' % (thisurl), img._repr_html_())
30 30 img = display.Image(url=thisurl)
31 31 nt.assert_equal(u'<img src="%s"/>' % (thisurl), img._repr_html_())
32 32 img = display.Image(url=thisurl, unconfined=True)
33 33 nt.assert_equal(u'<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 nt.assert_equal(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 nt.assert_equal(u'<IPython.core.display.GeoJSON object>', str(gj))
65 65
66 66 def test_retina_png():
67 67 here = os.path.dirname(__file__)
68 68 img = display.Image(os.path.join(here, "2x2.png"), retina=True)
69 69 nt.assert_equal(img.height, 1)
70 70 nt.assert_equal(img.width, 1)
71 71 data, md = img._repr_png_()
72 72 nt.assert_equal(md['width'], 1)
73 73 nt.assert_equal(md['height'], 1)
74 74
75 75 def test_embed_svg_url():
76 76 import gzip
77 77 from io import BytesIO
78 78 svg_data = b'<svg><circle x="0" y="0" r="1"/></svg>'
79 79 url = 'http://test.com/circle.svg'
80 80
81 81 gzip_svg = BytesIO()
82 82 with gzip.open(gzip_svg, 'wb') as fp:
83 83 fp.write(svg_data)
84 84 gzip_svg = gzip_svg.getvalue()
85 85
86 86 def mocked_urlopen(*args, **kwargs):
87 87 class MockResponse:
88 88 def __init__(self, svg):
89 89 self._svg_data = svg
90 90 self.headers = {'content-type': 'image/svg+xml'}
91 91
92 92 def read(self):
93 93 return self._svg_data
94 94
95 95 if args[0] == url:
96 96 return MockResponse(svg_data)
97 97 elif args[0] == url + 'z':
98 98 ret= MockResponse(gzip_svg)
99 99 ret.headers['content-encoding']= 'gzip'
100 100 return ret
101 101 return MockResponse(None)
102 102
103 103 with mock.patch('urllib.request.urlopen', side_effect=mocked_urlopen):
104 104 svg = display.SVG(url=url)
105 105 nt.assert_true(svg._repr_svg_().startswith('<svg'))
106 106 svg = display.SVG(url=url + 'z')
107 107 nt.assert_true(svg._repr_svg_().startswith('<svg'))
108 108
109 109 def test_retina_jpeg():
110 110 here = os.path.dirname(__file__)
111 111 img = display.Image(os.path.join(here, "2x2.jpg"), retina=True)
112 112 nt.assert_equal(img.height, 1)
113 113 nt.assert_equal(img.width, 1)
114 114 data, md = img._repr_jpeg_()
115 115 nt.assert_equal(md['width'], 1)
116 116 nt.assert_equal(md['height'], 1)
117 117
118 118 def test_base64image():
119 119 display.Image("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAACnej3aAAAAAWJLR0QAiAUdSAAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB94BCRQnOqNu0b4AAAAKSURBVAjXY2AAAAACAAHiIbwzAAAAAElFTkSuQmCC")
120 120
121 121 def test_image_filename_defaults():
122 122 '''test format constraint, and validity of jpeg and png'''
123 123 tpath = ipath.get_ipython_package_dir()
124 124 nt.assert_raises(ValueError, display.Image, filename=os.path.join(tpath, 'testing/tests/badformat.zip'),
125 125 embed=True)
126 126 nt.assert_raises(ValueError, display.Image)
127 127 nt.assert_raises(ValueError, display.Image, data='this is not an image', format='badformat', embed=True)
128 128 # check boths paths to allow packages to test at build and install time
129 129 imgfile = os.path.join(tpath, 'core/tests/2x2.png')
130 130 img = display.Image(filename=imgfile)
131 131 nt.assert_equal('png', img.format)
132 132 nt.assert_is_not_none(img._repr_png_())
133 133 img = display.Image(filename=os.path.join(tpath, 'testing/tests/logo.jpg'), embed=False)
134 134 nt.assert_equal('jpeg', img.format)
135 135 nt.assert_is_none(img._repr_jpeg_())
136 136
137 137 def _get_inline_config():
138 138 from ipykernel.pylab.config import InlineBackend
139 139 return InlineBackend.instance()
140 140
141 @dec.skip_without('matplotlib')
141
142 @dec.skip_without("ipykernel")
143 @dec.skip_without("matplotlib")
142 144 def test_set_matplotlib_close():
143 145 cfg = _get_inline_config()
144 146 cfg.close_figures = False
145 147 display.set_matplotlib_close()
146 148 assert cfg.close_figures
147 149 display.set_matplotlib_close(False)
148 150 assert not cfg.close_figures
149 151
150 152 _fmt_mime_map = {
151 153 'png': 'image/png',
152 154 'jpeg': 'image/jpeg',
153 155 'pdf': 'application/pdf',
154 156 'retina': 'image/png',
155 157 'svg': 'image/svg+xml',
156 158 }
157 159
158 160 @dec.skip_without('matplotlib')
159 161 def test_set_matplotlib_formats():
160 162 from matplotlib.figure import Figure
161 163 formatters = get_ipython().display_formatter.formatters
162 164 for formats in [
163 165 ('png',),
164 166 ('pdf', 'svg'),
165 167 ('jpeg', 'retina', 'png'),
166 168 (),
167 169 ]:
168 170 active_mimes = {_fmt_mime_map[fmt] for fmt in formats}
169 171 display.set_matplotlib_formats(*formats)
170 172 for mime, f in formatters.items():
171 173 if mime in active_mimes:
172 174 nt.assert_in(Figure, f)
173 175 else:
174 176 nt.assert_not_in(Figure, f)
175 177
176 @dec.skip_without('matplotlib')
178
179 @dec.skip_without("ipykernel")
180 @dec.skip_without("matplotlib")
177 181 def test_set_matplotlib_formats_kwargs():
178 182 from matplotlib.figure import Figure
179 183 ip = get_ipython()
180 184 cfg = _get_inline_config()
181 185 cfg.print_figure_kwargs.update(dict(foo='bar'))
182 186 kwargs = dict(quality=10)
183 187 display.set_matplotlib_formats('png', **kwargs)
184 188 formatter = ip.display_formatter.formatters['image/png']
185 189 f = formatter.lookup_by_type(Figure)
186 190 cell = f.__closure__[0].cell_contents
187 191 expected = kwargs
188 192 expected.update(cfg.print_figure_kwargs)
189 193 nt.assert_equal(cell, expected)
190 194
191 195 def test_display_available():
192 196 """
193 197 Test that display is available without import
194 198
195 199 We don't really care if it's in builtin or anything else, but it should
196 200 always be available.
197 201 """
198 202 ip = get_ipython()
199 203 with AssertNotPrints('NameError'):
200 204 ip.run_cell('display')
201 205 try:
202 206 ip.run_cell('del display')
203 207 except NameError:
204 208 pass # it's ok, it might be in builtins
205 209 # even if deleted it should be back
206 210 with AssertNotPrints('NameError'):
207 211 ip.run_cell('display')
208 212
209 213 def test_textdisplayobj_pretty_repr():
210 214 p = display.Pretty("This is a simple test")
211 215 nt.assert_equal(repr(p), '<IPython.core.display.Pretty object>')
212 216 nt.assert_equal(p.data, 'This is a simple test')
213 217
214 218 p._show_mem_addr = True
215 219 nt.assert_equal(repr(p), object.__repr__(p))
216 220
217 221 def test_displayobject_repr():
218 222 h = display.HTML('<br />')
219 223 nt.assert_equal(repr(h), '<IPython.core.display.HTML object>')
220 224 h._show_mem_addr = True
221 225 nt.assert_equal(repr(h), object.__repr__(h))
222 226 h._show_mem_addr = False
223 227 nt.assert_equal(repr(h), '<IPython.core.display.HTML object>')
224 228
225 229 j = display.Javascript('')
226 230 nt.assert_equal(repr(j), '<IPython.core.display.Javascript object>')
227 231 j._show_mem_addr = True
228 232 nt.assert_equal(repr(j), object.__repr__(j))
229 233 j._show_mem_addr = False
230 234 nt.assert_equal(repr(j), '<IPython.core.display.Javascript object>')
231 235
232 236 @mock.patch('warnings.warn')
233 237 def test_encourage_iframe_over_html(m_warn):
234 238 display.HTML()
235 239 m_warn.assert_not_called()
236 240
237 241 display.HTML('<br />')
238 242 m_warn.assert_not_called()
239 243
240 244 display.HTML('<html><p>Lots of content here</p><iframe src="http://a.com"></iframe>')
241 245 m_warn.assert_not_called()
242 246
243 247 display.HTML('<iframe src="http://a.com"></iframe>')
244 248 m_warn.assert_called_with('Consider using IPython.display.IFrame instead')
245 249
246 250 m_warn.reset_mock()
247 251 display.HTML('<IFRAME SRC="http://a.com"></IFRAME>')
248 252 m_warn.assert_called_with('Consider using IPython.display.IFrame instead')
249 253
250 254 def test_progress():
251 255 p = display.ProgressBar(10)
252 256 nt.assert_in('0/10',repr(p))
253 257 p.html_width = '100%'
254 258 p.progress = 5
255 259 nt.assert_equal(p._repr_html_(), "<progress style='width:100%' max='10' value='5'></progress>")
256 260
257 261 def test_progress_iter():
258 262 with capture_output(display=False) as captured:
259 263 for i in display.ProgressBar(5):
260 264 out = captured.stdout
261 265 nt.assert_in('{0}/5'.format(i), out)
262 266 out = captured.stdout
263 267 nt.assert_in('5/5', out)
264 268
265 269 def test_json():
266 270 d = {'a': 5}
267 271 lis = [d]
268 272 metadata = [
269 273 {'expanded': False, 'root': 'root'},
270 274 {'expanded': True, 'root': 'root'},
271 275 {'expanded': False, 'root': 'custom'},
272 276 {'expanded': True, 'root': 'custom'},
273 277 ]
274 278 json_objs = [
275 279 display.JSON(d),
276 280 display.JSON(d, expanded=True),
277 281 display.JSON(d, root='custom'),
278 282 display.JSON(d, expanded=True, root='custom'),
279 283 ]
280 284 for j, md in zip(json_objs, metadata):
281 285 nt.assert_equal(j._repr_json_(), (d, md))
282 286
283 287 with warnings.catch_warnings(record=True) as w:
284 288 warnings.simplefilter("always")
285 289 j = display.JSON(json.dumps(d))
286 290 nt.assert_equal(len(w), 1)
287 291 nt.assert_equal(j._repr_json_(), (d, metadata[0]))
288 292
289 293 json_objs = [
290 294 display.JSON(lis),
291 295 display.JSON(lis, expanded=True),
292 296 display.JSON(lis, root='custom'),
293 297 display.JSON(lis, expanded=True, root='custom'),
294 298 ]
295 299 for j, md in zip(json_objs, metadata):
296 300 nt.assert_equal(j._repr_json_(), (lis, md))
297 301
298 302 with warnings.catch_warnings(record=True) as w:
299 303 warnings.simplefilter("always")
300 304 j = display.JSON(json.dumps(lis))
301 305 nt.assert_equal(len(w), 1)
302 306 nt.assert_equal(j._repr_json_(), (lis, metadata[0]))
303 307
304 308 def test_video_embedding():
305 309 """use a tempfile, with dummy-data, to ensure that video embedding doesn't crash"""
306 310 v = display.Video("http://ignored")
307 311 assert not v.embed
308 312 html = v._repr_html_()
309 313 nt.assert_not_in('src="data:', html)
310 314 nt.assert_in('src="http://ignored"', html)
311 315
312 316 with nt.assert_raises(ValueError):
313 317 v = display.Video(b'abc')
314 318
315 319 with NamedFileInTemporaryDirectory('test.mp4') as f:
316 320 f.write(b'abc')
317 321 f.close()
318 322
319 323 v = display.Video(f.name)
320 324 assert not v.embed
321 325 html = v._repr_html_()
322 326 nt.assert_not_in('src="data:', html)
323 327
324 328 v = display.Video(f.name, embed=True)
325 329 html = v._repr_html_()
326 330 nt.assert_in('src="data:video/mp4;base64,YWJj"',html)
327 331
328 332 v = display.Video(f.name, embed=True, mimetype='video/other')
329 333 html = v._repr_html_()
330 334 nt.assert_in('src="data:video/other;base64,YWJj"',html)
331 335
332 336 v = display.Video(b'abc', embed=True, mimetype='video/mp4')
333 337 html = v._repr_html_()
334 338 nt.assert_in('src="data:video/mp4;base64,YWJj"',html)
335 339
336 340 v = display.Video(u'YWJj', embed=True, mimetype='video/xyz')
337 341 html = v._repr_html_()
338 342 nt.assert_in('src="data:video/xyz;base64,YWJj"',html)
339 343
340 344 def test_html_metadata():
341 345 s = "<h1>Test</h1>"
342 346 h = display.HTML(s, metadata={"isolated": True})
343 347 nt.assert_equal(h._repr_html_(), (s, {"isolated": True}))
344 348
345 349 def test_display_id():
346 350 ip = get_ipython()
347 351 with mock.patch.object(ip.display_pub, 'publish') as pub:
348 352 handle = display.display('x')
349 353 nt.assert_is(handle, None)
350 354 handle = display.display('y', display_id='secret')
351 355 nt.assert_is_instance(handle, display.DisplayHandle)
352 356 handle2 = display.display('z', display_id=True)
353 357 nt.assert_is_instance(handle2, display.DisplayHandle)
354 358 nt.assert_not_equal(handle.display_id, handle2.display_id)
355 359
356 360 nt.assert_equal(pub.call_count, 3)
357 361 args, kwargs = pub.call_args_list[0]
358 362 nt.assert_equal(args, ())
359 363 nt.assert_equal(kwargs, {
360 364 'data': {
361 365 'text/plain': repr('x')
362 366 },
363 367 'metadata': {},
364 368 })
365 369 args, kwargs = pub.call_args_list[1]
366 370 nt.assert_equal(args, ())
367 371 nt.assert_equal(kwargs, {
368 372 'data': {
369 373 'text/plain': repr('y')
370 374 },
371 375 'metadata': {},
372 376 'transient': {
373 377 'display_id': handle.display_id,
374 378 },
375 379 })
376 380 args, kwargs = pub.call_args_list[2]
377 381 nt.assert_equal(args, ())
378 382 nt.assert_equal(kwargs, {
379 383 'data': {
380 384 'text/plain': repr('z')
381 385 },
382 386 'metadata': {},
383 387 'transient': {
384 388 'display_id': handle2.display_id,
385 389 },
386 390 })
387 391
388 392
389 393 def test_update_display():
390 394 ip = get_ipython()
391 395 with mock.patch.object(ip.display_pub, 'publish') as pub:
392 396 with nt.assert_raises(TypeError):
393 397 display.update_display('x')
394 398 display.update_display('x', display_id='1')
395 399 display.update_display('y', display_id='2')
396 400 args, kwargs = pub.call_args_list[0]
397 401 nt.assert_equal(args, ())
398 402 nt.assert_equal(kwargs, {
399 403 'data': {
400 404 'text/plain': repr('x')
401 405 },
402 406 'metadata': {},
403 407 'transient': {
404 408 'display_id': '1',
405 409 },
406 410 'update': True,
407 411 })
408 412 args, kwargs = pub.call_args_list[1]
409 413 nt.assert_equal(args, ())
410 414 nt.assert_equal(kwargs, {
411 415 'data': {
412 416 'text/plain': repr('y')
413 417 },
414 418 'metadata': {},
415 419 'transient': {
416 420 'display_id': '2',
417 421 },
418 422 'update': True,
419 423 })
420 424
421 425
422 426 def test_display_handle():
423 427 ip = get_ipython()
424 428 handle = display.DisplayHandle()
425 429 nt.assert_is_instance(handle.display_id, str)
426 430 handle = display.DisplayHandle('my-id')
427 431 nt.assert_equal(handle.display_id, 'my-id')
428 432 with mock.patch.object(ip.display_pub, 'publish') as pub:
429 433 handle.display('x')
430 434 handle.update('y')
431 435
432 436 args, kwargs = pub.call_args_list[0]
433 437 nt.assert_equal(args, ())
434 438 nt.assert_equal(kwargs, {
435 439 'data': {
436 440 'text/plain': repr('x')
437 441 },
438 442 'metadata': {},
439 443 'transient': {
440 444 'display_id': handle.display_id,
441 445 }
442 446 })
443 447 args, kwargs = pub.call_args_list[1]
444 448 nt.assert_equal(args, ())
445 449 nt.assert_equal(kwargs, {
446 450 'data': {
447 451 'text/plain': repr('y')
448 452 },
449 453 'metadata': {},
450 454 'transient': {
451 455 'display_id': handle.display_id,
452 456 },
453 457 'update': True,
454 458 })
455 459
General Comments 0
You need to be logged in to leave comments. Login now