diff --git a/.travis.yml b/.travis.yml index d63ed602c0e2..fa9785a0a7f8 100644 --- a/.travis.yml +++ b/.travis.yml @@ -33,7 +33,7 @@ env: - NUMPY=numpy - PANDAS= - NPROC=2 - - TEST_ARGS=--no-pep8 + - TEST_ARGS= - NOSE_ARGS="--processes=$NPROC --process-timeout=300" language: python @@ -46,7 +46,7 @@ matrix: - python: 3.5 env: PANDAS=pandas NOSE_ARGS=--with-coverage - python: 3.5 - env: TEST_ARGS=--pep8 + env: TEST_ARGS=--pep8 -m pep8 - python: 3.5 env: BUILD_DOCS=true - python: "nightly" @@ -77,7 +77,15 @@ install: fi # Always install from pypi - pip install $PRE pep8 cycler coveralls coverage - - 'pip install git+https://github.com/jenshnielsen/nose.git@matplotlibnose' + # 'pip install git+https://github.com/jenshnielsen/nose.git@matplotlibnose' + - pip install pytest + + # some handy plugins for pytest, is this the right place to install them? + # https://pypi.python.org/pypi/pytest-cov for docs + - pip install pytest-cov + # https://pypi.python.org/pypi/pytest-pep8 for docs + - pip install pytest-pep8 + # We manually install humor sans using the package from Ubuntu 14.10. Unfortunatly humor sans is not # availible in the Ubuntu version used by Travis but we can manually install the deb from a later @@ -111,7 +119,7 @@ script: - | if [[ $BUILD_DOCS == false ]]; then export MPL_REPO_DIR=$PWD # needed for pep8-conformance test of the examples - gdb -return-child-result -batch -ex r -ex bt --args python tests.py $NOSE_ARGS $TEST_ARGS + gdb -return-child-result -batch -ex r -ex bt --args python tests.py $TEST_ARGS else cd doc python make.py html --small --warningsaserrors diff --git a/INSTALL b/INSTALL index 8df87b45f47d..4d0fa76a95b4 100644 --- a/INSTALL +++ b/INSTALL @@ -114,13 +114,13 @@ not contain test data or example code. If you want to try the many demos that come in the matplotlib source distribution, download the :file:`*.tar.gz` file and look in the :file:`examples` subdirectory. To run the test suite, copy the :file:`lib\matplotlib\tests` and -:file:`lib\mpl_toolkits\tests` directories from the source -distribution to :file:`sys.prefix\Lib\site-packages\matplotlib` and -:file:`sys.prefix\Lib\site-packages\mpl_toolkits` respectively, and -install `nose `_, `mock -`_, Pillow, MiKTeX, GhostScript, -ffmpeg, avconv, mencoder, ImageMagick, and `Inkscape -`_. +:file:`lib\mpl_toolkits\tests` directories from the source distribution to +:file:`sys.prefix\Lib\site-packages\matplotlib` and +:file:`sys.prefix\Lib\site-packages\mpl_toolkits` respectively, and install +`pytest `_, +`mock `_, +Pillow, MiKTeX, GhostScript, ffmpeg, avconv, mencoder, ImageMagick, and +`Inkscape `_. diff --git a/conftest.py b/conftest.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/doc/devel/testing.rst b/doc/devel/testing.rst index 8bbe720de771..de1358135ba6 100644 --- a/doc/devel/testing.rst +++ b/doc/devel/testing.rst @@ -3,20 +3,20 @@ Testing ======= -Matplotlib has a testing infrastructure based on nose_, making it easy +Matplotlib has a testing infrastructure based on pytest, making it easy to write new tests. The tests are in :mod:`matplotlib.tests`, and -customizations to the nose testing infrastructure are in +customizations to the pytest testing infrastructure are in :mod:`matplotlib.testing`. (There is other old testing cruft around, please ignore it while we consolidate our testing to these locations.) -.. _nose: http://nose.readthedocs.org/en/latest/ +.. pytest: http://pytest.readthedocs.org/en/latest/ Requirements ------------ The following software is required to run the tests: - - nose_, version 1.0 or later + - pytest - `mock `_, when running python versions < 3.3 @@ -33,6 +33,10 @@ Optionally you can install: - `pep8 `_ to test coding standards + - `pytest-cov `_ for coverage stats in pytest + + - `pytest-pep8 `_ for pep8 conformance in pytest + Building matplotlib for image comparison tests ---------------------------------------------- @@ -52,7 +56,7 @@ matplotlib source directory:: Running the tests ----------------- -Running the tests is simple. Make sure you have nose installed and run:: +Running the tests is simple. Make sure you have pytest installed and run:: python tests.py @@ -112,15 +116,15 @@ Writing a simple test Many elements of Matplotlib can be tested using standard tests. For example, here is a test from :mod:`matplotlib.tests.test_basic`:: - from nose.tools import assert_equal + import pytest def test_simple(): """ very simple example test """ - assert_equal(1+1,2) + assert 1+1 == 2 -Nose determines which functions are tests by searching for functions +Pytest determines which functions are tests by searching for functions beginning with "test" in their name. If the test has side effects that need to be cleaned up, such as @@ -203,7 +207,7 @@ Known failing tests ------------------- If you're writing a test, you may mark it as a known failing test with -the :func:`~matplotlib.testing.decorators.knownfailureif` +the :func:`~pytest.mark.xfail` decorator. This allows the test to be added to the test suite and run on the buildbots without causing undue alarm. For example, although the following test will fail, it is an expected failure:: @@ -211,7 +215,7 @@ the following test will fail, it is an expected failure:: from nose.tools import assert_equal from matplotlib.testing.decorators import knownfailureif - @knownfailureif(True) + @pytest.mark.xfail() def test_simple_fail(): '''very simple example test that should fail''' assert_equal(1+1,3) diff --git a/lib/matplotlib/__init__.py b/lib/matplotlib/__init__.py index 3c7e1c923f14..6b0322cf2440 100644 --- a/lib/matplotlib/__init__.py +++ b/lib/matplotlib/__init__.py @@ -1515,21 +1515,22 @@ def _init_tests(): "Expect many image comparison failures below.") try: - import nose + # import nose try: from unittest import mock except: import mock except ImportError: - print("matplotlib.test requires nose and mock to run.") + print("matplotlib.test requires mock to run. nose is currently being removed") raise def _get_extra_test_plugins(): - from .testing.noseclasses import KnownFailure - from nose.plugins import attrib + # from .testing.noseclasses import KnownFailure + # from nose.plugins import attrib - return [KnownFailure, attrib.Plugin] + #return [KnownFailure, attrib.Plugin] + pass def _get_nose_env(): diff --git a/lib/matplotlib/ignorenumpytests.py b/lib/matplotlib/ignorenumpytests.py new file mode 100644 index 000000000000..8713c731a143 --- /dev/null +++ b/lib/matplotlib/ignorenumpytests.py @@ -0,0 +1,29 @@ +import pytest +""" +So pytest is trying to load tests in numpy, and generates this error + +____________________________ ERROR at setup of test ____________________________ +file /home/travis/build/matplotlib/matplotlib/venv/lib/python2.7/site-packages/ +numpy/testing/nosetester.py, line 249 + def test(self, label='fast', verbose=1, extra_argv=None, doctests=False, + fixture 'self' not found + available fixtures: tmpdir_factory, pytestconfig, cov, cache, recwarn, + monkeypatch, record_xml_property, capfd, capsys, tmpdir + + use 'py.test --fixtures [testpath]' for help on them. +/home/travis/build/matplotlib/matplotlib/venv/lib/python2.7/site-packages/ + numpy/testing/nosetester.py:249 + +this file is intended to stop that behaviour, by blocking files from +being considered for collection if "numpy" is in the path +""" + +def pytest_ignore_collect(path, config): + if 'numpy' not in path.basename: + print('allowing ', path) + return True + else: + print('blocking ', path) + return False + +# return 'numpy' not in path.basename: \ No newline at end of file diff --git a/lib/matplotlib/sphinxext/tests/test_tinypages.py b/lib/matplotlib/sphinxext/tests/test_tinypages.py index 1b1834f478cc..6dc7e8ce8856 100644 --- a/lib/matplotlib/sphinxext/tests/test_tinypages.py +++ b/lib/matplotlib/sphinxext/tests/test_tinypages.py @@ -7,8 +7,7 @@ from subprocess import call, Popen, PIPE -from nose import SkipTest -from nose.tools import assert_true +import pytest HERE = dirname(__file__) TINY_PAGES = pjoin(HERE, 'tinypages') @@ -19,7 +18,7 @@ def setup(): try: ret = call(['sphinx-build', '--help'], stdout=PIPE, stderr=PIPE) except OSError: - raise SkipTest('Need sphinx-build on path for these tests') + raise pytest.skip('Need sphinx-build on path for these tests') if ret != 0: raise RuntimeError('sphinx-build does not return 0') @@ -62,29 +61,29 @@ def teardown_class(cls): shutil.rmtree(cls.page_build) def test_some_plots(self): - assert_true(isdir(self.html_dir)) + assert isdir(self.html_dir) def plot_file(num): return pjoin(self.html_dir, 'some_plots-{0}.png'.format(num)) range_10, range_6, range_4 = [plot_file(i) for i in range(1, 4)] # Plot 5 is range(6) plot - assert_true(file_same(range_6, plot_file(5))) + assert file_same(range_6, plot_file(5)) # Plot 7 is range(4) plot - assert_true(file_same(range_4, plot_file(7))) + assert file_same(range_4, plot_file(7)) # Plot 11 is range(10) plot - assert_true(file_same(range_10, plot_file(11))) + assert file_same(range_10, plot_file(11)) # Plot 12 uses the old range(10) figure and the new range(6) figure - assert_true(file_same(range_10, plot_file('12_00'))) - assert_true(file_same(range_6, plot_file('12_01'))) + assert file_same(range_10, plot_file('12_00')) + assert file_same(range_6, plot_file('12_01')) # Plot 13 shows close-figs in action - assert_true(file_same(range_4, plot_file(13))) + assert file_same(range_4, plot_file(13)) # Plot 14 has included source with open(pjoin(self.html_dir, 'some_plots.html'), 'rt') as fobj: html_contents = fobj.read() - assert_true('# Only a comment' in html_contents) + assert '# Only a comment' in html_contents # check plot defined in external file. - assert_true(file_same(range_4, pjoin(self.html_dir, 'range4.png'))) - assert_true(file_same(range_6, pjoin(self.html_dir, 'range6.png'))) + assert file_same(range_4, pjoin(self.html_dir, 'range4.png')) + assert file_same(range_6, pjoin(self.html_dir, 'range6.png')) # check if figure caption made it into html file - assert_true('This is the caption for plot 15.' in html_contents) + assert 'This is the caption for plot 15.' in html_contents diff --git a/lib/matplotlib/testing/decorators.py b/lib/matplotlib/testing/decorators.py index a73dbd150504..5f02bb358034 100644 --- a/lib/matplotlib/testing/decorators.py +++ b/lib/matplotlib/testing/decorators.py @@ -11,7 +11,6 @@ import warnings import unittest -import nose import numpy as np import matplotlib as mpl @@ -23,50 +22,51 @@ from matplotlib import pyplot as plt from matplotlib import ft2font from matplotlib import rcParams -from matplotlib.testing.noseclasses import KnownFailureTest, \ - KnownFailureDidNotFailTest, ImageComparisonFailure +from matplotlib.testing.noseclasses import KnownFailureDidNotFailTest, \ + ImageComparisonFailure from matplotlib.testing.compare import comparable_formats, compare_images, \ make_test_filename - - -def knownfailureif(fail_condition, msg=None, known_exception_class=None ): - """ - - Assume a will fail if *fail_condition* is True. *fail_condition* - may also be False or the string 'indeterminate'. - - *msg* is the error message displayed for the test. - - If *known_exception_class* is not None, the failure is only known - if the exception is an instance of this class. (Default = None) - - """ - # based on numpy.testing.dec.knownfailureif - if msg is None: - msg = 'Test known to fail' - def known_fail_decorator(f): - # Local import to avoid a hard nose dependency and only incur the - # import time overhead at actual test-time. - import nose - def failer(*args, **kwargs): - try: - # Always run the test (to generate images). - result = f(*args, **kwargs) - except Exception as err: - if fail_condition: - if known_exception_class is not None: - if not isinstance(err,known_exception_class): - # This is not the expected exception - raise - # (Keep the next ultra-long comment so in shows in console.) - raise KnownFailureTest(msg) # An error here when running nose means that you don't have the matplotlib.testing.noseclasses:KnownFailure plugin in use. - else: - raise - if fail_condition and fail_condition != 'indeterminate': - raise KnownFailureDidNotFailTest(msg) - return result - return nose.tools.make_decorator(f)(failer) - return known_fail_decorator +import pytest + + +# def knownfailureif(fail_condition, msg=None, known_exception_class=None ): +# """ +# +# Assume a will fail if *fail_condition* is True. *fail_condition* +# may also be False or the string 'indeterminate'. +# +# *msg* is the error message displayed for the test. +# +# If *known_exception_class* is not None, the failure is only known +# if the exception is an instance of this class. (Default = None) +# +# """ +# # based on numpy.testing.dec.knownfailureif +# if msg is None: +# msg = 'Test known to fail' +# def known_fail_decorator(f): +# # Local import to avoid a hard nose dependency and only incur the +# # import time overhead at actual test-time. +# import nose +# def failer(*args, **kwargs): +# try: +# # Always run the test (to generate images). +# result = f(*args, **kwargs) +# except Exception as err: +# if fail_condition: +# if known_exception_class is not None: +# if not isinstance(err,known_exception_class): +# # This is not the expected exception +# raise +# # (Keep the next ultra-long comment so in shows in console.) +# raise pytest.xfail(msg) # An error here when running nose means that you don't have the matplotlib.testing.noseclasses:KnownFailure plugin in use. +# else: +# raise +# if fail_condition and fail_condition != 'indeterminate': +# raise KnownFailureDidNotFailTest(msg) +# return result +# return nose.tools.make_decorator(f)(failer) +# return known_fail_decorator def _do_cleanup(original_units_registry, original_settings): @@ -220,7 +220,7 @@ def test(self): will_fail = True fail_msg = 'Do not have baseline image %s' % expected_fname - @knownfailureif( + @pytest.mark.xfail( will_fail, fail_msg, known_exception_class=ImageComparisonFailure) def do_test(): @@ -245,13 +245,43 @@ def do_test(): '(RMS %(rms).3f)'%err) except ImageComparisonFailure: if not check_freetype_version(self._freetype_version): - raise KnownFailureTest( + raise pytest.xfail( "Mismatched version of freetype. Test requires '%s', you have '%s'" % (self._freetype_version, ft2font.__freetype_version__)) raise yield (do_test,) + +def image_comparison_2(baseline_images=None, extensions=None, tol=0, + freetype_version=None, remove_text=False, + savefig_kwarg=None, style='classic'): + if baseline_images is None: + raise ValueError('baseline_images must be specified') + + if extensions is None: + # default extensions to test + extensions = ['png', 'pdf', 'svg'] + + if savefig_kwarg is None: + #default no kwargs to savefig + savefig_kwarg = dict() + + def compare_images_decorator(func): + newtest = ImageComparisonTest() + newtest._baseline_images = baseline_images + newtest._extensions = extensions + newtest._tol = tol + newtest._freetype_version = freetype_version + newtest._remove_text = remove_text + newtest._savefig_kwarg = savefig_kwarg + newtest._style = style + newtest._func = newtest.test + func = newtest.test + return func + return compare_images_decorator + + def image_comparison(baseline_images=None, extensions=None, tol=0, freetype_version=None, remove_text=False, savefig_kwarg=None, style='classic'): @@ -338,6 +368,7 @@ def compare_images_decorator(func): return new_class return compare_images_decorator + def _image_directories(func): """ Compute the baseline and result image directories for testing *func*. @@ -410,5 +441,5 @@ def backend_switcher(*args, **kwargs): plt.switch_backend(prev_backend) return result - return nose.tools.make_decorator(func)(backend_switcher) + return backend_switcher return switch_backend_decorator diff --git a/lib/matplotlib/testing/noseclasses.py b/lib/matplotlib/testing/noseclasses.py index d2ad1dde96fe..73106ccf07b0 100644 --- a/lib/matplotlib/testing/noseclasses.py +++ b/lib/matplotlib/testing/noseclasses.py @@ -4,50 +4,50 @@ from matplotlib.externals import six import os -from nose.plugins.errorclass import ErrorClass, ErrorClassPlugin +# from nose.plugins.errorclass import ErrorClass, ErrorClassPlugin from matplotlib.testing.exceptions import (KnownFailureTest, KnownFailureDidNotFailTest, ImageComparisonFailure) -class KnownFailure(ErrorClassPlugin): - '''Plugin that installs a KNOWNFAIL error class for the - KnownFailureClass exception. When KnownFailureTest is raised, - the exception will be logged in the knownfail attribute of the - result, 'K' or 'KNOWNFAIL' (verbose) will be output, and the - exception will not be counted as an error or failure. - - This is based on numpy.testing.noseclasses.KnownFailure. - ''' - enabled = True - knownfail = ErrorClass(KnownFailureTest, - label='KNOWNFAIL', - isfailure=False) - - def options(self, parser, env=os.environ): - env_opt = 'NOSE_WITHOUT_KNOWNFAIL' - parser.add_option('--no-knownfail', action='store_true', - dest='noKnownFail', default=env.get(env_opt, False), - help='Disable special handling of KnownFailureTest ' - 'exceptions') - - def configure(self, options, conf): - if not self.can_configure: - return - self.conf = conf - disable = getattr(options, 'noKnownFail', False) - if disable: - self.enabled = False - - def addError(self, test, err, *zero_nine_capt_args): - # Fixme (Really weird): if I don't leave empty method here, - # nose gets confused and KnownFails become testing errors when - # using the MplNosePlugin and MplTestCase. - - # The *zero_nine_capt_args captures an extra argument. There - # seems to be a bug in - # nose.testing.manager.ZeroNinePlugin.addError() in which a - # 3rd positional argument ("capt") is passed to the plugin's - # addError() method, even if one is not explicitly using the - # ZeroNinePlugin. - pass +# class KnownFailure(ErrorClassPlugin): +# '''Plugin that installs a KNOWNFAIL error class for the +# KnownFailureClass exception. When KnownFailureTest is raised, +# the exception will be logged in the knownfail attribute of the +# result, 'K' or 'KNOWNFAIL' (verbose) will be output, and the +# exception will not be counted as an error or failure. +# +# This is based on numpy.testing.noseclasses.KnownFailure. +# ''' +# enabled = True +# knownfail = ErrorClass(KnownFailureTest, +# label='KNOWNFAIL', +# isfailure=False) +# +# def options(self, parser, env=os.environ): +# env_opt = 'NOSE_WITHOUT_KNOWNFAIL' +# parser.add_option('--no-knownfail', action='store_true', +# dest='noKnownFail', default=env.get(env_opt, False), +# help='Disable special handling of KnownFailureTest ' +# 'exceptions') +# +# def configure(self, options, conf): +# if not self.can_configure: +# return +# self.conf = conf +# disable = getattr(options, 'noKnownFail', False) +# if disable: +# self.enabled = False +# +# def addError(self, test, err, *zero_nine_capt_args): +# # Fixme (Really weird): if I don't leave empty method here, +# # nose gets confused and KnownFails become testing errors when +# # using the MplNosePlugin and MplTestCase. +# +# # The *zero_nine_capt_args captures an extra argument. There +# # seems to be a bug in +# # nose.testing.manager.ZeroNinePlugin.addError() in which a +# # 3rd positional argument ("capt") is passed to the plugin's +# # addError() method, even if one is not explicitly using the +# # ZeroNinePlugin. +# pass diff --git a/lib/matplotlib/tests/conftest.py b/lib/matplotlib/tests/conftest.py new file mode 100644 index 000000000000..8ee46ece5f9c --- /dev/null +++ b/lib/matplotlib/tests/conftest.py @@ -0,0 +1,108 @@ +from . import test_mathtext +import pytest +import matplotlib +import matplotlib.pyplot as plt +from matplotlib.testing.decorators import image_comparison, cleanup + + +@pytest.mark.parametrize('tests', +[ + (test_mathtext.math_tests), + (test_mathtext.font_tests) +]) +@pytest.mark.parametrize('basename,fontset,extensions', +[ + ('mathtext', 'cm', None), + ('mathtext', 'stix', None), + ('mathtext', 'stixsans', None), + ('mathtext', 'dejavusans', None), + ('mathtext', 'dejavuserif', None), + ('mathfont', 'cm', ['png']), + ('mathfont', 'stix', ['png']), + ('mathfont', 'stixsans', ['png']), + ('mathfont', 'dejavusans', ['png']), + ('mathfont', 'dejavuserif', ['png']), +]) +def test_make_set(basename, fontset, tests, extensions): + def make_test(filename, test): + @image_comparison(baseline_images=[filename], extensions=extensions) + def single_test(): + matplotlib.rcParams['mathtext.fontset'] = fontset + fig = plt.figure(figsize=(5.25, 0.75)) + fig.text(0.5, 0.5, test, horizontalalignment='center', + verticalalignment='center') + func = single_test + func.__name__ = str("test_" + filename) + return func + + # We inject test functions into the global namespace, rather than + # using a generator, so that individual tests can be run more + # easily from the commandline and so each test will have its own + # result. + for i, test in enumerate(tests): + filename = '%s_%s_%02d' % (basename, fontset, i) + globals()['test_%s' % filename] = make_test(filename, test) + + + +# def pytest_generate_tests(metafunc): +# if 'stringinput' in metafunc.fixturenames: +# metafunc.parametrize("stringinput", +# metafunc.config.option.stringinput) +# +import pytest + +def pytest_collect_file(parent, path): + if path.ext == ".py" and path.basename.contains("test_mathtext"): + return test_mathtextFile(path, parent) + +class test_mathtextFile(pytest.File): + def collect(self): + + make_set('mathtext', ) + math_tests = test_mathtext.math_tests + fonts = ['cm', 'stix', 'stixsans', 'dejavusans', 'dejavuserif',] + + make_set('mathfont', 'cm', font_tests, ['png']) + make_set('mathfont', 'stix', font_tests, ['png']) + make_set('mathfont', 'stixsans', font_tests, ['png']) + make_set('mathfont', 'dejavusans', font_tests, ['png']) + make_set('mathfont', 'dejavuserif', font_tests, ['png']) + + for i, test in enumerate(tests): + filename = '%s_%s_%02d' % (basename, fontset, i) + globals()['test_%s' % filename] = make_test(filename, test) + + raw = yaml.safe_load(self.fspath.open()) + for name, spec in raw.items(): + yield test_mathtextItem(filename, test, extensions) + +class test_mathtextItem(pytest.Item): + def __init__(self, filename, test, extensions): + super(test_mathtextItem, self).__init__(name, parent) + self.filename = filename + self.test = test + self.extensions = extensions + @image_comparison(baseline_images=[self.filename], + extensions=self.extensions) + def runtest(self): + matplotlib.rcParams['mathtext.fontset'] = fontset + fig = plt.figure(figsize=(5.25, 0.75)) + fig.text(0.5, 0.5, test, horizontalalignment='center', + verticalalignment='center') + + def repr_failure(self, excinfo): + """ called when self.runtest() raises an exception. """ + pass + # if isinstance(excinfo.value, YamlException): + # return "\n".join([ + # "usecase execution failed", + # " spec failed: %r: %r" % excinfo.value.args[1:3], + # " no further details known at this point." + # ]) + + def reportinfo(self): + return self.fspath, 0, "usecase: %s" % self.name + +class YamlException(Exception): + """ custom exception for error reporting. """ \ No newline at end of file diff --git a/lib/matplotlib/tests/test_animation.py b/lib/matplotlib/tests/test_animation.py index 2a62cfb7a2ac..3dd5b6e42b81 100644 --- a/lib/matplotlib/tests/test_animation.py +++ b/lib/matplotlib/tests/test_animation.py @@ -7,12 +7,11 @@ import tempfile import numpy as np from numpy.testing import assert_equal -from nose import with_setup from matplotlib import pyplot as plt from matplotlib import animation -from matplotlib.testing.noseclasses import KnownFailureTest from matplotlib.testing.decorators import cleanup from matplotlib.testing.decorators import CleanupTest +import pytest class NullMovieWriter(animation.AbstractMovieWriter): @@ -65,12 +64,12 @@ def animate(i): anim.save(filename, fps=fps, dpi=dpi, writer=writer, savefig_kwargs=savefig_kwargs) - assert_equal(writer.fig, fig) - assert_equal(writer.outfile, filename) - assert_equal(writer.dpi, dpi) - assert_equal(writer.args, ()) - assert_equal(writer.savefig_kwargs, savefig_kwargs) - assert_equal(writer._count, num_frames) + assert writer.fig == fig + assert writer.outfile == filename + assert writer.dpi == dpi + assert writer.args == () + assert writer.savefig_kwargs == savefig_kwargs + assert writer._count == num_frames @animation.writers.register('null') @@ -109,7 +108,7 @@ def test_save_animation_smoketest(): @cleanup def check_save_animation(writer, extension='mp4'): if not animation.writers.is_available(writer): - raise KnownFailureTest("writer '%s' not available on this system" + pytest.xfail("writer '%s' not available on this system" % writer) fig, ax = plt.subplots() line, = ax.plot([], []) @@ -134,7 +133,7 @@ def animate(i): try: anim.save(F.name, fps=30, writer=writer, bitrate=500) except UnicodeDecodeError: - raise KnownFailureTest("There can be errors in the numpy " + + pytest.xfail("There can be errors in the numpy " + "import stack, " + "see issues #1891 and #2679") finally: diff --git a/lib/matplotlib/tests/test_arrow_patches.py b/lib/matplotlib/tests/test_arrow_patches.py index 0a624d0e2801..7bbba651d3a1 100644 --- a/lib/matplotlib/tests/test_arrow_patches.py +++ b/lib/matplotlib/tests/test_arrow_patches.py @@ -50,8 +50,3 @@ def test_boxarrow(): size=fontsize, transform=fig1.transFigure, bbox=dict(boxstyle=stylename, fc="w", ec="k")) - - -if __name__ == '__main__': - import nose - nose.runmodule(argv=['-s', '--with-doctest'], exit=False) diff --git a/lib/matplotlib/tests/test_artist.py b/lib/matplotlib/tests/test_artist.py index f4eb54ae07de..ecf8e4ff1571 100644 --- a/lib/matplotlib/tests/test_artist.py +++ b/lib/matplotlib/tests/test_artist.py @@ -16,7 +16,7 @@ import matplotlib as mpl from matplotlib.testing.decorators import image_comparison, cleanup -from nose.tools import (assert_true, assert_false) +# from nose.tools import (assert_true, assert_false) @cleanup @@ -154,28 +154,28 @@ def test_remove(): im = ax.imshow(np.arange(36).reshape(6, 6)) ln, = ax.plot(range(5)) - assert_true(fig.stale) - assert_true(ax.stale) + assert fig.stale + assert ax.stale fig.canvas.draw() - assert_false(fig.stale) - assert_false(ax.stale) - assert_false(ln.stale) + assert not fig.stale + assert not ax.stale + assert not ln.stale - assert_true(im in ax.mouseover_set) - assert_true(ln not in ax.mouseover_set) - assert_true(im.axes is ax) + assert im in ax.mouseover_set + assert ln not in ax.mouseover_set + assert im.axes is ax im.remove() ln.remove() for art in [im, ln]: - assert_true(art.axes is None) - assert_true(art.figure is None) + assert art.axes is None + assert art.figure is None - assert_true(im not in ax.mouseover_set) - assert_true(fig.stale) - assert_true(ax.stale) + assert im not in ax.mouseover_set + assert fig.stale + assert ax.stale @image_comparison(baseline_images=["default_edges"], remove_text=True, @@ -206,8 +206,3 @@ def test_properties(): warnings.simplefilter("always") ln.properties() assert len(w) == 0 - - -if __name__ == '__main__': - import nose - nose.runmodule(argv=['-s', '--with-doctest'], exit=False) diff --git a/lib/matplotlib/tests/test_axes.py b/lib/matplotlib/tests/test_axes.py index e3bfdaa8ce26..eafec267c2d4 100644 --- a/lib/matplotlib/tests/test_axes.py +++ b/lib/matplotlib/tests/test_axes.py @@ -5,10 +5,6 @@ from six.moves import xrange from itertools import chain import io - -from nose.tools import assert_equal, assert_raises, assert_false, assert_true -from nose.plugins.skip import SkipTest - import datetime import numpy as np @@ -25,12 +21,14 @@ from numpy.testing import assert_array_equal import warnings from matplotlib.cbook import IgnoredKeywordWarning +import pytest # Note: Some test cases are run twice: once normally and once with labeled data # These two must be defined in the same test function or need to have # different baseline images to prevent race conditions when nose runs # the tests with multiple threads. + @image_comparison(baseline_images=['formatter_ticker_001', 'formatter_ticker_002', 'formatter_ticker_003', @@ -104,7 +102,8 @@ def test_twin_axis_locaters_formatters(): ax1.yaxis.set_major_locator(majl) ax1.yaxis.set_minor_locator(minl) ax1.yaxis.set_major_formatter(plt.FormatStrFormatter('%08.2lf')) - ax1.yaxis.set_minor_formatter(plt.FixedFormatter(['tricks', 'mind', 'jedi'])) + ax1.yaxis.set_minor_formatter(plt.FixedFormatter( + ['tricks', 'mind', 'jedi'])) ax1.xaxis.set_major_locator(plt.LinearLocator()) ax1.xaxis.set_minor_locator(plt.FixedLocator([15, 35, 55, 75])) @@ -120,25 +119,26 @@ def test_twinx_cla(): ax2 = ax.twinx() ax3 = ax2.twiny() plt.draw() - assert_false(ax2.xaxis.get_visible()) - assert_false(ax2.patch.get_visible()) + assert not ax2.xaxis.get_visible() + assert not ax2.patch.get_visible() ax2.cla() ax3.cla() - assert_false(ax2.xaxis.get_visible()) - assert_false(ax2.patch.get_visible()) - assert_true(ax2.yaxis.get_visible()) + assert not ax2.xaxis.get_visible() + assert not ax2.patch.get_visible() + assert ax2.yaxis.get_visible() - assert_true(ax3.xaxis.get_visible()) - assert_false(ax3.patch.get_visible()) - assert_false(ax3.yaxis.get_visible()) + assert ax3.xaxis.get_visible() + assert not ax3.patch.get_visible() + assert not ax3.yaxis.get_visible() - assert_true(ax.xaxis.get_visible()) - assert_true(ax.patch.get_visible()) - assert_true(ax.yaxis.get_visible()) + assert ax.xaxis.get_visible() + assert ax.patch.get_visible() + assert ax.yaxis.get_visible() -@image_comparison(baseline_images=["minorticks_on_rcParams_both"], extensions=['png']) +@image_comparison(baseline_images=["minorticks_on_rcParams_both"], + extensions=['png']) def test_minorticks_on_rcParams_both(): fig = plt.figure() matplotlib.rcParams['xtick.minor.visible'] = True @@ -321,26 +321,27 @@ def test_single_date(): @image_comparison(baseline_images=['shaped_data']) def test_shaped_data(): - xdata = np.array([[0.53295185, 0.23052951, 0.19057629, 0.66724975, 0.96577916, - 0.73136095, 0.60823287, 0.01792100, 0.29744742, 0.27164665], - [0.27980120, 0.25814229, 0.02818193, 0.12966456, 0.57446277, - 0.58167607, 0.71028245, 0.69112737, 0.89923072, 0.99072476], - [0.81218578, 0.80464528, 0.76071809, 0.85616314, 0.12757994, - 0.94324936, 0.73078663, 0.09658102, 0.60703967, 0.77664978], - [0.28332265, 0.81479711, 0.86985333, 0.43797066, 0.32540082, - 0.43819229, 0.92230363, 0.49414252, 0.68168256, 0.05922372], - [0.10721335, 0.93904142, 0.79163075, 0.73232848, 0.90283839, - 0.68408046, 0.25502302, 0.95976614, 0.59214115, 0.13663711], - [0.28087456, 0.33127607, 0.15530412, 0.76558121, 0.83389773, - 0.03735974, 0.98717738, 0.71432229, 0.54881366, 0.86893953], - [0.77995937, 0.99555600, 0.29688434, 0.15646162, 0.05184800, - 0.37161935, 0.12998491, 0.09377296, 0.36882507, 0.36583435], - [0.37851836, 0.05315792, 0.63144617, 0.25003433, 0.69586032, - 0.11393988, 0.92362096, 0.88045438, 0.93530252, 0.68275072], - [0.86486596, 0.83236675, 0.82960664, 0.57796630, 0.25724233, - 0.84841095, 0.90862812, 0.64414887, 0.35652720, 0.71026066], - [0.01383268, 0.34060930, 0.76084285, 0.70800694, 0.87634056, - 0.08213693, 0.54655021, 0.98123181, 0.44080053, 0.86815815]]) + xdata = np.array( + [[0.53295185, 0.23052951, 0.19057629, 0.66724975, 0.96577916, + 0.73136095, 0.60823287, 0.01792100, 0.29744742, 0.27164665], + [0.27980120, 0.25814229, 0.02818193, 0.12966456, 0.57446277, + 0.58167607, 0.71028245, 0.69112737, 0.89923072, 0.99072476], + [0.81218578, 0.80464528, 0.76071809, 0.85616314, 0.12757994, + 0.94324936, 0.73078663, 0.09658102, 0.60703967, 0.77664978], + [0.28332265, 0.81479711, 0.86985333, 0.43797066, 0.32540082, + 0.43819229, 0.92230363, 0.49414252, 0.68168256, 0.05922372], + [0.10721335, 0.93904142, 0.79163075, 0.73232848, 0.90283839, + 0.68408046, 0.25502302, 0.95976614, 0.59214115, 0.13663711], + [0.28087456, 0.33127607, 0.15530412, 0.76558121, 0.83389773, + 0.03735974, 0.98717738, 0.71432229, 0.54881366, 0.86893953], + [0.77995937, 0.99555600, 0.29688434, 0.15646162, 0.05184800, + 0.37161935, 0.12998491, 0.09377296, 0.36882507, 0.36583435], + [0.37851836, 0.05315792, 0.63144617, 0.25003433, 0.69586032, + 0.11393988, 0.92362096, 0.88045438, 0.93530252, 0.68275072], + [0.86486596, 0.83236675, 0.82960664, 0.57796630, 0.25724233, + 0.84841095, 0.90862812, 0.64414887, 0.35652720, 0.71026066], + [0.01383268, 0.34060930, 0.76084285, 0.70800694, 0.87634056, + 0.08213693, 0.54655021, 0.98123181, 0.44080053, 0.86815815]]) y1 = np.arange(10) y1.shape = 1, 10 @@ -355,7 +356,8 @@ def test_shaped_data(): plt.plot(y2) plt.subplot(413) - assert_raises(ValueError, plt.plot, (y1, y2)) + with pytest.raises(ValueError): + plt.plot(y1, y2) plt.subplot(414) plt.plot(xdata[:, 1], xdata[1, :], 'o') @@ -401,7 +403,7 @@ def test_polar_wrap(): @image_comparison(baseline_images=['polar_units', 'polar_units_2']) def test_polar_units(): import matplotlib.testing.jpl_units as units - from nose.tools import assert_true + # from nose.tools import assert_true units.register() pi = np.pi @@ -426,7 +428,8 @@ def test_polar_units(): # make sure runits and theta units work y1 = [y*km for y in y1] plt.polar(x2, y1, color="blue", thetaunits="rad", runits="km") - assert_true(isinstance(plt.gca().get_xaxis().get_major_formatter(), units.UnitDblFormatter)) + assert isinstance(plt.gca().get_xaxis().get_major_formatter(), + units.UnitDblFormatter) @image_comparison(baseline_images=['polar_rmin']) @@ -522,12 +525,13 @@ def test_hexbin_extent(): @image_comparison(baseline_images=['hexbin_empty'], remove_text=True, - extensions=['png']) + extensions=['png']) def test_hexbin_empty(): # From #3886: creating hexbin from empty dataset raises ValueError ax = plt.gca() ax.hexbin([], []) + @cleanup def test_hexbin_pickable(): # From #1973: Test that picking a hexbin collection works @@ -590,7 +594,10 @@ def test_inverted_limits(): @image_comparison(baseline_images=['nonfinite_limits']) def test_nonfinite_limits(): x = np.arange(0., np.e, 0.01) - olderr = np.seterr(divide='ignore') # silence divide by zero warning from log(0) + + # silence divide by zero warning from log(0) + olderr = np.seterr(divide='ignore') + try: y = np.log(x) finally: @@ -618,7 +625,7 @@ def test_imshow(): ax.imshow(r) # Reuse testcase from above for a labeled data test - data={"r": r} + data = {"r": r} fig = plt.figure() ax = fig.add_subplot(111) ax.imshow("r", data=data) @@ -677,8 +684,10 @@ def test_fill_between_interpolate(): fig = plt.figure() ax = fig.add_subplot(211) ax.plot(x, y1, x, y2, color='black') - ax.fill_between(x, y1, y2, where=y2 >= y1, facecolor='white', hatch='/', interpolate=True) - ax.fill_between(x, y1, y2, where=y2 <= y1, facecolor='red', interpolate=True) + ax.fill_between(x, y1, y2, where=y2 >= y1, facecolor='white', + hatch='/', interpolate=True) + ax.fill_between(x, y1, y2, where=y2 <= y1, facecolor='red', + interpolate=True) # Test support for masked arrays. y2 = np.ma.masked_greater(y2, 1.0) @@ -686,8 +695,10 @@ def test_fill_between_interpolate(): y2[0] = np.ma.masked ax1 = fig.add_subplot(212, sharex=ax) ax1.plot(x, y1, x, y2, color='black') - ax1.fill_between(x, y1, y2, where=y2 >= y1, facecolor='green', interpolate=True) - ax1.fill_between(x, y1, y2, where=y2 <= y1, facecolor='red', interpolate=True) + ax1.fill_between(x, y1, y2, where=y2 >= y1, facecolor='green', + interpolate=True) + ax1.fill_between(x, y1, y2, where=y2 <= y1, facecolor='red', + interpolate=True) @image_comparison(baseline_images=['symlog']) @@ -844,12 +855,14 @@ def test_pcolorargs(): Z = np.sqrt(X**2 + Y**2)/5 _, ax = plt.subplots() - assert_raises(TypeError, ax.pcolormesh, y, x, Z) - assert_raises(TypeError, ax.pcolormesh, X, Y, Z.T) - assert_raises(TypeError, ax.pcolormesh, x, y, Z[:-1, :-1], - shading="gouraud") - assert_raises(TypeError, ax.pcolormesh, X, Y, Z[:-1, :-1], - shading="gouraud") + with pytest.raises(TypeError): + ax.pcolormesh(y, x, Z) + with pytest.raises(TypeError): + ax.pcolormesh(X, Y, Z.T) + with pytest.raises(TypeError): + ax.pcolormesh(x, y, Z[:-1, :-1], shading="gouraud") + with pytest.raises(TypeError): + ax.pcolormesh(X, Y, Z[:-1, :-1], shading="gouraud") @image_comparison(baseline_images=['canonical']) @@ -882,7 +895,8 @@ def test_arc_ellipse(): fig = plt.figure() ax = fig.add_subplot(211, aspect='auto') - ax.fill(x, y, alpha=0.2, facecolor='yellow', edgecolor='yellow', linewidth=1, zorder=1) + ax.fill(x, y, alpha=0.2, facecolor='yellow', edgecolor='yellow', + linewidth=1, zorder=1) e1 = patches.Arc((xcenter, ycenter), width, height, angle=angle, linewidth=2, fill=False, zorder=2) @@ -1109,20 +1123,23 @@ def test_hist_log(): @image_comparison(baseline_images=['hist_bar_empty'], remove_text=True, - extensions=['png']) + extensions=['png']) def test_hist_bar_empty(): # From #3886: creating hist from empty dataset raises ValueError ax = plt.gca() ax.hist([], histtype='bar') + @image_comparison(baseline_images=['hist_step_empty'], remove_text=True, - extensions=['png']) + extensions=['png']) def test_hist_step_empty(): # From #3886: creating hist from empty dataset raises ValueError ax = plt.gca() ax.hist([], histtype='step') -@image_comparison(baseline_images=['hist_steplog'], remove_text=True, tol=0.05) + +@image_comparison(baseline_images=['hist_steplog'], remove_text=True, + tol=0.05) def test_hist_steplog(): np.random.seed(0) data = np.random.standard_normal(2000) @@ -1141,7 +1158,8 @@ def test_hist_steplog(): plt.hist(data, 100, weights=weights, histtype='stepfilled', log=True) ax = plt.subplot(4, 1, 4) - plt.hist(data_big, 100, histtype='stepfilled', log=True, orientation='horizontal') + plt.hist(data_big, 100, histtype='stepfilled', log=True, + orientation='horizontal') @image_comparison(baseline_images=['hist_step_log_bottom'], @@ -1314,7 +1332,8 @@ def _as_mpl_axes(self): ax_via_gca = plt.gca(projection=prj2) assert ax_via_gca is not ax assert ax.get_theta_offset() == 0, ax.get_theta_offset() - assert ax_via_gca.get_theta_offset() == np.pi, ax_via_gca.get_theta_offset() + assert ax_via_gca.get_theta_offset() == \ + np.pi, ax_via_gca.get_theta_offset() # try getting the axes given an == (not is) polar projection ax_via_gca = plt.gca(projection=prj3) assert ax_via_gca is ax @@ -1351,7 +1370,7 @@ def test_stackplot(): ax.set_ylim((0, 70)) # Reuse testcase from above for a labeled data test - data={"x": x, "y1": y1, "y2": y2, "y3": y3} + data = {"x": x, "y1": y1, "y2": y2, "y3": y3} fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.stackplot("x", "y1", "y2", "y3", data=data) @@ -1725,7 +1744,8 @@ def test_bxp_bad_widths(): fig, ax = plt.subplots() ax.set_yscale('log') - assert_raises(ValueError, ax.bxp, logstats, widths=[1]) + with pytest.raises(ValueError): + ax.bxp(logstats, widths=[1]) @cleanup @@ -1737,7 +1757,8 @@ def test_bxp_bad_positions(): fig, ax = plt.subplots() ax.set_yscale('log') - assert_raises(ValueError, ax.bxp, logstats, positions=[2, 3]) + with pytest.raises(ValueError): + ax.bxp(logstats, positions=[2, 3]) @image_comparison(baseline_images=['boxplot', 'boxplot'], tol=1) @@ -1750,7 +1771,7 @@ def test_boxplot(): ax.set_ylim((-30, 30)) # Reuse testcase from above for a labeled data test - data={"x": [x, x]} + data = {"x": [x, x]} fig, ax = plt.subplots() ax.boxplot("x", bootstrap=10000, notch=1, data=data) ax.set_ylim((-30, 30)) @@ -1791,6 +1812,7 @@ def test_boxplot_autorange_whiskers(): ax.boxplot([x, x], bootstrap=10000, notch=1) ax.set_ylim((-5, 5)) + def _rc_test_bxp_helper(ax, rc_dict): x = np.linspace(-7, 7, 140) x = np.hstack([-25, x, 25]) @@ -1798,6 +1820,7 @@ def _rc_test_bxp_helper(ax, rc_dict): ax.boxplot([x, x]) return ax + @image_comparison(baseline_images=['boxplot_rc_parameters'], savefig_kwarg={'dpi': 100}, remove_text=True, tol=1) def test_boxplot_rc_parameters(): @@ -1893,7 +1916,8 @@ def test_boxplot_bad_medians_1(): x = np.linspace(-7, 7, 140) x = np.hstack([-25, x, 25]) fig, ax = plt.subplots() - assert_raises(ValueError, ax.boxplot, x, usermedians=[1, 2]) + with pytest.raises(ValueError): + ax.boxplot(x, usermedians=[1, 2]) @cleanup @@ -1901,7 +1925,8 @@ def test_boxplot_bad_medians_2(): x = np.linspace(-7, 7, 140) x = np.hstack([-25, x, 25]) fig, ax = plt.subplots() - assert_raises(ValueError, ax.boxplot, [x, x], usermedians=[[1, 2], [1, 2]]) + with pytest.raises(ValueError): + ax.boxplot([x, x], usermedians=[[1, 2], [1, 2]]) @cleanup @@ -1909,8 +1934,8 @@ def test_boxplot_bad_ci_1(): x = np.linspace(-7, 7, 140) x = np.hstack([-25, x, 25]) fig, ax = plt.subplots() - assert_raises(ValueError, ax.boxplot, [x, x], - conf_intervals=[[1, 2]]) + with pytest.raises(ValueError): + ax.boxplot([x, x], conf_intervals=[[1, 2]]) @cleanup @@ -1918,8 +1943,8 @@ def test_boxplot_bad_ci_2(): x = np.linspace(-7, 7, 140) x = np.hstack([-25, x, 25]) fig, ax = plt.subplots() - assert_raises(ValueError, ax.boxplot, [x, x], - conf_intervals=[[1, 2], [1]]) + with pytest.raises(ValueError): + ax.boxplot([x, x], conf_intervals=[[1, 2], [1]]) @image_comparison(baseline_images=['boxplot_mod_artists_after_plotting'], @@ -2102,7 +2127,8 @@ def test_violinplot_bad_positions(): # First 9 digits of frac(sqrt(47)) np.random.seed(855654600) data = [np.random.normal(size=100) for i in range(4)] - assert_raises(ValueError, ax.violinplot, data, positions=range(5)) + with pytest.raises(ValueError): + ax.violinplot(data, positions=range(5)) @cleanup @@ -2111,8 +2137,8 @@ def test_violinplot_bad_widths(): # First 9 digits of frac(sqrt(53)) np.random.seed(280109889) data = [np.random.normal(size=100) for i in range(4)] - assert_raises(ValueError, ax.violinplot, data, positions=range(4), - widths=[1, 2, 3]) + with pytest.raises(ValueError): + ax.violinplot(data, positions=range(4), widths=[1, 2, 3]) @cleanup @@ -2174,7 +2200,6 @@ def test_errorbar(): fig.suptitle('Variable errorbars') - # Reuse te first testcase from above for a labeled data test data = {"x": x, "y": y} fig = plt.figure() @@ -2194,9 +2219,12 @@ def test_errorbar_shape(): yerr = np.vstack((yerr1, 2*yerr1)).T xerr = 0.1 + yerr - assert_raises(ValueError, ax.errorbar, x, y, yerr=yerr, fmt='o') - assert_raises(ValueError, ax.errorbar, x, y, xerr=xerr, fmt='o') - assert_raises(ValueError, ax.errorbar, x, y, yerr=yerr, xerr=xerr, fmt='o') + with pytest.raises(ValueError): + ax.errorbar(x, y, yerr=yerr, fmt='o') + with pytest.raises(ValueError): + ax.errorbar(x, y, xerr=xerr, fmt='o') + with pytest.raises(ValueError): + ax.errorbar(x, y, yerr=yerr, xerr=xerr, fmt='o') @image_comparison(baseline_images=['errorbar_limits']) @@ -2275,7 +2303,8 @@ def test_hist_offset(): ax.hist(d2, bottom=15) -@image_comparison(baseline_images=['hist_step'], extensions=['png'], remove_text=True) +@image_comparison(baseline_images=['hist_step'], extensions=['png'], + remove_text=True) def test_hist_step(): # make some data d1 = np.linspace(1, 3, 20) @@ -2366,7 +2395,8 @@ def test_hist_stacked_normed(): ax.hist((d1, d2), stacked=True, normed=True) -@image_comparison(baseline_images=['hist_step_bottom'], extensions=['png'], remove_text=True) +@image_comparison(baseline_images=['hist_step_bottom'], + extensions=['png'], remove_text=True) def test_hist_step_bottom(): # make some data d1 = np.linspace(1, 3, 20) @@ -2389,7 +2419,8 @@ def test_hist_stacked_bar(): labels = ['green', 'orange', ' yellow', 'magenta', 'black'] fig = plt.figure() ax = fig.add_subplot(111) - ax.hist(d, bins=10, histtype='barstacked', align='mid', color=colors, label=labels) + ax.hist(d, bins=10, histtype='barstacked', align='mid', + color=colors, label=labels) ax.legend(loc='upper right', bbox_to_anchor=(1.0, 1.0), ncol=1) @@ -2426,6 +2457,7 @@ def test_rgba_markers(): for ax in axs: ax.axis([-1, 4, 0, 5]) + @image_comparison(baseline_images=['mollweide_grid'], remove_text=True) def test_mollweide_grid(): # test that both horizontal and vertical gridlines appear on the Mollweide @@ -2558,7 +2590,8 @@ def test_eventplot(): np.testing.assert_equal(num_collections, num_datasets) -@image_comparison(baseline_images=['test_eventplot_defaults'], extensions=['png'], remove_text=True) +@image_comparison(baseline_images=['test_eventplot_defaults'], + extensions=['png'], remove_text=True) def test_eventplot_defaults(): ''' test that eventplot produces the correct output given the default params @@ -2575,7 +2608,8 @@ def test_eventplot_defaults(): colls = axobj.eventplot(data) -@image_comparison(baseline_images=['test_eventplot_problem_kwargs'], extensions=['png'], remove_text=True) +@image_comparison(baseline_images=['test_eventplot_problem_kwargs'], + extensions=['png'], remove_text=True) def test_eventplot_problem_kwargs(): ''' test that 'singular' versions of LineCollection props raise an @@ -2601,9 +2635,9 @@ def test_eventplot_problem_kwargs(): linestyle=['dashdot', 'dotted']) # check that three IgnoredKeywordWarnings were raised - assert_equal(len(w), 3) - assert_true(all(issubclass(wi.category, IgnoredKeywordWarning) - for wi in w)) + assert len(w) == 3 + assert all(issubclass(wi.category, IgnoredKeywordWarning) + for wi in w) @cleanup @@ -2613,14 +2647,16 @@ def test_empty_eventplot(): plt.draw() -@image_comparison(baseline_images=['marker_styles'], extensions=['png'], remove_text=True) +@image_comparison(baseline_images=['marker_styles'], extensions=['png'], + remove_text=True) def test_marker_styles(): fig = plt.figure() ax = fig.add_subplot(111) - for y, marker in enumerate(sorted(matplotlib.markers.MarkerStyle.markers.keys(), - key=lambda x: str(type(x))+str(x))): - ax.plot((y % 2)*5 + np.arange(10)*10, np.ones(10)*10*y, linestyle='', marker=marker, - markersize=10+y/5, label=marker) + for y, marker in enumerate( + sorted(matplotlib.markers.MarkerStyle.markers.keys(), + key=lambda x: str(type(x))+str(x))): + ax.plot((y % 2)*5 + np.arange(10)*10, np.ones(10)*10*y, linestyle='', + marker=marker, markersize=10+y/5, label=marker) @image_comparison(baseline_images=['rc_markerfill'], extensions=['png']) @@ -2744,7 +2780,7 @@ def test_mixed_collection(): def test_subplot_key_hash(): ax = plt.subplot(np.float64(5.5), np.int64(1), np.float64(1.2)) ax.twinx() - assert_equal((5, 1, 0, None), ax.get_subplotspec().get_geometry()) + assert ax.get_subplotspec().get_geometry() == (5, 1, 0, None) @image_comparison(baseline_images=['specgram_freqs', @@ -2991,15 +3027,18 @@ def test_specgram_angle_freqs(): spec13 = ax13.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='twosided', mode='angle') - assert_raises(ValueError, ax11.specgram, y, NFFT=NFFT, Fs=Fs, + with pytest.raises(ValueError): + ax11.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='default', mode='phase', scale='dB') - assert_raises(ValueError, ax12.specgram, y, NFFT=NFFT, Fs=Fs, + with pytest.raises(ValueError): + ax12.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='onesided', mode='phase', scale='dB') - assert_raises(ValueError, ax13.specgram, y, NFFT=NFFT, Fs=Fs, + with pytest.raises(ValueError): + ax13.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='twosided', mode='phase', scale='dB') @@ -3038,15 +3077,18 @@ def test_specgram_noise_angle(): spec13 = ax13.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='twosided', mode='angle') - assert_raises(ValueError, ax11.specgram, y, NFFT=NFFT, Fs=Fs, + with pytest.raises(ValueError): + ax11.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='default', mode='phase', scale='dB') - assert_raises(ValueError, ax12.specgram, y, NFFT=NFFT, Fs=Fs, + with pytest.raises(ValueError): + ax12.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='onesided', mode='phase', scale='dB') - assert_raises(ValueError, ax13.specgram, y, NFFT=NFFT, Fs=Fs, + with pytest.raises(ValueError): + ax13.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='twosided', mode='phase', scale='dB') @@ -3093,15 +3135,18 @@ def test_specgram_freqs_phase(): spec13 = ax13.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='twosided', mode='phase') - assert_raises(ValueError, ax11.specgram, y, NFFT=NFFT, Fs=Fs, + with pytest.raises(ValueError): + ax11.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='default', mode='phase', scale='dB') - assert_raises(ValueError, ax12.specgram, y, NFFT=NFFT, Fs=Fs, + with pytest.raises(ValueError): + ax12.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='onesided', mode='phase', scale='dB') - assert_raises(ValueError, ax13.specgram, y, NFFT=NFFT, Fs=Fs, + with pytest.raises(ValueError): + ax13.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='twosided', mode='phase', scale='dB') @@ -3143,15 +3188,18 @@ def test_specgram_noise_phase(): pad_to=pad_to, sides='twosided', mode='phase', ) - assert_raises(ValueError, ax11.specgram, y, NFFT=NFFT, Fs=Fs, + with pytest.raises(ValueError): + ax11.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='default', mode='phase', scale='dB') - assert_raises(ValueError, ax12.specgram, y, NFFT=NFFT, Fs=Fs, + with pytest.raises(ValueError): + ax12.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='onesided', mode='phase', scale='dB') - assert_raises(ValueError, ax13.specgram, y, NFFT=NFFT, Fs=Fs, + with pytest.raises(ValueError): + ax13.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='twosided', mode='phase', scale='dB') @@ -3622,8 +3670,8 @@ def make_patch_spines_invisible(ax): # placed on the right by twinx above. par2.spines["right"].set_position(("axes", 1.2)) # Having been created by twinx, par2 has its frame off, so the line of its - # detached spine is invisible. First, activate the frame but make the patch - # and spines invisible. + # detached spine is invisible. First, activate the frame but make the + # patch and spines invisible. make_patch_spines_invisible(par2) # Second, show the right spine. par2.spines["right"].set_visible(True) @@ -3803,7 +3851,7 @@ def test_pie_center_radius(): labels = 'Frogs', 'Hogs', 'Dogs', 'Logs' sizes = [15, 30, 45, 10] colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral'] - explode = (0, 0.1, 0, 0) # only "explode" the 2nd slice (i.e. 'Hogs') + explode = (0, 0.1, 0, 0) # only "explode" the 2nd slice (i.e. 'Hogs') plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True, startangle=90, @@ -3889,10 +3937,11 @@ def test_set_get_ticklabels(): ax[0].set_xticklabels(('a', 'b', 'c', 'd')) ax[0].set_yticklabels(('11', '12', '13', '14')) - # set ticklabel to the other plot, expect the 2 plots have same label setting + # set ticklabel to the other plot, expect the 2 plots have + # same label setting # pass get_ticklabels return value as ticklabels argument - ax[1].set_xticklabels(ax[0].get_xticklabels() ) - ax[1].set_yticklabels(ax[0].get_yticklabels() ) + ax[1].set_xticklabels(ax[0].get_xticklabels()) + ax[1].set_yticklabels(ax[0].get_yticklabels()) @image_comparison(baseline_images=['o_marker_path_snap'], extensions=['png'], @@ -3915,17 +3964,17 @@ def test_margins(): fig1, ax1 = plt.subplots(1, 1) ax1.plot(data) ax1.margins(1) - assert_equal(ax1.margins(), (1, 1)) + assert ax1.margins() == (1, 1) fig2, ax2 = plt.subplots(1, 1) ax2.plot(data) ax2.margins(1, 0.5) - assert_equal(ax2.margins(), (1, 0.5)) + assert ax2.margins() == (1, 0.5) fig3, ax3 = plt.subplots(1, 1) ax3.plot(data) ax3.margins(x=1, y=0.5) - assert_equal(ax3.margins(), (1, 0.5)) + assert ax3.margins() == (1, 0.5) @cleanup @@ -3945,7 +3994,7 @@ def test_pathological_hexbin(): fig, ax = plt.subplots(1, 1) ax.hexbin(mylist, mylist) fig.savefig(out) - assert_equal(len(w), 0) + assert len(w) == 0 @cleanup @@ -3960,7 +4009,7 @@ def test_color_alias(): # issues 4157 and 4162 fig, ax = plt.subplots() line = ax.plot([0, 1], c='lime')[0] - assert_equal('lime', line.get_color()) + assert line.get_color() == 'lime' @cleanup @@ -3991,7 +4040,7 @@ def test_move_offsetlabel(): fig, ax = plt.subplots() ax.plot(data) ax.yaxis.tick_right() - assert_equal((1, 0.5), ax.yaxis.offsetText.get_position()) + assert ax.yaxis.offsetText.get_position() == (1, 0.5) @image_comparison(baseline_images=['rc_spines'], extensions=['png'], @@ -4041,22 +4090,22 @@ def test_rc_tick(): xax = ax1.xaxis yax = ax1.yaxis # tick1On bottom/left - assert xax._major_tick_kw['tick1On'] == False - assert xax._major_tick_kw['tick2On'] == True + assert not xax._major_tick_kw['tick1On'] + assert xax._major_tick_kw['tick2On'] - assert yax._major_tick_kw['tick1On'] == True - assert yax._major_tick_kw['tick2On'] == False + assert yax._major_tick_kw['tick1On'] + assert not yax._major_tick_kw['tick2On'] @cleanup def test_bar_negative_width(): fig, ax = plt.subplots() res = ax.bar(range(1, 5), range(1, 5), width=-1) - assert_equal(len(res), 4) + assert len(res) == 4 for indx, b in enumerate(res): - assert_equal(b._x, indx) - assert_equal(b._width, 1) - assert_equal(b._height, indx + 1) + assert b._x == indx + assert b._width == 1 + assert b._height == indx + 1 @cleanup @@ -4067,15 +4116,18 @@ def test_square_plot(): ax.plot(x, y, 'mo') ax.axis('square') xlim, ylim = ax.get_xlim(), ax.get_ylim() - assert_true(np.diff(xlim) == np.diff(ylim)) - assert_true(ax.get_aspect() == 'equal') + assert np.diff(xlim) + assert np.diff(ylim) + assert ax.get_aspect() == 'equal' @cleanup def test_no_None(): fig, ax = plt.subplots() - assert_raises(ValueError, plt.plot, None) - assert_raises(ValueError, plt.plot, None, None) + with pytest.raises(ValueError): + plt.plot(None) + with pytest.raises(ValueError): + plt.plot(None, None) @cleanup @@ -4097,15 +4149,15 @@ def test_shared_scale(): axs[0, 0].set_yscale("log") for ax in axs.flat: - assert_equal(ax.get_yscale(), 'log') - assert_equal(ax.get_xscale(), 'log') + assert ax.get_yscale() == 'log' + assert ax.get_xscale() == 'log' axs[1, 1].set_xscale("linear") axs[1, 1].set_yscale("linear") for ax in axs.flat: - assert_equal(ax.get_yscale(), 'linear') - assert_equal(ax.get_xscale(), 'linear') + assert ax.get_yscale() == 'linear' + assert ax.get_xscale() == 'linear' @cleanup @@ -4179,12 +4231,14 @@ def test_title_location_roundtrip(): ax.set_title('left', loc='left') ax.set_title('right', loc='right') - assert_equal('left', ax.get_title(loc='left')) - assert_equal('right', ax.get_title(loc='right')) - assert_equal('aardvark', ax.get_title()) + assert 'left' == ax.get_title(loc='left') + assert 'right' == ax.get_title(loc='right') + assert 'aardvark' == ax.get_title() - assert_raises(ValueError, ax.get_title, loc='foo') - assert_raises(ValueError, ax.set_title, 'fail', loc='foo') + with pytest.raises(ValueError): + ax.get_title(loc='foo') + with pytest.raises(ValueError): + ax.set_title('fail', loc='foo') @image_comparison(baseline_images=["loglog"], remove_text=True, @@ -4298,7 +4352,7 @@ def test_pandas_indexing_dates(): try: import pandas as pd except ImportError: - raise SkipTest("Pandas not installed") + pytest.skip("Pandas not installed") dates = np.arange('2005-02', '2005-03', dtype='datetime64[D]') values = np.sin(np.array(range(len(dates)))) @@ -4315,19 +4369,9 @@ def test_pandas_indexing_hist(): try: import pandas as pd except ImportError: - raise SkipTest("Pandas not installed") + pytest.skip("Pandas not installed") ser_1 = pd.Series(data=[1, 2, 2, 3, 3, 4, 4, 4, 4, 5]) ser_2 = ser_1.iloc[1:] fig, axes = plt.subplots() axes.hist(ser_2) - - -if __name__ == '__main__': - import nose - import sys - - args = ['-s', '--with-doctest'] - argv = sys.argv - argv = argv[:1] + args + argv[1:] - nose.runmodule(argv=argv, exit=False) diff --git a/lib/matplotlib/tests/test_backend_bases.py b/lib/matplotlib/tests/test_backend_bases.py index 780c34335891..db78ab978d73 100644 --- a/lib/matplotlib/tests/test_backend_bases.py +++ b/lib/matplotlib/tests/test_backend_bases.py @@ -6,7 +6,7 @@ import matplotlib.transforms as transforms import matplotlib.path as path -from nose.tools import assert_equal +# from nose.tools import assert_equal import numpy as np import os @@ -63,7 +63,7 @@ def test_get_default_filename(): fig = plt.figure() canvas = FigureCanvasBase(fig) filename = canvas.get_default_filename() - assert_equal(filename, 'image.png') + assert filename == 'image.png' finally: shutil.rmtree(test_dir) @@ -81,7 +81,7 @@ def test_get_default_filename_already_exists(): open(os.path.join(test_dir, 'image.png'), 'w').close() filename = canvas.get_default_filename() - assert_equal(filename, 'image-1.png') + assert filename == 'image-1.png' finally: shutil.rmtree(test_dir) diff --git a/lib/matplotlib/tests/test_backend_pdf.py b/lib/matplotlib/tests/test_backend_pdf.py index c062657499b6..7c0227a62711 100644 --- a/lib/matplotlib/tests/test_backend_pdf.py +++ b/lib/matplotlib/tests/test_backend_pdf.py @@ -12,8 +12,7 @@ from matplotlib import cm, rcParams from matplotlib.backends.backend_pdf import PdfPages from matplotlib import pyplot as plt -from matplotlib.testing.decorators import (image_comparison, knownfailureif, - cleanup) +from matplotlib.testing.decorators import (image_comparison, cleanup) if 'TRAVIS' not in os.environ: @image_comparison(baseline_images=['pdf_use14corefonts'], diff --git a/lib/matplotlib/tests/test_backend_pgf.py b/lib/matplotlib/tests/test_backend_pgf.py index 28be98c8f3cb..2813e7079d5b 100644 --- a/lib/matplotlib/tests/test_backend_pgf.py +++ b/lib/matplotlib/tests/test_backend_pgf.py @@ -8,14 +8,13 @@ import shutil import numpy as np -import nose -from nose.plugins.skip import SkipTest import matplotlib as mpl import matplotlib.pyplot as plt from matplotlib.compat import subprocess from matplotlib.testing.compare import compare_images, ImageComparisonFailure from matplotlib.testing.decorators import _image_directories, switch_backend +import pytest baseline_dir, result_dir = _image_directories(lambda: 'dummy func') @@ -83,7 +82,7 @@ def create_figure(): @switch_backend('pgf') def test_xelatex(): if not check_for('xelatex'): - raise SkipTest('xelatex + pgf is required') + raise pytest.skip('xelatex + pgf is required') rc_xelatex = {'font.family': 'serif', 'pgf.rcfonts': False} @@ -96,7 +95,7 @@ def test_xelatex(): @switch_backend('pgf') def test_pdflatex(): if not check_for('pdflatex'): - raise SkipTest('pdflatex + pgf is required') + raise pytest.skip('pdflatex + pgf is required') rc_pdflatex = {'font.family': 'serif', 'pgf.rcfonts': False, @@ -112,7 +111,7 @@ def test_pdflatex(): @switch_backend('pgf') def test_rcupdate(): if not check_for('xelatex') or not check_for('pdflatex'): - raise SkipTest('xelatex and pdflatex + pgf required') + raise pytest.skip('xelatex and pdflatex + pgf required') rc_sets = [] rc_sets.append({'font.family': 'sans-serif', @@ -141,7 +140,7 @@ def test_rcupdate(): @switch_backend('pgf') def test_pathclip(): if not check_for('xelatex'): - raise SkipTest('xelatex + pgf is required') + raise pytest.skip('xelatex + pgf is required') rc_xelatex = {'font.family': 'serif', 'pgf.rcfonts': False} @@ -159,7 +158,7 @@ def test_pathclip(): @switch_backend('pgf') def test_mixedmode(): if not check_for('xelatex'): - raise SkipTest('xelatex + pgf is required') + raise pytest.skip('xelatex + pgf is required') rc_xelatex = {'font.family': 'serif', 'pgf.rcfonts': False} @@ -175,7 +174,7 @@ def test_mixedmode(): @switch_backend('pgf') def test_bbox_inches(): if not check_for('xelatex'): - raise SkipTest('xelatex + pgf is required') + raise pytest.skip('xelatex + pgf is required') rc_xelatex = {'font.family': 'serif', 'pgf.rcfonts': False} @@ -191,8 +190,3 @@ def test_bbox_inches(): bbox = ax1.get_window_extent().transformed(fig.dpi_scale_trans.inverted()) compare_figure('pgf_bbox_inches.pdf', savefig_kwargs={'bbox_inches': bbox}) - - -if __name__ == '__main__': - import nose - nose.runmodule(argv=['-s', '--with-doctest'], exit=False) diff --git a/lib/matplotlib/tests/test_backend_ps.py b/lib/matplotlib/tests/test_backend_ps.py index ab346a4d0a41..add7617fdfc7 100644 --- a/lib/matplotlib/tests/test_backend_ps.py +++ b/lib/matplotlib/tests/test_backend_ps.py @@ -7,21 +7,20 @@ import re import numpy as np from matplotlib.externals import six - +import pytest import matplotlib import matplotlib.pyplot as plt from matplotlib import patheffects -from matplotlib.testing.decorators import cleanup, knownfailureif +from matplotlib.testing.decorators import cleanup -needs_ghostscript = knownfailureif( +needs_ghostscript = pytest.mark.xfail( matplotlib.checkdep_ghostscript()[0] is None, - "This test needs a ghostscript installation") - + reason="This test needs a ghostscript installation") -needs_tex = knownfailureif( +needs_tex = pytest.mark.xfail( not matplotlib.checkdep_tex(), - "This test needs a TeX installation") + reason="This test needs a TeX installation") def _test_savefig_to_stringio(format='ps', use_log=False): @@ -130,8 +129,3 @@ def test_patheffects(): ax.plot([1, 2, 3]) with io.BytesIO() as ps: fig.savefig(ps, format='ps') - - -if __name__ == '__main__': - import nose - nose.runmodule(argv=['-s', '--with-doctest'], exit=False) diff --git a/lib/matplotlib/tests/test_backend_qt4.py b/lib/matplotlib/tests/test_backend_qt4.py index 5dfdfdf6cf46..c6f3ef91740a 100644 --- a/lib/matplotlib/tests/test_backend_qt4.py +++ b/lib/matplotlib/tests/test_backend_qt4.py @@ -5,10 +5,10 @@ from matplotlib.externals.six import unichr from matplotlib import pyplot as plt from matplotlib.testing.decorators import cleanup, switch_backend -from matplotlib.testing.decorators import knownfailureif from matplotlib._pylab_helpers import Gcf import matplotlib import copy +import pytest try: # mock in python 3.3+ @@ -40,7 +40,7 @@ @cleanup -@knownfailureif(not HAS_QT) +@pytest.mark.xfail(not HAS_QT, reason='pyqt version 4 not installed') @switch_backend('Qt4Agg') def test_fig_close(): # save the state of Gcf.figs @@ -81,7 +81,7 @@ def receive(event): @cleanup -@knownfailureif(not HAS_QT) +@pytest.mark.xfail(not HAS_QT, reason='pyqt version 4 not installed') def test_shift(): assert_correct_key(QtCore.Qt.Key_A, ShiftModifier, @@ -89,7 +89,7 @@ def test_shift(): @cleanup -@knownfailureif(not HAS_QT) +@pytest.mark.xfail(not HAS_QT, reason='pyqt version 4 not installed') def test_lower(): assert_correct_key(QtCore.Qt.Key_A, QtCore.Qt.NoModifier, @@ -97,7 +97,7 @@ def test_lower(): @cleanup -@knownfailureif(not HAS_QT) +@pytest.mark.xfail(not HAS_QT, reason='pyqt version 4 not installed') def test_control(): assert_correct_key(QtCore.Qt.Key_A, ControlModifier, @@ -105,7 +105,7 @@ def test_control(): @cleanup -@knownfailureif(not HAS_QT) +@pytest.mark.xfail(not HAS_QT, reason='pyqt version 4 not installed') def test_unicode_upper(): assert_correct_key(QtCore.Qt.Key_Aacute, ShiftModifier, @@ -113,7 +113,7 @@ def test_unicode_upper(): @cleanup -@knownfailureif(not HAS_QT) +@pytest.mark.xfail(not HAS_QT, reason='pyqt version 4 not installed') def test_unicode_lower(): assert_correct_key(QtCore.Qt.Key_Aacute, QtCore.Qt.NoModifier, @@ -121,7 +121,7 @@ def test_unicode_lower(): @cleanup -@knownfailureif(not HAS_QT) +@pytest.mark.xfail(not HAS_QT, reason='pyqt version 4 not installed') def test_alt_control(): assert_correct_key(ControlKey, AltModifier, @@ -129,7 +129,7 @@ def test_alt_control(): @cleanup -@knownfailureif(not HAS_QT) +@pytest.mark.xfail(not HAS_QT, reason='pyqt version 4 not installed') def test_control_alt(): assert_correct_key(AltKey, ControlModifier, @@ -137,7 +137,7 @@ def test_control_alt(): @cleanup -@knownfailureif(not HAS_QT) +@pytest.mark.xfail(not HAS_QT, reason='pyqt version 4 not installed') def test_modifier_order(): assert_correct_key(QtCore.Qt.Key_Aacute, (ControlModifier | AltModifier | SuperModifier), @@ -145,7 +145,7 @@ def test_modifier_order(): @cleanup -@knownfailureif(not HAS_QT) +@pytest.mark.xfail(not HAS_QT, reason='pyqt version 4 not installed') def test_backspace(): assert_correct_key(QtCore.Qt.Key_Backspace, QtCore.Qt.NoModifier, @@ -153,7 +153,7 @@ def test_backspace(): @cleanup -@knownfailureif(not HAS_QT) +@pytest.mark.xfail(not HAS_QT, reason='pyqt version 4 not installed') def test_backspace_mod(): assert_correct_key(QtCore.Qt.Key_Backspace, ControlModifier, @@ -161,7 +161,7 @@ def test_backspace_mod(): @cleanup -@knownfailureif(not HAS_QT) +@pytest.mark.xfail(not HAS_QT, reason='pyqt version 4 not installed') def test_non_unicode_key(): assert_correct_key(QtCore.Qt.Key_Play, QtCore.Qt.NoModifier, diff --git a/lib/matplotlib/tests/test_backend_qt5.py b/lib/matplotlib/tests/test_backend_qt5.py index eefe86fd2001..3006aa88c59b 100644 --- a/lib/matplotlib/tests/test_backend_qt5.py +++ b/lib/matplotlib/tests/test_backend_qt5.py @@ -4,10 +4,10 @@ from matplotlib import pyplot as plt from matplotlib.testing.decorators import cleanup, switch_backend -from matplotlib.testing.decorators import knownfailureif from matplotlib._pylab_helpers import Gcf import matplotlib import copy +import pytest try: # mock in python 3.3+ @@ -34,7 +34,7 @@ @cleanup -@knownfailureif(not HAS_QT) +@pytest.mark.xfail(not HAS_QT, reason='pyqt version 5 not installed') @switch_backend('Qt5Agg') def test_fig_close(): # save the state of Gcf.figs @@ -75,7 +75,7 @@ def receive(event): @cleanup -@knownfailureif(not HAS_QT) +@pytest.mark.xfail(not HAS_QT, reason='pyqt version 5 not installed') def test_shift(): assert_correct_key(QtCore.Qt.Key_A, ShiftModifier, @@ -83,7 +83,7 @@ def test_shift(): @cleanup -@knownfailureif(not HAS_QT) +@pytest.mark.xfail(not HAS_QT, reason='pyqt version 5 not installed') def test_lower(): assert_correct_key(QtCore.Qt.Key_A, QtCore.Qt.NoModifier, @@ -91,7 +91,7 @@ def test_lower(): @cleanup -@knownfailureif(not HAS_QT) +@pytest.mark.xfail(not HAS_QT, reason='pyqt version 5 not installed') def test_control(): assert_correct_key(QtCore.Qt.Key_A, ControlModifier, @@ -99,7 +99,7 @@ def test_control(): @cleanup -@knownfailureif(not HAS_QT) +@pytest.mark.xfail(not HAS_QT, reason='pyqt version 5 not installed') def test_unicode_upper(): assert_correct_key(QtCore.Qt.Key_Aacute, ShiftModifier, @@ -107,7 +107,7 @@ def test_unicode_upper(): @cleanup -@knownfailureif(not HAS_QT) +@pytest.mark.xfail(not HAS_QT, reason='pyqt version 5 not installed') def test_unicode_lower(): assert_correct_key(QtCore.Qt.Key_Aacute, QtCore.Qt.NoModifier, @@ -115,7 +115,7 @@ def test_unicode_lower(): @cleanup -@knownfailureif(not HAS_QT) +@pytest.mark.xfail(not HAS_QT, reason='pyqt version 5 not installed') def test_alt_control(): assert_correct_key(ControlKey, AltModifier, @@ -123,7 +123,7 @@ def test_alt_control(): @cleanup -@knownfailureif(not HAS_QT) +@pytest.mark.xfail(not HAS_QT, reason='pyqt version 5 not installed') def test_control_alt(): assert_correct_key(AltKey, ControlModifier, @@ -131,7 +131,7 @@ def test_control_alt(): @cleanup -@knownfailureif(not HAS_QT) +@pytest.mark.xfail(not HAS_QT, reason='pyqt version 5 not installed') def test_modifier_order(): assert_correct_key(QtCore.Qt.Key_Aacute, (ControlModifier | AltModifier | SuperModifier), @@ -139,7 +139,7 @@ def test_modifier_order(): @cleanup -@knownfailureif(not HAS_QT) +@pytest.mark.xfail(not HAS_QT, reason='pyqt version 5 not installed') def test_backspace(): assert_correct_key(QtCore.Qt.Key_Backspace, QtCore.Qt.NoModifier, @@ -147,7 +147,7 @@ def test_backspace(): @cleanup -@knownfailureif(not HAS_QT) +@pytest.mark.xfail(not HAS_QT, reason='pyqt version 5 not installed') def test_backspace_mod(): assert_correct_key(QtCore.Qt.Key_Backspace, ControlModifier, @@ -155,7 +155,7 @@ def test_backspace_mod(): @cleanup -@knownfailureif(not HAS_QT) +@pytest.mark.xfail(not HAS_QT, reason='pyqt version 5 not installed') def test_non_unicode_key(): assert_correct_key(QtCore.Qt.Key_Play, QtCore.Qt.NoModifier, diff --git a/lib/matplotlib/tests/test_backend_svg.py b/lib/matplotlib/tests/test_backend_svg.py index 38116fab4fe7..00513dd8d4ee 100644 --- a/lib/matplotlib/tests/test_backend_svg.py +++ b/lib/matplotlib/tests/test_backend_svg.py @@ -9,12 +9,13 @@ import matplotlib.pyplot as plt from matplotlib.testing.decorators import cleanup -from matplotlib.testing.decorators import image_comparison, knownfailureif +from matplotlib.testing.decorators import image_comparison import matplotlib +import pytest -needs_tex = knownfailureif( +needs_tex = pytest.mark.xfail( not matplotlib.checkdep_tex(), - "This test needs a TeX installation") + reason="This test needs a TeX installation") @cleanup @@ -155,7 +156,6 @@ def _test_determinism(filename, usetex): import os import sys from subprocess import check_call - from nose.tools import assert_equal plots = [] for i in range(3): check_call([sys.executable, '-R', '-c', @@ -168,7 +168,7 @@ def _test_determinism(filename, usetex): plots.append(fd.read()) os.unlink(filename) for p in plots[1:]: - assert_equal(p, plots[0]) + assert p == plots[0] @cleanup @@ -182,8 +182,3 @@ def test_determinism_notex(): def test_determinism_tex(): # unique filename to allow for parallel testing _test_determinism('determinism_tex.svg', usetex=True) - - -if __name__ == '__main__': - import nose - nose.runmodule(argv=['-s', '--with-doctest'], exit=False) diff --git a/lib/matplotlib/tests/test_basic.py b/lib/matplotlib/tests/test_basic.py index db3d8b94ed4b..c34b954d7bf4 100644 --- a/lib/matplotlib/tests/test_basic.py +++ b/lib/matplotlib/tests/test_basic.py @@ -3,20 +3,20 @@ from matplotlib.externals import six -from nose.tools import assert_equal -from matplotlib.testing.decorators import knownfailureif -from pylab import * +import pylab +import sys +import pytest def test_simple(): - assert_equal(1 + 1, 2) + assert 1 + 1 == 2 -@knownfailureif(True) +@pytest.mark.xfail def test_simple_knownfail(): # Test the known fail mechanism. - assert_equal(1 + 1, 3) + assert 1 + 1 == 3 def test_override_builtins(): @@ -47,8 +47,3 @@ def test_override_builtins(): overridden = True assert not overridden - - -if __name__ == '__main__': - import nose - nose.runmodule(argv=['-s', '--with-doctest'], exit=False) diff --git a/lib/matplotlib/tests/test_bbox_tight.py b/lib/matplotlib/tests/test_bbox_tight.py index 7e05e5fd5432..875318b5a76f 100644 --- a/lib/matplotlib/tests/test_bbox_tight.py +++ b/lib/matplotlib/tests/test_bbox_tight.py @@ -18,10 +18,10 @@ savefig_kwarg=dict(bbox_inches='tight')) def test_bbox_inches_tight(): #: Test that a figure saved using bbox_inches='tight' is clipped correctly - data = [[ 66386, 174296, 75131, 577908, 32015], - [ 58230, 381139, 78045, 99308, 160454], - [ 89135, 80552, 152558, 497981, 603535], - [ 78415, 81858, 150656, 193263, 69638], + data = [[66386, 174296, 75131, 577908, 32015], + [58230, 381139, 78045, 99308, 160454], + [89135, 80552, 152558, 497981, 603535], + [78415, 81858, 150656, 193263, 69638], [139361, 331509, 343164, 781380, 52269]] colLabels = rowLabels = [''] * 5 @@ -93,7 +93,3 @@ def test_bbox_inches_tight_raster(): fig = plt.figure() ax = fig.add_subplot(111) ax.plot([1.0, 2.0], rasterized=True) - -if __name__ == '__main__': - import nose - nose.runmodule(argv=['-s', '--with-doctest'], exit=False) diff --git a/lib/matplotlib/tests/test_cbook.py b/lib/matplotlib/tests/test_cbook.py index 1b11fe026120..bfdda8f0982e 100644 --- a/lib/matplotlib/tests/test_cbook.py +++ b/lib/matplotlib/tests/test_cbook.py @@ -10,8 +10,9 @@ import numpy as np from numpy.testing.utils import (assert_array_equal, assert_approx_equal, assert_array_almost_equal) -from nose.tools import (assert_equal, assert_not_equal, raises, assert_true, - assert_raises) +import pytest +# from nose.tools import (assert_equal, assert_not_equal, raises, assert_true, +# assert_raises) import matplotlib.cbook as cbook import matplotlib.colors as mcolors @@ -20,20 +21,20 @@ def test_is_string_like(): y = np.arange(10) - assert_equal(cbook.is_string_like(y), False) + assert not cbook.is_string_like(y) y.shape = 10, 1 - assert_equal(cbook.is_string_like(y), False) + assert not cbook.is_string_like(y) y.shape = 1, 10 - assert_equal(cbook.is_string_like(y), False) + assert not cbook.is_string_like(y) assert cbook.is_string_like("hello world") - assert_equal(cbook.is_string_like(10), False) + assert not cbook.is_string_like(10) y = ['a', 'b', 'c'] - assert_equal(cbook.is_string_like(y), False) + assert not cbook.is_string_like(y) y = np.array(y) - assert_equal(cbook.is_string_like(y), False) + assert not cbook.is_string_like(y) y = np.array(y, dtype=object) assert cbook.is_string_like(y) @@ -50,38 +51,40 @@ def test_is_sequence_of_strings(): def test_restrict_dict(): d = {'foo': 'bar', 1: 2} d1 = cbook.restrict_dict(d, ['foo', 1]) - assert_equal(d1, d) + assert d1 == d d2 = cbook.restrict_dict(d, ['bar', 2]) - assert_equal(d2, {}) + assert not d2 # making sure the dict d2 is not empty d3 = cbook.restrict_dict(d, {'foo': 1}) - assert_equal(d3, {'foo': 'bar'}) + assert d3 == {'foo': 'bar'} d4 = cbook.restrict_dict(d, {}) - assert_equal(d4, {}) + assert not d4 d5 = cbook.restrict_dict(d, set(['foo', 2])) - assert_equal(d5, {'foo': 'bar'}) + assert d5 == {'foo': 'bar'} # check that d was not modified - assert_equal(d, {'foo': 'bar', 1: 2}) + assert d == {'foo': 'bar', 1: 2} class Test_delete_masked_points(object): - def setUp(self): - self.mask1 = [False, False, True, True, False, False] - self.arr0 = np.arange(1.0, 7.0) - self.arr1 = [1, 2, 3, np.nan, np.nan, 6] - self.arr2 = np.array(self.arr1) - self.arr3 = np.ma.array(self.arr2, mask=self.mask1) - self.arr_s = ['a', 'b', 'c', 'd', 'e', 'f'] - self.arr_s2 = np.array(self.arr_s) - self.arr_dt = [datetime(2008, 1, 1), datetime(2008, 1, 2), + + @classmethod + def setup_class(cls): + cls.mask1 = [False, False, True, True, False, False] + cls.arr0 = np.arange(1.0, 7.0) + cls.arr1 = [1, 2, 3, np.nan, np.nan, 6] + cls.arr2 = np.array(cls.arr1) + cls.arr3 = np.ma.array(cls.arr2, mask=cls.mask1) + cls.arr_s = ['a', 'b', 'c', 'd', 'e', 'f'] + cls.arr_s2 = np.array(cls.arr_s) + cls.arr_dt = [datetime(2008, 1, 1), datetime(2008, 1, 2), datetime(2008, 1, 3), datetime(2008, 1, 4), datetime(2008, 1, 5), datetime(2008, 1, 6)] - self.arr_dt2 = np.array(self.arr_dt) - self.arr_colors = ['r', 'g', 'b', 'c', 'm', 'y'] - self.arr_rgba = mcolors.colorConverter.to_rgba_array(self.arr_colors) + cls.arr_dt2 = np.array(cls.arr_dt) + cls.arr_colors = ['r', 'g', 'b', 'c', 'm', 'y'] + cls.arr_rgba = mcolors.colorConverter.to_rgba_array(cls.arr_colors) - @raises(ValueError) def test_bad_first_arg(self): - dmp('a string', self.arr0) + with pytest.raises(ValueError): + dmp('a string', self.arr0) def test_string_seq(self): actual = dmp(self.arr_s, self.arr1) @@ -167,17 +170,17 @@ def setup(self): } def test_form_main_list(self): - assert_true(isinstance(self.std_results, list)) + assert isinstance(self.std_results, list) def test_form_each_dict(self): for res in self.std_results: - assert_true(isinstance(res, dict)) + assert isinstance(res, dict) def test_form_dict_keys(self): for res in self.std_results: keys = sorted(list(res.keys())) for key in keys: - assert_true(key in self.known_keys) + assert key in self.known_keys def test_results_baseline(self): res = self.std_results[0] @@ -248,38 +251,39 @@ def test_results_withlabels(self): results = cbook.boxplot_stats(self.data, labels=labels) res = results[0] for lab, res in zip(labels, results): - assert_equal(res['label'], lab) + assert res['label'] == lab results = cbook.boxplot_stats(self.data) for res in results: assert('label' not in res) - @raises(ValueError) def test_label_error(self): - labels = [1, 2] - results = cbook.boxplot_stats(self.data, labels=labels) + with pytest.raises(ValueError): + labels = [1, 2] + results = cbook.boxplot_stats(self.data, labels=labels) - @raises(ValueError) def test_bad_dims(self): - data = np.random.normal(size=(34, 34, 34)) - results = cbook.boxplot_stats(data) + with pytest.raises(ValueError): + data = np.random.normal(size=(34, 34, 34)) + results = cbook.boxplot_stats(data) class Test_callback_registry(object): - def setup(self): - self.signal = 'test' - self.callbacks = cbook.CallbackRegistry() + @classmethod + def setup_class(cls): + cls.signal = 'test' + cls.callbacks = cbook.CallbackRegistry() def connect(self, s, func): return self.callbacks.connect(s, func) def is_empty(self): - assert_equal(self.callbacks._func_cid_map, {}) - assert_equal(self.callbacks.callbacks, {}) + assert not self.callbacks._func_cid_map + assert not self.callbacks.callbacks def is_not_empty(self): - assert_not_equal(self.callbacks._func_cid_map, {}) - assert_not_equal(self.callbacks.callbacks, {}) + assert self.callbacks._func_cid_map + assert self.callbacks.callbacks def test_callback_complete(self): # ensure we start with an empty registry @@ -290,15 +294,15 @@ def test_callback_complete(self): # test that we can add a callback cid1 = self.connect(self.signal, mini_me.dummy) - assert_equal(type(cid1), int) + assert type(cid1) is int self.is_not_empty() # test that we don't add a second callback cid2 = self.connect(self.signal, mini_me.dummy) - assert_equal(cid1, cid2) + assert cid1 == cid2 self.is_not_empty() - assert_equal(len(self.callbacks._func_cid_map), 1) - assert_equal(len(self.callbacks.callbacks), 1) + assert len(self.callbacks._func_cid_map) == 1 + assert len(self.callbacks.callbacks) == 1 del mini_me @@ -370,14 +374,14 @@ def test_to_midstep(): def test_step_fails(): - assert_raises(ValueError, cbook._step_validation, - np.arange(12).reshape(3, 4), 'a') - assert_raises(ValueError, cbook._step_validation, - np.arange(12), 'a') - assert_raises(ValueError, cbook._step_validation, - np.arange(12)) - assert_raises(ValueError, cbook._step_validation, - np.arange(12), np.arange(3)) + with pytest.raises(ValueError): + cbook._step_validation(np.arange(12).reshape(3, 4), 'a') + with pytest.raises(ValueError): + cbook._step_validation(np.arange(12), 'a') + with pytest.raises(ValueError): + cbook._step_validation(np.arange(12)) + with pytest.raises(ValueError): + cbook._step_validation(np.arange(12), np.arange(3)) def test_grouper(): diff --git a/lib/matplotlib/tests/test_coding_standards.py b/lib/matplotlib/tests/test_coding_standards.py index 6734fde7b6e6..60f21b096ca7 100644 --- a/lib/matplotlib/tests/test_coding_standards.py +++ b/lib/matplotlib/tests/test_coding_standards.py @@ -3,10 +3,7 @@ from fnmatch import fnmatch import os - -from nose.tools import assert_equal -from nose.plugins.skip import SkipTest -from matplotlib.testing.noseclasses import KnownFailureTest +# import pytest try: import pep8 @@ -86,199 +83,194 @@ def get_file_results(self): return self.file_errors -def assert_pep8_conformance(module=matplotlib, exclude_files=None, - extra_exclude_file=EXTRA_EXCLUDE_FILE, - pep8_additional_ignore=PEP8_ADDITIONAL_IGNORE, - dirname=None, expected_bad_files=None, - extra_exclude_directories=None): - """ - Tests the matplotlib codebase against the "pep8" tool. - - Users can add their own excluded files (should files exist in the - local directory which is not in the repository) by adding a - ".pep8_test_exclude.txt" file in the same directory as this test. - The file should be a line separated list of filenames/directories - as can be passed to the "pep8" tool's exclude list. - """ - - if not HAS_PEP8: - raise SkipTest('The pep8 tool is required for this test') - - # to get a list of bad files, rather than the specific errors, add - # "reporter=pep8.FileReport" to the StyleGuide constructor. - pep8style = pep8.StyleGuide(quiet=False, - reporter=StandardReportWithExclusions) - reporter = pep8style.options.reporter - - if expected_bad_files is not None: - reporter.expected_bad_files = expected_bad_files - - # Extend the number of PEP8 guidelines which are not checked. - pep8style.options.ignore = (pep8style.options.ignore + - tuple(pep8_additional_ignore)) - - # Support for egg shared object wrappers, which are not PEP8 compliant, - # nor part of the matplotlib repository. - # DO NOT ADD FILES *IN* THE REPOSITORY TO THIS LIST. - if exclude_files is not None: - pep8style.options.exclude.extend(exclude_files) - - # Allow users to add their own exclude list. - if extra_exclude_file is not None and os.path.exists(extra_exclude_file): - with open(extra_exclude_file, 'r') as fh: - extra_exclude = [line.strip() for line in fh if line.strip()] - pep8style.options.exclude.extend(extra_exclude) - - if extra_exclude_directories: - pep8style.options.exclude.extend(extra_exclude_directories) - - if dirname is None: - dirname = os.path.dirname(module.__file__) - result = pep8style.check_files([dirname]) - if reporter is StandardReportWithExclusions: - msg = ("Found code syntax errors (and warnings):\n" - "{0}".format('\n'.join(reporter._global_deferred_print))) - else: - msg = "Found code syntax errors (and warnings)." - assert_equal(result.total_errors, 0, msg) - - # If we've been using the exclusions reporter, check that we didn't - # exclude files unnecessarily. - if reporter is StandardReportWithExclusions: - unexpectedly_good = sorted(set(reporter.expected_bad_files) - - reporter.matched_exclusions) - - if unexpectedly_good: - raise ValueError('Some exclude patterns were unnecessary as the ' - 'files they pointed to either passed the PEP8 ' - 'tests or do not point to a file:\n ' - '{0}'.format('\n '.join(unexpectedly_good))) - - -def test_pep8_conformance_installed_files(): - exclude_files = ['_delaunay.py', - '_image.py', - '_tri.py', - '_backend_agg.py', - '_tkagg.py', - 'ft2font.py', - '_cntr.py', - '_contour.py', - '_png.py', - '_path.py', - 'ttconv.py', - '_gtkagg.py', - '_backend_gdk.py', - 'pyparsing*', - '_qhull.py', - '_macosx.py'] - - expected_bad_files = ['_cm.py', - '_mathtext_data.py', - 'backend_bases.py', - 'cbook.py', - 'collections.py', - 'font_manager.py', - 'fontconfig_pattern.py', - 'gridspec.py', - 'legend_handler.py', - 'mathtext.py', - 'patheffects.py', - 'pylab.py', - 'pyplot.py', - 'rcsetup.py', - 'stackplot.py', - 'texmanager.py', - 'transforms.py', - 'type1font.py', - 'widgets.py', - 'testing/decorators.py', - 'testing/jpl_units/Duration.py', - 'testing/jpl_units/Epoch.py', - 'testing/jpl_units/EpochConverter.py', - 'testing/jpl_units/StrConverter.py', - 'testing/jpl_units/UnitDbl.py', - 'testing/jpl_units/UnitDblConverter.py', - 'testing/jpl_units/UnitDblFormatter.py', - 'testing/jpl_units/__init__.py', - 'tri/triinterpolate.py', - 'tests/test_axes.py', - 'tests/test_bbox_tight.py', - 'tests/test_delaunay.py', - 'tests/test_image.py', - 'tests/test_legend.py', - 'tests/test_lines.py', - 'tests/test_mathtext.py', - 'tests/test_rcparams.py', - 'tests/test_simplification.py', - 'tests/test_streamplot.py', - 'tests/test_subplots.py', - 'tests/test_tightlayout.py', - 'tests/test_triangulation.py', - 'compat/subprocess.py', - 'backends/__init__.py', - 'backends/backend_agg.py', - 'backends/backend_cairo.py', - 'backends/backend_cocoaagg.py', - 'backends/backend_gdk.py', - 'backends/backend_gtk.py', - 'backends/backend_gtk3.py', - 'backends/backend_gtk3cairo.py', - 'backends/backend_gtkagg.py', - 'backends/backend_gtkcairo.py', - 'backends/backend_macosx.py', - 'backends/backend_mixed.py', - 'backends/backend_pgf.py', - 'backends/backend_ps.py', - 'backends/backend_svg.py', - 'backends/backend_template.py', - 'backends/backend_tkagg.py', - 'backends/tkagg.py', - 'backends/windowing.py', - 'backends/qt_editor/formlayout.py', - 'sphinxext/mathmpl.py', - 'sphinxext/only_directives.py', - 'sphinxext/plot_directive.py', - 'projections/__init__.py', - 'projections/geo.py', - 'projections/polar.py', - 'externals/six.py'] - expected_bad_files = ['*/matplotlib/' + s for s in expected_bad_files] - assert_pep8_conformance(module=matplotlib, - exclude_files=exclude_files, - expected_bad_files=expected_bad_files) - - -def test_pep8_conformance_examples(): - mpldir = os.environ.get('MPL_REPO_DIR', None) - if mpldir is None: - # try and guess! - fp = os.getcwd() - while len(fp) > 2: - if os.path.isdir(os.path.join(fp, 'examples')): - mpldir = fp - break - fp, tail = os.path.split(fp) - - if mpldir is None: - raise KnownFailureTest("can not find the examples, set env " - "MPL_REPO_DIR to point to the top-level path " - "of the source tree") - - exdir = os.path.join(mpldir, 'examples') - blacklist = () - expected_bad_files = ['*/pylab_examples/table_demo.py', - '*/pylab_examples/tricontour_demo.py', - '*/pylab_examples/tripcolor_demo.py', - '*/pylab_examples/triplot_demo.py', - '*/shapes_and_collections/artist_reference.py'] - assert_pep8_conformance(dirname=exdir, - extra_exclude_directories=blacklist, - pep8_additional_ignore=PEP8_ADDITIONAL_IGNORE + - ['E116', 'E501', 'E402'], - expected_bad_files=expected_bad_files) - - -if __name__ == '__main__': - import nose - nose.runmodule(argv=['-s', '--with-doctest'], exit=False) +# def assert_pep8_conformance(module=matplotlib, exclude_files=None, +# extra_exclude_file=EXTRA_EXCLUDE_FILE, +# pep8_additional_ignore=PEP8_ADDITIONAL_IGNORE, +# dirname=None, expected_bad_files=None, +# extra_exclude_directories=None): +# """ +# Tests the matplotlib codebase against the "pep8" tool. +# +# Users can add their own excluded files (should files exist in the +# local directory which is not in the repository) by adding a +# ".pep8_test_exclude.txt" file in the same directory as this test. +# The file should be a line separated list of filenames/directories +# as can be passed to the "pep8" tool's exclude list. +# """ +# +# if not HAS_PEP8: +# raise pytest.skip('The pep8 tool is required for this test') +# +# # to get a list of bad files, rather than the specific errors, add +# # "reporter=pep8.FileReport" to the StyleGuide constructor. +# pep8style = pep8.StyleGuide(quiet=False, +# reporter=StandardReportWithExclusions) +# reporter = pep8style.options.reporter +# +# if expected_bad_files is not None: +# reporter.expected_bad_files = expected_bad_files +# +# # Extend the number of PEP8 guidelines which are not checked. +# pep8style.options.ignore = (pep8style.options.ignore + +# tuple(pep8_additional_ignore)) +# +# # Support for egg shared object wrappers, which are not PEP8 compliant, +# # nor part of the matplotlib repository. +# # DO NOT ADD FILES *IN* THE REPOSITORY TO THIS LIST. +# if exclude_files is not None: +# pep8style.options.exclude.extend(exclude_files) +# +# # Allow users to add their own exclude list. +# if extra_exclude_file is not None and os.path.exists(extra_exclude_file): +# with open(extra_exclude_file, 'r') as fh: +# extra_exclude = [line.strip() for line in fh if line.strip()] +# pep8style.options.exclude.extend(extra_exclude) +# +# if extra_exclude_directories: +# pep8style.options.exclude.extend(extra_exclude_directories) +# +# if dirname is None: +# dirname = os.path.dirname(module.__file__) +# result = pep8style.check_files([dirname]) +# if reporter is StandardReportWithExclusions: +# msg = ("Found code syntax errors (and warnings):\n" +# "{0}".format('\n'.join(reporter._global_deferred_print))) +# else: +# msg = "Found code syntax errors (and warnings)." +# assert result.total_errors == 0, msg +# +# # If we've been using the exclusions reporter, check that we didn't +# # exclude files unnecessarily. +# if reporter is StandardReportWithExclusions: +# unexpectedly_good = sorted(set(reporter.expected_bad_files) - +# reporter.matched_exclusions) +# +# if unexpectedly_good: +# raise ValueError('Some exclude patterns were unnecessary as the ' +# 'files they pointed to either passed the PEP8 ' +# 'tests or do not point to a file:\n ' +# '{0}'.format('\n '.join(unexpectedly_good))) + + +# def test_pep8_conformance_installed_files(): +# exclude_files = ['_delaunay.py', +# '_image.py', +# '_tri.py', +# '_backend_agg.py', +# '_tkagg.py', +# 'ft2font.py', +# '_cntr.py', +# '_contour.py', +# '_png.py', +# '_path.py', +# 'ttconv.py', +# '_gtkagg.py', +# '_backend_gdk.py', +# 'pyparsing*', +# '_qhull.py', +# '_macosx.py'] +# +# expected_bad_files = ['_cm.py', +# '_mathtext_data.py', +# 'backend_bases.py', +# 'cbook.py', +# 'collections.py', +# 'font_manager.py', +# 'fontconfig_pattern.py', +# 'gridspec.py', +# 'legend_handler.py', +# 'mathtext.py', +# 'patheffects.py', +# 'pylab.py', +# 'pyplot.py', +# 'rcsetup.py', +# 'stackplot.py', +# 'texmanager.py', +# 'transforms.py', +# 'type1font.py', +# 'widgets.py', +# 'testing/decorators.py', +# 'testing/jpl_units/Duration.py', +# 'testing/jpl_units/Epoch.py', +# 'testing/jpl_units/EpochConverter.py', +# 'testing/jpl_units/StrConverter.py', +# 'testing/jpl_units/UnitDbl.py', +# 'testing/jpl_units/UnitDblConverter.py', +# 'testing/jpl_units/UnitDblFormatter.py', +# 'testing/jpl_units/__init__.py', +# 'tri/triinterpolate.py', +# 'tests/test_axes.py', +# 'tests/test_bbox_tight.py', +# 'tests/test_delaunay.py', +# 'tests/test_image.py', +# 'tests/test_legend.py', +# 'tests/test_lines.py', +# 'tests/test_mathtext.py', +# 'tests/test_rcparams.py', +# 'tests/test_simplification.py', +# 'tests/test_streamplot.py', +# 'tests/test_subplots.py', +# 'tests/test_tightlayout.py', +# 'tests/test_triangulation.py', +# 'compat/subprocess.py', +# 'backends/__init__.py', +# 'backends/backend_agg.py', +# 'backends/backend_cairo.py', +# 'backends/backend_cocoaagg.py', +# 'backends/backend_gdk.py', +# 'backends/backend_gtk.py', +# 'backends/backend_gtk3.py', +# 'backends/backend_gtk3cairo.py', +# 'backends/backend_gtkagg.py', +# 'backends/backend_gtkcairo.py', +# 'backends/backend_macosx.py', +# 'backends/backend_mixed.py', +# 'backends/backend_pgf.py', +# 'backends/backend_ps.py', +# 'backends/backend_svg.py', +# 'backends/backend_template.py', +# 'backends/backend_tkagg.py', +# 'backends/tkagg.py', +# 'backends/windowing.py', +# 'backends/qt_editor/formlayout.py', +# 'sphinxext/mathmpl.py', +# 'sphinxext/only_directives.py', +# 'sphinxext/plot_directive.py', +# 'projections/__init__.py', +# 'projections/geo.py', +# 'projections/polar.py', +# 'externals/six.py'] +# expected_bad_files = ['*/matplotlib/' + s for s in expected_bad_files] +# assert_pep8_conformance(module=matplotlib, +# exclude_files=exclude_files, +# expected_bad_files=expected_bad_files) + + +# def test_pep8_conformance_examples(): +# mpldir = os.environ.get('MPL_REPO_DIR', None) +# if mpldir is None: +# # try and guess! +# fp = os.getcwd() +# while len(fp) > 2: +# if os.path.isdir(os.path.join(fp, 'examples')): +# mpldir = fp +# break +# fp, tail = os.path.split(fp) +# +# if mpldir is None: +# raise pytest.xfail("can not find the examples, set env " +# "MPL_REPO_DIR to point to the top-level path " +# "of the source tree") +# +# exdir = os.path.join(mpldir, 'examples') +# blacklist = () +# expected_bad_files = ['*/pylab_examples/table_demo.py', +# '*/pylab_examples/tricontour_demo.py', +# '*/pylab_examples/tripcolor_demo.py', +# '*/pylab_examples/triplot_demo.py', +# '*/shapes_and_collections/artist_reference.py'] +# assert_pep8_conformance(dirname=exdir, +# extra_exclude_directories=blacklist, +# pep8_additional_ignore=PEP8_ADDITIONAL_IGNORE + +# ['E116', 'E501', 'E402'], +# expected_bad_files=expected_bad_files) diff --git a/lib/matplotlib/tests/test_collections.py b/lib/matplotlib/tests/test_collections.py index 3001147b1841..4b866fd98262 100644 --- a/lib/matplotlib/tests/test_collections.py +++ b/lib/matplotlib/tests/test_collections.py @@ -8,7 +8,6 @@ import io -from nose.tools import assert_equal import numpy as np from numpy.testing import assert_array_equal, assert_array_almost_equal @@ -91,7 +90,7 @@ def test__EventCollection__get_orientation(): orientation ''' _, coll, props = generate_EventCollection_plot() - assert_equal(props['orientation'], coll.get_orientation()) + assert props['orientation'] == coll.get_orientation() @cleanup @@ -101,7 +100,7 @@ def test__EventCollection__is_horizontal(): orientation ''' _, coll, _ = generate_EventCollection_plot() - assert_equal(True, coll.is_horizontal()) + assert coll.is_horizontal() @cleanup @@ -110,7 +109,7 @@ def test__EventCollection__get_linelength(): check to make sure the default linelength matches the input linelength ''' _, coll, props = generate_EventCollection_plot() - assert_equal(props['linelength'], coll.get_linelength()) + assert props['linelength'] == coll.get_linelength() @cleanup @@ -119,7 +118,7 @@ def test__EventCollection__get_lineoffset(): check to make sure the default lineoffset matches the input lineoffset ''' _, coll, props = generate_EventCollection_plot() - assert_equal(props['lineoffset'], coll.get_lineoffset()) + assert props['lineoffset'] == coll.get_lineoffset() @cleanup @@ -128,7 +127,7 @@ def test__EventCollection__get_linestyle(): check to make sure the default linestyle matches the input linestyle ''' _, coll, _ = generate_EventCollection_plot() - assert_equal(coll.get_linestyle(), [(None, None)]) + assert coll.get_linestyle() == [(None, None)] @cleanup @@ -223,8 +222,8 @@ def test__EventCollection__switch_orientation(): splt, coll, props = generate_EventCollection_plot() new_orientation = 'vertical' coll.switch_orientation() - assert_equal(new_orientation, coll.get_orientation()) - assert_equal(False, coll.is_horizontal()) + assert new_orientation == coll.get_orientation() + assert not coll.is_horizontal() new_positions = coll.get_positions() check_segments(coll, new_positions, @@ -246,8 +245,8 @@ def test__EventCollection__switch_orientation_2x(): coll.switch_orientation() coll.switch_orientation() new_positions = coll.get_positions() - assert_equal(props['orientation'], coll.get_orientation()) - assert_equal(True, coll.is_horizontal()) + assert props['orientation'] == coll.get_orientation() + assert coll.is_horizontal() np.testing.assert_array_equal(props['positions'], new_positions) check_segments(coll, new_positions, @@ -265,8 +264,8 @@ def test__EventCollection__set_orientation(): splt, coll, props = generate_EventCollection_plot() new_orientation = 'vertical' coll.set_orientation(new_orientation) - assert_equal(new_orientation, coll.get_orientation()) - assert_equal(False, coll.is_horizontal()) + assert new_orientation == coll.get_orientation() + assert not coll.is_horizontal() check_segments(coll, props['positions'], props['linelength'], @@ -285,7 +284,7 @@ def test__EventCollection__set_linelength(): splt, coll, props = generate_EventCollection_plot() new_linelength = 15 coll.set_linelength(new_linelength) - assert_equal(new_linelength, coll.get_linelength()) + assert new_linelength == coll.get_linelength() check_segments(coll, props['positions'], new_linelength, @@ -303,7 +302,7 @@ def test__EventCollection__set_lineoffset(): splt, coll, props = generate_EventCollection_plot() new_lineoffset = -5. coll.set_lineoffset(new_lineoffset) - assert_equal(new_lineoffset, coll.get_lineoffset()) + assert new_lineoffset == coll.get_lineoffset() check_segments(coll, props['positions'], props['linelength'], @@ -321,7 +320,7 @@ def test__EventCollection__set_linestyle(): splt, coll, _ = generate_EventCollection_plot() new_linestyle = 'dashed' coll.set_linestyle(new_linestyle) - assert_equal(coll.get_linestyle(), [(0, (6.0, 6.0))]) + assert coll.get_linestyle() == [(0, (6.0, 6.0))] splt.set_title('EventCollection: set_linestyle') @@ -334,7 +333,7 @@ def test__EventCollection__set_linestyle_single_dash(): splt, coll, _ = generate_EventCollection_plot() new_linestyle = (0, (6., 6.)) coll.set_linestyle(new_linestyle) - assert_equal(coll.get_linestyle(), [(0, (6.0, 6.0))]) + assert coll.get_linestyle() == [(0, (6.0, 6.0))] splt.set_title('EventCollection: set_linestyle') @@ -346,7 +345,7 @@ def test__EventCollection__set_linewidth(): splt, coll, _ = generate_EventCollection_plot() new_linewidth = 5 coll.set_linewidth(new_linewidth) - assert_equal(coll.get_linewidth(), new_linewidth) + assert coll.get_linewidth() == new_linewidth splt.set_title('EventCollection: set_linewidth') @@ -385,10 +384,10 @@ def check_segments(coll, positions, linelength, lineoffset, orientation): # test to make sure each segment is correct for i, segment in enumerate(segments): - assert_equal(segment[0, pos1], lineoffset + linelength / 2.) - assert_equal(segment[1, pos1], lineoffset - linelength / 2.) - assert_equal(segment[0, pos2], positions[i]) - assert_equal(segment[1, pos2], positions[i]) + assert segment[0, pos1] == lineoffset + linelength / 2. + assert segment[1, pos1] == lineoffset - linelength / 2. + assert segment[0, pos2] == positions[i] + assert segment[1, pos2] == positions[i] def check_allprop(values, target): @@ -398,7 +397,7 @@ def check_allprop(values, target): note: this is not a test, it is used by tests ''' for value in values: - assert_equal(value, target) + assert value == target def check_allprop_array(values, target): @@ -428,7 +427,7 @@ def test_add_collection(): ax.add_collection(coll) bounds = ax.dataLim.bounds coll = ax.scatter([], []) - assert_equal(ax.dataLim.bounds, bounds) + assert ax.dataLim.bounds == bounds @cleanup @@ -437,7 +436,7 @@ def test_quiver_limits(): x, y = np.arange(8), np.arange(10) data = u = v = np.linspace(0, 10, 80).reshape(10, 8) q = plt.quiver(x, y, u, v) - assert_equal(q.get_datalim(ax.transData).bounds, (0., 0., 7., 9.)) + assert q.get_datalim(ax.transData).bounds == (0., 0., 7., 9.) plt.figure() ax = plt.axes() @@ -446,7 +445,7 @@ def test_quiver_limits(): y, x = np.meshgrid(y, x) trans = mtransforms.Affine2D().translate(25, 32) + ax.transData plt.quiver(x, y, np.sin(x), np.cos(y), transform=trans) - assert_equal(ax.dataLim.bounds, (20.0, 30.0, 15.0, 6.0)) + assert ax.dataLim.bounds == (20.0, 30.0, 15.0, 6.0) @cleanup @@ -615,8 +614,3 @@ def test_size_in_xy(): ax.set_xlim(0, 30) ax.set_ylim(0, 30) - - -if __name__ == '__main__': - import nose - nose.runmodule(argv=['-s', '--with-doctest'], exit=False) diff --git a/lib/matplotlib/tests/test_colorbar.py b/lib/matplotlib/tests/test_colorbar.py index 8d0bc1d709b8..47c32b50dcd3 100644 --- a/lib/matplotlib/tests/test_colorbar.py +++ b/lib/matplotlib/tests/test_colorbar.py @@ -296,8 +296,3 @@ def test_colorbar_ticks(): cbar = fig.colorbar(cs, ax=ax, extend='neither', orientation='horizontal', ticks=clevs) assert len(cbar.ax.xaxis.get_ticklocs()) == len(clevs) - - -if __name__ == '__main__': - import nose - nose.runmodule(argv=['-s', '--with-doctest'], exit=False) diff --git a/lib/matplotlib/tests/test_colors.py b/lib/matplotlib/tests/test_colors.py index c9166a5a7db3..bd17ea1e4da6 100644 --- a/lib/matplotlib/tests/test_colors.py +++ b/lib/matplotlib/tests/test_colors.py @@ -5,7 +5,7 @@ import itertools from distutils.version import LooseVersion as V -from nose.tools import assert_raises, assert_equal, assert_true +# from nose.tools import assert_raises, assert_equal, assert_true import numpy as np from numpy.testing.utils import assert_array_equal, assert_array_almost_equal @@ -15,7 +15,8 @@ import matplotlib.cbook as cbook import matplotlib.pyplot as plt from matplotlib.testing.decorators import (image_comparison, - cleanup, knownfailureif) + cleanup) +import pytest def test_colormap_endian(): @@ -70,7 +71,7 @@ def test_BoundaryNorm(): expected = [-1, 0, 1, 2] for v, ex in zip(vals, expected): ret = bn(v) - assert_true(isinstance(ret, six.integer_types)) + assert isinstance(ret, six.integer_types) assert_array_equal(ret, ex) assert_array_equal(bn([v]), ex) @@ -79,7 +80,7 @@ def test_BoundaryNorm(): expected = [-1, 0, 2, 3] for v, ex in zip(vals, expected): ret = bn(v) - assert_true(isinstance(ret, six.integer_types)) + assert isinstance(ret, six.integer_types) assert_array_equal(ret, ex) assert_array_equal(bn([v]), ex) @@ -88,7 +89,7 @@ def test_BoundaryNorm(): expected = [0, 0, 2, 2] for v, ex in zip(vals, expected): ret = bn(v) - assert_true(isinstance(ret, six.integer_types)) + assert isinstance(ret, six.integer_types) assert_array_equal(ret, ex) assert_array_equal(bn([v]), ex) @@ -109,9 +110,9 @@ def test_BoundaryNorm(): # Non-trivial masked arrays vals = np.ma.masked_invalid([np.Inf, np.NaN]) - assert_true(np.all(bn(vals).mask)) + assert np.all(bn(vals).mask) vals = np.ma.masked_invalid([np.Inf]) - assert_true(np.all(bn(vals).mask)) + assert np.all(bn(vals).mask) def test_LogNorm(): @@ -134,8 +135,8 @@ def test_PowerNorm(): expected = [0, 0, 1/16, 1/4, 1] pnorm = mcolors.PowerNorm(2, vmin=0, vmax=8) assert_array_almost_equal(pnorm(a), expected) - assert_equal(pnorm(a[0]), expected[0]) - assert_equal(pnorm(a[2]), expected[2]) + assert pnorm(a[0]) == expected[0] + assert pnorm(a[2]) == expected[2] assert_array_almost_equal(a[1:], pnorm.inverse(pnorm(a))[1:]) # Clip = True @@ -143,16 +144,16 @@ def test_PowerNorm(): expected = [0, 0, 0, 1, 1] pnorm = mcolors.PowerNorm(2, vmin=2, vmax=8, clip=True) assert_array_almost_equal(pnorm(a), expected) - assert_equal(pnorm(a[0]), expected[0]) - assert_equal(pnorm(a[-1]), expected[-1]) + assert pnorm(a[0]) == expected[0] + assert pnorm(a[-1]) == expected[-1] # Clip = True at call time a = np.array([-0.5, 0, 1, 8, 16], dtype=np.float) expected = [0, 0, 0, 1, 1] pnorm = mcolors.PowerNorm(2, vmin=2, vmax=8, clip=False) assert_array_almost_equal(pnorm(a, clip=True), expected) - assert_equal(pnorm(a[0], clip=True), expected[0]) - assert_equal(pnorm(a[-1], clip=True), expected[-1]) + assert pnorm(a[0], clip=True) == expected[0] + assert pnorm(a[-1], clip=True) == expected[-1] def test_Normalize(): @@ -281,7 +282,8 @@ def test_cmap_and_norm_from_levels_and_colors2(): 'Wih extend={0!r} and data ' 'value={1!r}'.format(extend, d_val)) - assert_raises(ValueError, mcolors.from_levels_and_colors, levels, colors) + with pytest.raises(ValueError): + mcolors.from_levels_and_colors(levels, colors) def test_rgb_hsv_round_trip(): @@ -311,8 +313,10 @@ def gray_from_float_rgb(): def gray_from_float_rgba(): return mcolors.colorConverter.to_rgba(0.4) - assert_raises(ValueError, gray_from_float_rgb) - assert_raises(ValueError, gray_from_float_rgba) + with pytest.raises(ValueError): + gray_from_float_rgb() + with pytest.raises(ValueError): + gray_from_float_rgba() @image_comparison(baseline_images=['light_source_shading_topo'], @@ -396,8 +400,9 @@ def test_light_source_shading_default(): assert_array_almost_equal(rgb, expect, decimal=2) -@knownfailureif((V(np.__version__) <= V('1.9.0') - and V(np.__version__) >= V('1.7.0'))) +@pytest.mark.xfail((V(np.__version__) <= V('1.9.0') + and V(np.__version__) >= V('1.7.0')), + reason='numpy version needs to be between 1.7 and 1.9') # Numpy 1.9.1 fixed a bug in masked arrays which resulted in # additional elements being masked when calculating the gradient thus # the output is different with earlier numpy versions. @@ -534,8 +539,3 @@ def _azimuth2math(azimuth, elevation): theta = np.radians((90 - azimuth) % 360) phi = np.radians(90 - elevation) return theta, phi - - -if __name__ == '__main__': - import nose - nose.runmodule(argv=['-s', '--with-doctest'], exit=False) diff --git a/lib/matplotlib/tests/test_compare_images.py b/lib/matplotlib/tests/test_compare_images.py index f9ee9159f204..e90b0b631b1a 100644 --- a/lib/matplotlib/tests/test_compare_images.py +++ b/lib/matplotlib/tests/test_compare_images.py @@ -6,7 +6,7 @@ import os import shutil -from nose.tools import assert_equal, assert_not_equal, assert_almost_equal +from numpy.testing import assert_almost_equal from matplotlib.testing.compare import compare_images from matplotlib.testing.decorators import _image_directories @@ -37,10 +37,10 @@ def image_comparison_expect_rms(im1, im2, tol, expect_rms): results = compare_images(im1, im2, tol=tol, in_decorator=True) if expect_rms is None: - assert_equal(None, results) + assert results is None else: - assert_not_equal(None, results) - assert_almost_equal(expect_rms, results['rms'], places=4) + assert results is not None + assert_almost_equal(expect_rms, results['rms'], decimal=4) def test_image_compare_basic(): @@ -99,8 +99,3 @@ def test_image_compare_shade_difference(): # Now test the reverse comparison. image_comparison_expect_rms(im2, im1, tol=0, expect_rms=1.0) - - -if __name__ == '__main__': - import nose - nose.runmodule(argv=['-s', '--with-doctest'], exit=False) diff --git a/lib/matplotlib/tests/test_contour.py b/lib/matplotlib/tests/test_contour.py index 1abe239b3b5d..9ae8224968b6 100644 --- a/lib/matplotlib/tests/test_contour.py +++ b/lib/matplotlib/tests/test_contour.py @@ -9,7 +9,7 @@ from matplotlib import mlab from matplotlib.testing.decorators import cleanup, image_comparison from matplotlib import pyplot as plt -from nose.tools import assert_equal, assert_raises +import pytest import warnings import re @@ -284,12 +284,13 @@ def test_contourf_decreasing_levels(): # github issue 5477. z = [[0.1, 0.3], [0.5, 0.7]] plt.figure() - assert_raises(ValueError, plt.contourf, z, [1.0, 0.0]) + with pytest.raises(ValueError): + plt.contourf(z, [1.0, 0.0]) # Legacy contouring algorithm gives a warning rather than raising an error, # plus a DeprecationWarning. with warnings.catch_warnings(record=True) as w: plt.contourf(z, [1.0, 0.0], corner_mask='legacy') - assert_equal(len(w), 2) + assert len(w) == 2 @cleanup @@ -310,7 +311,3 @@ def test_vminvmax_warning(): assert (str(w[0].message).startswith( ("vmax is deprecated and will be removed in 2.2 "))) - -if __name__ == '__main__': - import nose - nose.runmodule(argv=['-s', '--with-doctest'], exit=False) diff --git a/lib/matplotlib/tests/test_cycles.py b/lib/matplotlib/tests/test_cycles.py index 5cec742f29ba..8c25bd7e0b57 100644 --- a/lib/matplotlib/tests/test_cycles.py +++ b/lib/matplotlib/tests/test_cycles.py @@ -4,8 +4,7 @@ from matplotlib.cbook import MatplotlibDeprecationWarning import matplotlib.pyplot as plt import numpy as np -from nose.tools import assert_raises - +import pytest from cycler import cycler @@ -173,16 +172,15 @@ def test_cycle_reset(): @cleanup def test_invalid_input_forms(): fig, ax = plt.subplots() - assert_raises((TypeError, ValueError), ax.set_prop_cycle, 1) - assert_raises((TypeError, ValueError), ax.set_prop_cycle, [1, 2]) - assert_raises((TypeError, ValueError), ax.set_prop_cycle, 'color', 'fish') - assert_raises((TypeError, ValueError), ax.set_prop_cycle, 'linewidth', 1) - assert_raises((TypeError, ValueError), ax.set_prop_cycle, - 'linewidth', {'1': 1, '2': 2}) - assert_raises((TypeError, ValueError), ax.set_prop_cycle, - linewidth=1, color='r') - - -if __name__ == '__main__': - import nose - nose.runmodule(argv=['-s', '--with-doctest'], exit=False) + with pytest.raises((TypeError, ValueError)): + ax.set_prop_cycle(1) + with pytest.raises((TypeError, ValueError)): + ax.set_prop_cycle([1, 2]) + with pytest.raises((TypeError, ValueError)): + ax.set_prop_cycle('color', 'fish') + with pytest.raises((TypeError, ValueError)): + ax.set_prop_cycle('linewidth', 1) + with pytest.raises((TypeError, ValueError)): + ax.set_prop_cycle('linewidth', {'1': 1, '2': 2}) + with pytest.raises((TypeError, ValueError)): + ax.set_prop_cycle(linewidth=1, color='r') diff --git a/lib/matplotlib/tests/test_dates.py b/lib/matplotlib/tests/test_dates.py index 54afc633bf7e..ed2ecceb1522 100644 --- a/lib/matplotlib/tests/test_dates.py +++ b/lib/matplotlib/tests/test_dates.py @@ -14,11 +14,11 @@ from unittest import mock except ImportError: import mock -from nose.tools import assert_raises, assert_equal from matplotlib.testing.decorators import image_comparison, cleanup import matplotlib.pyplot as plt import matplotlib.dates as mdates +import pytest @image_comparison(baseline_images=['date_empty'], extensions=['png']) @@ -105,7 +105,8 @@ def test_too_many_date_ticks(): ax.set_xlim((t0, tf), auto=True) ax.plot([], []) ax.xaxis.set_major_locator(mdates.DayLocator()) - assert_raises(RuntimeError, fig.savefig, 'junk.png') + with pytest.raises(RuntimeError): + fig.savefig('junk.png') @image_comparison(baseline_images=['RRuleLocator_bounds'], extensions=['png']) @@ -189,7 +190,7 @@ def test_strftime_fields(dt): minute=dt.minute, second=dt.second, microsecond=dt.microsecond)) - assert_equal(formatter.strftime(dt), formatted_date_str) + assert formatter.strftime(dt) == formatted_date_str try: # Test strftime("%x") with the current locale. @@ -197,8 +198,8 @@ def test_strftime_fields(dt): locale_formatter = mdates.DateFormatter("%x") locale_d_fmt = locale.nl_langinfo(locale.D_FMT) expanded_formatter = mdates.DateFormatter(locale_d_fmt) - assert_equal(locale_formatter.strftime(dt), - expanded_formatter.strftime(dt)) + assert locale_formatter.strftime(dt) == \ + expanded_formatter.strftime(dt) except (ImportError, AttributeError): pass @@ -216,8 +217,7 @@ def test_date_formatter_callable(): formatter = mdates.AutoDateFormatter(locator) formatter.scaled[-10] = callable_formatting_function - assert_equal(formatter([datetime.datetime(2014, 12, 25)]), - ['25-12//2014']) + assert formatter([datetime.datetime(2014, 12, 25)]) == ['25-12//2014'] def test_drange(): @@ -230,12 +230,12 @@ def test_drange(): delta = datetime.timedelta(hours=1) # We expect 24 values in drange(start, end, delta), because drange returns # dates from an half open interval [start, end) - assert_equal(24, len(mdates.drange(start, end, delta))) + assert 24 == len(mdates.drange(start, end, delta)) # if end is a little bit later, we expect the range to contain one element # more end = end + datetime.timedelta(microseconds=1) - assert_equal(25, len(mdates.drange(start, end, delta))) + assert 25 == len(mdates.drange(start, end, delta)) # reset end end = datetime.datetime(2011, 1, 2, tzinfo=mdates.UTC) @@ -244,8 +244,8 @@ def test_drange(): # 4 hours = 1/6 day, this is an "dangerous" float delta = datetime.timedelta(hours=4) daterange = mdates.drange(start, end, delta) - assert_equal(6, len(daterange)) - assert_equal(mdates.num2date(daterange[-1]), end - delta) + assert 6 == len(daterange) + assert mdates.num2date(daterange[-1]) == (end - delta) @cleanup @@ -265,7 +265,8 @@ def test_empty_date_with_year_formatter(): ax.xaxis.set_major_formatter(yearFmt) with tempfile.TemporaryFile() as fh: - assert_raises(ValueError, fig.savefig, fh) + with pytest.raises(ValueError): + fig.savefig(fh) def test_auto_date_locator(): @@ -336,8 +337,7 @@ def _create_auto_date_locator(date1, date2): for t_delta, expected in results: d2 = d1 + t_delta locator = _create_auto_date_locator(d1, d2) - assert_equal(list(map(str, mdates.num2date(locator()))), - expected) + assert list(map(str, mdates.num2date(locator()))) == expected @image_comparison(baseline_images=['date_inverted_limit'], @@ -353,8 +353,3 @@ def test_date_inverted_limit(): tf + datetime.timedelta(days=5)) ax.invert_yaxis() fig.subplots_adjust(left=0.25) - - -if __name__ == '__main__': - import nose - nose.runmodule(argv=['-s', '--with-doctest'], exit=False) diff --git a/lib/matplotlib/tests/test_delaunay.py b/lib/matplotlib/tests/test_delaunay.py index 82284513fec9..b31c9afbba30 100644 --- a/lib/matplotlib/tests/test_delaunay.py +++ b/lib/matplotlib/tests/test_delaunay.py @@ -1,33 +1,37 @@ from __future__ import (absolute_import, division, print_function, unicode_literals) +import matplotlib as mpl +from matplotlib import pyplot as plt from matplotlib.externals import six from matplotlib.externals.six.moves import xrange import warnings import numpy as np -from matplotlib.testing.decorators import image_comparison, knownfailureif +from matplotlib.testing.decorators import image_comparison from matplotlib.cbook import MatplotlibDeprecationWarning with warnings.catch_warnings(): # the module is deprecated. The tests should be removed when the module is. warnings.simplefilter('ignore', MatplotlibDeprecationWarning) from matplotlib.delaunay.triangulate import Triangulation -from matplotlib import pyplot as plt -import matplotlib as mpl + def constant(x, y): return np.ones(x.shape, x.dtype) constant.title = 'Constant' + def xramp(x, y): return x xramp.title = 'X Ramp' + def yramp(x, y): return y yramp.title = 'Y Ramp' + def exponential(x, y): x = x*9 y = y*9 @@ -42,41 +46,48 @@ def exponential(x, y): f = (0.75 * np.exp(-(x2*x2+y2*y2)/4.0) + 0.75 * np.exp(-x1*x1/49.0 - y1/10.0) + 0.5 * np.exp(-(x7*x7 + y3*y3)/4.0) - - 0.2 * np.exp(-x4*x4 -y7*y7)) + 0.2 * np.exp(-x4*x4 - y7*y7)) return f exponential.title = 'Exponential and Some Gaussians' + def cliff(x, y): f = np.tanh(9.0*(y-x) + 1.0)/9.0 return f cliff.title = 'Cliff' + def saddle(x, y): f = (1.25 + np.cos(5.4*y))/(6.0 + 6.0*(3*x-1.0)**2) return f saddle.title = 'Saddle' + def gentle(x, y): f = np.exp(-5.0625*((x-0.5)**2+(y-0.5)**2))/3.0 return f gentle.title = 'Gentle Peak' + def steep(x, y): f = np.exp(-20.25*((x-0.5)**2+(y-0.5)**2))/3.0 return f steep.title = 'Steep Peak' + def sphere(x, y): circle = 64-81*((x-0.5)**2 + (y-0.5)**2) f = np.where(circle >= 0, np.sqrt(np.clip(circle,0,100)) - 0.5, 0.0) return f sphere.title = 'Sphere' + def trig(x, y): f = 2.0*np.cos(10.0*x)*np.sin(10.0*y) + np.sin(10.0*x*y) return f trig.title = 'Cosines and Sines' + def gauss(x, y): x = 5.0-10.0*x y = 5.0-10.0*y @@ -86,6 +97,7 @@ def gauss(x, y): return f gauss.title = 'Gaussian Peak and Gaussian Ridges' + def cloverleaf(x, y): ex = np.exp((10.0-20.0*x)/3.0) ey = np.exp((10.0-20.0*y)/3.0) @@ -96,18 +108,22 @@ def cloverleaf(x, y): return f cloverleaf.title = 'Cloverleaf' + def cosine_peak(x, y): circle = np.hypot(80*x-40.0, 90*y-45.) f = np.exp(-0.04*circle) * np.cos(0.15*circle) return f cosine_peak.title = 'Cosine Peak' -allfuncs = [exponential, cliff, saddle, gentle, steep, sphere, trig, gauss, cloverleaf, cosine_peak] +allfuncs = [exponential, cliff, saddle, gentle, steep, sphere, trig, gauss, + cloverleaf, cosine_peak] class LinearTester(object): name = 'Linear' - def __init__(self, xrange=(0.0, 1.0), yrange=(0.0, 1.0), nrange=101, npoints=250): + + def __init__(self, xrange=(0.0, 1.0), yrange=(0.0, 1.0), + nrange=101, npoints=250): self.xrange = xrange self.yrange = yrange self.nrange = nrange @@ -133,8 +149,10 @@ def plot(self, func, interp=True, plotter='imshow'): z = lpi[self.yrange[0]:self.yrange[1]:complex(0,self.nrange), self.xrange[0]:self.xrange[1]:complex(0,self.nrange)] else: - y, x = np.mgrid[self.yrange[0]:self.yrange[1]:complex(0,self.nrange), - self.xrange[0]:self.xrange[1]:complex(0,self.nrange)] + y, x = np.mgrid[self.yrange[0]:self.yrange[1]: + complex(0, self.nrange), + self.xrange[0]:self.xrange[1]: + complex(0, self.nrange)] z = func(x, y) z = np.where(np.isinf(z), 0.0, z) @@ -142,17 +160,21 @@ def plot(self, func, interp=True, plotter='imshow'): extent = (self.xrange[0], self.xrange[1], self.yrange[0], self.yrange[1]) fig = plt.figure() - plt.hot() # Some like it hot + plt.hot() # Some like it hot if plotter == 'imshow': - plt.imshow(np.nan_to_num(z), interpolation='nearest', extent=extent, origin='lower') + plt.imshow(np.nan_to_num(z), interpolation='nearest', + extent=extent, origin='lower') elif plotter == 'contour': - Y, X = np.ogrid[self.yrange[0]:self.yrange[1]:complex(0,self.nrange), + Y, X = \ + np.ogrid[self.yrange[0]:self.yrange[1]:complex(0,self.nrange), self.xrange[0]:self.xrange[1]:complex(0,self.nrange)] plt.contour(np.ravel(X), np.ravel(Y), z, 20) x = self.x y = self.y - lc = mpl.collections.LineCollection(np.array([((x[i], y[i]), (x[j], y[j])) - for i, j in self.tri.edge_db]), colors=[(0,0,0,0.2)]) + lc = mpl.collections.LineCollection( + np.array([((x[i], y[i]), + (x[j], y[j])) for i, j in self.tri.edge_db]), + colors=[(0, 0, 0, 0.2)]) ax = plt.gca() ax.add_collection(lc) @@ -165,12 +187,15 @@ def plot(self, func, interp=True, plotter='imshow'): else: plt.title(title) + class NNTester(LinearTester): name = 'Natural Neighbors' + def interpolator(self, func): z = func(self.x, self.y) return self.tri.nn_extrapolator(z, bbox=self.xrange+self.yrange) + def make_all_2d_testfuncs(allfuncs=allfuncs): def make_test(func): filenames = [ @@ -206,14 +231,17 @@ def reference_test(): ref_interpolator = Triangulation([0,10,10,0], [0,0,10,10]).linear_interpolator([1,10,5,2.0]) + def test_1d_grid(): res = ref_interpolator[3:6:2j,1:1:1j] assert np.allclose(res, [[1.6],[1.9]], rtol=0) + def test_0d_grid(): res = ref_interpolator[3:3:1j,1:1:1j] assert np.allclose(res, [[1.6]], rtol=0) + @image_comparison(baseline_images=['delaunay-1d-interp'], extensions=['png']) def test_1d_plots(): x_range = slice(0.25,9.75,20j) diff --git a/lib/matplotlib/tests/test_dviread.py b/lib/matplotlib/tests/test_dviread.py index 260e7f429d82..15b69f2bb650 100644 --- a/lib/matplotlib/tests/test_dviread.py +++ b/lib/matplotlib/tests/test_dviread.py @@ -3,25 +3,33 @@ from matplotlib.externals import six -from nose.tools import assert_equal, with_setup import matplotlib.dviread as dr import os.path import json +import pytest original_find_tex_file = dr.find_tex_file -def setup_PsfontsMap(): +def teardown_PsfontsMap(): + dr.find_tex_file = original_find_tex_file + + +@pytest.fixture() +def setup_PsfontsMap(request): dr.find_tex_file = lambda x: x + def fin(): + teardown_PsfontsMap() + request.addfinalizer(fin) + def teardown_PsfontsMap(): dr.find_tex_file = original_find_tex_file -@with_setup(setup_PsfontsMap, teardown_PsfontsMap) -def test_PsfontsMap(): +def test_PsfontsMap(setup_PsfontsMap): filename = os.path.join( os.path.dirname(__file__), 'baseline_images', 'dviread', 'test.map') @@ -30,34 +38,34 @@ def test_PsfontsMap(): for n in [1, 2, 3, 4, 5]: key = 'TeXfont%d' % n entry = fontmap[key] - assert_equal(entry.texname, key) - assert_equal(entry.psname, 'PSfont%d' % n) + assert entry.texname == key + assert entry.psname == 'PSfont%d' % n if n not in [3, 5]: - assert_equal(entry.encoding, 'font%d.enc' % n) + assert entry.encoding == 'font%d.enc' % n elif n == 3: - assert_equal(entry.encoding, 'enc3.foo') + assert entry.encoding == 'enc3.foo' # We don't care about the encoding of TeXfont5, which specifies # multiple encodings. if n not in [1, 5]: - assert_equal(entry.filename, 'font%d.pfa' % n) + assert entry.filename == 'font%d.pfa' % n else: - assert_equal(entry.filename, 'font%d.pfb' % n) + assert entry.filename == 'font%d.pfb' % n if n == 4: - assert_equal(entry.effects, {'slant': -0.1, 'extend': 2.2}) + assert entry.effects == {'slant': -0.1, 'extend': 2.2} else: - assert_equal(entry.effects, {}) + assert entry.effects == {} # Some special cases entry = fontmap['TeXfont6'] - assert_equal(entry.filename, None) - assert_equal(entry.encoding, None) + assert entry.filename is None + assert entry.encoding is None entry = fontmap['TeXfont7'] - assert_equal(entry.filename, None) - assert_equal(entry.encoding, 'font7.enc') + assert entry.filename is None + assert entry.encoding == 'font7.enc' entry = fontmap['TeXfont8'] - assert_equal(entry.filename, 'font8.pfb') - assert_equal(entry.encoding, None) + assert entry.filename == 'font8.pfb' + assert entry.encoding is None entry = fontmap['TeXfont9'] - assert_equal(entry.filename, '/absolute/font9.pfb') + assert entry.filename == '/absolute/font9.pfb' def test_dviread(): @@ -72,4 +80,4 @@ def test_dviread(): for t in page.text], 'boxes': [[b.x, b.y, b.height, b.width] for b in page.boxes]} for page in dvi] - assert_equal(data, correct) + assert data == correct diff --git a/lib/matplotlib/tests/test_figure.py b/lib/matplotlib/tests/test_figure.py index 631474c23287..b1219a7b046d 100644 --- a/lib/matplotlib/tests/test_figure.py +++ b/lib/matplotlib/tests/test_figure.py @@ -3,8 +3,9 @@ from matplotlib.externals import six from matplotlib.externals.six.moves import xrange +import pytest -from nose.tools import assert_equal, assert_true +# from nose.tools import assert_equal, assert_true from matplotlib.testing.decorators import image_comparison, cleanup from matplotlib.axes import Axes import matplotlib.pyplot as plt @@ -23,14 +24,14 @@ def test_figure_label(): plt.figure(0) plt.figure(1) plt.figure(3) - assert_equal(plt.get_fignums(), [0, 1, 3, 4, 5]) - assert_equal(plt.get_figlabels(), ['', 'today', '', 'tomorrow', '']) + assert plt.get_fignums() == [0, 1, 3, 4, 5] + assert plt.get_figlabels() == ['', 'today', '', 'tomorrow', ''] plt.close(10) plt.close() plt.close(5) plt.close('tomorrow') - assert_equal(plt.get_fignums(), [0, 1]) - assert_equal(plt.get_figlabels(), ['', 'today']) + assert plt.get_fignums() == [0, 1] + assert plt.get_figlabels() == ['', 'today'] @cleanup @@ -40,14 +41,14 @@ def test_fignum_exists(): plt.figure(2) plt.figure('three') plt.figure() - assert_equal(plt.fignum_exists('one'), True) - assert_equal(plt.fignum_exists(2), True) - assert_equal(plt.fignum_exists('three'), True) - assert_equal(plt.fignum_exists(4), True) + assert plt.fignum_exists('one') + assert plt.fignum_exists(2) + assert plt.fignum_exists('three') + assert plt.fignum_exists(4) plt.close('one') plt.close(4) - assert_equal(plt.fignum_exists('one'), False) - assert_equal(plt.fignum_exists(4), False) + assert not plt.fignum_exists('one') + assert not plt.fignum_exists(4) @image_comparison(baseline_images=['figure_today']) @@ -70,25 +71,25 @@ def test_gca(): fig = plt.figure() ax1 = fig.add_axes([0, 0, 1, 1]) - assert_true(fig.gca(projection='rectilinear') is ax1) - assert_true(fig.gca() is ax1) + assert fig.gca(projection='rectilinear') is ax1 + assert fig.gca() is ax1 ax2 = fig.add_subplot(121, projection='polar') - assert_true(fig.gca() is ax2) - assert_true(fig.gca(polar=True)is ax2) + assert fig.gca() is ax2 + assert fig.gca(polar=True)is ax2 ax3 = fig.add_subplot(122) - assert_true(fig.gca() is ax3) + assert fig.gca() is ax3 # the final request for a polar axes will end up creating one # with a spec of 111. - assert_true(fig.gca(polar=True) is not ax3) - assert_true(fig.gca(polar=True) is not ax2) - assert_equal(fig.gca().get_geometry(), (1, 1, 1)) + assert fig.gca(polar=True) is not ax3 + assert fig.gca(polar=True) is not ax2 + assert fig.gca().get_geometry(), (1, 1, 1) fig.sca(ax1) - assert_true(fig.gca(projection='rectilinear') is ax1) - assert_true(fig.gca() is ax1) + assert fig.gca(projection='rectilinear') is ax1 + assert fig.gca() is ax1 @image_comparison(baseline_images=['figure_suptitle']) @@ -165,21 +166,21 @@ def test_set_fig_size(): # check figwidth fig.set_figwidth(5) - assert_equal(fig.get_figwidth(), 5) + assert fig.get_figwidth() == 5 # check figheight fig.set_figheight(1) - assert_equal(fig.get_figheight(), 1) + assert fig.get_figheight() == 1 # check using set_size_inches fig.set_size_inches(2, 4) - assert_equal(fig.get_figwidth(), 2) - assert_equal(fig.get_figheight(), 4) + assert fig.get_figwidth() == 2 + assert fig.get_figheight() == 4 # check using tuple to first argument fig.set_size_inches((1, 3)) - assert_equal(fig.get_figwidth(), 1) - assert_equal(fig.get_figheight(), 3) + assert fig.get_figwidth() == 1 + assert fig.get_figheight() == 3 @cleanup @@ -189,7 +190,7 @@ def test_axes_remove(): for ax in axes.ravel()[:-1]: assert ax in fig.axes assert axes[-1, -1] not in fig.axes - assert_equal(len(fig.axes), 3) + assert len(fig.axes) == 3 def test_figaspect(): @@ -201,8 +202,3 @@ def test_figaspect(): assert h / w == 0.5 w, h = plt.figaspect(np.zeros((2, 2))) assert h / w == 1 - - -if __name__ == "__main__": - import nose - nose.runmodule(argv=['-s', '--with-doctest'], exit=False) diff --git a/lib/matplotlib/tests/test_font_manager.py b/lib/matplotlib/tests/test_font_manager.py index bb87bebeb999..b1672e103533 100644 --- a/lib/matplotlib/tests/test_font_manager.py +++ b/lib/matplotlib/tests/test_font_manager.py @@ -1,7 +1,6 @@ from __future__ import (absolute_import, division, print_function, unicode_literals) -from nose.tools import assert_equal from matplotlib.externals import six import os @@ -19,7 +18,7 @@ def test_font_priority(): ['cmmi10', 'Bitstream Vera Sans']}): font = findfont( FontProperties(family=["sans-serif"])) - assert_equal(os.path.basename(font), 'cmmi10.ttf') + assert os.path.basename(font) == 'cmmi10.ttf' # Smoketest get_charmap, which isn't used internally anymore font = get_font(font) @@ -46,5 +45,5 @@ def test_json_serialization(): {'family': 'Bitstream Vera Sans', 'weight': 700}, {'family': 'no such font family'}): fp = FontProperties(**prop) - assert_equal(fontManager.findfont(fp, rebuild_if_missing=False), - copy.findfont(fp, rebuild_if_missing=False)) + assert fontManager.findfont(fp, rebuild_if_missing=False) == \ + copy.findfont(fp, rebuild_if_missing=False) diff --git a/lib/matplotlib/tests/test_gridspec.py b/lib/matplotlib/tests/test_gridspec.py index 57616397f5e3..26f3db89e448 100644 --- a/lib/matplotlib/tests/test_gridspec.py +++ b/lib/matplotlib/tests/test_gridspec.py @@ -1,8 +1,8 @@ import matplotlib.gridspec as gridspec -from nose.tools import assert_equal +import numpy def test_equal(): gs = gridspec.GridSpec(2, 1) - assert_equal(gs[0, 0], gs[0, 0]) - assert_equal(gs[:, 0], gs[:, 0]) + assert gs[0, 0] == gs[0, 0] + assert gs[:, 0] == gs[:, 0] diff --git a/lib/matplotlib/tests/test_image.py b/lib/matplotlib/tests/test_image.py index 9ffa6d9d1e5e..607145bc2cd8 100644 --- a/lib/matplotlib/tests/test_image.py +++ b/lib/matplotlib/tests/test_image.py @@ -7,14 +7,15 @@ import numpy as np -from matplotlib.testing.decorators import (image_comparison, - knownfailureif, cleanup) +from matplotlib.testing.decorators import image_comparison, cleanup from matplotlib.image import BboxImage, imread, NonUniformImage from matplotlib.transforms import Bbox from matplotlib import rcParams, rc_context import matplotlib.pyplot as plt - -from numpy.testing import assert_array_equal +from numpy.testing import assert_array_equal, assert_array_almost_equal +import pytest +import io +import os try: from PIL import Image @@ -43,6 +44,7 @@ def test_image_interps(): ax3.imshow(X, interpolation='bicubic') ax3.set_ylabel('bicubic') + @image_comparison(baseline_images=['interp_nearest_vs_none'], extensions=['pdf', 'svg'], remove_text=True) def test_interp_nearest_vs_none(): @@ -63,7 +65,8 @@ def test_interp_nearest_vs_none(): ax2.set_title('interpolation nearest') -@image_comparison(baseline_images=['figimage-0', 'figimage-1'], extensions=['png']) +@image_comparison(baseline_images=['figimage-0', 'figimage-1'], + extensions=['png']) def test_figimage(): 'test the figimage method' @@ -80,6 +83,7 @@ def test_figimage(): fig.figimage(img[:,::-1], xo=100, yo=0, origin='lower') fig.figimage(img[::-1,::-1], xo=100, yo=100, origin='lower') + @cleanup def test_image_python_io(): fig = plt.figure() @@ -90,7 +94,8 @@ def test_image_python_io(): buffer.seek(0) plt.imread(buffer) -@knownfailureif(not HAS_PIL) + +@pytest.mark.xfail(not HAS_PIL, reason='PIL is not installed') def test_imread_pil_uint16(): img = plt.imread(os.path.join(os.path.dirname(__file__), 'baseline_images', 'test_image', 'uint16.tif')) @@ -106,6 +111,7 @@ def test_imread_pil_uint16(): # plt.imread(fname) # os.remove(fname) + def test_imsave(): # The goal here is that the user can specify an output logical DPI # for the image, but this will not actually add any extra pixels @@ -135,6 +141,7 @@ def test_imsave(): assert_array_equal(arr_dpi1, arr_dpi100) + def test_imsave_color_alpha(): # Test that imsave accept arrays with ndim=3 where the third dimension is # color and alpha without raising any exceptions, and that the data is @@ -240,6 +247,7 @@ def test_image_clip(): im = ax.imshow(d, extent=(-pi,pi,-pi/2,pi/2)) + @image_comparison(baseline_images=['image_cliprect']) def test_image_cliprect(): import matplotlib.patches as patches @@ -250,9 +258,11 @@ def test_image_cliprect(): im = ax.imshow(d, extent=(0,5,0,5)) - rect = patches.Rectangle(xy=(1,1), width=2, height=2, transform=im.axes.transData) + rect = patches.Rectangle(xy=(1,1), width=2, height=2, + transform=im.axes.transData) im.set_clip_path(rect) + @image_comparison(baseline_images=['imshow'], remove_text=True) def test_imshow(): import numpy as np @@ -265,23 +275,27 @@ def test_imshow(): ax.set_xlim(0,3) ax.set_ylim(0,3) -@image_comparison(baseline_images=['no_interpolation_origin'], remove_text=True) + +@image_comparison(baseline_images=['no_interpolation_origin'], + remove_text=True) def test_no_interpolation_origin(): fig = plt.figure() ax = fig.add_subplot(211) - ax.imshow(np.arange(100).reshape((2, 50)), origin="lower", interpolation='none') + ax.imshow(np.arange(100).reshape((2, 50)), origin="lower", + interpolation='none') ax = fig.add_subplot(212) ax.imshow(np.arange(100).reshape((2, 50)), interpolation='none') + @image_comparison(baseline_images=['image_shift'], remove_text=True, extensions=['pdf', 'svg']) def test_image_shift(): from matplotlib.colors import LogNorm imgData = [[1.0/(x) + 1.0/(y) for x in range(1,100)] for y in range(1,100)] - tMin=734717.945208 - tMax=734717.946366 + tMin = 734717.945208 + tMax = 734717.946366 fig = plt.figure() ax = fig.add_subplot(111) @@ -289,6 +303,7 @@ def test_image_shift(): extent=(tMin, tMax, 1, 100)) ax.set_aspect('auto') + @cleanup def test_image_edges(): f = plt.figure(figsize=[1, 1]) @@ -319,7 +334,9 @@ def test_image_edges(): assert g != 100, 'Expected a non-green edge - but sadly, it was.' -@image_comparison(baseline_images=['image_composite_background'], remove_text=True) + +@image_comparison(baseline_images=['image_composite_background'], + remove_text=True) def test_image_composite_background(): fig = plt.figure() ax = fig.add_subplot(111) @@ -329,7 +346,9 @@ def test_image_composite_background(): ax.set_facecolor((1, 0, 0, 0.5)) ax.set_xlim([0, 12]) -@image_comparison(baseline_images=['image_composite_alpha'], remove_text=True) + +@image_comparison(baseline_images=['image_composite_alpha'], + remove_text=True) def test_image_composite_alpha(): """ Tests that the alpha value is recognized and correctly applied in the @@ -339,11 +358,13 @@ def test_image_composite_alpha(): ax = fig.add_subplot(111) arr = np.zeros((11, 21, 4)) arr[:, :, 0] = 1 - arr[:, :, 3] = np.concatenate((np.arange(0, 1.1, 0.1), np.arange(0, 1, 0.1)[::-1])) + arr[:, :, 3] = np.concatenate((np.arange(0, 1.1, 0.1), + np.arange(0, 1, 0.1)[::-1])) arr2 = np.zeros((21, 11, 4)) arr2[:, :, 0] = 1 arr2[:, :, 1] = 1 - arr2[:, :, 3] = np.concatenate((np.arange(0, 1.1, 0.1), np.arange(0, 1, 0.1)[::-1]))[:, np.newaxis] + arr2[:, :, 3] = np.concatenate((np.arange(0, 1.1, 0.1), + np.arange(0, 1, 0.1)[::-1]))[:, np.newaxis] ax.imshow(arr, extent=[1, 2, 5, 0], alpha=0.3) ax.imshow(arr, extent=[2, 3, 5, 0], alpha=0.6) ax.imshow(arr, extent=[3, 4, 5, 0]) @@ -355,27 +376,30 @@ def test_image_composite_alpha(): ax.set_ylim([5, 0]) -@image_comparison(baseline_images=['rasterize_10dpi'], extensions=['pdf','svg'], remove_text=True) +@image_comparison(baseline_images=['rasterize_10dpi'], + extensions=['pdf','svg'], + remove_text=True) def test_rasterize_dpi(): # This test should check rasterized rendering with high output resolution. - # It plots a rasterized line and a normal image with implot. So it will catch - # when images end up in the wrong place in case of non-standard dpi setting. - # Instead of high-res rasterization i use low-res. Therefore the fact that the - # resolution is non-standard is is easily checked by image_comparison. + # It plots a rasterized line and a normal image with implot. So it will + # catch when images end up in the wrong place in case of non-standard + # dpi setting. Instead of high-res rasterization i use low-res. Therefore + # the fact that the resolution is non-standard is is easily checked by + # image_comparison. import numpy as np import matplotlib.pyplot as plt img = np.asarray([[1, 2], [3, 4]]) - fig, axes = plt.subplots(1, 3, figsize = (3, 1)) + fig, axes = plt.subplots(1, 3, figsize=(3, 1)) axes[0].imshow(img) axes[1].plot([0,1],[0,1], linewidth=20., rasterized=True) - axes[1].set(xlim = (0,1), ylim = (-1, 2)) + axes[1].set(xlim=(0,1), ylim=(-1, 2)) axes[2].plot([0,1],[0,1], linewidth=20.) - axes[2].set(xlim = (0,1), ylim = (-1, 2)) + axes[2].set(xlim=(0,1), ylim=(-1, 2)) # Low-dpi PDF rasterization errors prevent proper image comparison tests. # Hide detailed structures like the axes spines. @@ -412,14 +436,15 @@ def test_get_window_extent_for_AxisImage(): # object at a given location and check that get_window_extent() # returns the correct bounding box values (in pixels). - im = np.array([[0.25, 0.75, 1.0, 0.75], [0.1, 0.65, 0.5, 0.4], \ + im = np.array([[0.25, 0.75, 1.0, 0.75], [0.1, 0.65, 0.5, 0.4], [0.6, 0.3, 0.0, 0.2], [0.7, 0.9, 0.4, 0.6]]) fig = plt.figure(figsize=(10, 10), dpi=100) ax = plt.subplot() ax.set_position([0, 0, 1, 1]) ax.set_xlim(0, 1) ax.set_ylim(0, 1) - im_obj = ax.imshow(im, extent=[0.4, 0.7, 0.2, 0.9], interpolation='nearest') + im_obj = ax.imshow(im, extent=[0.4, 0.7, 0.2, 0.9], + interpolation='nearest') fig.canvas.draw() renderer = fig.canvas.renderer @@ -455,7 +480,8 @@ def test_nonuniformimage_setnorm(): im = NonUniformImage(ax) im.set_norm(plt.Normalize()) -@knownfailureif(not HAS_PIL) + +@pytest.mark.xfail(not HAS_PIL, reason='PIL is not installed') @cleanup def test_jpeg_alpha(): plt.figure(figsize=(1, 1), dpi=300) @@ -476,7 +502,8 @@ def test_jpeg_alpha(): # If this fails, there will be only one color (all black). If this # is working, we should have all 256 shades of grey represented. print("num colors: ", len(image.getcolors(256))) - assert len(image.getcolors(256)) >= 175 and len(image.getcolors(256)) <= 185 + assert len(image.getcolors(256)) >= 175 + assert len(image.getcolors(256)) <= 185 # The fully transparent part should be red, not white or black # or anything else print("corner pixel: ", image.getpixel((0, 0))) @@ -515,8 +542,3 @@ def test_minimized_rasterized(): else: if image['width'] != width: assert False - - -if __name__=='__main__': - import nose - nose.runmodule(argv=['-s','--with-doctest'], exit=False) diff --git a/lib/matplotlib/tests/test_labeled_data_unpacking.py b/lib/matplotlib/tests/test_labeled_data_unpacking.py index d07d481b1f57..a5110266cbb0 100644 --- a/lib/matplotlib/tests/test_labeled_data_unpacking.py +++ b/lib/matplotlib/tests/test_labeled_data_unpacking.py @@ -1,17 +1,8 @@ from __future__ import (absolute_import, division, print_function) -from nose.tools import (assert_raises, assert_equal) -from nose.plugins.skip import SkipTest - -try: - # 3.2+ versions - from nose.tools import assert_regex, assert_not_regex -except ImportError: - # 2.7 versions - from nose.tools import assert_regexp_matches, assert_not_regexp_matches - assert_regex = assert_regexp_matches - assert_not_regex = assert_not_regexp_matches +import pytest +import re from ..testing import assert_produces_warning from .. import unpack_labeled_data @@ -50,13 +41,17 @@ def plot_func_varags(ax, *args, **kwargs): def test_compiletime_checks(): """test decorator invocations -> no replacements""" - def func(ax, x, y): pass + def func(ax, x, y): + pass - def func_args(ax, x, y, *args): pass + def func_args(ax, x, y, *args): + pass - def func_kwargs(ax, x, y, **kwargs): pass + def func_kwargs(ax, x, y, **kwargs): + pass - def func_no_ax_args(*args, **kwargs): pass + def func_no_ax_args(*args, **kwargs): + pass # this is ok unpack_labeled_data(replace_names=["x", "y"])(func) @@ -69,12 +64,14 @@ def f(): # z is unknown unpack_labeled_data(replace_names=["x", "y", "z"])(func_args) - assert_raises(AssertionError, f) + with pytest.raises(AssertionError): + f() def f(): unpack_labeled_data(replace_names=["x", "y"])(func_no_ax_args) - assert_raises(AssertionError, f) + with pytest.raises(AssertionError): + f() # no replacements at all -> all ok... unpack_labeled_data(replace_names=[], label_namer=None)(func) @@ -86,12 +83,14 @@ def f(): def f(): unpack_labeled_data(label_namer="z")(func) - assert_raises(AssertionError, f) + with pytest.raises(AssertionError): + f() def f(): unpack_labeled_data(label_namer="z")(func_args) - assert_raises(AssertionError, f) + with pytest.raises(AssertionError): + f() # but "ok-ish", if func has kwargs -> will show up at runtime :-( unpack_labeled_data(label_namer="z")(func_kwargs) unpack_labeled_data(label_namer="z")(func_no_ax_args) @@ -125,60 +124,61 @@ def f(): func(None, x="a", y="b") # This sets a label although the function can't handle it. - assert_raises(TypeError, f) + with pytest.raises(TypeError): + f() def test_function_call_without_data(): """test without data -> no replacements""" for func in all_funcs: - assert_equal(func(None, "x", "y"), - "x: ['x'], y: ['y'], ls: x, w: xyz, label: None") - assert_equal(func(None, x="x", y="y"), - "x: ['x'], y: ['y'], ls: x, w: xyz, label: None") - assert_equal(func(None, "x", "y", label=""), - "x: ['x'], y: ['y'], ls: x, w: xyz, label: ") - assert_equal(func(None, "x", "y", label="text"), - "x: ['x'], y: ['y'], ls: x, w: xyz, label: text") - assert_equal(func(None, x="x", y="y", label=""), - "x: ['x'], y: ['y'], ls: x, w: xyz, label: ") - assert_equal(func(None, x="x", y="y", label="text"), - "x: ['x'], y: ['y'], ls: x, w: xyz, label: text") + assert func(None, "x", "y") == \ + "x: ['x'], y: ['y'], ls: x, w: xyz, label: None" + assert func(None, x="x", y="y") == \ + "x: ['x'], y: ['y'], ls: x, w: xyz, label: None" + assert func(None, "x", "y", label="") == \ + "x: ['x'], y: ['y'], ls: x, w: xyz, label: " + assert func(None, "x", "y", label="text") == \ + "x: ['x'], y: ['y'], ls: x, w: xyz, label: text" + assert func(None, x="x", y="y", label="") == \ + "x: ['x'], y: ['y'], ls: x, w: xyz, label: " + assert func(None, x="x", y="y", label="text") == \ + "x: ['x'], y: ['y'], ls: x, w: xyz, label: text" def test_function_call_with_dict_data(): """Test with dict data -> label comes from the value of 'x' parameter """ data = {"a": [1, 2], "b": [8, 9], "w": "NOT"} for func in all_funcs: - assert_equal(func(None, "a", "b", data=data), - "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: b") - assert_equal(func(None, x="a", y="b", data=data), - "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: b") - assert_equal(func(None, "a", "b", label="", data=data), - "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: ") - assert_equal(func(None, "a", "b", label="text", data=data), - "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: text") - assert_equal(func(None, x="a", y="b", label="", data=data), - "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: ") - assert_equal(func(None, x="a", y="b", label="text", data=data), - "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: text") + assert func(None, "a", "b", data=data) == \ + "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: b" + assert func(None, x="a", y="b", data=data) == \ + "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: b" + assert func(None, "a", "b", label="", data=data) == \ + "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: " + assert func(None, "a", "b", label="text", data=data) == \ + "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: text" + assert func(None, x="a", y="b", label="", data=data) == \ + "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: " + assert func(None, x="a", y="b", label="text", data=data) == \ + "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: text" def test_function_call_with_dict_data_not_in_data(): "test for the case that one var is not in data -> half replaces, half kept" data = {"a": [1, 2], "w": "NOT"} for func in all_funcs: - assert_equal(func(None, "a", "b", data=data), - "x: [1, 2], y: ['b'], ls: x, w: xyz, label: b") - assert_equal(func(None, x="a", y="b", data=data), - "x: [1, 2], y: ['b'], ls: x, w: xyz, label: b") - assert_equal(func(None, "a", "b", label="", data=data), - "x: [1, 2], y: ['b'], ls: x, w: xyz, label: ") - assert_equal(func(None, "a", "b", label="text", data=data), - "x: [1, 2], y: ['b'], ls: x, w: xyz, label: text") - assert_equal(func(None, x="a", y="b", label="", data=data), - "x: [1, 2], y: ['b'], ls: x, w: xyz, label: ") - assert_equal(func(None, x="a", y="b", label="text", data=data), - "x: [1, 2], y: ['b'], ls: x, w: xyz, label: text") + assert func(None, "a", "b", data=data) == \ + "x: [1, 2], y: ['b'], ls: x, w: xyz, label: b" + assert func(None, x="a", y="b", data=data) == \ + "x: [1, 2], y: ['b'], ls: x, w: xyz, label: b" + assert func(None, "a", "b", label="", data=data) == \ + "x: [1, 2], y: ['b'], ls: x, w: xyz, label: " + assert func(None, "a", "b", label="text", data=data) == \ + "x: [1, 2], y: ['b'], ls: x, w: xyz, label: text" + assert func(None, x="a", y="b", label="", data=data) == \ + "x: [1, 2], y: ['b'], ls: x, w: xyz, label: " + assert func(None, x="a", y="b", label="text", data=data) == \ + "x: [1, 2], y: ['b'], ls: x, w: xyz, label: text" def test_function_call_with_pandas_data(): @@ -186,23 +186,23 @@ def test_function_call_with_pandas_data(): try: import pandas as pd except ImportError: - raise SkipTest("Pandas not installed") + raise pytest.skip("Pandas not installed") data = pd.DataFrame({"a": [1, 2], "b": [8, 9], "w": ["NOT", "NOT"]}) for func in all_funcs: - assert_equal(func(None, "a", "b", data=data), - "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: b") - assert_equal(func(None, x="a", y="b", data=data), - "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: b") - assert_equal(func(None, "a", "b", label="", data=data), - "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: ") - assert_equal(func(None, "a", "b", label="text", data=data), - "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: text") - assert_equal(func(None, x="a", y="b", label="", data=data), - "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: ") - assert_equal(func(None, x="a", y="b", label="text", data=data), - "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: text") + assert func(None, "a", "b", data=data) == \ + "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: b" + assert func(None, x="a", y="b", data=data) == \ + "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: b" + assert func(None, "a", "b", label="", data=data) == \ + "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: " + assert func(None, "a", "b", label="text", data=data) == \ + "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: text" + assert func(None, x="a", y="b", label="", data=data) == \ + "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: " + assert func(None, x="a", y="b", label="text", data=data) == \ + "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: text" def test_function_call_replace_all(): @@ -214,21 +214,24 @@ def func_replace_all(ax, x, y, ls="x", label=None, w="NOT"): return "x: %s, y: %s, ls: %s, w: %s, label: %s" % ( list(x), list(y), ls, w, label) - assert_equal(func_replace_all(None, "a", "b", w="x", data=data), - "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: b") - assert_equal(func_replace_all(None, x="a", y="b", w="x", data=data), - "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: b") - assert_equal(func_replace_all(None, "a", "b", w="x", label="", data=data), - "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: ") - assert_equal( - func_replace_all(None, "a", "b", w="x", label="text", data=data), - "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: text") - assert_equal( - func_replace_all(None, x="a", y="b", w="x", label="", data=data), - "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: ") - assert_equal( - func_replace_all(None, x="a", y="b", w="x", label="text", data=data), - "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: text") + assert func_replace_all(None, "a", "b", w="x", + data=data) == \ + "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: b" + assert func_replace_all(None, x="a", y="b", w="x", + data=data) == \ + "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: b" + assert func_replace_all(None, "a", "b", w="x", + label="", data=data) == \ + "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: " + assert func_replace_all(None, "a", "b", w="x", + label="text", data=data) == \ + "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: text" + assert func_replace_all(None, x="a", y="b", w="x", + label="", data=data) == \ + "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: " + assert func_replace_all(None, x="a", y="b", w="x", + label="text", data=data) == \ + "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: text" @unpack_labeled_data(label_namer="y") def func_varags_replace_all(ax, *args, **kwargs): @@ -244,27 +247,25 @@ def func_varags_replace_all(ax, *args, **kwargs): # in the first case, we can't get a "y" argument, # as we don't know the names of the *args - assert_equal(func_varags_replace_all(None, x="a", y="b", w="x", data=data), - "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: b") - assert_equal( - func_varags_replace_all(None, "a", "b", w="x", label="", data=data), - "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: ") - assert_equal( - func_varags_replace_all(None, "a", "b", w="x", label="text", - data=data), - "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: text") - assert_equal( - func_varags_replace_all(None, x="a", y="b", w="x", label="", - data=data), - "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: ") - assert_equal( - func_varags_replace_all(None, x="a", y="b", w="x", label="text", - data=data), - "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: text") + assert func_varags_replace_all(None, x="a", y="b", + w="x", data=data) == \ + "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: b" + assert func_varags_replace_all(None, "a", "b", w="x", + label="", data=data) == \ + "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: " + assert func_varags_replace_all(None, "a", "b", w="x", + label="text", data=data) == \ + "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: text" + assert func_varags_replace_all(None, x="a", y="b", w="x", + label="", data=data) == \ + "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: " + assert func_varags_replace_all(None, x="a", y="b", w="x", + label="text", data=data) == \ + "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: text" with assert_produces_warning(): - assert_equal(func_varags_replace_all(None, "a", "b", w="x", data=data), - "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: None") + assert func_varags_replace_all(None, "a", "b", w="x", data=data) == \ + "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: None" def test_no_label_replacements(): @@ -276,14 +277,14 @@ def func_no_label(ax, x, y, ls="x", label=None, w="xyz"): list(x), list(y), ls, w, label) data = {"a": [1, 2], "b": [8, 9], "w": "NOT"} - assert_equal(func_no_label(None, "a", "b", data=data), - "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: None") - assert_equal(func_no_label(None, x="a", y="b", data=data), - "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: None") - assert_equal(func_no_label(None, "a", "b", label="", data=data), - "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: ") - assert_equal(func_no_label(None, "a", "b", label="text", data=data), - "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: text") + assert func_no_label(None, "a", "b", data=data) == \ + "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: None" + assert func_no_label(None, x="a", y="b", data=data) == \ + "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: None" + assert func_no_label(None, "a", "b", label="", data=data) == \ + "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: " + assert func_no_label(None, "a", "b", label="text", data=data) == \ + "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: text" def test_more_args_than_pos_parameter(): @@ -296,7 +297,7 @@ def func(ax, x, y, z=1): def f(): func(None, "a", "b", "z", "z", data=data) - assert_raises(RuntimeError, f) + pytest.raises(RuntimeError, f) def test_function_call_with_replace_all_args(): @@ -317,10 +318,10 @@ def funcy(ax, *args, **kwargs): func = unpack_labeled_data(replace_all_args=True, replace_names=["w"], label_namer="y")(funcy) - assert_equal(func(None, "a", "b", w="x", label="", data=data), - "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: ") - assert_equal(func(None, "a", "b", w="x", label="text", data=data), - "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: text") + assert func(None, "a", "b", w="x", label="", data=data) == \ + "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: " + assert func(None, "a", "b", w="x", label="text", data=data) == \ + "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: text" func2 = unpack_labeled_data(replace_all_args=True, replace_names=["w"], label_namer="y", @@ -328,47 +329,54 @@ def funcy(ax, *args, **kwargs): "label", "w"])( funcy) - assert_equal(func2(None, "a", "b", w="x", data=data), - "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: b") - assert_equal(func2(None, "a", "b", w="x", label="", data=data), - "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: ") - assert_equal(func2(None, "a", "b", w="x", label="text", data=data), - "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: text") + assert func2(None, "a", "b", w="x", data=data) == \ + "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: b" + assert func2(None, "a", "b", w="x", label="", data=data) == \ + "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: " + assert func2(None, "a", "b", w="x", label="text", data=data) == \ + "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: text" def test_docstring_addition(): + all_positional_all_keyword = \ + re.compile(r".*All positional and all keyword arguments\.") + all_positional = \ + re.compile(r".*All positional arguments\.") + all_arguments = \ + re.compile(r".*All arguments with the following names: .*") + all_arguments_with_following_names = \ + re.compile(r".*All arguments with the following names: '.*', '.*'\.") + x_string = \ + re.compile(r".*'x'.*") + bar_string = \ + re.compile(r".*'bar'.*") + @unpack_labeled_data() def funcy(ax, *args, **kwargs): """Funcy does nothing""" pass - assert_regex(funcy.__doc__, - r".*All positional and all keyword arguments\.") - assert_not_regex(funcy.__doc__, r".*All positional arguments\.") - assert_not_regex(funcy.__doc__, - r".*All arguments with the following names: .*") + assert all_positional_all_keyword.search(funcy.__doc__) + assert not all_positional.search(funcy.__doc__) + assert not all_arguments.search(funcy.__doc__) @unpack_labeled_data(replace_all_args=True, replace_names=[]) def funcy(ax, x, y, z, bar=None): """Funcy does nothing""" pass - assert_regex(funcy.__doc__, r".*All positional arguments\.") - assert_not_regex(funcy.__doc__, - r".*All positional and all keyword arguments\.") - assert_not_regex(funcy.__doc__, - r".*All arguments with the following names: .*") + assert all_positional.search(funcy.__doc__) + assert not all_positional_all_keyword.search(funcy.__doc__) + assert not all_arguments.search(funcy.__doc__) @unpack_labeled_data(replace_all_args=True, replace_names=["bar"]) def funcy(ax, x, y, z, bar=None): """Funcy does nothing""" pass - assert_regex(funcy.__doc__, r".*All positional arguments\.") - assert_regex(funcy.__doc__, - r".*All arguments with the following names: 'bar'\.") - assert_not_regex(funcy.__doc__, - r".*All positional and all keyword arguments\.") + assert all_positional.search(funcy.__doc__) + assert all_arguments.search(funcy.__doc__) + assert not all_positional_all_keyword.search(funcy.__doc__) @unpack_labeled_data(replace_names=["x", "bar"]) def funcy(ax, x, y, z, bar=None): @@ -376,13 +384,11 @@ def funcy(ax, x, y, z, bar=None): pass # lists can print in any order, so test for both x,bar and bar,x - assert_regex(funcy.__doc__, - r".*All arguments with the following names: '.*', '.*'\.") - assert_regex(funcy.__doc__, r".*'x'.*") - assert_regex(funcy.__doc__, r".*'bar'.*") - assert_not_regex(funcy.__doc__, - r".*All positional and all keyword arguments\.") - assert_not_regex(funcy.__doc__, r".*All positional arguments\.") + assert all_arguments_with_following_names.search(funcy.__doc__) + assert x_string.search(funcy.__doc__) + assert bar_string.search(funcy.__doc__) + assert not all_positional_all_keyword.search(funcy.__doc__) + assert not all_positional.search(funcy.__doc__) def test_positional_parameter_names_as_function(): @@ -396,20 +402,18 @@ def funcy(ax, *args, **kwargs): # the normal case... data = {"x": "X", "hy1": "Y"} - assert_equal(funcy(None, "x", "hy1", data=data), - "('X', 'Y') | {}") - assert_equal(funcy(None, "x", "hy1", "c", data=data), - "('X', 'Y', 'c') | {}") + assert funcy(None, "x", "hy1", data=data) == "('X', 'Y') | {}" + assert funcy(None, "x", "hy1", "c", data=data) == "('X', 'Y', 'c') | {}" # no arbitrary long args with data def f(): - assert_equal(funcy(None, "x", "y", "c", "x", "y", "x", "y", data=data), - "('X', 'Y', 'c', 'X', 'Y', 'X', 'Y') | {}") - assert_raises(ValueError, f) + assert funcy(None, "x", "y", "c", "x", "y", "x", "y", data=data) == \ + "('X', 'Y', 'c', 'X', 'Y', 'X', 'Y') | {}" + with pytest.raises((AssertionError, ValueError)): + f() # In the two arg case, if a valid color spec is in data, we warn but use # it as data... data = {"x": "X", "y": "Y", "ro": "!!"} with assert_produces_warning(RuntimeWarning): - assert_equal(funcy(None, "y", "ro", data=data), - "('Y', '!!') | {}") + assert funcy(None, "y", "ro", data=data) == "('Y', '!!') | {}" diff --git a/lib/matplotlib/tests/test_legend.py b/lib/matplotlib/tests/test_legend.py index a43231b964ee..481b2e63e5f7 100644 --- a/lib/matplotlib/tests/test_legend.py +++ b/lib/matplotlib/tests/test_legend.py @@ -8,7 +8,6 @@ from unittest import mock except ImportError: import mock -from nose.tools import assert_equal import numpy as np from matplotlib.testing.decorators import image_comparison, cleanup @@ -109,7 +108,8 @@ def test_fancy(): plt.subplot(121) plt.scatter(list(xrange(10)), list(xrange(10, 0, -1)), label='XX\nXX') plt.plot([5] * 10, 'o--', label='XX') - plt.errorbar(list(xrange(10)), list(xrange(10)), xerr=0.5, yerr=0.5, label='XX') + plt.errorbar(list(xrange(10)), list(xrange(10)), + xerr=0.5, yerr=0.5, label='XX') plt.legend(loc="center left", bbox_to_anchor=[1.0, 0.5], ncol=2, shadow=True, title="My legend", numpoints=1) @@ -122,7 +122,8 @@ def test_framealpha(): plt.legend(framealpha=0.5) -@image_comparison(baseline_images=['scatter_rc3', 'scatter_rc1'], remove_text=True) +@image_comparison(baseline_images=['scatter_rc3', 'scatter_rc1'], + remove_text=True) def test_rc(): # using subplot triggers some offsetbox functionality untested elsewhere fig = plt.figure() @@ -162,7 +163,7 @@ def test_legend_remove(): lines = ax.plot(range(10)) leg = fig.legend(lines, "test") leg.remove() - assert_equal(fig.legends, []) + assert fig.legends == [] leg = ax.legend("test") leg.remove() assert ax.get_legend() is None @@ -259,8 +260,3 @@ def test_nanscatter(): ax.legend() ax.grid(True) - - -if __name__ == '__main__': - import nose - nose.runmodule(argv=['-s', '--with-doctest'], exit=False) diff --git a/lib/matplotlib/tests/test_lines.py b/lib/matplotlib/tests/test_lines.py index 775b02990add..3bbdb3232ec7 100644 --- a/lib/matplotlib/tests/test_lines.py +++ b/lib/matplotlib/tests/test_lines.py @@ -6,15 +6,14 @@ from matplotlib.externals import six import itertools +import matplotlib as mpl import matplotlib.lines as mlines -import nose -from nose.tools import assert_true, assert_raises from timeit import repeat import numpy as np - import matplotlib.pyplot as plt from matplotlib.testing.decorators import cleanup, image_comparison import sys +import pytest @cleanup @@ -57,8 +56,8 @@ def test_invisible_Line_rendering(): # gives about 290 ms for N = 10**7 pts slowdown_factor = (t_unvisible_line/t_no_line) - slowdown_threshold = 2 # trying to avoid false positive failures - assert_true(slowdown_factor < slowdown_threshold) + slowdown_threshold = 2 # trying to avoid false positive failures + assert slowdown_factor < slowdown_threshold @cleanup @@ -109,12 +108,8 @@ def test_linestyle_variants(): @cleanup def test_valid_linestyles(): - if sys.version_info[:2] < (2, 7): - raise nose.SkipTest("assert_raises as context manager " - "not supported with Python < 2.7") - line = mlines.Line2D([], []) - with assert_raises(ValueError): + with pytest.raises(ValueError): line.set_linestyle('aardvark') @@ -156,11 +151,8 @@ def test_marker_fill_styles(): def test_nan_is_sorted(): + # Exercises issue from PR #2744 (NaN throwing warning in _is_sorted) line = mlines.Line2D([],[]) - assert_true(line._is_sorted(np.array([1, 2, 3]))) - assert_true(line._is_sorted(np.array([1, np.nan, 3]))) - assert_true(not line._is_sorted([3, 5] + [np.nan] * 100 + [0, 2])) - - -if __name__ == '__main__': - nose.runmodule(argv=['-s', '--with-doctest'], exit=False) + assert line._is_sorted(np.array([1,2,3])) + assert line._is_sorted(np.array([1,np.nan,3])) + assert not line._is_sorted([3, 5] + [np.nan] * 100 + [0, 2]) diff --git a/lib/matplotlib/tests/test_mathtext.py b/lib/matplotlib/tests/test_mathtext.py index eeac74ad3878..c6361d793a83 100644 --- a/lib/matplotlib/tests/test_mathtext.py +++ b/lib/matplotlib/tests/test_mathtext.py @@ -7,7 +7,7 @@ import numpy as np import matplotlib -from matplotlib.testing.decorators import image_comparison, knownfailureif, cleanup +from matplotlib.testing.decorators import image_comparison, cleanup import matplotlib.pyplot as plt from matplotlib import mathtext @@ -88,26 +88,27 @@ r'${x}_{92}^{31415}+\pi $', r'${x}_{{y}_{b}^{a}}^{{z}_{c}^{d}}$', r'${y}_{3}^{\prime \prime \prime }$', - r"$\left( \xi \left( 1 - \xi \right) \right)$", # Bug 2969451 - r"$\left(2 \, a=b\right)$", # Sage bug #8125 - r"$? ! &$", # github issue #466 - r'$\operatorname{cos} x$', # github issue #553 + r"$\left( \xi \left( 1 - \xi \right) \right)$", # Bug 2969451 + r"$\left(2 \, a=b\right)$", # Sage bug #8125 + r"$? ! &$", # github issue #466 + r'$\operatorname{cos} x$', # github issue #553 r'$\sum _{\genfrac{}{}{0}{}{0\leq i\leq m}{0 M \: M \; M \ M \enspace M \quad M \qquad M \! M$', r'$\Cup$ $\Cap$ $\leftharpoonup$ $\barwedge$ $\rightharpoonup$', r'$\dotplus$ $\doteq$ $\doteqdot$ $\ddots$', - r'$xyz^kx_kx^py^{p-2} d_i^jb_jc_kd x^j_i E^0 E^0_u$', # github issue #4873 + r'$xyz^kx_kx^py^{p-2} d_i^jb_jc_kd x^j_i E^0 E^0_u$', # github issue #4873 r'${xyz}^k{x}_{k}{x}^{p}{y}^{p-2} {d}_{i}^{j}{b}_{j}{c}_{k}{d} {x}^{j}_{i}{E}^{0}{E}^0_u$', r'${\int}_x^x x\oint_x^x x\int_{X}^{X}x\int_x x \int^x x \int_{x} x\int^{x}{\int}_{x} x{\int}^{x}_{x}x$', r'testing$^{123}$', ' '.join('$\\' + p + '$' for p in sorted(mathtext.Parser._snowflake)), r'$6-2$; $-2$; $ -2$; ${-2}$; ${ -2}$; $20^{+3}_{-2}$', - r'$\overline{\omega}^x \frac{1}{2}_0^x$', # github issue #5444 - r'$1{,}234{, }567{ , }890$ and $1,234,567,890$', # github issue 5799 + r'$\overline{\omega}^x \frac{1}{2}_0^x$', # github issue #5444 + r'$1{,}234{, }567{ , }890$ and $1,234,567,890$', # github issue 5799 ] + digits = "0123456789" uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" lowercase = "abcdefghijklmnopqrstuvwxyz" @@ -156,13 +157,15 @@ for set in chars: font_tests.append(wrapper % set) + def make_set(basename, fontset, tests, extensions=None): def make_test(filename, test): @image_comparison(baseline_images=[filename], extensions=extensions) def single_test(): matplotlib.rcParams['mathtext.fontset'] = fontset fig = plt.figure(figsize=(5.25, 0.75)) - fig.text(0.5, 0.5, test, horizontalalignment='center', verticalalignment='center') + fig.text(0.5, 0.5, test, horizontalalignment='center', + verticalalignment='center') func = single_test func.__name__ = str("test_" + filename) return func @@ -187,6 +190,7 @@ def single_test(): make_set('mathfont', 'dejavusans', font_tests, ['png']) make_set('mathfont', 'dejavuserif', font_tests, ['png']) + def test_fontinfo(): import matplotlib.font_manager as font_manager import matplotlib.ft2font as ft2font @@ -195,6 +199,7 @@ def test_fontinfo(): table = font.get_sfnt_table("head") assert table['version'] == (1, 0) + def test_mathtext_exceptions(): errors = [ (r'$\hspace{}$', r'Expected \hspace{n}'), @@ -228,6 +233,7 @@ def test_mathtext_exceptions(): else: assert False, "Expected '%s', but didn't get it" % msg + @cleanup def test_single_minus_sign(): plt.figure(figsize=(0.3, 0.3)) @@ -243,8 +249,3 @@ def test_single_minus_sign(): # If this fails, it would be all white assert not np.all(array == 0xff) - - -if __name__ == '__main__': - import nose - nose.runmodule(argv=['-s', '--with-doctest'], exit=False) diff --git a/lib/matplotlib/tests/test_mlab.py b/lib/matplotlib/tests/test_mlab.py index c11f8ec450a0..179006bbdcd2 100644 --- a/lib/matplotlib/tests/test_mlab.py +++ b/lib/matplotlib/tests/test_mlab.py @@ -8,13 +8,12 @@ from numpy.testing import assert_allclose, assert_array_equal import numpy.ma.testutils as matest import numpy as np -from nose.tools import (assert_equal, assert_almost_equal, assert_not_equal, - assert_true, assert_raises) +from numpy.testing import assert_almost_equal import matplotlib.mlab as mlab import matplotlib.cbook as cbook -from matplotlib.testing.decorators import knownfailureif, CleanupTestCase - +from matplotlib.testing.decorators import CleanupTestCase +import pytest try: from mpl_toolkits.natgrid import _natgrid @@ -34,11 +33,11 @@ def test_colinear_pca(self): def test_prctile(self): # test odd lengths x = [1, 2, 3] - assert_equal(mlab.prctile(x, 50), np.median(x)) + assert mlab.prctile(x, 50) == np.median(x) # test even lengths x = [1, 2, 3, 4] - assert_equal(mlab.prctile(x, 50), np.median(x)) + assert mlab.prctile(x, 50) == np.median(x) # derived from email sent by jason-sage to MPL-user on 20090914 ob1 = [1, 1, 2, 2, 1, 2, 4, 3, 2, 2, 2, 3, @@ -88,7 +87,7 @@ def test_logspace_none(self): res = mlab.logspace(xmin, xmax, N) targ = np.logspace(np.log10(xmin), np.log10(xmax), N) assert_array_equal(targ, res) - assert_equal(res.size, 0) + assert res.size == 0 def test_logspace_single(self): xmin = .03 @@ -97,7 +96,7 @@ def test_logspace_single(self): res = mlab.logspace(xmin, xmax, N) targ = np.logspace(np.log10(xmin), np.log10(xmax), N) assert_array_equal(targ, res) - assert_equal(res.size, 1) + assert res.size == 1 class stride_testcase(CleanupTestCase): @@ -123,147 +122,157 @@ def calc_window_target(self, x, NFFT, noverlap=0): def test_stride_windows_2D_ValueError(self): x = np.arange(10)[np.newaxis] - assert_raises(ValueError, mlab.stride_windows, x, 5) + with pytest.raises(ValueError): + mlab.stride_windows(x, 5) def test_stride_windows_0D_ValueError(self): x = np.array(0) - assert_raises(ValueError, mlab.stride_windows, x, 5) + with pytest.raises(ValueError): + mlab.stride_windows(x, 5) def test_stride_windows_noverlap_gt_n_ValueError(self): x = np.arange(10) - assert_raises(ValueError, mlab.stride_windows, x, 2, 3) + with pytest.raises(ValueError): + mlab.stride_windows(x, 2, 3) def test_stride_windows_noverlap_eq_n_ValueError(self): x = np.arange(10) - assert_raises(ValueError, mlab.stride_windows, x, 2, 2) + with pytest.raises(ValueError): + mlab.stride_windows(x, 2, 2) def test_stride_windows_n_gt_lenx_ValueError(self): x = np.arange(10) - assert_raises(ValueError, mlab.stride_windows, x, 11) + with pytest.raises(ValueError): + mlab.stride_windows(x, 11) def test_stride_windows_n_lt_1_ValueError(self): x = np.arange(10) - assert_raises(ValueError, mlab.stride_windows, x, 0) + with pytest.raises(ValueError): + mlab.stride_windows(x, 0) def test_stride_repeat_2D_ValueError(self): x = np.arange(10)[np.newaxis] - assert_raises(ValueError, mlab.stride_repeat, x, 5) + with pytest.raises(ValueError): + mlab.stride_repeat(x, 5) def test_stride_repeat_axis_lt_0_ValueError(self): x = np.array(0) - assert_raises(ValueError, mlab.stride_repeat, x, 5, axis=-1) + with pytest.raises(ValueError): + mlab.stride_repeat(x, 5, axis=-1) def test_stride_repeat_axis_gt_1_ValueError(self): x = np.array(0) - assert_raises(ValueError, mlab.stride_repeat, x, 5, axis=2) + with pytest.raises(ValueError): + mlab.stride_repeat(x, 5, axis=2) def test_stride_repeat_n_lt_1_ValueError(self): x = np.arange(10) - assert_raises(ValueError, mlab.stride_repeat, x, 0) + with pytest.raises(ValueError): + mlab.stride_repeat(x, 0) def test_stride_repeat_n1_axis0(self): x = np.arange(10) y = mlab.stride_repeat(x, 1) - assert_equal((1, ) + x.shape, y.shape) + assert (1, ) + x.shape == y.shape assert_array_equal(x, y.flat) - assert_true(self.get_base(y) is x) + assert self.get_base(y) is x def test_stride_repeat_n1_axis1(self): x = np.arange(10) y = mlab.stride_repeat(x, 1, axis=1) - assert_equal(x.shape + (1, ), y.shape) + assert x.shape + (1, ) == y.shape assert_array_equal(x, y.flat) - assert_true(self.get_base(y) is x) + assert self.get_base(y) is x def test_stride_repeat_n5_axis0(self): x = np.arange(10) y = mlab.stride_repeat(x, 5) yr = np.repeat(x[np.newaxis], 5, axis=0) - assert_equal(yr.shape, y.shape) + assert yr.shape == y.shape assert_array_equal(yr, y) - assert_equal((5, ) + x.shape, y.shape) - assert_true(self.get_base(y) is x) + assert (5, ) + x.shape == y.shape + assert self.get_base(y) is x def test_stride_repeat_n5_axis1(self): x = np.arange(10) y = mlab.stride_repeat(x, 5, axis=1) yr = np.repeat(x[np.newaxis], 5, axis=0).T - assert_equal(yr.shape, y.shape) + assert yr.shape == y.shape assert_array_equal(yr, y) - assert_equal(x.shape + (5, ), y.shape) - assert_true(self.get_base(y) is x) + assert x.shape + (5, ) == y.shape + assert self.get_base(y) is x def test_stride_windows_n1_noverlap0_axis0(self): x = np.arange(10) y = mlab.stride_windows(x, 1) yt = self.calc_window_target(x, 1) - assert_equal(yt.shape, y.shape) + assert yt.shape == y.shape assert_array_equal(yt, y) - assert_equal((1, ) + x.shape, y.shape) - assert_true(self.get_base(y) is x) + assert (1, ) + x.shape == y.shape + assert self.get_base(y) is x def test_stride_windows_n1_noverlap0_axis1(self): x = np.arange(10) y = mlab.stride_windows(x, 1, axis=1) yt = self.calc_window_target(x, 1).T - assert_equal(yt.shape, y.shape) + assert yt.shape == y.shape assert_array_equal(yt, y) - assert_equal(x.shape + (1, ), y.shape) - assert_true(self.get_base(y) is x) + assert x.shape + (1, ) == y.shape + assert self.get_base(y) is x def test_stride_windows_n5_noverlap0_axis0(self): x = np.arange(100) y = mlab.stride_windows(x, 5) yt = self.calc_window_target(x, 5) - assert_equal(yt.shape, y.shape) + assert yt.shape == y.shape assert_array_equal(yt, y) - assert_equal((5, 20), y.shape) - assert_true(self.get_base(y) is x) + assert (5, 20) == y.shape + assert self.get_base(y) is x def test_stride_windows_n5_noverlap0_axis1(self): x = np.arange(100) y = mlab.stride_windows(x, 5, axis=1) yt = self.calc_window_target(x, 5).T - assert_equal(yt.shape, y.shape) + assert yt.shape == y.shape assert_array_equal(yt, y) - assert_equal((20, 5), y.shape) - assert_true(self.get_base(y) is x) + assert (20, 5) == y.shape + assert self.get_base(y) is x def test_stride_windows_n15_noverlap2_axis0(self): x = np.arange(100) y = mlab.stride_windows(x, 15, 2) yt = self.calc_window_target(x, 15, 2) - assert_equal(yt.shape, y.shape) + assert yt.shape == y.shape assert_array_equal(yt, y) - assert_equal((15, 7), y.shape) - assert_true(self.get_base(y) is x) + assert (15, 7) == y.shape + assert self.get_base(y) is x def test_stride_windows_n15_noverlap2_axis1(self): x = np.arange(100) y = mlab.stride_windows(x, 15, 2, axis=1) yt = self.calc_window_target(x, 15, 2).T - assert_equal(yt.shape, y.shape) + assert yt.shape == y.shape assert_array_equal(yt, y) - assert_equal((7, 15), y.shape) - assert_true(self.get_base(y) is x) + assert (7, 15) == y.shape + assert self.get_base(y) is x def test_stride_windows_n13_noverlapn3_axis0(self): x = np.arange(100) y = mlab.stride_windows(x, 13, -3) yt = self.calc_window_target(x, 13, -3) - assert_equal(yt.shape, y.shape) + assert yt.shape == y.shape assert_array_equal(yt, y) - assert_equal((13, 6), y.shape) - assert_true(self.get_base(y) is x) + assert (13, 6) == y.shape + assert self.get_base(y) is x def test_stride_windows_n13_noverlapn3_axis1(self): x = np.arange(100) y = mlab.stride_windows(x, 13, -3, axis=1) yt = self.calc_window_target(x, 13, -3).T - assert_equal(yt.shape, y.shape) + assert yt.shape == y.shape assert_array_equal(yt, y) - assert_equal((6, 13), y.shape) - assert_true(self.get_base(y) is x) + assert (6, 13) == y.shape + assert self.get_base(y) is x def test_stride_windows_n32_noverlap0_axis0_unflatten(self): n = 32 @@ -271,7 +280,7 @@ def test_stride_windows_n32_noverlap0_axis0_unflatten(self): x1 = np.tile(x, (21, 1)) x2 = x1.flatten() y = mlab.stride_windows(x2, n) - assert_equal(y.shape, x1.T.shape) + assert y.shape == x1.T.shape assert_array_equal(y, x1.T) def test_stride_windows_n32_noverlap0_axis1_unflatten(self): @@ -280,7 +289,7 @@ def test_stride_windows_n32_noverlap0_axis1_unflatten(self): x1 = np.tile(x, (21, 1)) x2 = x1.flatten() y = mlab.stride_windows(x2, n, axis=1) - assert_equal(y.shape, x1.shape) + assert y.shape == x1.shape assert_array_equal(y, x1) def test_stride_ensure_integer_type(self): @@ -337,7 +346,8 @@ def test_rec2csv_bad_shape_ValueError(self): (str('y'), np.float)]) # the bad recarray should trigger a ValueError for having ndim > 1. - assert_raises(ValueError, mlab.rec2csv, bad, self.fd) + with pytest.raises(ValueError): + mlab.rec2csv(bad, self.fd) def test_csv2rec_names_with_comments(self): self.fd.write('# comment\n1,2,3\n4,5,6\n') @@ -399,25 +409,26 @@ def test_window_hanning_ones(self): def test_apply_window_1D_axis1_ValueError(self): x = self.sig_rand window = mlab.window_hanning - assert_raises(ValueError, mlab.apply_window, x, window, axis=1, - return_window=False) + with pytest.raises(ValueError): + mlab.apply_window(x, window, axis=1, return_window=False) def test_apply_window_1D_els_wrongsize_ValueError(self): x = self.sig_rand window = mlab.window_hanning(np.ones(x.shape[0]-1)) - assert_raises(ValueError, mlab.apply_window, x, window) + with pytest.raises(ValueError): + mlab.apply_window(x, window) def test_apply_window_0D_ValueError(self): x = np.array(0) window = mlab.window_hanning - assert_raises(ValueError, mlab.apply_window, x, window, axis=1, - return_window=False) + with pytest.raises(ValueError): + mlab.apply_window(x, window, axis=1, return_window=False) def test_apply_window_3D_ValueError(self): x = self.sig_rand[np.newaxis][np.newaxis] window = mlab.window_hanning - assert_raises(ValueError, mlab.apply_window, x, window, axis=1, - return_window=False) + with pytest.raises(ValueError): + mlab.apply_window(x, window, axis=1, return_window=False) def test_apply_window_hanning_1D(self): x = self.sig_rand @@ -425,8 +436,8 @@ def test_apply_window_hanning_1D(self): window1 = mlab.window_hanning(np.ones(x.shape[0])) y, window2 = mlab.apply_window(x, window, return_window=True) yt = window(x) - assert_equal(yt.shape, y.shape) - assert_equal(x.shape, y.shape) + assert yt.shape == y.shape + assert x.shape == y.shape assert_allclose(yt, y, atol=1e-06) assert_array_equal(window1, window2) @@ -435,8 +446,8 @@ def test_apply_window_hanning_1D_axis0(self): window = mlab.window_hanning y = mlab.apply_window(x, window, axis=0, return_window=False) yt = window(x) - assert_equal(yt.shape, y.shape) - assert_equal(x.shape, y.shape) + assert yt.shape == y.shape + assert x.shape == y.shape assert_allclose(yt, y, atol=1e-06) def test_apply_window_hanning_els_1D_axis0(self): @@ -445,8 +456,8 @@ def test_apply_window_hanning_els_1D_axis0(self): window1 = mlab.window_hanning y = mlab.apply_window(x, window, axis=0, return_window=False) yt = window1(x) - assert_equal(yt.shape, y.shape) - assert_equal(x.shape, y.shape) + assert yt.shape == y.shape + assert x.shape == y.shape assert_allclose(yt, y, atol=1e-06) def test_apply_window_hanning_2D_axis0(self): @@ -456,8 +467,8 @@ def test_apply_window_hanning_2D_axis0(self): yt = np.zeros_like(x) for i in range(x.shape[1]): yt[:, i] = window(x[:, i]) - assert_equal(yt.shape, y.shape) - assert_equal(x.shape, y.shape) + assert yt.shape == y.shape + assert x.shape == y.shape assert_allclose(yt, y, atol=1e-06) def test_apply_window_hanning_els1_2D_axis0(self): @@ -468,8 +479,8 @@ def test_apply_window_hanning_els1_2D_axis0(self): yt = np.zeros_like(x) for i in range(x.shape[1]): yt[:, i] = window1(x[:, i]) - assert_equal(yt.shape, y.shape) - assert_equal(x.shape, y.shape) + assert yt.shape == y.shape + assert x.shape == y.shape assert_allclose(yt, y, atol=1e-06) def test_apply_window_hanning_els2_2D_axis0(self): @@ -480,8 +491,8 @@ def test_apply_window_hanning_els2_2D_axis0(self): yt = np.zeros_like(x) for i in range(x.shape[1]): yt[:, i] = window1*x[:, i] - assert_equal(yt.shape, y.shape) - assert_equal(x.shape, y.shape) + assert yt.shape == y.shape + assert x.shape == y.shape assert_allclose(yt, y, atol=1e-06) assert_array_equal(window1, window2) @@ -491,8 +502,8 @@ def test_apply_window_hanning_els3_2D_axis0(self): window1 = mlab.window_hanning(np.ones(x.shape[0])) y, window2 = mlab.apply_window(x, window, axis=0, return_window=True) yt = mlab.apply_window(x, window1, axis=0, return_window=False) - assert_equal(yt.shape, y.shape) - assert_equal(x.shape, y.shape) + assert yt.shape == y.shape + assert x.shape == y.shape assert_allclose(yt, y, atol=1e-06) assert_array_equal(window1, window2) @@ -503,8 +514,8 @@ def test_apply_window_hanning_2D_axis1(self): yt = np.zeros_like(x) for i in range(x.shape[0]): yt[i, :] = window(x[i, :]) - assert_equal(yt.shape, y.shape) - assert_equal(x.shape, y.shape) + assert yt.shape == y.shape + assert x.shape == y.shape assert_allclose(yt, y, atol=1e-06) def test_apply_window_hanning_2D__els1_axis1(self): @@ -515,8 +526,8 @@ def test_apply_window_hanning_2D__els1_axis1(self): yt = np.zeros_like(x) for i in range(x.shape[0]): yt[i, :] = window1(x[i, :]) - assert_equal(yt.shape, y.shape) - assert_equal(x.shape, y.shape) + assert yt.shape == y.shape + assert x.shape == y.shape assert_allclose(yt, y, atol=1e-06) def test_apply_window_hanning_2D_els2_axis1(self): @@ -527,8 +538,8 @@ def test_apply_window_hanning_2D_els2_axis1(self): yt = np.zeros_like(x) for i in range(x.shape[0]): yt[i, :] = window1 * x[i, :] - assert_equal(yt.shape, y.shape) - assert_equal(x.shape, y.shape) + assert yt.shape == y.shape + assert x.shape == y.shape assert_allclose(yt, y, atol=1e-06) assert_array_equal(window1, window2) @@ -538,8 +549,8 @@ def test_apply_window_hanning_2D_els3_axis1(self): window1 = mlab.window_hanning(np.ones(x.shape[1])) y = mlab.apply_window(x, window, axis=1, return_window=False) yt = mlab.apply_window(x, window1, axis=1, return_window=False) - assert_equal(yt.shape, y.shape) - assert_equal(x.shape, y.shape) + assert yt.shape == y.shape + assert x.shape == y.shape assert_allclose(yt, y, atol=1e-06) def test_apply_window_stride_windows_hanning_2D_n13_noverlapn3_axis0(self): @@ -548,8 +559,8 @@ def test_apply_window_stride_windows_hanning_2D_n13_noverlapn3_axis0(self): yi = mlab.stride_windows(x, n=13, noverlap=2, axis=0) y = mlab.apply_window(yi, window, axis=0, return_window=False) yt = self.check_window_apply_repeat(x, window, 13, 2) - assert_equal(yt.shape, y.shape) - assert_not_equal(x.shape, y.shape) + assert yt.shape == y.shape + assert x.shape != y.shape assert_allclose(yt, y, atol=1e-06) def test_apply_window_hanning_2D_stack_axis1(self): @@ -625,31 +636,31 @@ def test_detrend_none_0D_zeros(self): input = 0. targ = input res = mlab.detrend_none(input) - assert_equal(input, targ) + assert input == targ def test_detrend_none_0D_zeros_axis1(self): input = 0. targ = input res = mlab.detrend_none(input, axis=1) - assert_equal(input, targ) + assert input == targ def test_detrend_str_none_0D_zeros(self): input = 0. targ = input res = mlab.detrend(input, key='none') - assert_equal(input, targ) + assert input == targ def test_detrend_detrend_none_0D_zeros(self): input = 0. targ = input res = mlab.detrend(input, key=mlab.detrend_none) - assert_equal(input, targ) + assert input == targ def test_detrend_none_0D_off(self): input = 5.5 targ = input res = mlab.detrend_none(input) - assert_equal(input, targ) + assert input == targ def test_detrend_none_1D_off(self): input = self.sig_off @@ -673,7 +684,7 @@ def test_detrend_none_1D_base_slope_off_list(self): input = self.sig_base + self.sig_slope + self.sig_off targ = input.tolist() res = mlab.detrend_none(input.tolist()) - assert_equal(res, targ) + assert res == targ def test_detrend_none_2D(self): arri = [self.sig_base, @@ -1096,43 +1107,53 @@ def test_demean_2D_axism1(self): def test_detrend_bad_key_str_ValueError(self): input = self.sig_slope[np.newaxis] - assert_raises(ValueError, mlab.detrend, input, key='spam') + with pytest.raises(ValueError): + mlab.detrend(input, key='spam') def test_detrend_bad_key_var_ValueError(self): input = self.sig_slope[np.newaxis] - assert_raises(ValueError, mlab.detrend, input, key=5) + with pytest.raises(ValueError): + mlab.detrend(input, key=5) def test_detrend_mean_0D_d0_ValueError(self): input = 5.5 - assert_raises(ValueError, mlab.detrend_mean, input, axis=0) + with pytest.raises(ValueError): + mlab.detrend_mean(input, axis=0) def test_detrend_0D_d0_ValueError(self): input = 5.5 - assert_raises(ValueError, mlab.detrend, input, axis=0) + with pytest.raises(ValueError): + mlab.detrend(input, axis=0) def test_detrend_mean_1D_d1_ValueError(self): input = self.sig_slope - assert_raises(ValueError, mlab.detrend_mean, input, axis=1) + with pytest.raises(ValueError): + mlab.detrend_mean(input, axis=1) def test_detrend_1D_d1_ValueError(self): input = self.sig_slope - assert_raises(ValueError, mlab.detrend, input, axis=1) + with pytest.raises(ValueError): + mlab.detrend(input, axis=1) def test_demean_1D_d1_ValueError(self): input = self.sig_slope - assert_raises(ValueError, mlab.demean, input, axis=1) + with pytest.raises(ValueError): + mlab.demean(input, axis=1) def test_detrend_mean_2D_d2_ValueError(self): input = self.sig_slope[np.newaxis] - assert_raises(ValueError, mlab.detrend_mean, input, axis=2) + with pytest.raises(ValueError): + mlab.detrend_mean(input, axis=2) def test_detrend_2D_d2_ValueError(self): input = self.sig_slope[np.newaxis] - assert_raises(ValueError, mlab.detrend, input, axis=2) + with pytest.raises(ValueError): + mlab.detrend(input, axis=2) def test_demean_2D_d2_ValueError(self): input = self.sig_slope[np.newaxis] - assert_raises(ValueError, mlab.demean, input, axis=2) + with pytest.raises(ValueError): + mlab.demean(input, axis=2) def test_detrend_linear_0D_zeros(self): input = 0. @@ -1196,7 +1217,8 @@ def test_detrend_linear_1d_slope_off_list(self): def test_detrend_linear_2D_ValueError(self): input = self.sig_slope[np.newaxis] - assert_raises(ValueError, mlab.detrend_linear, input) + with pytest.raises(ValueError): + mlab.detrend_linear(input) def test_detrend_str_linear_2d_slope_off_axis0(self): arri = [self.sig_off, @@ -1397,13 +1419,13 @@ def createStim(self, fstims, iscomplex, sides, nsides, len_x=None, self.NFFT_density_real = NFFT_density_real def check_freqs(self, vals, targfreqs, resfreqs, fstims): - assert_true(resfreqs.argmin() == 0) - assert_true(resfreqs.argmax() == len(resfreqs)-1) + assert resfreqs.argmin() == 0 + assert resfreqs.argmax() == len(resfreqs)-1 assert_allclose(resfreqs, targfreqs, atol=1e-06) for fstim in fstims: i = np.abs(resfreqs - fstim).argmin() - assert_true(vals[i] > vals[i+2]) - assert_true(vals[i] > vals[i-2]) + assert vals[i] > vals[i+2] + assert vals[i] > vals[i-2] def check_maxfreq(self, spec, fsp, fstims): # skip the test if there are no frequencies @@ -1431,58 +1453,59 @@ def check_maxfreq(self, spec, fsp, fstims): def test_spectral_helper_raises_complex_same_data(self): # test that mode 'complex' cannot be used if x is not y - assert_raises(ValueError, mlab._spectral_helper, - x=self.y, y=self.y+1, mode='complex') + with pytest.raises(ValueError): + mlab._spectral_helper(x=self.y, y=self.y+1, mode='complex') def test_spectral_helper_raises_magnitude_same_data(self): # test that mode 'magnitude' cannot be used if x is not y - assert_raises(ValueError, mlab._spectral_helper, - x=self.y, y=self.y+1, mode='magnitude') + with pytest.raises(ValueError): + mlab._spectral_helper(x=self.y, y=self.y+1, mode='magnitude') def test_spectral_helper_raises_angle_same_data(self): # test that mode 'angle' cannot be used if x is not y - assert_raises(ValueError, mlab._spectral_helper, - x=self.y, y=self.y+1, mode='angle') + with pytest.raises(ValueError): + mlab._spectral_helper(x=self.y, y=self.y+1, mode='angle') def test_spectral_helper_raises_phase_same_data(self): # test that mode 'phase' cannot be used if x is not y - assert_raises(ValueError, mlab._spectral_helper, - x=self.y, y=self.y+1, mode='phase') + with pytest.raises(ValueError): + mlab._spectral_helper(x=self.y, y=self.y+1, mode='phase') def test_spectral_helper_raises_unknown_mode(self): # test that unknown value for mode cannot be used - assert_raises(ValueError, mlab._spectral_helper, - x=self.y, mode='spam') + with pytest.raises(ValueError): + mlab._spectral_helper(x=self.y, mode='spam') def test_spectral_helper_raises_unknown_sides(self): # test that unknown value for sides cannot be used - assert_raises(ValueError, mlab._spectral_helper, - x=self.y, y=self.y, sides='eggs') + with pytest.raises(ValueError): + mlab._spectral_helper(x=self.y, y=self.y, sides='eggs') def test_spectral_helper_raises_noverlap_gt_NFFT(self): # test that noverlap cannot be larger than NFFT - assert_raises(ValueError, mlab._spectral_helper, - x=self.y, y=self.y, NFFT=10, noverlap=20) + with pytest.raises(ValueError): + mlab._spectral_helper(x=self.y, y=self.y, NFFT=10, noverlap=20) def test_spectral_helper_raises_noverlap_eq_NFFT(self): # test that noverlap cannot be equal to NFFT - assert_raises(ValueError, mlab._spectral_helper, - x=self.y, NFFT=10, noverlap=10) + with pytest.raises(ValueError): + mlab._spectral_helper(x=self.y, NFFT=10, noverlap=10) def test_spectral_helper_raises_winlen_ne_NFFT(self): # test that the window length cannot be different from NFFT - assert_raises(ValueError, mlab._spectral_helper, - x=self.y, y=self.y, NFFT=10, window=np.ones(9)) + with pytest.raises(ValueError): + mlab._spectral_helper(x=self.y, y=self.y, + NFFT=10, window=np.ones(9)) def test_single_spectrum_helper_raises_mode_default(self): # test that mode 'default' cannot be used with _single_spectrum_helper - assert_raises(ValueError, mlab._single_spectrum_helper, - x=self.y, mode='default') + with pytest.raises(ValueError): + mlab._single_spectrum_helper(x=self.y, mode='default') def test_single_spectrum_helper_raises_mode_psd(self): # test that mode 'psd' cannot be used with _single_spectrum_helper - assert_raises(ValueError, mlab._single_spectrum_helper, - x=self.y, mode='psd') + with pytest.raises(ValueError): + mlab._single_spectrum_helper(x=self.y, mode='psd') def test_spectral_helper_psd(self): freqs = self.freqs_density @@ -1497,8 +1520,8 @@ def test_spectral_helper_psd(self): assert_allclose(fsp, freqs, atol=1e-06) assert_allclose(t, self.t_density, atol=1e-06) - assert_equal(spec.shape[0], freqs.shape[0]) - assert_equal(spec.shape[1], self.t_specgram.shape[0]) + assert spec.shape[0] == freqs.shape[0] + assert spec.shape[1] == self.t_specgram.shape[0] def test_spectral_helper_magnitude_specgram(self): freqs = self.freqs_specgram @@ -1513,8 +1536,8 @@ def test_spectral_helper_magnitude_specgram(self): assert_allclose(fsp, freqs, atol=1e-06) assert_allclose(t, self.t_specgram, atol=1e-06) - assert_equal(spec.shape[0], freqs.shape[0]) - assert_equal(spec.shape[1], self.t_specgram.shape[0]) + assert spec.shape[0] == freqs.shape[0] + assert spec.shape[1] == self.t_specgram.shape[0] def test_spectral_helper_magnitude_magnitude_spectrum(self): freqs = self.freqs_spectrum @@ -1529,8 +1552,8 @@ def test_spectral_helper_magnitude_magnitude_spectrum(self): assert_allclose(fsp, freqs, atol=1e-06) assert_allclose(t, self.t_spectrum, atol=1e-06) - assert_equal(spec.shape[0], freqs.shape[0]) - assert_equal(spec.shape[1], 1) + assert spec.shape[0] == freqs.shape[0] + assert spec.shape[1] == 1 def test_csd(self): freqs = self.freqs_density @@ -1541,7 +1564,7 @@ def test_csd(self): pad_to=self.pad_to_density, sides=self.sides) assert_allclose(fsp, freqs, atol=1e-06) - assert_equal(spec.shape, freqs.shape) + assert spec.shape == freqs.shape def test_psd(self): freqs = self.freqs_density @@ -1551,7 +1574,7 @@ def test_psd(self): noverlap=self.nover_density, pad_to=self.pad_to_density, sides=self.sides) - assert_equal(spec.shape, freqs.shape) + assert spec.shape == freqs.shape self.check_freqs(spec, freqs, fsp, self.fstims) def test_psd_detrend_mean_func_offset(self): @@ -1587,8 +1610,8 @@ def test_psd_detrend_mean_func_offset(self): assert_array_equal(fsp_b, fsp_c) assert_allclose(spec_g, spec_c, atol=1e-08) # these should not be almost equal - assert_raises(AssertionError, - assert_allclose, spec_b, spec_c, atol=1e-08) + with pytest.raises(AssertionError): + assert_allclose(spec_b, spec_c, atol=1e-08) def test_psd_detrend_mean_str_offset(self): if self.NFFT_density is None: @@ -1623,8 +1646,8 @@ def test_psd_detrend_mean_str_offset(self): assert_array_equal(fsp_b, fsp_c) assert_allclose(spec_g, spec_c, atol=1e-08) # these should not be almost equal - assert_raises(AssertionError, - assert_allclose, spec_b, spec_c, atol=1e-08) + with pytest.raises(AssertionError): + assert_allclose(spec_b, spec_c, atol=1e-08) def test_psd_detrend_linear_func_trend(self): if self.NFFT_density is None: @@ -1659,8 +1682,8 @@ def test_psd_detrend_linear_func_trend(self): assert_array_equal(fsp_b, fsp_c) assert_allclose(spec_g, spec_c, atol=1e-08) # these should not be almost equal - assert_raises(AssertionError, - assert_allclose, spec_b, spec_c, atol=1e-08) + with pytest.raises(AssertionError): + assert_allclose(spec_b, spec_c, atol=1e-08) def test_psd_detrend_linear_str_trend(self): if self.NFFT_density is None: @@ -1695,8 +1718,8 @@ def test_psd_detrend_linear_str_trend(self): assert_array_equal(fsp_b, fsp_c) assert_allclose(spec_g, spec_c, atol=1e-08) # these should not be almost equal - assert_raises(AssertionError, - assert_allclose, spec_b, spec_c, atol=1e-08) + with pytest.raises(AssertionError): + assert_allclose(spec_b, spec_c, atol=1e-08) def test_psd_window_hanning(self): if self.NFFT_density is None: @@ -1739,8 +1762,8 @@ def test_psd_window_hanning(self): assert_array_equal(fsp_b, fsp_c) assert_allclose(spec_g, spec_c, atol=1e-08) # these should not be almost equal - assert_raises(AssertionError, - assert_allclose, spec_b, spec_c, atol=1e-08) + with pytest.raises(AssertionError): + assert_allclose(spec_b, spec_c, atol=1e-08) def test_psd_window_hanning_detrend_linear(self): if self.NFFT_density is None: @@ -1788,8 +1811,8 @@ def test_psd_window_hanning_detrend_linear(self): assert_array_equal(fsp_b, fsp_c) assert_allclose(spec_g, spec_c, atol=1e-08) # these should not be almost equal - assert_raises(AssertionError, - assert_allclose, spec_b, spec_c, atol=1e-08) + with pytest.raises(AssertionError): + assert_allclose(spec_b, spec_c, atol=1e-08) def test_psd_windowarray(self): freqs = self.freqs_density @@ -1801,7 +1824,7 @@ def test_psd_windowarray(self): sides=self.sides, window=np.ones(self.NFFT_density_real)) assert_allclose(fsp, freqs, atol=1e-06) - assert_equal(spec.shape, freqs.shape) + assert spec.shape == freqs.shape def test_psd_windowarray_scale_by_freq(self): freqs = self.freqs_density @@ -1844,7 +1867,7 @@ def test_complex_spectrum(self): sides=self.sides, pad_to=self.pad_to_spectrum) assert_allclose(fsp, freqs, atol=1e-06) - assert_equal(spec.shape, freqs.shape) + assert spec.shape == freqs.shape def test_magnitude_spectrum(self): freqs = self.freqs_spectrum @@ -1852,7 +1875,7 @@ def test_magnitude_spectrum(self): Fs=self.Fs, sides=self.sides, pad_to=self.pad_to_spectrum) - assert_equal(spec.shape, freqs.shape) + assert spec.shape == freqs.shape self.check_maxfreq(spec, fsp, self.fstims) self.check_freqs(spec, freqs, fsp, self.fstims) @@ -1863,7 +1886,7 @@ def test_angle_spectrum(self): sides=self.sides, pad_to=self.pad_to_spectrum) assert_allclose(fsp, freqs, atol=1e-06) - assert_equal(spec.shape, freqs.shape) + assert spec.shape == freqs.shape def test_phase_spectrum(self): freqs = self.freqs_spectrum @@ -1872,7 +1895,7 @@ def test_phase_spectrum(self): sides=self.sides, pad_to=self.pad_to_spectrum) assert_allclose(fsp, freqs, atol=1e-06) - assert_equal(spec.shape, freqs.shape) + assert spec.shape == freqs.shape def test_specgram_auto(self): freqs = self.freqs_specgram @@ -1887,8 +1910,8 @@ def test_specgram_auto(self): assert_allclose(fsp, freqs, atol=1e-06) assert_allclose(t, self.t_specgram, atol=1e-06) - assert_equal(spec.shape[0], freqs.shape[0]) - assert_equal(spec.shape[1], self.t_specgram.shape[0]) + assert spec.shape[0] == freqs.shape[0] + assert spec.shape[1] == self.t_specgram.shape[0] # since we are using a single freq, all time slices # should be about the same @@ -1911,8 +1934,8 @@ def test_specgram_default(self): assert_allclose(fsp, freqs, atol=1e-06) assert_allclose(t, self.t_specgram, atol=1e-06) - assert_equal(spec.shape[0], freqs.shape[0]) - assert_equal(spec.shape[1], self.t_specgram.shape[0]) + assert spec.shape[0] == freqs.shape[0] + assert spec.shape[1] == self.t_specgram.shape[0] # since we are using a single freq, all time slices # should be about the same @@ -1935,8 +1958,8 @@ def test_specgram_psd(self): assert_allclose(fsp, freqs, atol=1e-06) assert_allclose(t, self.t_specgram, atol=1e-06) - assert_equal(spec.shape[0], freqs.shape[0]) - assert_equal(spec.shape[1], self.t_specgram.shape[0]) + assert spec.shape[0] == freqs.shape[0] + assert spec.shape[1] == self.t_specgram.shape[0] # since we are using a single freq, all time slices # should be about the same if np.abs(spec.max()) != 0: @@ -1957,8 +1980,8 @@ def test_specgram_complex(self): assert_allclose(fsp, freqs, atol=1e-06) assert_allclose(t, self.t_specgram, atol=1e-06) - assert_equal(spec.shape[0], freqs.shape[0]) - assert_equal(spec.shape[1], self.t_specgram.shape[0]) + assert spec.shape[0] == freqs.shape[0] + assert spec.shape[1] == self.t_specgram.shape[0] self.check_freqs(specm, freqs, fsp, self.fstims) @@ -1975,8 +1998,8 @@ def test_specgram_magnitude(self): assert_allclose(fsp, freqs, atol=1e-06) assert_allclose(t, self.t_specgram, atol=1e-06) - assert_equal(spec.shape[0], freqs.shape[0]) - assert_equal(spec.shape[1], self.t_specgram.shape[0]) + assert spec.shape[0] == freqs.shape[0] + assert spec.shape[1] == self.t_specgram.shape[0] # since we are using a single freq, all time slices # should be about the same if np.abs(spec.max()) != 0: @@ -1997,8 +2020,8 @@ def test_specgram_angle(self): assert_allclose(fsp, freqs, atol=1e-06) assert_allclose(t, self.t_specgram, atol=1e-06) - assert_equal(spec.shape[0], freqs.shape[0]) - assert_equal(spec.shape[1], self.t_specgram.shape[0]) + assert spec.shape[0] == freqs.shape[0] + assert spec.shape[1] == self.t_specgram.shape[0] def test_specgram_phase(self): freqs = self.freqs_specgram @@ -2014,8 +2037,8 @@ def test_specgram_phase(self): assert_allclose(fsp, freqs, atol=1e-06) assert_allclose(t, self.t_specgram, atol=1e-06) - assert_equal(spec.shape[0], freqs.shape[0]) - assert_equal(spec.shape[1], self.t_specgram.shape[0]) + assert spec.shape[0] == freqs.shape[0] + assert spec.shape[1] == self.t_specgram.shape[0] def test_psd_csd_equal(self): freqs = self.freqs_density @@ -2751,7 +2774,8 @@ def get_z(x, y): np.ma.getmask(correct_zi_masked)) -@knownfailureif(not HAS_NATGRID) +@pytest.mark.xfail(not HAS_NATGRID, + reason='import of the natgrid toolkit failed') def test_griddata_nn(): # z is a linear function of x and y. def get_z(x, y): @@ -2771,10 +2795,10 @@ def get_z(x, y): np.testing.assert_array_almost_equal(zi, correct_zi, 5) # Decreasing xi or yi should raise ValueError. - assert_raises(ValueError, mlab.griddata, x, y, z, xi[::-1], yi, - interp='nn') - assert_raises(ValueError, mlab.griddata, x, y, z, xi, yi[::-1], - interp='nn') + with pytest.raises(ValueError): + mlab.griddata(x, y, z, xi[::-1], yi, interp='nn') + with pytest.raises(ValueError): + mlab.griddata(x, y, z, xi, yi[::-1], interp='nn') # Passing 2D xi and yi arrays to griddata. xi, yi = np.meshgrid(xi, yi) @@ -2790,11 +2814,11 @@ def get_z(x, y): np.ma.getmask(correct_zi_masked)) -#***************************************************************** +# ***************************************************************** # These Tests where taken from SCIPY with some minor modifications # this can be retreived from: # https://github.com/scipy/scipy/blob/master/scipy/stats/tests/test_kdeoth.py -#***************************************************************** +# ***************************************************************** class gaussian_kde_tests(): @@ -2844,17 +2868,20 @@ def test_kde_bandwidth_method(self): class gaussian_kde_custom_tests(object): def test_no_data(self): """Pass no data into the GaussianKDE class.""" - assert_raises(ValueError, mlab.GaussianKDE, []) + with pytest.raises(ValueError): + mlab.GaussianKDE([]) def test_single_dataset_element(self): """Pass a single dataset element into the GaussianKDE class.""" - assert_raises(ValueError, mlab.GaussianKDE, [42]) + with pytest.raises(ValueError): + mlab.GaussianKDE([42]) def test_silverman_multidim_dataset(self): """Use a multi-dimensional array as the dataset and test silverman's output""" x1 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) - assert_raises(np.linalg.LinAlgError, mlab.GaussianKDE, x1, "silverman") + with pytest.raises(np.linalg.LinAlgError): + mlab.GaussianKDE(x1, "silverman") def test_silverman_singledim_dataset(self): """Use a single dimension list as the dataset and test silverman's @@ -2868,7 +2895,8 @@ def test_scott_multidim_dataset(self): """Use a multi-dimensional array as the dataset and test scott's output """ x1 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) - assert_raises(np.linalg.LinAlgError, mlab.GaussianKDE, x1, "scott") + with pytest.raises(np.linalg.LinAlgError): + mlab.GaussianKDE(x1, "scott") def test_scott_singledim_dataset(self): """Use a single-dimensional array as the dataset and test scott's @@ -2881,7 +2909,8 @@ def test_scott_singledim_dataset(self): def test_scalar_empty_dataset(self): """Use an empty array as the dataset and test the scalar's cov factor """ - assert_raises(ValueError, mlab.GaussianKDE, [], bw_method=5) + with pytest.raises(ValueError): + mlab.GaussianKDE([], bw_method=5) def test_scalar_covariance_dataset(self): """Use a dataset and test a scalar's cov factor @@ -2891,7 +2920,7 @@ def test_scalar_covariance_dataset(self): multidim_data = [np.random.randn(n_basesample) for i in range(5)] kde = mlab.GaussianKDE(multidim_data, bw_method=0.5) - assert_equal(kde.covariance_factor(), 0.5) + assert kde.covariance_factor() == 0.5 def test_callable_covariance_dataset(self): """Use a multi-dimensional array as the dataset and test the callable's @@ -2903,7 +2932,7 @@ def test_callable_covariance_dataset(self): def callable_fun(x): return 0.55 kde = mlab.GaussianKDE(multidim_data, bw_method=callable_fun) - assert_equal(kde.covariance_factor(), 0.55) + assert kde.covariance_factor() == 0.55 def test_callable_singledim_dataset(self): """Use a single-dimensional array as the dataset and test the @@ -2921,7 +2950,8 @@ def test_wrong_bw_method(self): np.random.seed(8765678) n_basesample = 50 data = np.random.randn(n_basesample) - assert_raises(ValueError, mlab.GaussianKDE, data, bw_method="invalid") + with pytest.raises(ValueError): + mlab.GaussianKDE(data, bw_method="invalid") class gaussian_kde_evaluate_tests(object): @@ -2947,7 +2977,8 @@ def test_evaluate_inv_dim(self): multidim_data = np.random.randn(n_basesample) kde = mlab.GaussianKDE(multidim_data) x2 = [[1], [2], [3]] - assert_raises(ValueError, kde.evaluate, x2) + with pytest.raises(ValueError): + kde.evaluate(x2) def test_evaluate_dim_and_num(self): """ Tests if evaluated against a one by one array""" @@ -2963,7 +2994,8 @@ def test_evaluate_point_dim_not_one(self): x1 = np.arange(3, 10, 2) x2 = [np.arange(3, 10, 2), np.arange(3, 10, 2)] kde = mlab.GaussianKDE(x1) - assert_raises(ValueError, kde.evaluate, x2) + with pytest.raises(ValueError): + kde.evaluate(x2) def test_evaluate_equal_dim_and_num_lt(self): """Test when line 3810 fails""" @@ -2980,22 +3012,22 @@ def test_contiguous_regions(): # Starts and ends with True mask = [True]*a + [False]*b + [True]*c expected = [(0, a), (a+b, a+b+c)] - assert_equal(mlab.contiguous_regions(mask), expected) + assert mlab.contiguous_regions(mask) == expected d, e = 6, 7 # Starts with True ends with False mask = mask + [False]*e - assert_equal(mlab.contiguous_regions(mask), expected) + assert mlab.contiguous_regions(mask) == expected # Starts with False ends with True mask = [False]*d + mask[:-e] expected = [(d, d+a), (d+a+b, d+a+b+c)] - assert_equal(mlab.contiguous_regions(mask), expected) + assert mlab.contiguous_regions(mask) == expected # Starts and ends with False mask = mask + [False]*e - assert_equal(mlab.contiguous_regions(mask), expected) + assert mlab.contiguous_regions(mask) == expected # No True in mask - assert_equal(mlab.contiguous_regions([False]*5), []) + assert mlab.contiguous_regions([False]*5) == [] # Empty mask - assert_equal(mlab.contiguous_regions([]), []) + assert mlab.contiguous_regions([]) == [] def test_psd_onesided_norm(): @@ -3008,13 +3040,3 @@ def test_psd_onesided_norm(): sides='onesided') Su_1side = np.append([Su[0]], Su[1:4] + Su[4:][::-1]) assert_allclose(P, Su_1side, atol=1e-06) - - -if __name__ == '__main__': - import nose - import sys - - args = ['-s', '--with-doctest'] - argv = sys.argv - argv = argv[:1] + args + argv[1:] - nose.runmodule(argv=argv, exit=False) diff --git a/lib/matplotlib/tests/test_offsetbox.py b/lib/matplotlib/tests/test_offsetbox.py index 0b6bfea3adeb..ffc5cd2f7dd6 100644 --- a/lib/matplotlib/tests/test_offsetbox.py +++ b/lib/matplotlib/tests/test_offsetbox.py @@ -1,8 +1,8 @@ from __future__ import (absolute_import, division, print_function, unicode_literals) -import nose -from nose.tools import assert_true, assert_false +# import nose +# from nose.tools import assert_true, assert_false from matplotlib.testing.decorators import image_comparison, cleanup import matplotlib.pyplot as plt import matplotlib.patches as mpatches @@ -78,9 +78,6 @@ def test_offsetbox_clip_children(): ax.add_artist(anchored_box) fig.canvas.draw() - assert_false(fig.stale) + assert not fig.stale da.clip_children = True - assert_true(fig.stale) - -if __name__ == '__main__': - nose.runmodule(argv=['-s', '--with-doctest'], exit=False) + assert fig.stale diff --git a/lib/matplotlib/tests/test_patches.py b/lib/matplotlib/tests/test_patches.py index a2e21255540f..0293d5a187bf 100644 --- a/lib/matplotlib/tests/test_patches.py +++ b/lib/matplotlib/tests/test_patches.py @@ -277,8 +277,3 @@ def test_wedge_range(): ax.set_xlim([-2, 8]) ax.set_ylim([-2, 9]) - - -if __name__ == '__main__': - import nose - nose.runmodule(argv=['-s', '--with-doctest'], exit=False) diff --git a/lib/matplotlib/tests/test_path.py b/lib/matplotlib/tests/test_path.py index 5f606461916e..44888ea5aa22 100644 --- a/lib/matplotlib/tests/test_path.py +++ b/lib/matplotlib/tests/test_path.py @@ -7,10 +7,10 @@ from matplotlib.path import Path from matplotlib.patches import Polygon -from nose.tools import assert_raises, assert_equal from matplotlib.testing.decorators import image_comparison import matplotlib.pyplot as plt from matplotlib import transforms +import pytest def test_readonly_path(): @@ -19,7 +19,8 @@ def test_readonly_path(): def modify_vertices(): path.vertices = path.vertices * 2.0 - assert_raises(AttributeError, modify_vertices) + with pytest.raises(AttributeError): + modify_vertices() def test_point_in_path(): @@ -87,7 +88,7 @@ def test_make_compound_path_empty(): # We should be able to make a compound path with no arguments. # This makes it easier to write generic path based code. r = Path.make_compound_path() - assert_equal(r.vertices.shape, (0, 2)) + assert r.vertices.shape == (0, 2) @image_comparison(baseline_images=['xkcd'], remove_text=True) @@ -147,8 +148,3 @@ def test_path_no_doubled_point_in_to_polygon(): assert np.all(poly_clipped[-2] != poly_clipped[-1]) assert np.all(poly_clipped[-1] == poly_clipped[0]) - - -if __name__ == '__main__': - import nose - nose.runmodule(argv=['-s', '--with-doctest'], exit=False) diff --git a/lib/matplotlib/tests/test_patheffects.py b/lib/matplotlib/tests/test_patheffects.py index b8a068362316..5ad6bb218318 100644 --- a/lib/matplotlib/tests/test_patheffects.py +++ b/lib/matplotlib/tests/test_patheffects.py @@ -5,17 +5,16 @@ import numpy as np -from matplotlib.testing.decorators import (image_comparison, cleanup, - knownfailureif) +from matplotlib.testing.decorators import (image_comparison, cleanup) import matplotlib.pyplot as plt import matplotlib.patheffects as path_effects +import pytest try: # mock in python 3.3+ from unittest import mock except ImportError: import mock -from nose.tools import assert_equal @image_comparison(baseline_images=['patheffect1'], remove_text=True) @@ -85,7 +84,7 @@ def test_patheffect3(): @cleanup -@knownfailureif(True) +@pytest.mark.xfail(True, reason='Set to True for unknown reasons') def test_PathEffect_points_to_pixels(): fig = plt.figure(dpi=150) p1, = plt.plot(range(10)) @@ -101,13 +100,12 @@ def test_PathEffect_points_to_pixels(): # Confirm that using a path effects renderer maintains point sizes # appropriately. Otherwise rendered font would be the wrong size. - assert_equal(renderer.points_to_pixels(15), - pe_renderer.points_to_pixels(15)) + assert renderer.points_to_pixels(15) == pe_renderer.points_to_pixels(15) def test_SimplePatchShadow_offset(): pe = path_effects.SimplePatchShadow(offset=(4, 5)) - assert_equal(pe._offset, (4, 5)) + assert pe._offset == (4, 5) @image_comparison(baseline_images=['collection']) @@ -127,8 +125,3 @@ def test_collection(): linewidth=3)]) text.set_bbox({'boxstyle': 'sawtooth', 'facecolor': 'none', 'edgecolor': 'blue'}) - - -if __name__ == '__main__': - import nose - nose.runmodule(argv=['-s', '--with-doctest'], exit=False) diff --git a/lib/matplotlib/tests/test_pickle.py b/lib/matplotlib/tests/test_pickle.py index da2e7f699e90..a3f9a0c67c4c 100644 --- a/lib/matplotlib/tests/test_pickle.py +++ b/lib/matplotlib/tests/test_pickle.py @@ -7,10 +7,9 @@ from io import BytesIO -from nose.tools import assert_equal, assert_not_equal import numpy as np -from matplotlib.testing.decorators import cleanup, image_comparison +from matplotlib.testing.decorators import cleanup, image_comparison_2 import matplotlib.pyplot as plt import matplotlib.transforms as mtransforms @@ -127,8 +126,11 @@ def test_simple(): pickle.dump(fig, BytesIO(), pickle.HIGHEST_PROTOCOL) -@cleanup -@image_comparison(baseline_images=['multi_pickle'], +# cleanup is removed for this one test, because it makes pytest +# attempt to find tests in decorators.py, and generate an error at +# ImageComparisonTest.Test() +# @cleanup +@image_comparison_2(baseline_images=['multi_pickle'], extensions=['png'], remove_text=True) def test_complete(): fig = plt.figure('Figure with a label?', figsize=(10, 6)) @@ -184,16 +186,18 @@ def test_complete(): plt.close('all') # make doubly sure that there are no figures left - assert_equal(plt._pylab_helpers.Gcf.figs, {}) + assert plt._pylab_helpers.Gcf.figs == {} # wind back the fh and load in the figure result_fh.seek(0) fig = pickle.load(result_fh) # make sure there is now a figure manager - assert_not_equal(plt._pylab_helpers.Gcf.figs, {}) + # simply asserting 'not plt._pylab_helpers.Gcf.figs' resulted in + # a strange error + assert len(plt._pylab_helpers.Gcf.figs) > 0 - assert_equal(fig.get_label(), 'Figure with a label?') + assert fig.get_label() == 'Figure with a label?' @cleanup @@ -276,15 +280,9 @@ def test_transform(): obj = pickle.loads(pf) # Check parent -> child links of TransformWrapper. - assert_equal(obj.wrapper._child, obj.composite) + assert obj.wrapper._child == obj.composite # Check child -> parent links of TransformWrapper. - assert_equal( - [v() for v in obj.wrapper._parents.values()], [obj.composite2]) + assert [v() for v in obj.wrapper._parents.values()] == [obj.composite2] # Check input and output dimensions are set as expected. - assert_equal(obj.wrapper.input_dims, obj.composite.input_dims) - assert_equal(obj.wrapper.output_dims, obj.composite.output_dims) - - -if __name__ == '__main__': - import nose - nose.runmodule(argv=['-s']) + assert obj.wrapper.input_dims == obj.composite.input_dims + assert obj.wrapper.output_dims == obj.composite.output_dims diff --git a/lib/matplotlib/tests/test_quiver.py b/lib/matplotlib/tests/test_quiver.py index 21d96aa7d1c0..fac24cfef424 100644 --- a/lib/matplotlib/tests/test_quiver.py +++ b/lib/matplotlib/tests/test_quiver.py @@ -106,8 +106,3 @@ def test_quiver_key_pivot(): ax.quiverkey(q, 1, 0.5, 1, 'E', labelpos='E') ax.quiverkey(q, 0.5, 0, 1, 'S', labelpos='S') ax.quiverkey(q, 0, 0.5, 1, 'W', labelpos='W') - - -if __name__ == '__main__': - import nose - nose.runmodule() diff --git a/lib/matplotlib/tests/test_rcparams.py b/lib/matplotlib/tests/test_rcparams.py index bc39a50ed22f..70a469c00678 100644 --- a/lib/matplotlib/tests/test_rcparams.py +++ b/lib/matplotlib/tests/test_rcparams.py @@ -13,11 +13,8 @@ import matplotlib as mpl import matplotlib.pyplot as plt from matplotlib.tests import assert_str_equal -from matplotlib.testing.decorators import cleanup, knownfailureif +from matplotlib.testing.decorators import cleanup import matplotlib.colors as mcolors -from nose.tools import assert_true, assert_raises, assert_equal -from nose.plugins.skip import SkipTest -import nose from itertools import chain import numpy as np from matplotlib.rcsetup import (validate_bool_maybe_none, @@ -29,7 +26,7 @@ validate_cycler, validate_hatch, validate_hist_bins) - +import pytest mpl.rc('text', usetex=False) mpl.rc('lines', linewidth=22) @@ -116,12 +113,12 @@ def test_RcParams_class(): def test_rcparams_update(): if sys.version_info[:2] < (2, 7): - raise nose.SkipTest("assert_raises as context manager " + raise pytest.skip("assert_raises as context manager " "not supported with Python < 2.7") rc = mpl.RcParams({'figure.figsize': (3.5, 42)}) bad_dict = {'figure.figsize': (3.5, 42, 1)} # make sure validation happens on input - with assert_raises(ValueError): + with pytest.raises(ValueError): with warnings.catch_warnings(): warnings.filterwarnings('ignore', @@ -132,9 +129,9 @@ def test_rcparams_update(): def test_rcparams_init(): if sys.version_info[:2] < (2, 7): - raise nose.SkipTest("assert_raises as context manager " + raise pytest.skip("assert_raises as context manager " "not supported with Python < 2.7") - with assert_raises(ValueError): + with pytest.raises(ValueError): with warnings.catch_warnings(): warnings.filterwarnings('ignore', message='.*(validate)', @@ -164,13 +161,13 @@ def test_Bug_2543(): from copy import deepcopy _deep_copy = deepcopy(mpl.rcParams) # real test is that this does not raise - assert_true(validate_bool_maybe_none(None) is None) - assert_true(validate_bool_maybe_none("none") is None) + assert validate_bool_maybe_none(None) is None + assert validate_bool_maybe_none("none") is None _fonttype = mpl.rcParams['svg.fonttype'] - assert_true(_fonttype == mpl.rcParams['svg.embed_char_paths']) + assert _fonttype == mpl.rcParams['svg.embed_char_paths'] with mpl.rc_context(): mpl.rcParams['svg.embed_char_paths'] = False - assert_true(mpl.rcParams['svg.fonttype'] == "none") + assert mpl.rcParams['svg.fonttype'] == "none" @cleanup @@ -178,13 +175,14 @@ def test_Bug_2543_newer_python(): # only split from above because of the usage of assert_raises # as a context manager, which only works in 2.7 and above if sys.version_info[:2] < (2, 7): - raise nose.SkipTest("assert_raises as context manager not supported with Python < 2.7") + raise pytest.skip( + "assert_raises as context manager not supported with Python < 2.7") from matplotlib.rcsetup import validate_bool_maybe_none, validate_bool - with assert_raises(ValueError): + with pytest.raises(ValueError): validate_bool_maybe_none("blah") - with assert_raises(ValueError): + with pytest.raises(ValueError): validate_bool(None) - with assert_raises(ValueError): + with pytest.raises(ValueError): with mpl.rc_context(): mpl.rcParams['svg.fonttype'] = True @@ -195,7 +193,7 @@ def _legend_rcparam_helper(param_dict, target, get_func): _, ax = plt.subplots() ax.plot(range(3), label='test') leg = ax.legend() - assert_equal(getattr(leg.legendPatch, get_func)(), target) + assert getattr(leg.legendPatch, get_func)() == target def test_legend_facecolor(): @@ -248,19 +246,19 @@ def test_Issue_1713(): def _validation_test_helper(validator, arg, target): res = validator(arg) if isinstance(target, np.ndarray): - assert_true(np.all(res == target)) + assert np.all(res == target) elif not isinstance(target, Cycler): - assert_equal(res, target) + assert res == target else: # Cyclers can't simply be asserted equal. They don't implement __eq__ - assert_equal(list(res), list(target)) + assert list(res) == list(target) def _validation_fail_helper(validator, arg, exception_type): if sys.version_info[:2] < (2, 7): - raise nose.SkipTest("assert_raises as context manager not " + raise pytest.skip("assert_raises as context manager not " "supported with Python < 2.7") - with assert_raises(exception_type): + with pytest.raises(exception_type): validator(arg) @@ -400,18 +398,16 @@ def test_rcparams_reset_after_fail(): if sys.version_info[:2] >= (2, 7): from collections import OrderedDict else: - raise SkipTest("Test can only be run in Python >= 2.7 as it requires OrderedDict") + raise pytest.skip("Test can only be run in Python >= 2.7" + " as it requires OrderedDict") with mpl.rc_context(rc={'text.usetex': False}): assert mpl.rcParams['text.usetex'] is False - with assert_raises(KeyError): - with mpl.rc_context(rc=OrderedDict([('text.usetex', True),('test.blah', True)])): + with pytest.raises(KeyError): + with mpl.rc_context(rc=OrderedDict([('text.usetex', True), + ('test.blah', True)])): pass assert mpl.rcParams['text.usetex'] is False - - -if __name__ == '__main__': - nose.runmodule(argv=['-s', '--with-doctest'], exit=False) diff --git a/lib/matplotlib/tests/test_sankey.py b/lib/matplotlib/tests/test_sankey.py index bcb565d99496..7abe6e18f26b 100644 --- a/lib/matplotlib/tests/test_sankey.py +++ b/lib/matplotlib/tests/test_sankey.py @@ -10,8 +10,3 @@ def test_sankey(): # lets just create a sankey instance and check the code runs sankey = Sankey() sankey.add() - - -if __name__ == '__main__': - import nose - nose.runmodule(argv=['-s', '--with-doctest'], exit=False) diff --git a/lib/matplotlib/tests/test_simplification.py b/lib/matplotlib/tests/test_simplification.py index df16d0de3e5f..82c3e6be899f 100644 --- a/lib/matplotlib/tests/test_simplification.py +++ b/lib/matplotlib/tests/test_simplification.py @@ -5,14 +5,14 @@ import numpy as np import matplotlib -from matplotlib.testing.decorators import image_comparison, knownfailureif, cleanup +from matplotlib.testing.decorators import image_comparison, cleanup import matplotlib.pyplot as plt +import pytest -from pylab import * +import pylab import numpy as np from matplotlib import patches, path, transforms -from nose.tools import raises import io nan = np.nan @@ -21,16 +21,18 @@ # NOTE: All of these tests assume that path.simplify is set to True # (the default) + @image_comparison(baseline_images=['clipping'], remove_text=True) def test_clipping(): t = np.arange(0.0, 2.0, 0.01) - s = np.sin(2*pi*t) + s = np.sin(2*pylab.pi*t) fig = plt.figure() ax = fig.add_subplot(111) ax.plot(t, s, linewidth=1.0) ax.set_ylim((-0.20, -0.28)) + @image_comparison(baseline_images=['overflow'], remove_text=True) def test_overflow(): x = np.array([1.0,2.0,3.0,2.0e5]) @@ -41,6 +43,7 @@ def test_overflow(): ax.plot(x,y) ax.set_xlim(xmin=2,xmax=6) + @image_comparison(baseline_images=['clipping_diamond'], remove_text=True) def test_diamond(): x = np.array([0.0, 1.0, 0.0, -1.0, 0.0]) @@ -52,6 +55,7 @@ def test_diamond(): ax.set_xlim(xmin=-0.6, xmax=0.6) ax.set_ylim(ymin=-0.6, ymax=0.6) + @cleanup def test_noise(): np.random.seed(0) @@ -68,10 +72,12 @@ def test_noise(): assert len(simplified) == 3884 + @cleanup def test_sine_plus_noise(): np.random.seed(0) - x = np.sin(np.linspace(0, np.pi * 2.0, 1000)) + np.random.uniform(size=(1000,)) * 0.01 + x = np.sin(np.linspace(0, np.pi * 2.0, 1000)) + \ + np.random.uniform(size=(1000,)) * 0.01 fig = plt.figure() ax = fig.add_subplot(111) @@ -84,11 +90,14 @@ def test_sine_plus_noise(): assert len(simplified) == 876 + @image_comparison(baseline_images=['simplify_curve'], remove_text=True) def test_simplify_curve(): pp1 = patches.PathPatch( - Path([(0, 0), (1, 0), (1, 1), (nan, 1), (0, 0), (2, 0), (2, 2), (0, 0)], - [Path.MOVETO, Path.CURVE3, Path.CURVE3, Path.CURVE3, Path.CURVE3, Path.CURVE3, Path.CURVE3, Path.CLOSEPOLY]), + Path([(0, 0), (1, 0), (1, 1), (nan, 1), + (0, 0), (2, 0), (2, 2), (0, 0)], + [Path.MOVETO, Path.CURVE3, Path.CURVE3, Path.CURVE3, + Path.CURVE3, Path.CURVE3, Path.CURVE3, Path.CLOSEPOLY]), fc="none") fig = plt.figure() @@ -97,20 +106,23 @@ def test_simplify_curve(): ax.set_xlim((0, 2)) ax.set_ylim((0, 2)) + @image_comparison(baseline_images=['hatch_simplify'], remove_text=True) def test_hatch(): fig = plt.figure() ax = fig.add_subplot(111) - ax.add_patch(Rectangle((0, 0), 1, 1, fill=False, hatch="/")) + ax.add_patch(pylab.Rectangle((0, 0), 1, 1, fill=False, hatch="/")) ax.set_xlim((0.45, 0.55)) ax.set_ylim((0.45, 0.55)) + @image_comparison(baseline_images=['fft_peaks'], remove_text=True) def test_fft_peaks(): fig = plt.figure() - t = arange(65536) + t = pylab.arange(65536) ax = fig.add_subplot(111) - p1 = ax.plot(abs(fft(sin(2*pi*.01*t)*blackman(len(t))))) + p1 = ax.plot(abs(pylab.numpy.fft( + pylab.sin(2*pylab.pi*.01*t)*pylab.blackman(len(t))))) path = p1[0].get_path() transform = p1[0].get_transform() @@ -119,6 +131,7 @@ def test_fft_peaks(): assert len(simplified) == 20 + @cleanup def test_start_with_moveto(): # Should be entirely clipped away to a single MOVETO @@ -155,15 +168,17 @@ def test_start_with_moveto(): verts = np.fromstring(decodebytes(data), dtype='