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