Debian Codegraph @

tests/test_display.py

raw
1 """Tests for IPython.lib.display."""
2
3 # -----------------------------------------------------------------------------
4 # Copyright (c) 2012, the IPython Development Team.
5 #
6 # Distributed under the terms of the Modified BSD License.
7 #
8 # The full license is in the file COPYING.txt, distributed with this software.
9 # -----------------------------------------------------------------------------
10
11 # -----------------------------------------------------------------------------
12 # Imports
13 # -----------------------------------------------------------------------------
14 from tempfile import NamedTemporaryFile, mkdtemp
15 from os.path import split, join as pjoin, dirname
16 import pathlib
17 from unittest import TestCase, mock
18 import struct
19 import wave
20 from io import BytesIO
21
22 # Third-party imports
23 import pytest
24
25 try:
26 import numpy
27 except ImportError:
28 pass
29
30 # Our own imports
31 from IPython.lib import display
32
33 from IPython.testing.decorators import skipif_not_numpy
34
35 # -----------------------------------------------------------------------------
36 # Classes and functions
37 # -----------------------------------------------------------------------------
38
39 # --------------------------
40 # FileLink tests
41 # --------------------------
42
43
44 def test_instantiation_FileLink():
45 """FileLink: Test class can be instantiated"""
46 fl = display.FileLink("example.txt")
47 # TODO: remove if when only Python >= 3.6 is supported
48 fl = display.FileLink(pathlib.PurePath("example.txt"))
49
50
51 def test_warning_on_non_existent_path_FileLink():
52 """FileLink: Calling _repr_html_ on non-existent files returns a warning"""
53 fl = display.FileLink("example.txt")
54 assert fl._repr_html_().startswith("Path (<tt>example.txt</tt>)")
55
56
57 def test_existing_path_FileLink():
58 """FileLink: Calling _repr_html_ functions as expected on existing filepath"""
59 tf = NamedTemporaryFile()
60 fl = display.FileLink(tf.name)
61 actual = fl._repr_html_()
62 expected = "<a href='%s' target='_blank'>%s</a><br>" % (tf.name, tf.name)
63 assert actual == expected
64
65
66 def test_existing_path_FileLink_repr():
67 """FileLink: Calling repr() functions as expected on existing filepath"""
68 tf = NamedTemporaryFile()
69 fl = display.FileLink(tf.name)
70 actual = repr(fl)
71 expected = tf.name
72 assert actual == expected
73
74
75 def test_error_on_directory_to_FileLink():
76 """FileLink: Raises error when passed directory"""
77 td = mkdtemp()
78 pytest.raises(ValueError, display.FileLink, td)
79
80
81 # --------------------------
82 # FileLinks tests
83 # --------------------------
84
85
86 def test_instantiation_FileLinks():
87 """FileLinks: Test class can be instantiated"""
88 fls = display.FileLinks("example")
89
90
91 def test_warning_on_non_existent_path_FileLinks():
92 """FileLinks: Calling _repr_html_ on non-existent files returns a warning"""
93 fls = display.FileLinks("example")
94 assert fls._repr_html_().startswith("Path (<tt>example</tt>)")
95
96
97 def test_existing_path_FileLinks():
98 """FileLinks: Calling _repr_html_ functions as expected on existing dir"""
99 td = mkdtemp()
100 tf1 = NamedTemporaryFile(dir=td)
101 tf2 = NamedTemporaryFile(dir=td)
102 fl = display.FileLinks(td)
103 actual = fl._repr_html_()
104 actual = actual.split("\n")
105 actual.sort()
106 # the links should always have forward slashes, even on windows, so replace
107 # backslashes with forward slashes here
108 expected = [
109 "%s/<br>" % td,
110 "&nbsp;&nbsp;<a href='%s' target='_blank'>%s</a><br>"
111 % (tf2.name.replace("\\", "/"), split(tf2.name)[1]),
112 "&nbsp;&nbsp;<a href='%s' target='_blank'>%s</a><br>"
113 % (tf1.name.replace("\\", "/"), split(tf1.name)[1]),
114 ]
115 expected.sort()
116 # We compare the sorted list of links here as that's more reliable
117 assert actual == expected
118
119
120 def test_existing_path_FileLinks_alt_formatter():
121 """FileLinks: Calling _repr_html_ functions as expected w/ an alt formatter"""
122 td = mkdtemp()
123 tf1 = NamedTemporaryFile(dir=td)
124 tf2 = NamedTemporaryFile(dir=td)
125
126 def fake_formatter(dirname, fnames, included_suffixes):
127 return ["hello", "world"]
128
129 fl = display.FileLinks(td, notebook_display_formatter=fake_formatter)
130 actual = fl._repr_html_()
131 actual = actual.split("\n")
132 actual.sort()
133 expected = ["hello", "world"]
134 expected.sort()
135 # We compare the sorted list of links here as that's more reliable
136 assert actual == expected
137
138
139 def test_existing_path_FileLinks_repr():
140 """FileLinks: Calling repr() functions as expected on existing directory"""
141 td = mkdtemp()
142 tf1 = NamedTemporaryFile(dir=td)
143 tf2 = NamedTemporaryFile(dir=td)
144 fl = display.FileLinks(td)
145 actual = repr(fl)
146 actual = actual.split("\n")
147 actual.sort()
148 expected = ["%s/" % td, " %s" % split(tf1.name)[1], " %s" % split(tf2.name)[1]]
149 expected.sort()
150 # We compare the sorted list of links here as that's more reliable
151 assert actual == expected
152
153
154 def test_existing_path_FileLinks_repr_alt_formatter():
155 """FileLinks: Calling repr() functions as expected w/ alt formatter"""
156 td = mkdtemp()
157 tf1 = NamedTemporaryFile(dir=td)
158 tf2 = NamedTemporaryFile(dir=td)
159
160 def fake_formatter(dirname, fnames, included_suffixes):
161 return ["hello", "world"]
162
163 fl = display.FileLinks(td, terminal_display_formatter=fake_formatter)
164 actual = repr(fl)
165 actual = actual.split("\n")
166 actual.sort()
167 expected = ["hello", "world"]
168 expected.sort()
169 # We compare the sorted list of links here as that's more reliable
170 assert actual == expected
171
172
173 def test_error_on_file_to_FileLinks():
174 """FileLinks: Raises error when passed file"""
175 td = mkdtemp()
176 tf1 = NamedTemporaryFile(dir=td)
177 pytest.raises(ValueError, display.FileLinks, tf1.name)
178
179
180 def test_recursive_FileLinks():
181 """FileLinks: Does not recurse when recursive=False"""
182 td = mkdtemp()
183 tf = NamedTemporaryFile(dir=td)
184 subtd = mkdtemp(dir=td)
185 subtf = NamedTemporaryFile(dir=subtd)
186 fl = display.FileLinks(td)
187 actual = str(fl)
188 actual = actual.split("\n")
189 assert len(actual) == 4, actual
190 fl = display.FileLinks(td, recursive=False)
191 actual = str(fl)
192 actual = actual.split("\n")
193 assert len(actual) == 2, actual
194
195
196 def test_audio_from_file():
197 path = pjoin(dirname(__file__), "test.wav")
198 display.Audio(filename=path)
199
200
201 class TestAudioDataWithNumpy(TestCase):
202 @skipif_not_numpy
203 def test_audio_from_numpy_array(self):
204 test_tone = get_test_tone()
205 audio = display.Audio(test_tone, rate=44100)
206 assert len(read_wav(audio.data)) == len(test_tone)
207
208 @skipif_not_numpy
209 def test_audio_from_list(self):
210 test_tone = get_test_tone()
211 audio = display.Audio(list(test_tone), rate=44100)
212 assert len(read_wav(audio.data)) == len(test_tone)
213
214 @skipif_not_numpy
215 def test_audio_from_numpy_array_without_rate_raises(self):
216 self.assertRaises(ValueError, display.Audio, get_test_tone())
217
218 @skipif_not_numpy
219 def test_audio_data_normalization(self):
220 expected_max_value = numpy.iinfo(numpy.int16).max
221 for scale in [1, 0.5, 2]:
222 audio = display.Audio(get_test_tone(scale), rate=44100)
223 actual_max_value = numpy.max(numpy.abs(read_wav(audio.data)))
224 assert actual_max_value == expected_max_value
225
226 @skipif_not_numpy
227 def test_audio_data_without_normalization(self):
228 max_int16 = numpy.iinfo(numpy.int16).max
229 for scale in [1, 0.5, 0.2]:
230 test_tone = get_test_tone(scale)
231 test_tone_max_abs = numpy.max(numpy.abs(test_tone))
232 expected_max_value = int(max_int16 * test_tone_max_abs)
233 audio = display.Audio(test_tone, rate=44100, normalize=False)
234 actual_max_value = numpy.max(numpy.abs(read_wav(audio.data)))
235 assert actual_max_value == expected_max_value
236
237 def test_audio_data_without_normalization_raises_for_invalid_data(self):
238 self.assertRaises(
239 ValueError, lambda: display.Audio([1.001], rate=44100, normalize=False)
240 )
241 self.assertRaises(
242 ValueError, lambda: display.Audio([-1.001], rate=44100, normalize=False)
243 )
244
245
246 def simulate_numpy_not_installed():
247 try:
248 import numpy
249
250 return mock.patch("numpy.array", mock.MagicMock(side_effect=ImportError))
251 except ModuleNotFoundError:
252 return lambda x: x
253
254
255 @simulate_numpy_not_installed()
256 class TestAudioDataWithoutNumpy(TestAudioDataWithNumpy):
257 # All tests from `TestAudioDataWithNumpy` are inherited.
258
259 @skipif_not_numpy
260 def test_audio_raises_for_nested_list(self):
261 stereo_signal = [list(get_test_tone())] * 2
262 self.assertRaises(TypeError, lambda: display.Audio(stereo_signal, rate=44100))
263
264
265 @skipif_not_numpy
266 def get_test_tone(scale=1):
267 return numpy.sin(2 * numpy.pi * 440 * numpy.linspace(0, 1, 44100)) * scale
268
269
270 def read_wav(data):
271 with wave.open(BytesIO(data)) as wave_file:
272 wave_data = wave_file.readframes(wave_file.getnframes())
273 num_samples = wave_file.getnframes() * wave_file.getnchannels()
274 return struct.unpack("<%sh" % num_samples, wave_data)
275
276
277 def test_code_from_file():
278 c = display.Code(filename=__file__)
279 assert c._repr_html_().startswith("<style>")