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