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