##// END OF EJS Templates
Update "validity of jpeg and png" test
Grant Nestor -
Show More
@@ -1,363 +1,363 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.tempdir import NamedFileInTemporaryDirectory
15 15 from IPython import paths as ipath
16 16 from IPython.testing.tools import AssertPrints, AssertNotPrints
17 17
18 18 import IPython.testing.decorators as dec
19 19
20 20 def test_image_size():
21 21 """Simple test for display.Image(args, width=x,height=y)"""
22 22 thisurl = 'http://www.google.fr/images/srpr/logo3w.png'
23 23 img = display.Image(url=thisurl, width=200, height=200)
24 24 nt.assert_equal(u'<img src="%s" width="200" height="200"/>' % (thisurl), img._repr_html_())
25 25 img = display.Image(url=thisurl, metadata={'width':200, 'height':200})
26 26 nt.assert_equal(u'<img src="%s" width="200" height="200"/>' % (thisurl), img._repr_html_())
27 27 img = display.Image(url=thisurl, width=200)
28 28 nt.assert_equal(u'<img src="%s" width="200"/>' % (thisurl), img._repr_html_())
29 29 img = display.Image(url=thisurl)
30 30 nt.assert_equal(u'<img src="%s"/>' % (thisurl), img._repr_html_())
31 31 img = display.Image(url=thisurl, unconfined=True)
32 32 nt.assert_equal(u'<img src="%s" class="unconfined"/>' % (thisurl), img._repr_html_())
33 33
34 34
35 35 def test_geojson():
36 36
37 37 gj = display.GeoJSON(data={
38 38 "type": "Feature",
39 39 "geometry": {
40 40 "type": "Point",
41 41 "coordinates": [-81.327, 296.038]
42 42 },
43 43 "properties": {
44 44 "name": "Inca City"
45 45 }
46 46 },
47 47 url_template="http://s3-eu-west-1.amazonaws.com/whereonmars.cartodb.net/{basemap_id}/{z}/{x}/{y}.png",
48 48 layer_options={
49 49 "basemap_id": "celestia_mars-shaded-16k_global",
50 50 "attribution": "Celestia/praesepe",
51 51 "minZoom": 0,
52 52 "maxZoom": 18,
53 53 })
54 54 nt.assert_equal(u'<IPython.core.display.GeoJSON object>', str(gj))
55 55
56 56 def test_retina_png():
57 57 here = os.path.dirname(__file__)
58 58 img = display.Image(os.path.join(here, "2x2.png"), retina=True)
59 59 nt.assert_equal(img.height, 1)
60 60 nt.assert_equal(img.width, 1)
61 61 data, md = img._repr_png_()
62 62 nt.assert_equal(md['width'], 1)
63 63 nt.assert_equal(md['height'], 1)
64 64
65 65 def test_retina_jpeg():
66 66 here = os.path.dirname(__file__)
67 67 img = display.Image(os.path.join(here, "2x2.jpg"), retina=True)
68 68 nt.assert_equal(img.height, 1)
69 69 nt.assert_equal(img.width, 1)
70 70 data, md = img._repr_jpeg_()
71 71 nt.assert_equal(md['width'], 1)
72 72 nt.assert_equal(md['height'], 1)
73 73
74 74 def test_base64image():
75 75 display.Image("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAACnej3aAAAAAWJLR0QAiAUdSAAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB94BCRQnOqNu0b4AAAAKSURBVAjXY2AAAAACAAHiIbwzAAAAAElFTkSuQmCC")
76 76
77 77 def test_image_filename_defaults():
78 78 '''test format constraint, and validity of jpeg and png'''
79 79 tpath = ipath.get_ipython_package_dir()
80 # nt.assert_raises(ValueError, display.Image, filename=os.path.join(tpath, 'testing/tests/badformat.gif'),
81 # embed=True)
80 nt.assert_raises(ValueError, display.Image, filename=os.path.join(tpath, 'testing/tests/badformat.zip'),
81 embed=True)
82 82 nt.assert_raises(ValueError, display.Image)
83 83 nt.assert_raises(ValueError, display.Image, data='this is not an image', format='badformat', embed=True)
84 84 # check boths paths to allow packages to test at build and install time
85 85 imgfile = os.path.join(tpath, 'core/tests/2x2.png')
86 86 img = display.Image(filename=imgfile)
87 87 nt.assert_equal('png', img.format)
88 88 nt.assert_is_not_none(img._repr_png_())
89 89 img = display.Image(filename=os.path.join(tpath, 'testing/tests/logo.jpg'), embed=False)
90 90 nt.assert_equal('jpeg', img.format)
91 91 nt.assert_is_none(img._repr_jpeg_())
92 92
93 93 def _get_inline_config():
94 94 from ipykernel.pylab.config import InlineBackend
95 95 return InlineBackend.instance()
96 96
97 97 @dec.skip_without('matplotlib')
98 98 def test_set_matplotlib_close():
99 99 cfg = _get_inline_config()
100 100 cfg.close_figures = False
101 101 display.set_matplotlib_close()
102 102 assert cfg.close_figures
103 103 display.set_matplotlib_close(False)
104 104 assert not cfg.close_figures
105 105
106 106 _fmt_mime_map = {
107 107 'png': 'image/png',
108 108 'jpeg': 'image/jpeg',
109 109 'pdf': 'application/pdf',
110 110 'retina': 'image/png',
111 111 'svg': 'image/svg+xml',
112 112 }
113 113
114 114 @dec.skip_without('matplotlib')
115 115 def test_set_matplotlib_formats():
116 116 from matplotlib.figure import Figure
117 117 formatters = get_ipython().display_formatter.formatters
118 118 for formats in [
119 119 ('png',),
120 120 ('pdf', 'svg'),
121 121 ('jpeg', 'retina', 'png'),
122 122 (),
123 123 ]:
124 124 active_mimes = {_fmt_mime_map[fmt] for fmt in formats}
125 125 display.set_matplotlib_formats(*formats)
126 126 for mime, f in formatters.items():
127 127 if mime in active_mimes:
128 128 nt.assert_in(Figure, f)
129 129 else:
130 130 nt.assert_not_in(Figure, f)
131 131
132 132 @dec.skip_without('matplotlib')
133 133 def test_set_matplotlib_formats_kwargs():
134 134 from matplotlib.figure import Figure
135 135 ip = get_ipython()
136 136 cfg = _get_inline_config()
137 137 cfg.print_figure_kwargs.update(dict(foo='bar'))
138 138 kwargs = dict(quality=10)
139 139 display.set_matplotlib_formats('png', **kwargs)
140 140 formatter = ip.display_formatter.formatters['image/png']
141 141 f = formatter.lookup_by_type(Figure)
142 142 cell = f.__closure__[0].cell_contents
143 143 expected = kwargs
144 144 expected.update(cfg.print_figure_kwargs)
145 145 nt.assert_equal(cell, expected)
146 146
147 147 def test_display_available():
148 148 """
149 149 Test that display is available without import
150 150
151 151 We don't really care if it's in builtin or anything else, but it should
152 152 always be available.
153 153 """
154 154 ip = get_ipython()
155 155 with AssertNotPrints('NameError'):
156 156 ip.run_cell('display')
157 157 try:
158 158 ip.run_cell('del display')
159 159 except NameError:
160 160 pass # it's ok, it might be in builtins
161 161 # even if deleted it should be back
162 162 with AssertNotPrints('NameError'):
163 163 ip.run_cell('display')
164 164
165 165 def test_textdisplayobj_pretty_repr():
166 166 p = display.Pretty("This is a simple test")
167 167 nt.assert_equal(repr(p), '<IPython.core.display.Pretty object>')
168 168 nt.assert_equal(p.data, 'This is a simple test')
169 169
170 170 p._show_mem_addr = True
171 171 nt.assert_equal(repr(p), object.__repr__(p))
172 172
173 173 def test_displayobject_repr():
174 174 h = display.HTML('<br />')
175 175 nt.assert_equal(repr(h), '<IPython.core.display.HTML object>')
176 176 h._show_mem_addr = True
177 177 nt.assert_equal(repr(h), object.__repr__(h))
178 178 h._show_mem_addr = False
179 179 nt.assert_equal(repr(h), '<IPython.core.display.HTML object>')
180 180
181 181 j = display.Javascript('')
182 182 nt.assert_equal(repr(j), '<IPython.core.display.Javascript object>')
183 183 j._show_mem_addr = True
184 184 nt.assert_equal(repr(j), object.__repr__(j))
185 185 j._show_mem_addr = False
186 186 nt.assert_equal(repr(j), '<IPython.core.display.Javascript object>')
187 187
188 188 def test_json():
189 189 d = {'a': 5}
190 190 lis = [d]
191 191 md = {'expanded': False}
192 192 md2 = {'expanded': True}
193 193 j = display.JSON(d)
194 194 j2 = display.JSON(d, expanded=True)
195 195 nt.assert_equal(j._repr_json_(), (d, md))
196 196 nt.assert_equal(j2._repr_json_(), (d, md2))
197 197
198 198 with warnings.catch_warnings(record=True) as w:
199 199 warnings.simplefilter("always")
200 200 j = display.JSON(json.dumps(d))
201 201 nt.assert_equal(len(w), 1)
202 202 nt.assert_equal(j._repr_json_(), (d, md))
203 203 nt.assert_equal(j2._repr_json_(), (d, md2))
204 204
205 205 j = display.JSON(lis)
206 206 j2 = display.JSON(lis, expanded=True)
207 207 nt.assert_equal(j._repr_json_(), (lis, md))
208 208 nt.assert_equal(j2._repr_json_(), (lis, md2))
209 209
210 210 with warnings.catch_warnings(record=True) as w:
211 211 warnings.simplefilter("always")
212 212 j = display.JSON(json.dumps(lis))
213 213 nt.assert_equal(len(w), 1)
214 214 nt.assert_equal(j._repr_json_(), (lis, md))
215 215 nt.assert_equal(j2._repr_json_(), (lis, md2))
216 216
217 217 def test_video_embedding():
218 218 """use a tempfile, with dummy-data, to ensure that video embedding doesn't crash"""
219 219 v = display.Video("http://ignored")
220 220 assert not v.embed
221 221 html = v._repr_html_()
222 222 nt.assert_not_in('src="data:', html)
223 223 nt.assert_in('src="http://ignored"', html)
224 224
225 225 with nt.assert_raises(ValueError):
226 226 v = display.Video(b'abc')
227 227
228 228 with NamedFileInTemporaryDirectory('test.mp4') as f:
229 229 f.write(b'abc')
230 230 f.close()
231 231
232 232 v = display.Video(f.name)
233 233 assert not v.embed
234 234 html = v._repr_html_()
235 235 nt.assert_not_in('src="data:', html)
236 236
237 237 v = display.Video(f.name, embed=True)
238 238 html = v._repr_html_()
239 239 nt.assert_in('src="data:video/mp4;base64,YWJj"',html)
240 240
241 241 v = display.Video(f.name, embed=True, mimetype='video/other')
242 242 html = v._repr_html_()
243 243 nt.assert_in('src="data:video/other;base64,YWJj"',html)
244 244
245 245 v = display.Video(b'abc', embed=True, mimetype='video/mp4')
246 246 html = v._repr_html_()
247 247 nt.assert_in('src="data:video/mp4;base64,YWJj"',html)
248 248
249 249 v = display.Video(u'YWJj', embed=True, mimetype='video/xyz')
250 250 html = v._repr_html_()
251 251 nt.assert_in('src="data:video/xyz;base64,YWJj"',html)
252 252
253 253
254 254 def test_display_id():
255 255 ip = get_ipython()
256 256 with mock.patch.object(ip.display_pub, 'publish') as pub:
257 257 handle = display.display('x')
258 258 nt.assert_is(handle, None)
259 259 handle = display.display('y', display_id='secret')
260 260 nt.assert_is_instance(handle, display.DisplayHandle)
261 261 handle2 = display.display('z', display_id=True)
262 262 nt.assert_is_instance(handle2, display.DisplayHandle)
263 263 nt.assert_not_equal(handle.display_id, handle2.display_id)
264 264
265 265 nt.assert_equal(pub.call_count, 3)
266 266 args, kwargs = pub.call_args_list[0]
267 267 nt.assert_equal(args, ())
268 268 nt.assert_equal(kwargs, {
269 269 'data': {
270 270 'text/plain': repr('x')
271 271 },
272 272 'metadata': {},
273 273 })
274 274 args, kwargs = pub.call_args_list[1]
275 275 nt.assert_equal(args, ())
276 276 nt.assert_equal(kwargs, {
277 277 'data': {
278 278 'text/plain': repr('y')
279 279 },
280 280 'metadata': {},
281 281 'transient': {
282 282 'display_id': handle.display_id,
283 283 },
284 284 })
285 285 args, kwargs = pub.call_args_list[2]
286 286 nt.assert_equal(args, ())
287 287 nt.assert_equal(kwargs, {
288 288 'data': {
289 289 'text/plain': repr('z')
290 290 },
291 291 'metadata': {},
292 292 'transient': {
293 293 'display_id': handle2.display_id,
294 294 },
295 295 })
296 296
297 297
298 298 def test_update_display():
299 299 ip = get_ipython()
300 300 with mock.patch.object(ip.display_pub, 'publish') as pub:
301 301 with nt.assert_raises(TypeError):
302 302 display.update_display('x')
303 303 display.update_display('x', display_id='1')
304 304 display.update_display('y', display_id='2')
305 305 args, kwargs = pub.call_args_list[0]
306 306 nt.assert_equal(args, ())
307 307 nt.assert_equal(kwargs, {
308 308 'data': {
309 309 'text/plain': repr('x')
310 310 },
311 311 'metadata': {},
312 312 'transient': {
313 313 'display_id': '1',
314 314 },
315 315 'update': True,
316 316 })
317 317 args, kwargs = pub.call_args_list[1]
318 318 nt.assert_equal(args, ())
319 319 nt.assert_equal(kwargs, {
320 320 'data': {
321 321 'text/plain': repr('y')
322 322 },
323 323 'metadata': {},
324 324 'transient': {
325 325 'display_id': '2',
326 326 },
327 327 'update': True,
328 328 })
329 329
330 330
331 331 def test_display_handle():
332 332 ip = get_ipython()
333 333 handle = display.DisplayHandle()
334 334 nt.assert_is_instance(handle.display_id, str)
335 335 handle = display.DisplayHandle('my-id')
336 336 nt.assert_equal(handle.display_id, 'my-id')
337 337 with mock.patch.object(ip.display_pub, 'publish') as pub:
338 338 handle.display('x')
339 339 handle.update('y')
340 340
341 341 args, kwargs = pub.call_args_list[0]
342 342 nt.assert_equal(args, ())
343 343 nt.assert_equal(kwargs, {
344 344 'data': {
345 345 'text/plain': repr('x')
346 346 },
347 347 'metadata': {},
348 348 'transient': {
349 349 'display_id': handle.display_id,
350 350 }
351 351 })
352 352 args, kwargs = pub.call_args_list[1]
353 353 nt.assert_equal(args, ())
354 354 nt.assert_equal(kwargs, {
355 355 'data': {
356 356 'text/plain': repr('y')
357 357 },
358 358 'metadata': {},
359 359 'transient': {
360 360 'display_id': handle.display_id,
361 361 },
362 362 'update': True,
363 363 })
General Comments 0
You need to be logged in to leave comments. Login now