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