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