##// END OF EJS Templates
Merge pull request #13888 from krassowski/improve-autosugessions...
Merge pull request #13888 from krassowski/improve-autosugessions Improve autosugessions

File last commit:

r26913:a1ddd3bc
r28043:855e4595 merge
Show More
test_display.py
272 lines | 9.1 KiB | text/x-python | PythonLexer
Greg Caporaso
added test file for the display module, beginning with basic tests of the FileLink, FileLinks, and DirectoryLink classes
r8366 """Tests for IPython.lib.display.
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2012, the IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
Greg Caporaso
added tests of formatting functionality
r8369 from tempfile import NamedTemporaryFile, mkdtemp
Thomas Kluyver
Add failing test for Audio display object
r13548 from os.path import split, join as pjoin, dirname
Terry Davis
Remove unused sys & fallback pathlib (3.5+) imports.
r25447 import pathlib
Matan Gover
Add normalize parameter to Audio.
r24973 from unittest import TestCase, mock
import struct
import wave
from io import BytesIO
Greg Caporaso
added test file for the display module, beginning with basic tests of the FileLink, FileLinks, and DirectoryLink classes
r8366
# Third-party imports
Samuel Gaist
[lib][tests][deepreload] Remove nose
r26913 import pytest
Matthias Bussonnier
Properly don't require numpy to run tests....
r25029
try:
import numpy
except ImportError:
pass
Greg Caporaso
added test file for the display module, beginning with basic tests of the FileLink, FileLinks, and DirectoryLink classes
r8366
# Our own imports
from IPython.lib import display
Matthias Bussonnier
Properly don't require numpy to run tests....
r25029 from IPython.testing.decorators import skipif_not_numpy
Greg Caporaso
added test file for the display module, beginning with basic tests of the FileLink, FileLinks, and DirectoryLink classes
r8366 #-----------------------------------------------------------------------------
# Classes and functions
#-----------------------------------------------------------------------------
#--------------------------
# FileLink tests
#--------------------------
def test_instantiation_FileLink():
Greg Caporaso
removing DirectoryLink class (which was an alias for FileLink) and modifying FileLink to raise an error if a directory is provided. @ellisonbg pointed out that these give a 404. I think removing this for now is the way to go as we don't have an immediate use case for DirectoryLink - FileLinks is what we would want users to call for linking to a directory.
r8835 """FileLink: Test class can be instantiated"""
Greg Caporaso
added test file for the display module, beginning with basic tests of the FileLink, FileLinks, and DirectoryLink classes
r8366 fl = display.FileLink('example.txt')
Cristian Ciupitu
FileLink: add test with path-like object...
r24228 # TODO: remove if when only Python >= 3.6 is supported
kousik
Removed codepath for Python < 3.6 from test functions #11949
r25246 fl = display.FileLink(pathlib.PurePath('example.txt'))
Greg Caporaso
added test file for the display module, beginning with basic tests of the FileLink, FileLinks, and DirectoryLink classes
r8366
Min ho Kim
Fixed typos
r25167 def test_warning_on_non_existent_path_FileLink():
Samuel Gaist
[lib][tests][deepreload] Remove nose
r26913 """FileLink: Calling _repr_html_ on non-existent files returns a warning"""
fl = display.FileLink("example.txt")
assert fl._repr_html_().startswith("Path (<tt>example.txt</tt>)")
Greg Caporaso
added test file for the display module, beginning with basic tests of the FileLink, FileLinks, and DirectoryLink classes
r8366
Greg Caporaso
added tests of formatting functionality
r8369 def test_existing_path_FileLink():
Greg Caporaso
removing DirectoryLink class (which was an alias for FileLink) and modifying FileLink to raise an error if a directory is provided. @ellisonbg pointed out that these give a 404. I think removing this for now is the way to go as we don't have an immediate use case for DirectoryLink - FileLinks is what we would want users to call for linking to a directory.
r8835 """FileLink: Calling _repr_html_ functions as expected on existing filepath
"""
Greg Caporaso
added tests of formatting functionality
r8369 tf = NamedTemporaryFile()
fl = display.FileLink(tf.name)
actual = fl._repr_html_()
Matthias Bussonnier
start removing nose from IPython/lib/tests/test_display.py
r26722 expected = "<a href='%s' target='_blank'>%s</a><br>" % (tf.name, tf.name)
assert actual == expected
Greg Caporaso
added tests of formatting functionality
r8369
Greg Caporaso
added tests of repr()
r8444 def test_existing_path_FileLink_repr():
Greg Caporaso
removing DirectoryLink class (which was an alias for FileLink) and modifying FileLink to raise an error if a directory is provided. @ellisonbg pointed out that these give a 404. I think removing this for now is the way to go as we don't have an immediate use case for DirectoryLink - FileLinks is what we would want users to call for linking to a directory.
r8835 """FileLink: Calling repr() functions as expected on existing filepath
"""
Greg Caporaso
added tests of repr()
r8444 tf = NamedTemporaryFile()
fl = display.FileLink(tf.name)
actual = repr(fl)
expected = tf.name
Matthias Bussonnier
start removing nose from IPython/lib/tests/test_display.py
r26722 assert actual == expected
Greg Caporaso
added tests of repr()
r8444
Greg Caporaso
added tests to confirm that error is raise when FileLink is passed a directory. Also specifically disallowed passing a file to FileLinks for consistency.
r8836 def test_error_on_directory_to_FileLink():
"""FileLink: Raises error when passed directory
"""
td = mkdtemp()
Samuel Gaist
[lib][tests][deepreload] Remove nose
r26913 pytest.raises(ValueError, display.FileLink, td)
Greg Caporaso
added tests to confirm that error is raise when FileLink is passed a directory. Also specifically disallowed passing a file to FileLinks for consistency.
r8836
Greg Caporaso
added test file for the display module, beginning with basic tests of the FileLink, FileLinks, and DirectoryLink classes
r8366 #--------------------------
# FileLinks tests
#--------------------------
def test_instantiation_FileLinks():
Greg Caporaso
removing DirectoryLink class (which was an alias for FileLink) and modifying FileLink to raise an error if a directory is provided. @ellisonbg pointed out that these give a 404. I think removing this for now is the way to go as we don't have an immediate use case for DirectoryLink - FileLinks is what we would want users to call for linking to a directory.
r8835 """FileLinks: Test class can be instantiated
"""
Greg Caporaso
added tests of formatting functionality
r8369 fls = display.FileLinks('example')
Greg Caporaso
added test file for the display module, beginning with basic tests of the FileLink, FileLinks, and DirectoryLink classes
r8366
Min ho Kim
Fixed typos
r25167 def test_warning_on_non_existent_path_FileLinks():
Samuel Gaist
[lib][tests][deepreload] Remove nose
r26913 """FileLinks: Calling _repr_html_ on non-existent files returns a warning"""
fls = display.FileLinks("example")
assert fls._repr_html_().startswith("Path (<tt>example</tt>)")
Greg Caporaso
added test file for the display module, beginning with basic tests of the FileLink, FileLinks, and DirectoryLink classes
r8366
Greg Caporaso
added tests of formatting functionality
r8369 def test_existing_path_FileLinks():
Greg Caporaso
removing DirectoryLink class (which was an alias for FileLink) and modifying FileLink to raise an error if a directory is provided. @ellisonbg pointed out that these give a 404. I think removing this for now is the way to go as we don't have an immediate use case for DirectoryLink - FileLinks is what we would want users to call for linking to a directory.
r8835 """FileLinks: Calling _repr_html_ functions as expected on existing dir
"""
Greg Caporaso
added tests of formatting functionality
r8369 td = mkdtemp()
tf1 = NamedTemporaryFile(dir=td)
tf2 = NamedTemporaryFile(dir=td)
fl = display.FileLinks(td)
actual = fl._repr_html_()
actual = actual.split('\n')
actual.sort()
Greg Caporaso
this should address the failure in #2732...
r9093 # the links should always have forward slashes, even on windows, so replace
# backslashes with forward slashes here
Greg Caporaso
noew removes trailing slashes if they are provided in input so the output can be formatted consistently by always appending a trailing slash (which previously could result in two trailing slashes if the input path included a trailing slash)
r8631 expected = ["%s/<br>" % td,
MinRK
there shouldn't be a 'files/' prefix in FileLink[s]...
r14894 "&nbsp;&nbsp;<a href='%s' target='_blank'>%s</a><br>" %\
Greg Caporaso
this should address the failure in #2732...
r9093 (tf2.name.replace("\\","/"),split(tf2.name)[1]),
MinRK
there shouldn't be a 'files/' prefix in FileLink[s]...
r14894 "&nbsp;&nbsp;<a href='%s' target='_blank'>%s</a><br>" %\
Greg Caporaso
this should address the failure in #2732...
r9093 (tf1.name.replace("\\","/"),split(tf1.name)[1])]
Greg Caporaso
added tests of formatting functionality
r8369 expected.sort()
# We compare the sorted list of links here as that's more reliable
Matthias Bussonnier
start removing nose from IPython/lib/tests/test_display.py
r26722 assert actual == expected
Greg Caporaso
added tests of formatting functionality
r8369
Greg Caporaso
added tests of passing alternative formatter functions
r8632 def test_existing_path_FileLinks_alt_formatter():
Greg Caporaso
removing DirectoryLink class (which was an alias for FileLink) and modifying FileLink to raise an error if a directory is provided. @ellisonbg pointed out that these give a 404. I think removing this for now is the way to go as we don't have an immediate use case for DirectoryLink - FileLinks is what we would want users to call for linking to a directory.
r8835 """FileLinks: Calling _repr_html_ functions as expected w/ an alt formatter
Greg Caporaso
added tests of passing alternative formatter functions
r8632 """
td = mkdtemp()
tf1 = NamedTemporaryFile(dir=td)
tf2 = NamedTemporaryFile(dir=td)
Greg Caporaso
added included_suffixes as an option to display formatters - previously it wasn't possible to pass these in if defining custom display formatters
r8802 def fake_formatter(dirname,fnames,included_suffixes):
Greg Caporaso
updating to make interface more intuitive now that we're not using os.path.walk
r8801 return ["hello","world"]
Greg Caporaso
added tests of passing alternative formatter functions
r8632 fl = display.FileLinks(td,notebook_display_formatter=fake_formatter)
actual = fl._repr_html_()
actual = actual.split('\n')
actual.sort()
expected = ["hello","world"]
expected.sort()
# We compare the sorted list of links here as that's more reliable
Matthias Bussonnier
start removing nose from IPython/lib/tests/test_display.py
r26722 assert actual == expected
Greg Caporaso
added tests of passing alternative formatter functions
r8632
Greg Caporaso
added tests of repr()
r8444 def test_existing_path_FileLinks_repr():
Greg Caporaso
removing DirectoryLink class (which was an alias for FileLink) and modifying FileLink to raise an error if a directory is provided. @ellisonbg pointed out that these give a 404. I think removing this for now is the way to go as we don't have an immediate use case for DirectoryLink - FileLinks is what we would want users to call for linking to a directory.
r8835 """FileLinks: Calling repr() functions as expected on existing directory """
Greg Caporaso
added tests of repr()
r8444 td = mkdtemp()
tf1 = NamedTemporaryFile(dir=td)
tf2 = NamedTemporaryFile(dir=td)
fl = display.FileLinks(td)
actual = repr(fl)
actual = actual.split('\n')
actual.sort()
Greg Caporaso
noew removes trailing slashes if they are provided in input so the output can be formatted consistently by always appending a trailing slash (which previously could result in two trailing slashes if the input path included a trailing slash)
r8631 expected = ['%s/' % td, ' %s' % split(tf1.name)[1],' %s' % split(tf2.name)[1]]
Greg Caporaso
added tests of repr()
r8444 expected.sort()
# We compare the sorted list of links here as that's more reliable
Matthias Bussonnier
start removing nose from IPython/lib/tests/test_display.py
r26722 assert actual == expected
Greg Caporaso
added tests of passing alternative formatter functions
r8632 def test_existing_path_FileLinks_repr_alt_formatter():
Greg Caporaso
removing DirectoryLink class (which was an alias for FileLink) and modifying FileLink to raise an error if a directory is provided. @ellisonbg pointed out that these give a 404. I think removing this for now is the way to go as we don't have an immediate use case for DirectoryLink - FileLinks is what we would want users to call for linking to a directory.
r8835 """FileLinks: Calling repr() functions as expected w/ alt formatter
Greg Caporaso
added tests of passing alternative formatter functions
r8632 """
td = mkdtemp()
tf1 = NamedTemporaryFile(dir=td)
tf2 = NamedTemporaryFile(dir=td)
Greg Caporaso
added included_suffixes as an option to display formatters - previously it wasn't possible to pass these in if defining custom display formatters
r8802 def fake_formatter(dirname,fnames,included_suffixes):
Greg Caporaso
updating to make interface more intuitive now that we're not using os.path.walk
r8801 return ["hello","world"]
Greg Caporaso
added tests of passing alternative formatter functions
r8632 fl = display.FileLinks(td,terminal_display_formatter=fake_formatter)
actual = repr(fl)
actual = actual.split('\n')
actual.sort()
expected = ["hello","world"]
expected.sort()
# We compare the sorted list of links here as that's more reliable
Matthias Bussonnier
start removing nose from IPython/lib/tests/test_display.py
r26722 assert actual == expected
Greg Caporaso
added tests to confirm that error is raise when FileLink is passed a directory. Also specifically disallowed passing a file to FileLinks for consistency.
r8836 def test_error_on_file_to_FileLinks():
"""FileLinks: Raises error when passed file
"""
td = mkdtemp()
tf1 = NamedTemporaryFile(dir=td)
Samuel Gaist
[lib][tests][deepreload] Remove nose
r26913 pytest.raises(ValueError, display.FileLinks, tf1.name)
Greg Caporaso
added tests of repr()
r8444
Doug Blank
recursive==False uses next(iter) for PY3 compatability; added tests to make sure it doesn't recurse
r19367 def test_recursive_FileLinks():
"""FileLinks: Does not recurse when recursive=False
"""
td = mkdtemp()
tf = NamedTemporaryFile(dir=td)
subtd = mkdtemp(dir=td)
subtf = NamedTemporaryFile(dir=subtd)
fl = display.FileLinks(td)
actual = str(fl)
actual = actual.split('\n')
Matthias Bussonnier
start removing nose from IPython/lib/tests/test_display.py
r26722 assert len(actual) == 4, actual
Doug Blank
recursive==False uses next(iter) for PY3 compatability; added tests to make sure it doesn't recurse
r19367 fl = display.FileLinks(td, recursive=False)
actual = str(fl)
actual = actual.split('\n')
Matthias Bussonnier
start removing nose from IPython/lib/tests/test_display.py
r26722 assert len(actual) == 2, actual
Doug Blank
recursive==False uses next(iter) for PY3 compatability; added tests to make sure it doesn't recurse
r19367
Thomas Kluyver
Add failing test for Audio display object
r13548 def test_audio_from_file():
path = pjoin(dirname(__file__), 'test.wav')
Doug Blank
recursive==False uses next(iter) for PY3 compatability; added tests to make sure it doesn't recurse
r19367 display.Audio(filename=path)
Thomas Kluyver
Add display class for syntax-highlighted code
r24130
Matan Gover
Add normalize parameter to Audio.
r24973 class TestAudioDataWithNumpy(TestCase):
Matthias Bussonnier
Properly don't require numpy to run tests....
r25029
@skipif_not_numpy
Matan Gover
Add normalize parameter to Audio.
r24973 def test_audio_from_numpy_array(self):
test_tone = get_test_tone()
audio = display.Audio(test_tone, rate=44100)
Matthias Bussonnier
start removing nose from IPython/lib/tests/test_display.py
r26722 assert len(read_wav(audio.data)) == len(test_tone)
Matan Gover
Add normalize parameter to Audio.
r24973
Matthias Bussonnier
Properly don't require numpy to run tests....
r25029 @skipif_not_numpy
Matan Gover
Add normalize parameter to Audio.
r24973 def test_audio_from_list(self):
test_tone = get_test_tone()
audio = display.Audio(list(test_tone), rate=44100)
Matthias Bussonnier
start removing nose from IPython/lib/tests/test_display.py
r26722 assert len(read_wav(audio.data)) == len(test_tone)
Matan Gover
Add normalize parameter to Audio.
r24973
Matthias Bussonnier
Properly don't require numpy to run tests....
r25029 @skipif_not_numpy
Matan Gover
Add normalize parameter to Audio.
r24973 def test_audio_from_numpy_array_without_rate_raises(self):
Samuel Gaist
[lib][tests][deepreload] Remove nose
r26913 self.assertRaises(ValueError, display.Audio, get_test_tone())
Matan Gover
Add normalize parameter to Audio.
r24973
Matthias Bussonnier
Properly don't require numpy to run tests....
r25029 @skipif_not_numpy
Matan Gover
Add normalize parameter to Audio.
r24973 def test_audio_data_normalization(self):
expected_max_value = numpy.iinfo(numpy.int16).max
for scale in [1, 0.5, 2]:
audio = display.Audio(get_test_tone(scale), rate=44100)
actual_max_value = numpy.max(numpy.abs(read_wav(audio.data)))
Matthias Bussonnier
start removing nose from IPython/lib/tests/test_display.py
r26722 assert actual_max_value == expected_max_value
Matan Gover
Add normalize parameter to Audio.
r24973
Matthias Bussonnier
Properly don't require numpy to run tests....
r25029 @skipif_not_numpy
Matan Gover
Add normalize parameter to Audio.
r24973 def test_audio_data_without_normalization(self):
max_int16 = numpy.iinfo(numpy.int16).max
for scale in [1, 0.5, 0.2]:
test_tone = get_test_tone(scale)
test_tone_max_abs = numpy.max(numpy.abs(test_tone))
expected_max_value = int(max_int16 * test_tone_max_abs)
audio = display.Audio(test_tone, rate=44100, normalize=False)
actual_max_value = numpy.max(numpy.abs(read_wav(audio.data)))
Matthias Bussonnier
start removing nose from IPython/lib/tests/test_display.py
r26722 assert actual_max_value == expected_max_value
Matan Gover
Add normalize parameter to Audio.
r24973
def test_audio_data_without_normalization_raises_for_invalid_data(self):
Samuel Gaist
[lib][tests][deepreload] Remove nose
r26913 self.assertRaises(
Matan Gover
Add normalize parameter to Audio.
r24973 ValueError,
lambda: display.Audio([1.001], rate=44100, normalize=False))
Samuel Gaist
[lib][tests][deepreload] Remove nose
r26913 self.assertRaises(
Matan Gover
Add normalize parameter to Audio.
r24973 ValueError,
lambda: display.Audio([-1.001], rate=44100, normalize=False))
def simulate_numpy_not_installed():
Matthias Bussonnier
more skipping numpy when not installed
r25032 try:
import numpy
return mock.patch('numpy.array', mock.MagicMock(side_effect=ImportError))
except ModuleNotFoundError:
return lambda x:x
Matan Gover
Add normalize parameter to Audio.
r24973
@simulate_numpy_not_installed()
class TestAudioDataWithoutNumpy(TestAudioDataWithNumpy):
# All tests from `TestAudioDataWithNumpy` are inherited.
Matthias Bussonnier
Properly don't require numpy to run tests....
r25029 @skipif_not_numpy
Matan Gover
Add normalize parameter to Audio.
r24973 def test_audio_raises_for_nested_list(self):
Matan Gover
Fix Audio from data without numpy on Python 3.
r24972 stereo_signal = [list(get_test_tone())] * 2
Samuel Gaist
[lib][tests][deepreload] Remove nose
r26913 self.assertRaises(TypeError, lambda: display.Audio(stereo_signal, rate=44100))
Matan Gover
Add normalize parameter to Audio.
r24973
Matthias Bussonnier
more skipping numpy when not installed
r25032 @skipif_not_numpy
Matan Gover
Add normalize parameter to Audio.
r24973 def get_test_tone(scale=1):
return numpy.sin(2 * numpy.pi * 440 * numpy.linspace(0, 1, 44100)) * scale
def read_wav(data):
with wave.open(BytesIO(data)) as wave_file:
wave_data = wave_file.readframes(wave_file.getnframes())
num_samples = wave_file.getnframes() * wave_file.getnchannels()
return struct.unpack('<%sh' % num_samples, wave_data)
Matan Gover
Add basic tests for display.Audio from data....
r24971
Thomas Kluyver
Add display class for syntax-highlighted code
r24130 def test_code_from_file():
c = display.Code(filename=__file__)
assert c._repr_html_().startswith('<style>')