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