From 4c39e5322e2cb85e0c8d45a061dcefa358a4489d Mon Sep 17 00:00:00 2001 From: Jason King Date: Sat, 31 Oct 2015 23:12:09 +1100 Subject: [PATCH 001/174] ENH: use pytest instead of nose. --- lib/matplotlib/tests/test_artist.py | 28 +- lib/matplotlib/tests/test_axes.py | 127 +++---- lib/matplotlib/tests/test_backend_bases.py | 6 +- lib/matplotlib/tests/test_cbook.py | 47 ++- lib/matplotlib/tests/test_colors.py | 30 +- lib/matplotlib/tests/test_figure.py | 57 ++-- lib/matplotlib/tests/test_lines.py | 18 +- lib/matplotlib/tests/test_mlab.py | 368 ++++++++++----------- lib/matplotlib/tests/test_offsetbox.py | 8 +- lib/matplotlib/tests/test_rcparams.py | 26 +- lib/matplotlib/tests/test_skew.py | 2 +- lib/matplotlib/tests/test_spines.py | 10 +- lib/matplotlib/tests/test_ticker.py | 42 +-- lib/matplotlib/tests/test_triangulation.py | 38 +-- tox.ini | 2 +- 15 files changed, 405 insertions(+), 404 deletions(-) diff --git a/lib/matplotlib/tests/test_artist.py b/lib/matplotlib/tests/test_artist.py index f4eb54ae07de..ae732cae0273 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 == True + assert ax.stale == True fig.canvas.draw() - assert_false(fig.stale) - assert_false(ax.stale) - assert_false(ln.stale) + assert fig.stale == False + assert ax.stale == False + assert ln.stale == False - 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 == True + assert ax.stale == True @image_comparison(baseline_images=["default_edges"], remove_text=True, diff --git a/lib/matplotlib/tests/test_axes.py b/lib/matplotlib/tests/test_axes.py index e3bfdaa8ce26..d8ff530555d9 100644 --- a/lib/matplotlib/tests/test_axes.py +++ b/lib/matplotlib/tests/test_axes.py @@ -6,7 +6,7 @@ from itertools import chain import io -from nose.tools import assert_equal, assert_raises, assert_false, assert_true +# from nose.tools import assert_equal, pytest.raises, assert_false, assert_true from nose.plugins.skip import SkipTest import datetime @@ -120,22 +120,22 @@ 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 ax2.xaxis.get_visible() == False + assert x2.patch.get_visible() == False ax2.cla() ax3.cla() - assert_false(ax2.xaxis.get_visible()) - assert_false(ax2.patch.get_visible()) - assert_true(ax2.yaxis.get_visible()) + assert ax2.xaxis.get_visible() == False + assert ax2.patch.get_visible() == False + assert ax2.yaxis.get_visible() == True - assert_true(ax3.xaxis.get_visible()) - assert_false(ax3.patch.get_visible()) - assert_false(ax3.yaxis.get_visible()) + assert ax3.xaxis.get_visible() == True + assert ax3.patch.get_visible() == False + assert ax3.yaxis.get_visible() == False - assert_true(ax.xaxis.get_visible()) - assert_true(ax.patch.get_visible()) - assert_true(ax.yaxis.get_visible()) + assert ax.xaxis.get_visible() == True + assert ax.patch.get_visible() == True + assert ax.yaxis.get_visible() == True @image_comparison(baseline_images=["minorticks_on_rcParams_both"], extensions=['png']) @@ -355,7 +355,7 @@ def test_shaped_data(): plt.plot(y2) plt.subplot(413) - assert_raises(ValueError, plt.plot, (y1, y2)) + pytest.raises(ValueError, plt.plot, (y1, y2)) plt.subplot(414) plt.plot(xdata[:, 1], xdata[1, :], 'o') @@ -401,7 +401,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 +426,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) == True @image_comparison(baseline_images=['polar_rmin']) @@ -844,11 +845,11 @@ 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], + pytest.raises(TypeError, ax.pcolormesh, y, x, Z) + pytest.raises(TypeError, ax.pcolormesh, X, Y, Z.T) + pytest.raises(TypeError, ax.pcolormesh, x, y, Z[:-1, :-1], shading="gouraud") - assert_raises(TypeError, ax.pcolormesh, X, Y, Z[:-1, :-1], + pytest.raises(TypeError, ax.pcolormesh, X, Y, Z[:-1, :-1], shading="gouraud") @@ -1725,7 +1726,7 @@ def test_bxp_bad_widths(): fig, ax = plt.subplots() ax.set_yscale('log') - assert_raises(ValueError, ax.bxp, logstats, widths=[1]) + pytest.raises(ValueError, ax.bxp, logstats, widths=[1]) @cleanup @@ -1737,7 +1738,7 @@ def test_bxp_bad_positions(): fig, ax = plt.subplots() ax.set_yscale('log') - assert_raises(ValueError, ax.bxp, logstats, positions=[2, 3]) + pytest.raises(ValueError, ax.bxp, logstats, positions=[2, 3]) @image_comparison(baseline_images=['boxplot', 'boxplot'], tol=1) @@ -1893,7 +1894,7 @@ 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]) + pytest.raises(ValueError, ax.boxplot, x, usermedians=[1, 2]) @cleanup @@ -1901,7 +1902,7 @@ 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]]) + pytest.raises(ValueError, ax.boxplot, [x, x], usermedians=[[1, 2], [1, 2]]) @cleanup @@ -1909,7 +1910,7 @@ 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], + pytest.raises(ValueError, ax.boxplot, [x, x], conf_intervals=[[1, 2]]) @@ -1918,7 +1919,7 @@ 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], + pytest.raises(ValueError, ax.boxplot, [x, x], conf_intervals=[[1, 2], [1]]) @@ -2102,7 +2103,7 @@ 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)) + pytest.raises(ValueError, ax.violinplot, data, positions=range(5)) @cleanup @@ -2111,7 +2112,7 @@ 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), + pytest.raises(ValueError, ax.violinplot, data, positions=range(4), widths=[1, 2, 3]) @@ -2194,9 +2195,9 @@ 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') + pytest.raises(ValueError, ax.errorbar, x, y, yerr=yerr, fmt='o') + pytest.raises(ValueError, ax.errorbar, x, y, xerr=xerr, fmt='o') + pytest.raises(ValueError, ax.errorbar, x, y, yerr=yerr, xerr=xerr, fmt='o') @image_comparison(baseline_images=['errorbar_limits']) @@ -2601,8 +2602,8 @@ 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) + assert len(w) == 3 + assert all(issubclass(wi.category, IgnoredKeywordWarning) for wi in w)) @@ -2744,7 +2745,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 +2992,15 @@ 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, + 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, + 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, + pytest.raises(ValueError, ax13.specgram, y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='twosided', mode='phase', scale='dB') @@ -3038,15 +3039,15 @@ 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, + 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, + 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, + pytest.raises(ValueError, ax13.specgram, y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='twosided', mode='phase', scale='dB') @@ -3093,15 +3094,15 @@ 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, + 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, + 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, + pytest.raises(ValueError, ax13.specgram, y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='twosided', mode='phase', scale='dB') @@ -3143,15 +3144,15 @@ def test_specgram_noise_phase(): pad_to=pad_to, sides='twosided', mode='phase', ) - assert_raises(ValueError, ax11.specgram, y, NFFT=NFFT, Fs=Fs, + 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, + 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, + pytest.raises(ValueError, ax13.specgram, y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='twosided', mode='phase', scale='dB') @@ -3915,17 +3916,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 +3946,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 +3961,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 +3992,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'], @@ -4052,11 +4053,11 @@ def test_rc_tick(): 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 +4068,15 @@ 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) == np.diff(ylim) == True + assert ax.get_aspect() == 'equal' == True @cleanup def test_no_None(): fig, ax = plt.subplots() - assert_raises(ValueError, plt.plot, None) - assert_raises(ValueError, plt.plot, None, None) + pytest.raises(ValueError, plt.plot, None) + pytest.raises(ValueError, plt.plot, None, None) @cleanup @@ -4097,15 +4098,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 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_cbook.py b/lib/matplotlib/tests/test_cbook.py index 1b11fe026120..28767841f53d 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 cbook.is_string_like(y) == False y.shape = 10, 1 - assert_equal(cbook.is_string_like(y), False) + assert cbook.is_string_like(y) == False y.shape = 1, 10 - assert_equal(cbook.is_string_like(y), False) + assert cbook.is_string_like(y) == False assert cbook.is_string_like("hello world") - assert_equal(cbook.is_string_like(10), False) + assert cbook.is_string_like(10) == False y = ['a', 'b', 'c'] - assert_equal(cbook.is_string_like(y), False) + assert cbook.is_string_like(y) == False y = np.array(y) - assert_equal(cbook.is_string_like(y), False) + assert cbook.is_string_like(y) == False y = np.array(y, dtype=object) assert cbook.is_string_like(y) @@ -50,17 +51,17 @@ 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): @@ -167,17 +168,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] @@ -370,14 +371,10 @@ 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)) + pytest.raise(ValueError, cbook._step_validation(np.arange(12).reshape(3, 4), 'a')) + pytest.raise(ValueError, cbook._step_validation(np.arange(12), 'a')) + pytest.raise(ValueError, cbook._step_validation(np.arange(12))) + pytest.raise(ValueError, cbook._step_validation(np.arange(12), np.arange(3))) def test_grouper(): diff --git a/lib/matplotlib/tests/test_colors.py b/lib/matplotlib/tests/test_colors.py index c9166a5a7db3..6e238de3e9cd 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 @@ -70,7 +70,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 +79,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 +88,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 +109,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 +134,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 +143,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 +281,7 @@ 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) + pytest.raise(ValueError, mcolors.from_levels_and_colors(levels, colors)) def test_rgb_hsv_round_trip(): @@ -311,8 +311,8 @@ 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) + pytest.raise(ValueError, gray_from_float_rgb()) + pytest.raise(ValueError, gray_from_float_rgba()) @image_comparison(baseline_images=['light_source_shading_topo'], diff --git a/lib/matplotlib/tests/test_figure.py b/lib/matplotlib/tests/test_figure.py index 631474c23287..36eb7bb89e5c 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 plt.fignum_exists('one') == False + assert plt.fignum_exists(4) == False @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(): diff --git a/lib/matplotlib/tests/test_lines.py b/lib/matplotlib/tests/test_lines.py index 775b02990add..7aaeae1a8b98 100644 --- a/lib/matplotlib/tests/test_lines.py +++ b/lib/matplotlib/tests/test_lines.py @@ -6,9 +6,11 @@ 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 +import pytest from timeit import repeat import numpy as np @@ -58,7 +60,7 @@ def test_invisible_Line_rendering(): slowdown_factor = (t_unvisible_line/t_no_line) slowdown_threshold = 2 # trying to avoid false positive failures - assert_true(slowdown_factor < slowdown_threshold) + assert slowdown_factor < slowdown_threshold @cleanup @@ -113,9 +115,8 @@ def test_valid_linestyles(): raise nose.SkipTest("assert_raises as context manager " "not supported with Python < 2.7") - line = mlines.Line2D([], []) - with assert_raises(ValueError): - line.set_linestyle('aardvark') + line = mpl.lines.Line2D([], []) + pytest.raise(ValueErrorline.set_linestyle('aardvark')) @image_comparison(baseline_images=['line_collection_dashes'], remove_text=True) @@ -156,10 +157,11 @@ def test_marker_fill_styles(): def test_nan_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])) + # Exercises issue from PR #2744 (NaN throwing warning in _is_sorted) + line = mpl.lines.Line2D([],[]) + 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]) if __name__ == '__main__': diff --git a/lib/matplotlib/tests/test_mlab.py b/lib/matplotlib/tests/test_mlab.py index c11f8ec450a0..d838eb06782c 100644 --- a/lib/matplotlib/tests/test_mlab.py +++ b/lib/matplotlib/tests/test_mlab.py @@ -8,8 +8,8 @@ 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 nose.tools import (assert_equal, assert_almost_equal, assert_not_equal, +# assert_true, assert_raises) import matplotlib.mlab as mlab import matplotlib.cbook as cbook @@ -34,11 +34,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 +88,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 +97,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,137 +123,137 @@ 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) + pytest.raise(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) + pytest.raise(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) + pytest.raise(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) + pytest.raise(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) + pytest.raise(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) + pytest.raise(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) + pytest.raise(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) + pytest.raise(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) + pytest.raise(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) + pytest.raise(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 (13, 6) == y.shape assert_true(self.get_base(y) is x) def test_stride_windows_n13_noverlapn3_axis1(self): @@ -262,8 +262,8 @@ def test_stride_windows_n13_noverlapn3_axis1(self): yt = self.calc_window_target(x, 13, -3).T assert_equal(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 +271,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 +280,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 +337,7 @@ 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) + pytest.raise(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 +399,25 @@ 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) + pytest.raise(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) + pytest.raise(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) + pytest.raise(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) + pytest.raise(ValueError, mlab.apply_window(x, window, axis=1, + return_window=False)) def test_apply_window_hanning_1D(self): x = self.sig_rand @@ -425,8 +425,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 +435,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 +445,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 +456,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 +468,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 +480,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 +491,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 +503,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 +515,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 +527,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 +538,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 +548,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 +625,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 +673,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 +1096,43 @@ 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') + pytest.raise(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) + pytest.raise(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) + pytest.raise(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) + pytest.raise(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) + pytest.raise(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) + pytest.raise(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) + pytest.raise(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) + pytest.raise(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) + pytest.raise(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) + pytest.raise(ValueError, mlab.demean(input, axis=2)) def test_detrend_linear_0D_zeros(self): input = 0. @@ -1196,7 +1196,7 @@ 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) + pytest.raise(ValueError, mlab.detrend_linear(input)) def test_detrend_str_linear_2d_slope_off_axis0(self): arri = [self.sig_off, @@ -1397,13 +1397,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 +1431,58 @@ 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') + pytest.raise(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') + pytest.raise(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') + pytest.raise(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') + pytest.raise(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') + pytest.raise(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') + pytest.raise(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) + pytest.raise(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) + pytest.raise(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)) + pytest.raise(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') + pytest.raise(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') + pytest.raise(ValueError, mlab._single_spectrum_helper( + x=self.y, mode='psd')) def test_spectral_helper_psd(self): freqs = self.freqs_density @@ -1497,8 +1497,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 +1513,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 +1529,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 +1541,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 +1551,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 +1587,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) + pytest.raise(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 +1623,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) + pytest.raise(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 +1659,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) + pytest.raise(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 +1695,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) + pytest.raise(AssertionError, + assert_allclose(spec_b, spec_c, atol=1e-08)) def test_psd_window_hanning(self): if self.NFFT_density is None: @@ -1739,8 +1739,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) + pytest.raise(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 +1788,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) + pytest.raise(AssertionError, + assert_allclose(spec_b, spec_c, atol=1e-08)) def test_psd_windowarray(self): freqs = self.freqs_density @@ -1801,7 +1801,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 +1844,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 +1852,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 +1863,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 +1872,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 +1887,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 +1911,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 +1935,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 +1957,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 +1975,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 +1997,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 +2014,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 @@ -2771,10 +2771,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') + pytest.raise(ValueError, mlab.griddata(x, y, z, xi[::-1], yi, + interp='nn')) + pytest.raise(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) @@ -2844,17 +2844,17 @@ 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, []) + pytest.raise(ValueError, mlab.GaussianKDE,([])) def test_single_dataset_element(self): """Pass a single dataset element into the GaussianKDE class.""" - assert_raises(ValueError, mlab.GaussianKDE, [42]) + pytest.raise(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") + pytest.raise(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 +2868,7 @@ 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") + pytest.raise(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 +2881,7 @@ 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) + pytest.raise(ValueError, mlab.GaussianKDE([], bw_method=5)) def test_scalar_covariance_dataset(self): """Use a dataset and test a scalar's cov factor @@ -2891,7 +2891,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 +2903,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 +2921,7 @@ 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") + pytest.raise(ValueError, mlab.GaussianKDE(data, bw_method="invalid")) class gaussian_kde_evaluate_tests(object): @@ -2947,7 +2947,7 @@ 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) + pytest.raise(ValueError, kde.evaluate(x2)) def test_evaluate_dim_and_num(self): """ Tests if evaluated against a one by one array""" @@ -2963,7 +2963,7 @@ 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) + pytest.raise(ValueError, kde.evaluate(x2)) def test_evaluate_equal_dim_and_num_lt(self): """Test when line 3810 fails""" @@ -2980,22 +2980,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(): diff --git a/lib/matplotlib/tests/test_offsetbox.py b/lib/matplotlib/tests/test_offsetbox.py index 0b6bfea3adeb..57496b7a856d 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,9 @@ 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) + assert fig.stale if __name__ == '__main__': nose.runmodule(argv=['-s', '--with-doctest'], exit=False) diff --git a/lib/matplotlib/tests/test_rcparams.py b/lib/matplotlib/tests/test_rcparams.py index bc39a50ed22f..754933db85f2 100644 --- a/lib/matplotlib/tests/test_rcparams.py +++ b/lib/matplotlib/tests/test_rcparams.py @@ -15,9 +15,9 @@ from matplotlib.tests import assert_str_equal from matplotlib.testing.decorators import cleanup, knownfailureif import matplotlib.colors as mcolors -from nose.tools import assert_true, assert_raises, assert_equal -from nose.plugins.skip import SkipTest -import nose +# 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, @@ -164,13 +164,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 @@ -195,7 +195,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,20 +248,20 @@ 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 " "supported with Python < 2.7") - with assert_raises(exception_type): - validator(arg) + ptest.raise(exception_type,validator(arg)) + def test_validators(): diff --git a/lib/matplotlib/tests/test_skew.py b/lib/matplotlib/tests/test_skew.py index fd72cadba90a..3ccc150896df 100644 --- a/lib/matplotlib/tests/test_skew.py +++ b/lib/matplotlib/tests/test_skew.py @@ -7,7 +7,7 @@ import itertools from matplotlib.externals import six -from nose.tools import assert_true +# from nose.tools import assert_true import numpy as np import matplotlib.pyplot as plt from matplotlib.testing.decorators import cleanup, image_comparison diff --git a/lib/matplotlib/tests/test_spines.py b/lib/matplotlib/tests/test_spines.py index 2f6a9a3084cc..3c436ce3ef0f 100644 --- a/lib/matplotlib/tests/test_spines.py +++ b/lib/matplotlib/tests/test_spines.py @@ -2,7 +2,7 @@ unicode_literals) import numpy as np -from nose.tools import assert_true, assert_less +# from nose.tools import assert_true from matplotlib.externals import six import matplotlib @@ -71,11 +71,11 @@ def test_label_without_ticks(): spine = ax.spines['left'] spinebbox = spine.get_transform().transform_path( spine.get_path()).get_extents() - assert_less(ax.yaxis.label.get_position()[0], spinebbox.xmin, - "Y-Axis label not left of the spine") + assert (ax.yaxis.label.get_position()[0] < spinebbox.xmin, + "Y-Axis label not left of the spine") spine = ax.spines['bottom'] spinebbox = spine.get_transform().transform_path( spine.get_path()).get_extents() - assert_less(ax.xaxis.label.get_position()[1], spinebbox.ymin, - "X-Axis label not below the spine") + assert (ax.xaxis.label.get_position()[1] < spinebbox.ymin, + "X-Axis label not below the spine") diff --git a/lib/matplotlib/tests/test_ticker.py b/lib/matplotlib/tests/test_ticker.py index 438be20aa7ce..80f50ba6fb16 100644 --- a/lib/matplotlib/tests/test_ticker.py +++ b/lib/matplotlib/tests/test_ticker.py @@ -2,8 +2,8 @@ unicode_literals) from matplotlib.externals import six -import nose.tools -from nose.tools import assert_raises +# import nose.tools +# from nose.tools import assert_raises from numpy.testing import assert_almost_equal import numpy as np import matplotlib @@ -52,7 +52,7 @@ def test_AutoMinorLocator(): def test_LogLocator(): loc = mticker.LogLocator(numticks=5) - assert_raises(ValueError, loc.tick_values, 0, 1000) + pytest.raise(ValueError, loc.tick_values(0, 1000)) test_value = np.array([1.00000000e-05, 1.00000000e-03, 1.00000000e-01, 1.00000000e+01, 1.00000000e+03, 1.00000000e+05, @@ -71,8 +71,8 @@ def test_LinearLocator_set_params(): """ loc = mticker.LinearLocator(numticks=2) loc.set_params(numticks=8, presets={(0, 1): []}) - nose.tools.assert_equal(loc.numticks, 8) - nose.tools.assert_equal(loc.presets, {(0, 1): []}) + assert loc.numticks == 8 + assert loc.presets == {(0, 1): []} def test_LogLocator_set_params(): @@ -84,10 +84,10 @@ def test_LogLocator_set_params(): """ loc = mticker.LogLocator() loc.set_params(numticks=8, numdecs=8, subs=[2.0], base=8) - nose.tools.assert_equal(loc.numticks, 8) - nose.tools.assert_equal(loc.numdecs, 8) - nose.tools.assert_equal(loc.base, 8) - nose.tools.assert_equal(loc.subs, [2.0]) + assert loc.numticks == 8 + assert loc.numdecs == 8 + assert loc.base == 8 + assert loc.subs == [2.0] def test_NullLocator_set_params(): @@ -98,7 +98,7 @@ def test_NullLocator_set_params(): loc = mticker.NullLocator() with warnings.catch_warnings(record=True) as w: loc.set_params() - nose.tools.assert_equal(len(w), 1) + assert len(w) == 1 def test_MultipleLocator_set_params(): @@ -109,7 +109,7 @@ def test_MultipleLocator_set_params(): """ mult = mticker.MultipleLocator(base=0.7) mult.set_params(base=1.7) - nose.tools.assert_equal(mult._base, 1.7) + assert mult._base == 1.7 def test_LogitLocator_set_params(): @@ -119,7 +119,7 @@ def test_LogitLocator_set_params(): """ loc = mticker.LogitLocator() # Defaults to false. loc.set_params(minor=True) - nose.tools.assert_true(loc.minor) + assert loc.minor def test_FixedLocator_set_params(): @@ -130,7 +130,7 @@ def test_FixedLocator_set_params(): """ fixed = mticker.FixedLocator(range(0, 24), nbins=5) fixed.set_params(nbins=7) - nose.tools.assert_equal(fixed.nbins, 7) + assert fixed.nbins == 7 def test_IndexLocator_set_params(): @@ -141,8 +141,8 @@ def test_IndexLocator_set_params(): """ index = mticker.IndexLocator(base=3, offset=4) index.set_params(base=7, offset=7) - nose.tools.assert_equal(index._base, 7) - nose.tools.assert_equal(index.offset, 7) + assert index._base == 7 + assert index.offset == 7 def test_SymmetricalLogLocator_set_params(): @@ -155,8 +155,8 @@ def test_SymmetricalLogLocator_set_params(): # since we only test for the params change. I will pass empty transform sym = mticker.SymmetricalLogLocator(None) sym.set_params(subs=[2.0], numticks=8) - nose.tools.assert_equal(sym._subs, [2.0]) - nose.tools.assert_equal(sym.numticks, 8) + assert sym._subs == [2.0] + assert sym.numticks == 8 def _logfe_helper(formatter, base, locs, i, expected_result): @@ -185,7 +185,7 @@ def get_view_interval(self): # Should be a blank string for non-integer powers if labelOnlyBase=True formatter = mticker.LogFormatterExponent(base=10, labelOnlyBase=True) formatter.axis = FakeAxis() - nose.tools.assert_equal(formatter(10**0.1), '') + assert formatter(10**0.1) == '' # Otherwise, non-integer powers should be nicely formatted locs = np.array([0.1, 0.00001, np.pi, 0.2, -0.2, -0.00001]) @@ -354,17 +354,17 @@ def test_use_offset(): for use_offset in [True, False]: with matplotlib.rc_context({'axes.formatter.useoffset': use_offset}): tmp_form = mticker.ScalarFormatter() - nose.tools.assert_equal(use_offset, tmp_form.get_useOffset()) + assert use_offset == tmp_form.get_useOffset() def test_formatstrformatter(): # test % style formatter tmp_form = mticker.FormatStrFormatter('%05d') - nose.tools.assert_equal('00002', tmp_form(2)) + assert '00002' == tmp_form(2) # test str.format() style formatter tmp_form = mticker.StrMethodFormatter('{x:05d}') - nose.tools.assert_equal('00002', tmp_form(2)) + assert '00002' == tmp_form(2) if __name__ == '__main__': import nose diff --git a/lib/matplotlib/tests/test_triangulation.py b/lib/matplotlib/tests/test_triangulation.py index 966990373434..26239970169f 100644 --- a/lib/matplotlib/tests/test_triangulation.py +++ b/lib/matplotlib/tests/test_triangulation.py @@ -6,7 +6,7 @@ import numpy as np import matplotlib.pyplot as plt import matplotlib.tri as mtri -from nose.tools import assert_equal, assert_raises, assert_true, assert_false +# from nose.tools import assert_equal, assert_raises, assert_true, assert_false from numpy.testing import assert_array_equal, assert_array_almost_equal,\ assert_array_less import numpy.ma.testutils as matest @@ -37,14 +37,14 @@ def test_delaunay(): assert_array_almost_equal(triang.y, y) # Triangles - integers. - assert_equal(len(triang.triangles), ntriangles) - assert_equal(np.min(triang.triangles), 0) - assert_equal(np.max(triang.triangles), npoints-1) + assert len(triang.triangles) == ntriangles + assert np.min(triang.triangles) == 0 + assert np.max(triang.triangles) == npoints-1 # Edges - integers. - assert_equal(len(triang.edges), nedges) - assert_equal(np.min(triang.edges), 0) - assert_equal(np.max(triang.edges), npoints-1) + assert len(triang.edges) == nedges + assert np.min(triang.edges) == 0 + assert np.max(triang.edges) == npoints-1 # Neighbors - integers. # Check that neighbors calculated by C++ triangulation class are the same @@ -84,7 +84,7 @@ def test_delaunay_points_in_line(): # that delaunay code fails gracefully. x = np.linspace(0.0, 10.0, 11) y = np.linspace(0.0, 10.0, 11) - assert_raises(RuntimeError, mtri.Triangulation, x, y) + pytest.raise(RuntimeError, mtri.Triangulation(x, y)) # Add an extra point not on the line and the triangulation is OK. x = np.append(x, 2.0) @@ -94,16 +94,16 @@ def test_delaunay_points_in_line(): def test_delaunay_insufficient_points(): # Triangulation should raise a ValueError if passed less than 3 points. - assert_raises(ValueError, mtri.Triangulation, [], []) - assert_raises(ValueError, mtri.Triangulation, [1], [5]) - assert_raises(ValueError, mtri.Triangulation, [1, 2], [5, 6]) + pytest.raise(ValueError, mtri.Triangulation([], [])) + pytest.raise(ValueError, mtri.Triangulation([1], [5])) + pytest.raise(ValueError, mtri.Triangulation([1, 2], [5, 6])) # Triangulation should also raise a ValueError if passed duplicate points # such that there are less than 3 unique points. - assert_raises(ValueError, mtri.Triangulation, [1, 2, 1], [5, 6, 5]) - assert_raises(ValueError, mtri.Triangulation, [1, 2, 2], [5, 6, 6]) - assert_raises(ValueError, mtri.Triangulation, [1, 1, 1, 2, 1, 2], - [5, 5, 5, 6, 5, 6]) + pytest.raise(ValueError, mtri.Triangulation([1, 2, 1], [5, 6, 5])) + pytest.raise(ValueError, mtri.Triangulation([1, 2, 2], [5, 6, 6])) + pytest.raise(ValueError, mtri.Triangulation([1, 1, 1, 2, 1, 2], + [5, 5, 5, 6, 5, 6])) def test_delaunay_robust(): @@ -147,7 +147,7 @@ def tris_contain_point(triang, xy): # overlapping triangles; qhull is OK. triang = mtri.Triangulation(tri_points[:, 0], tri_points[:, 1]) for test_point in test_points: - assert_equal(tris_contain_point(triang, test_point), 1) + assert tris_contain_point(triang, test_point) == 1 # If ignore the first point of tri_points, matplotlib.delaunay throws a # KeyError when calculating the convex hull; qhull is OK. @@ -281,7 +281,7 @@ def test_trifinder(): assert_array_equal(tris, [-1, 0, 1, -1]) triang.set_mask([1, 0]) - assert_equal(trifinder, triang.get_trifinder()) + assert trifinder == triang.get_trifinder() tris = trifinder(xs, ys) assert_array_equal(tris, [-1, -1, 1, -1]) @@ -966,10 +966,10 @@ def test_trirefiner_fortran_contiguous_triangles(): # github issue 4180. Test requires two arrays of triangles that are # identical except that one is C-contiguous and one is fortran-contiguous. triangles1 = np.array([[2, 0, 3], [2, 1, 0]]) - assert_false(np.isfortran(triangles1)) + assert not np.isfortran(triangles1) triangles2 = np.array(triangles1, copy=True, order='F') - assert_true(np.isfortran(triangles2)) + assert np.isfortran(triangles2) x = np.array([0.39, 0.59, 0.43, 0.32]) y = np.array([33.99, 34.01, 34.19, 34.18]) diff --git a/tox.ini b/tox.ini index 296cefb56281..97af758fa7ac 100644 --- a/tox.ini +++ b/tox.ini @@ -12,6 +12,6 @@ commands = sh -c 'rm -f $HOME/.matplotlib/fontList*' {envpython} {toxinidir}/tests.py --processes=-1 --process-timeout=300 deps = - nose + pytest mock numpy From f10a36ba9c62538485e595d6df365a785407563f Mon Sep 17 00:00:00 2001 From: Jason King Date: Wed, 4 Nov 2015 21:44:58 +1100 Subject: [PATCH 002/174] pytest.raises(), not pytest.raise() --- lib/matplotlib/tests/test_cbook.py | 8 +- lib/matplotlib/tests/test_colors.py | 6 +- lib/matplotlib/tests/test_lines.py | 2 +- lib/matplotlib/tests/test_mlab.py | 106 ++++++++++----------- lib/matplotlib/tests/test_ticker.py | 2 +- lib/matplotlib/tests/test_triangulation.py | 14 +-- 6 files changed, 69 insertions(+), 69 deletions(-) diff --git a/lib/matplotlib/tests/test_cbook.py b/lib/matplotlib/tests/test_cbook.py index 28767841f53d..c3bc786c6f08 100644 --- a/lib/matplotlib/tests/test_cbook.py +++ b/lib/matplotlib/tests/test_cbook.py @@ -371,10 +371,10 @@ def test_to_midstep(): def test_step_fails(): - pytest.raise(ValueError, cbook._step_validation(np.arange(12).reshape(3, 4), 'a')) - pytest.raise(ValueError, cbook._step_validation(np.arange(12), 'a')) - pytest.raise(ValueError, cbook._step_validation(np.arange(12))) - pytest.raise(ValueError, cbook._step_validation(np.arange(12), np.arange(3))) + pytest.raises(ValueError, cbook._step_validation(np.arange(12).reshape(3, 4), 'a')) + pytest.raises(ValueError, cbook._step_validation(np.arange(12), 'a')) + pytest.raises(ValueError, cbook._step_validation(np.arange(12))) + pytest.raises(ValueError, cbook._step_validation(np.arange(12), np.arange(3))) def test_grouper(): diff --git a/lib/matplotlib/tests/test_colors.py b/lib/matplotlib/tests/test_colors.py index 6e238de3e9cd..6cbbe4125a0c 100644 --- a/lib/matplotlib/tests/test_colors.py +++ b/lib/matplotlib/tests/test_colors.py @@ -281,7 +281,7 @@ def test_cmap_and_norm_from_levels_and_colors2(): 'Wih extend={0!r} and data ' 'value={1!r}'.format(extend, d_val)) - pytest.raise(ValueError, mcolors.from_levels_and_colors(levels, colors)) + pytest.raises(ValueError, mcolors.from_levels_and_colors(levels, colors)) def test_rgb_hsv_round_trip(): @@ -311,8 +311,8 @@ def gray_from_float_rgb(): def gray_from_float_rgba(): return mcolors.colorConverter.to_rgba(0.4) - pytest.raise(ValueError, gray_from_float_rgb()) - pytest.raise(ValueError, gray_from_float_rgba()) + pytest.raises(ValueError, gray_from_float_rgb()) + pytest.raises(ValueError, gray_from_float_rgba()) @image_comparison(baseline_images=['light_source_shading_topo'], diff --git a/lib/matplotlib/tests/test_lines.py b/lib/matplotlib/tests/test_lines.py index 7aaeae1a8b98..268fde346f2f 100644 --- a/lib/matplotlib/tests/test_lines.py +++ b/lib/matplotlib/tests/test_lines.py @@ -116,7 +116,7 @@ def test_valid_linestyles(): "not supported with Python < 2.7") line = mpl.lines.Line2D([], []) - pytest.raise(ValueErrorline.set_linestyle('aardvark')) + pytest.raises(ValueErrorline.set_linestyle('aardvark')) @image_comparison(baseline_images=['line_collection_dashes'], remove_text=True) diff --git a/lib/matplotlib/tests/test_mlab.py b/lib/matplotlib/tests/test_mlab.py index d838eb06782c..0139ba77edce 100644 --- a/lib/matplotlib/tests/test_mlab.py +++ b/lib/matplotlib/tests/test_mlab.py @@ -123,43 +123,43 @@ def calc_window_target(self, x, NFFT, noverlap=0): def test_stride_windows_2D_ValueError(self): x = np.arange(10)[np.newaxis] - pytest.raise(ValueError, mlab.stride_windows( x, 5)) + pytest.raises(ValueError, mlab.stride_windows( x, 5)) def test_stride_windows_0D_ValueError(self): x = np.array(0) - pytest.raise(ValueError, mlab.stride_windows( x, 5)) + pytest.raises(ValueError, mlab.stride_windows( x, 5)) def test_stride_windows_noverlap_gt_n_ValueError(self): x = np.arange(10) - pytest.raise(ValueError, mlab.stride_windows(x, 2, 3) + pytest.raises(ValueError, mlab.stride_windows(x, 2, 3) def test_stride_windows_noverlap_eq_n_ValueError(self): x = np.arange(10) - pytest.raise(ValueError, mlab.stride_windows(x, 2, 2)) + pytest.raises(ValueError, mlab.stride_windows(x, 2, 2)) def test_stride_windows_n_gt_lenx_ValueError(self): x = np.arange(10) - pytest.raise(ValueError, mlab.stride_windows(x, 11)) + pytest.raises(ValueError, mlab.stride_windows(x, 11)) def test_stride_windows_n_lt_1_ValueError(self): x = np.arange(10) - pytest.raise(ValueError, mlab.stride_windows(x, 0)) + pytest.raises(ValueError, mlab.stride_windows(x, 0)) def test_stride_repeat_2D_ValueError(self): x = np.arange(10)[np.newaxis] - pytest.raise(ValueError, mlab.stride_repeat(x, 5)) + pytest.raises(ValueError, mlab.stride_repeat(x, 5)) def test_stride_repeat_axis_lt_0_ValueError(self): x = np.array(0) - pytest.raise(ValueError, mlab.stride_repeat(x, 5, axis=-1)) + pytest.raises(ValueError, mlab.stride_repeat(x, 5, axis=-1)) def test_stride_repeat_axis_gt_1_ValueError(self): x = np.array(0) - pytest.raise(ValueError, mlab.stride_repeat(x, 5, axis=2)) + pytest.raises(ValueError, mlab.stride_repeat(x, 5, axis=2)) def test_stride_repeat_n_lt_1_ValueError(self): x = np.arange(10) - pytest.raise(ValueError, mlab.stride_repeat(x, 0)) + pytest.raises(ValueError, mlab.stride_repeat(x, 0)) def test_stride_repeat_n1_axis0(self): x = np.arange(10) @@ -337,7 +337,7 @@ def test_rec2csv_bad_shape_ValueError(self): (str('y'), np.float)]) # the bad recarray should trigger a ValueError for having ndim > 1. - pytest.raise(ValueError, mlab.rec2csv( bad, self.fd)) + 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,24 +399,24 @@ def test_window_hanning_ones(self): def test_apply_window_1D_axis1_ValueError(self): x = self.sig_rand window = mlab.window_hanning - pytest.raise(ValueError, mlab.apply_window( x, window, axis=1, + 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)) - pytest.raise(ValueError, mlab.apply_window(x, window)) + pytest.raises(ValueError, mlab.apply_window(x, window)) def test_apply_window_0D_ValueError(self): x = np.array(0) window = mlab.window_hanning - pytest.raise(ValueError, mlab.apply_window(x, window, axis=1, + 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 - pytest.raise(ValueError, mlab.apply_window(x, window, axis=1, + pytest.raises(ValueError, mlab.apply_window(x, window, axis=1, return_window=False)) def test_apply_window_hanning_1D(self): @@ -1096,43 +1096,43 @@ def test_demean_2D_axism1(self): def test_detrend_bad_key_str_ValueError(self): input = self.sig_slope[np.newaxis] - pytest.raise(ValueError, mlab.detrend(input, key='spam')) + pytest.raises(ValueError, mlab.detrend(input, key='spam')) def test_detrend_bad_key_var_ValueError(self): input = self.sig_slope[np.newaxis] - pytest.raise(ValueError, mlab.detrend(input, key=5)) + pytest.raises(ValueError, mlab.detrend(input, key=5)) def test_detrend_mean_0D_d0_ValueError(self): input = 5.5 - pytest.raise(ValueError, mlab.detrend_mean(input, axis=0)) + pytest.raises(ValueError, mlab.detrend_mean(input, axis=0)) def test_detrend_0D_d0_ValueError(self): input = 5.5 - pytest.raise(ValueError, mlab.detrend(input, axis=0)) + pytest.raises(ValueError, mlab.detrend(input, axis=0)) def test_detrend_mean_1D_d1_ValueError(self): input = self.sig_slope - pytest.raise(ValueError, mlab.detrend_mean(input, axis=1)) + pytest.raises(ValueError, mlab.detrend_mean(input, axis=1)) def test_detrend_1D_d1_ValueError(self): input = self.sig_slope - pytest.raise(ValueError, mlab.detrend(input, axis=1)) + pytest.raises(ValueError, mlab.detrend(input, axis=1)) def test_demean_1D_d1_ValueError(self): input = self.sig_slope - pytest.raise(ValueError, mlab.demean(input, axis=1)) + pytest.raises(ValueError, mlab.demean(input, axis=1)) def test_detrend_mean_2D_d2_ValueError(self): input = self.sig_slope[np.newaxis] - pytest.raise(ValueError, mlab.detrend_mean(input, axis=2)) + pytest.raises(ValueError, mlab.detrend_mean(input, axis=2)) def test_detrend_2D_d2_ValueError(self): input = self.sig_slope[np.newaxis] - pytest.raise(ValueError, mlab.detrend(input, axis=2)) + pytest.raises(ValueError, mlab.detrend(input, axis=2)) def test_demean_2D_d2_ValueError(self): input = self.sig_slope[np.newaxis] - pytest.raise(ValueError, mlab.demean(input, axis=2)) + pytest.raises(ValueError, mlab.demean(input, axis=2)) def test_detrend_linear_0D_zeros(self): input = 0. @@ -1196,7 +1196,7 @@ def test_detrend_linear_1d_slope_off_list(self): def test_detrend_linear_2D_ValueError(self): input = self.sig_slope[np.newaxis] - pytest.raise(ValueError, mlab.detrend_linear(input)) + pytest.raises(ValueError, mlab.detrend_linear(input)) def test_detrend_str_linear_2d_slope_off_axis0(self): arri = [self.sig_off, @@ -1431,57 +1431,57 @@ 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 - pytest.raise(ValueError, mlab._spectral_helper( + 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 - pytest.raise(ValueError, mlab._spectral_helper( + 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 - pytest.raise(ValueError, mlab._spectral_helper( + 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 - pytest.raise(ValueError, mlab._spectral_helper( + 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 - pytest.raise(ValueError, mlab._spectral_helper( + 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 - pytest.raise(ValueError, mlab._spectral_helper( + 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 - pytest.raise(ValueError, mlab._spectral_helper( + 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 - pytest.raise(ValueError, mlab._spectral_helper( + 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 - pytest.raise(ValueError, mlab._spectral_helper( + 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 - pytest.raise(ValueError, mlab._single_spectrum_helper( + 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 - pytest.raise(ValueError, mlab._single_spectrum_helper( + pytest.raises(ValueError, mlab._single_spectrum_helper( x=self.y, mode='psd')) def test_spectral_helper_psd(self): @@ -1587,7 +1587,7 @@ 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 - pytest.raise(AssertionError, + pytest.raises(AssertionError, assert_allclose(spec_b, spec_c, atol=1e-08)) def test_psd_detrend_mean_str_offset(self): @@ -1623,7 +1623,7 @@ 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 - pytest.raise(AssertionError, + pytest.raises(AssertionError, assert_allclose(spec_b, spec_c, atol=1e-08)) def test_psd_detrend_linear_func_trend(self): @@ -1659,7 +1659,7 @@ 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 - pytest.raise(AssertionError, + pytest.raises(AssertionError, assert_allclose(spec_b, spec_c, atol=1e-08)) def test_psd_detrend_linear_str_trend(self): @@ -1695,7 +1695,7 @@ 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 - pytest.raise(AssertionError, + pytest.raises(AssertionError, assert_allclose(spec_b, spec_c, atol=1e-08)) def test_psd_window_hanning(self): @@ -1739,7 +1739,7 @@ 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 - pytest.raise(AssertionError, + pytest.raises(AssertionError, assert_allclose(spec_b, spec_c, atol=1e-08)) def test_psd_window_hanning_detrend_linear(self): @@ -1788,7 +1788,7 @@ 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 - pytest.raise(AssertionError, + pytest.raises(AssertionError, assert_allclose(spec_b, spec_c, atol=1e-08)) def test_psd_windowarray(self): @@ -2771,9 +2771,9 @@ def get_z(x, y): np.testing.assert_array_almost_equal(zi, correct_zi, 5) # Decreasing xi or yi should raise ValueError. - pytest.raise(ValueError, mlab.griddata(x, y, z, xi[::-1], yi, + pytest.raises(ValueError, mlab.griddata(x, y, z, xi[::-1], yi, interp='nn')) - pytest.raise(ValueError, mlab.griddata(x, y, z, xi, yi[::-1], + pytest.raises(ValueError, mlab.griddata(x, y, z, xi, yi[::-1], interp='nn')) # Passing 2D xi and yi arrays to griddata. @@ -2844,17 +2844,17 @@ def test_kde_bandwidth_method(self): class gaussian_kde_custom_tests(object): def test_no_data(self): """Pass no data into the GaussianKDE class.""" - pytest.raise(ValueError, mlab.GaussianKDE,([])) + pytest.raises(ValueError, mlab.GaussianKDE,([])) def test_single_dataset_element(self): """Pass a single dataset element into the GaussianKDE class.""" - pytest.raise(ValueError, mlab.GaussianKDE([42])) + 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]]) - pytest.raise(np.linalg.LinAlgError, mlab.GaussianKDE(x1, "silverman")) + 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 +2868,7 @@ 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]]) - pytest.raise(np.linalg.LinAlgError, mlab.GaussianKDE(x1, "scott")) + 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 +2881,7 @@ 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 """ - pytest.raise(ValueError, mlab.GaussianKDE([], bw_method=5)) + pytest.raises(ValueError, mlab.GaussianKDE([], bw_method=5)) def test_scalar_covariance_dataset(self): """Use a dataset and test a scalar's cov factor @@ -2921,7 +2921,7 @@ def test_wrong_bw_method(self): np.random.seed(8765678) n_basesample = 50 data = np.random.randn(n_basesample) - pytest.raise(ValueError, mlab.GaussianKDE(data, bw_method="invalid")) + pytest.raises(ValueError, mlab.GaussianKDE(data, bw_method="invalid")) class gaussian_kde_evaluate_tests(object): @@ -2947,7 +2947,7 @@ def test_evaluate_inv_dim(self): multidim_data = np.random.randn(n_basesample) kde = mlab.GaussianKDE(multidim_data) x2 = [[1], [2], [3]] - pytest.raise(ValueError, kde.evaluate(x2)) + pytest.raises(ValueError, kde.evaluate(x2)) def test_evaluate_dim_and_num(self): """ Tests if evaluated against a one by one array""" @@ -2963,7 +2963,7 @@ 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) - pytest.raise(ValueError, kde.evaluate(x2)) + pytest.raises(ValueError, kde.evaluate(x2)) def test_evaluate_equal_dim_and_num_lt(self): """Test when line 3810 fails""" diff --git a/lib/matplotlib/tests/test_ticker.py b/lib/matplotlib/tests/test_ticker.py index 80f50ba6fb16..578c73e640cf 100644 --- a/lib/matplotlib/tests/test_ticker.py +++ b/lib/matplotlib/tests/test_ticker.py @@ -52,7 +52,7 @@ def test_AutoMinorLocator(): def test_LogLocator(): loc = mticker.LogLocator(numticks=5) - pytest.raise(ValueError, loc.tick_values(0, 1000)) + pytest.raises(ValueError, loc.tick_values(0, 1000)) test_value = np.array([1.00000000e-05, 1.00000000e-03, 1.00000000e-01, 1.00000000e+01, 1.00000000e+03, 1.00000000e+05, diff --git a/lib/matplotlib/tests/test_triangulation.py b/lib/matplotlib/tests/test_triangulation.py index 26239970169f..1c08228fd907 100644 --- a/lib/matplotlib/tests/test_triangulation.py +++ b/lib/matplotlib/tests/test_triangulation.py @@ -84,7 +84,7 @@ def test_delaunay_points_in_line(): # that delaunay code fails gracefully. x = np.linspace(0.0, 10.0, 11) y = np.linspace(0.0, 10.0, 11) - pytest.raise(RuntimeError, mtri.Triangulation(x, y)) + pytest.raises(RuntimeError, mtri.Triangulation(x, y)) # Add an extra point not on the line and the triangulation is OK. x = np.append(x, 2.0) @@ -94,15 +94,15 @@ def test_delaunay_points_in_line(): def test_delaunay_insufficient_points(): # Triangulation should raise a ValueError if passed less than 3 points. - pytest.raise(ValueError, mtri.Triangulation([], [])) - pytest.raise(ValueError, mtri.Triangulation([1], [5])) - pytest.raise(ValueError, mtri.Triangulation([1, 2], [5, 6])) + pytest.raises(ValueError, mtri.Triangulation([], [])) + pytest.raises(ValueError, mtri.Triangulation([1], [5])) + pytest.raises(ValueError, mtri.Triangulation([1, 2], [5, 6])) # Triangulation should also raise a ValueError if passed duplicate points # such that there are less than 3 unique points. - pytest.raise(ValueError, mtri.Triangulation([1, 2, 1], [5, 6, 5])) - pytest.raise(ValueError, mtri.Triangulation([1, 2, 2], [5, 6, 6])) - pytest.raise(ValueError, mtri.Triangulation([1, 1, 1, 2, 1, 2], + pytest.raises(ValueError, mtri.Triangulation([1, 2, 1], [5, 6, 5])) + pytest.raises(ValueError, mtri.Triangulation([1, 2, 2], [5, 6, 6])) + pytest.raises(ValueError, mtri.Triangulation([1, 1, 1, 2, 1, 2], [5, 5, 5, 6, 5, 6])) From c17005bb541bb6fd063397fbd24d3e966af779b8 Mon Sep 17 00:00:00 2001 From: Jason King Date: Wed, 4 Nov 2015 22:43:15 +1100 Subject: [PATCH 003/174] pytest.raises() calls needed some massaging --- lib/matplotlib/tests/test_axes.py | 94 +++++++++++++++---------------- 1 file changed, 47 insertions(+), 47 deletions(-) diff --git a/lib/matplotlib/tests/test_axes.py b/lib/matplotlib/tests/test_axes.py index d8ff530555d9..c2a03f1a11a8 100644 --- a/lib/matplotlib/tests/test_axes.py +++ b/lib/matplotlib/tests/test_axes.py @@ -355,7 +355,7 @@ def test_shaped_data(): plt.plot(y2) plt.subplot(413) - pytest.raises(ValueError, plt.plot, (y1, y2)) + pytest.raises(ValueError, plt.plot(y1, y2)) plt.subplot(414) plt.plot(xdata[:, 1], xdata[1, :], 'o') @@ -845,12 +845,12 @@ def test_pcolorargs(): Z = np.sqrt(X**2 + Y**2)/5 _, ax = plt.subplots() - pytest.raises(TypeError, ax.pcolormesh, y, x, Z) - pytest.raises(TypeError, ax.pcolormesh, X, Y, Z.T) - pytest.raises(TypeError, ax.pcolormesh, x, y, Z[:-1, :-1], - shading="gouraud") - pytest.raises(TypeError, ax.pcolormesh, X, Y, Z[:-1, :-1], - shading="gouraud") + pytest.raises(TypeError, ax.pcolormesh(y, x, Z)) + pytest.raises(TypeError, ax.pcolormesh(X, Y, Z.T)) + pytest.raises(TypeError, ax.pcolormesh(x, y, Z[:-1, :-1], + shading="gouraud")) + pytest.raises(TypeError, ax.pcolormesh(X, Y, Z[:-1, :-1], + shading="gouraud")) @image_comparison(baseline_images=['canonical']) @@ -1726,7 +1726,7 @@ def test_bxp_bad_widths(): fig, ax = plt.subplots() ax.set_yscale('log') - pytest.raises(ValueError, ax.bxp, logstats, widths=[1]) + pytest.raises(ValueError, ax.bxp(logstats, widths=[1])) @cleanup @@ -1738,7 +1738,7 @@ def test_bxp_bad_positions(): fig, ax = plt.subplots() ax.set_yscale('log') - pytest.raises(ValueError, ax.bxp, logstats, positions=[2, 3]) + pytest.raises(ValueError, ax.bxp(logstats, positions=[2, 3])) @image_comparison(baseline_images=['boxplot', 'boxplot'], tol=1) @@ -1894,7 +1894,7 @@ def test_boxplot_bad_medians_1(): x = np.linspace(-7, 7, 140) x = np.hstack([-25, x, 25]) fig, ax = plt.subplots() - pytest.raises(ValueError, ax.boxplot, x, usermedians=[1, 2]) + pytest.raises(ValueError, ax.boxplot(x, usermedians=[1, 2])) @cleanup @@ -1902,7 +1902,7 @@ def test_boxplot_bad_medians_2(): x = np.linspace(-7, 7, 140) x = np.hstack([-25, x, 25]) fig, ax = plt.subplots() - pytest.raises(ValueError, ax.boxplot, [x, x], usermedians=[[1, 2], [1, 2]]) + pytest.raises(ValueError, ax.boxplot([x, x], usermedians=[[1, 2], [1, 2]])) @cleanup @@ -1910,8 +1910,8 @@ def test_boxplot_bad_ci_1(): x = np.linspace(-7, 7, 140) x = np.hstack([-25, x, 25]) fig, ax = plt.subplots() - pytest.raises(ValueError, ax.boxplot, [x, x], - conf_intervals=[[1, 2]]) + pytest.raises(ValueError, ax.boxplot([x, x], + conf_intervals=[[1, 2]])) @cleanup @@ -1919,8 +1919,8 @@ def test_boxplot_bad_ci_2(): x = np.linspace(-7, 7, 140) x = np.hstack([-25, x, 25]) fig, ax = plt.subplots() - pytest.raises(ValueError, ax.boxplot, [x, x], - conf_intervals=[[1, 2], [1]]) + pytest.raises(ValueError, ax.boxplot([x, x], + conf_intervals=[[1, 2], [1]])) @image_comparison(baseline_images=['boxplot_mod_artists_after_plotting'], @@ -2103,7 +2103,7 @@ 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)] - pytest.raises(ValueError, ax.violinplot, data, positions=range(5)) + pytest.raises(ValueError, ax.violinplot(data, positions=range(5))) @cleanup @@ -2112,8 +2112,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)] - pytest.raises(ValueError, ax.violinplot, data, positions=range(4), - widths=[1, 2, 3]) + pytest.raises(ValueError, ax.violinplot(data, positions=range(4), + widths=[1, 2, 3])) @cleanup @@ -2195,9 +2195,9 @@ def test_errorbar_shape(): yerr = np.vstack((yerr1, 2*yerr1)).T xerr = 0.1 + yerr - pytest.raises(ValueError, ax.errorbar, x, y, yerr=yerr, fmt='o') - pytest.raises(ValueError, ax.errorbar, x, y, xerr=xerr, fmt='o') - pytest.raises(ValueError, ax.errorbar, x, y, yerr=yerr, xerr=xerr, fmt='o') + pytest.raises(ValueError, ax.errorbar(x, y, yerr=yerr, fmt='o')) + pytest.raises(ValueError, ax.errorbar(x, y, xerr=xerr, fmt='o')) + pytest.raises(ValueError, ax.errorbar(x, y, yerr=yerr, xerr=xerr, fmt='o')) @image_comparison(baseline_images=['errorbar_limits']) @@ -2992,17 +2992,17 @@ def test_specgram_angle_freqs(): spec13 = ax13.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='twosided', mode='angle') - pytest.raises(ValueError, ax11.specgram, y, NFFT=NFFT, Fs=Fs, + pytest.raises(ValueError, ax11.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='default', - mode='phase', scale='dB') + mode='phase', scale='dB')) - pytest.raises(ValueError, ax12.specgram, y, NFFT=NFFT, Fs=Fs, + pytest.raises(ValueError, ax12.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='onesided', - mode='phase', scale='dB') + mode='phase', scale='dB')) - pytest.raises(ValueError, ax13.specgram, y, NFFT=NFFT, Fs=Fs, + pytest.raises(ValueError, ax13.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='twosided', - mode='phase', scale='dB') + mode='phase', scale='dB')) @image_comparison(baseline_images=['specgram_angle_noise'], @@ -3039,17 +3039,17 @@ def test_specgram_noise_angle(): spec13 = ax13.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='twosided', mode='angle') - pytest.raises(ValueError, ax11.specgram, y, NFFT=NFFT, Fs=Fs, + pytest.raises(ValueError, ax11.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='default', - mode='phase', scale='dB') + mode='phase', scale='dB')) - pytest.raises(ValueError, ax12.specgram, y, NFFT=NFFT, Fs=Fs, + pytest.raises(ValueError, ax12.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='onesided', - mode='phase', scale='dB') + mode='phase', scale='dB')) - pytest.raises(ValueError, ax13.specgram, y, NFFT=NFFT, Fs=Fs, + pytest.raises(ValueError, ax13.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='twosided', - mode='phase', scale='dB') + mode='phase', scale='dB')) @image_comparison(baseline_images=['specgram_phase_freqs'], @@ -3094,17 +3094,17 @@ def test_specgram_freqs_phase(): spec13 = ax13.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='twosided', mode='phase') - pytest.raises(ValueError, ax11.specgram, y, NFFT=NFFT, Fs=Fs, + pytest.raises(ValueError, ax11.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='default', - mode='phase', scale='dB') + mode='phase', scale='dB')) - pytest.raises(ValueError, ax12.specgram, y, NFFT=NFFT, Fs=Fs, + pytest.raises(ValueError, ax12.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='onesided', - mode='phase', scale='dB') + mode='phase', scale='dB')) - pytest.raises(ValueError, ax13.specgram, y, NFFT=NFFT, Fs=Fs, + pytest.raises(ValueError, ax13.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='twosided', - mode='phase', scale='dB') + mode='phase', scale='dB')) @image_comparison(baseline_images=['specgram_phase_noise'], @@ -3144,17 +3144,17 @@ def test_specgram_noise_phase(): pad_to=pad_to, sides='twosided', mode='phase', ) - pytest.raises(ValueError, ax11.specgram, y, NFFT=NFFT, Fs=Fs, + pytest.raises(ValueError, ax11.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='default', - mode='phase', scale='dB') + mode='phase', scale='dB')) - pytest.raises(ValueError, ax12.specgram, y, NFFT=NFFT, Fs=Fs, + pytest.raises(ValueError, ax12.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='onesided', - mode='phase', scale='dB') + mode='phase', scale='dB')) - pytest.raises(ValueError, ax13.specgram, y, NFFT=NFFT, Fs=Fs, + pytest.raises(ValueError, ax13.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='twosided', - mode='phase', scale='dB') + mode='phase', scale='dB')) @image_comparison(baseline_images=['psd_freqs'], remove_text=True, @@ -4075,8 +4075,8 @@ def test_square_plot(): @cleanup def test_no_None(): fig, ax = plt.subplots() - pytest.raises(ValueError, plt.plot, None) - pytest.raises(ValueError, plt.plot, None, None) + pytest.raises(ValueError, plt.plot(None)) + pytest.raises(ValueError, plt.plot(None, None)) @cleanup From 1a75b755e2003426818c044d4b74dbc521a8b20c Mon Sep 17 00:00:00 2001 From: Jason King Date: Wed, 4 Nov 2015 22:48:24 +1100 Subject: [PATCH 004/174] replace nose with pytest in INSTALL --- INSTALL | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) 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 `_. From b123ed73df08a3f7bbe54194c1cead8928d5fa94 Mon Sep 17 00:00:00 2001 From: Jason King Date: Thu, 5 Nov 2015 00:30:17 +1100 Subject: [PATCH 005/174] altering more assert_equal calls. --- lib/matplotlib/tests/test_axes.py | 2 +- lib/matplotlib/tests/test_basic.py | 4 +- lib/matplotlib/tests/test_cbook.py | 18 +- lib/matplotlib/tests/test_collections.py | 48 ++-- lib/matplotlib/tests/test_dates.py | 22 +- lib/matplotlib/tests/test_dviread.py | 30 +-- lib/matplotlib/tests/test_font_manager.py | 6 +- .../tests/test_labeled_data_unpacking.py | 209 +++++++++--------- lib/matplotlib/tests/test_legend.py | 2 +- lib/matplotlib/tests/test_mlab.py | 2 +- lib/matplotlib/tests/test_path.py | 2 +- lib/matplotlib/tests/test_patheffects.py | 6 +- lib/matplotlib/tests/test_pickle.py | 15 +- lib/matplotlib/tests/test_table.py | 2 +- lib/matplotlib/tests/test_transforms.py | 20 +- lib/matplotlib/tests/test_type1font.py | 12 +- 16 files changed, 201 insertions(+), 199 deletions(-) diff --git a/lib/matplotlib/tests/test_axes.py b/lib/matplotlib/tests/test_axes.py index c2a03f1a11a8..e3d1154ed364 100644 --- a/lib/matplotlib/tests/test_axes.py +++ b/lib/matplotlib/tests/test_axes.py @@ -2604,7 +2604,7 @@ def test_eventplot_problem_kwargs(): # check that three IgnoredKeywordWarnings were raised assert len(w) == 3 assert all(issubclass(wi.category, IgnoredKeywordWarning) - for wi in w)) + for wi in w) @cleanup diff --git a/lib/matplotlib/tests/test_basic.py b/lib/matplotlib/tests/test_basic.py index db3d8b94ed4b..f960be09fe6e 100644 --- a/lib/matplotlib/tests/test_basic.py +++ b/lib/matplotlib/tests/test_basic.py @@ -10,13 +10,13 @@ def test_simple(): - assert_equal(1 + 1, 2) + assert 1 + 1 == 2 @knownfailureif(True) def test_simple_knownfail(): # Test the known fail mechanism. - assert_equal(1 + 1, 3) + assert 1 + 1 == 3 def test_override_builtins(): diff --git a/lib/matplotlib/tests/test_cbook.py b/lib/matplotlib/tests/test_cbook.py index c3bc786c6f08..a649defe2009 100644 --- a/lib/matplotlib/tests/test_cbook.py +++ b/lib/matplotlib/tests/test_cbook.py @@ -249,7 +249,7 @@ 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: @@ -275,12 +275,12 @@ 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 self.callbacks._func_cid_map() == {} + assert 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 @@ -291,15 +291,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 diff --git a/lib/matplotlib/tests/test_collections.py b/lib/matplotlib/tests/test_collections.py index 3001147b1841..a6c7a19221a7 100644 --- a/lib/matplotlib/tests/test_collections.py +++ b/lib/matplotlib/tests/test_collections.py @@ -91,7 +91,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 +101,7 @@ def test__EventCollection__is_horizontal(): orientation ''' _, coll, _ = generate_EventCollection_plot() - assert_equal(True, coll.is_horizontal()) + assert coll.is_horizontal() @cleanup @@ -110,7 +110,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 +119,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 +128,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 +223,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 +246,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 +265,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 +285,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 +303,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 +321,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 +334,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 +346,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 +385,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 +398,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 +428,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 +437,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 +446,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 diff --git a/lib/matplotlib/tests/test_dates.py b/lib/matplotlib/tests/test_dates.py index 54afc633bf7e..14f1d43d428e 100644 --- a/lib/matplotlib/tests/test_dates.py +++ b/lib/matplotlib/tests/test_dates.py @@ -189,7 +189,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 +197,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 +216,8 @@ 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 @@ -336,8 +336,8 @@ 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'], diff --git a/lib/matplotlib/tests/test_dviread.py b/lib/matplotlib/tests/test_dviread.py index 260e7f429d82..1d585a77b644 100644 --- a/lib/matplotlib/tests/test_dviread.py +++ b/lib/matplotlib/tests/test_dviread.py @@ -30,34 +30,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(): diff --git a/lib/matplotlib/tests/test_font_manager.py b/lib/matplotlib/tests/test_font_manager.py index bb87bebeb999..91deaca845dc 100644 --- a/lib/matplotlib/tests/test_font_manager.py +++ b/lib/matplotlib/tests/test_font_manager.py @@ -19,7 +19,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 +46,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)) + assertfontManager.findfont(fp, rebuild_if_missing=False) == + copy.findfont(fp, rebuild_if_missing=False) diff --git a/lib/matplotlib/tests/test_labeled_data_unpacking.py b/lib/matplotlib/tests/test_labeled_data_unpacking.py index d07d481b1f57..5ad2244c6583 100644 --- a/lib/matplotlib/tests/test_labeled_data_unpacking.py +++ b/lib/matplotlib/tests/test_labeled_data_unpacking.py @@ -2,6 +2,7 @@ from nose.tools import (assert_raises, assert_equal) from nose.plugins.skip import SkipTest +import pytest try: # 3.2+ versions @@ -131,54 +132,54 @@ def f(): def test_function_call_without_data(): """test without data -> no replacements""" for func in all_funcs: - assert_equal(func(None, "x", "y"), + 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_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", 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(): @@ -191,18 +192,18 @@ def test_function_call_with_pandas_data(): 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 +215,21 @@ 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 +245,27 @@ 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), + 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_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( + 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_equal( + 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_equal( + 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") + 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(): @@ -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,12 +329,12 @@ 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(): @@ -396,20 +397,20 @@ 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') | {}" + pytest.raises(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..e66a6fd86a70 100644 --- a/lib/matplotlib/tests/test_legend.py +++ b/lib/matplotlib/tests/test_legend.py @@ -162,7 +162,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 diff --git a/lib/matplotlib/tests/test_mlab.py b/lib/matplotlib/tests/test_mlab.py index 0139ba77edce..0f92f3963dc4 100644 --- a/lib/matplotlib/tests/test_mlab.py +++ b/lib/matplotlib/tests/test_mlab.py @@ -260,7 +260,7 @@ 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 (6, 13) == y.shape assert self.get_base(y) is x diff --git a/lib/matplotlib/tests/test_path.py b/lib/matplotlib/tests/test_path.py index 5f606461916e..2c4b036c237c 100644 --- a/lib/matplotlib/tests/test_path.py +++ b/lib/matplotlib/tests/test_path.py @@ -87,7 +87,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) diff --git a/lib/matplotlib/tests/test_patheffects.py b/lib/matplotlib/tests/test_patheffects.py index b8a068362316..8be45f8a79c1 100644 --- a/lib/matplotlib/tests/test_patheffects.py +++ b/lib/matplotlib/tests/test_patheffects.py @@ -101,13 +101,13 @@ 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']) diff --git a/lib/matplotlib/tests/test_pickle.py b/lib/matplotlib/tests/test_pickle.py index da2e7f699e90..682421d35023 100644 --- a/lib/matplotlib/tests/test_pickle.py +++ b/lib/matplotlib/tests/test_pickle.py @@ -184,7 +184,7 @@ 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) @@ -193,7 +193,7 @@ def test_complete(): # make sure there is now a figure manager assert_not_equal(plt._pylab_helpers.Gcf.figs, {}) - assert_equal(fig.get_label(), 'Figure with a label?') + assert fig.get_label() == 'Figure with a label?' @cleanup @@ -276,13 +276,12 @@ 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]) - # 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) + assert list(obj.wrapper._parents.values()) == [obj.composite2] + assert (obj.wrapper.input_dims == obj.composite.input_dims) + assert (obj.wrapper.output_dims == obj.composite.output_dims) + if __name__ == '__main__': diff --git a/lib/matplotlib/tests/test_table.py b/lib/matplotlib/tests/test_table.py index ef768d89e935..2aa3ff5b9563 100644 --- a/lib/matplotlib/tests/test_table.py +++ b/lib/matplotlib/tests/test_table.py @@ -120,4 +120,4 @@ def test_customcell(): for t, c in zip(types, codes): cell = CustomCell((0, 0), visible_edges=t, width=1, height=1) code = tuple(s for _, s in cell.get_path().iter_segments()) - assert_equal(c, code) + assert c == code diff --git a/lib/matplotlib/tests/test_transforms.py b/lib/matplotlib/tests/test_transforms.py index d961741c06ac..e2f0196055f2 100644 --- a/lib/matplotlib/tests/test_transforms.py +++ b/lib/matplotlib/tests/test_transforms.py @@ -264,9 +264,9 @@ def setUp(self): # self.stack2_subset.write_graphviz(file('stack2_subset.dot', 'w')) def test_transform_depth(self): - assert_equal(self.stack1.depth, 4) - assert_equal(self.stack2.depth, 4) - assert_equal(self.stack2_subset.depth, 3) + assert self.stack1.depth == 4 + assert self.stack2.depth == 4 + assert self.stack2_subset.depth == 3 def test_left_to_right_iteration(self): stack3 = (self.ta1 + (self.tn1 + (self.ta2 + self.tn2))) + self.ta3 @@ -288,10 +288,10 @@ def test_transform_shortcuts(self): self.assertEqual(self.stack1 - self.stack2_subset, self.ta1) self.assertEqual(self.stack2 - self.stack2_subset, self.ta1) - assert_equal((self.stack2_subset - self.stack2), - self.ta1.inverted(), - ) - assert_equal((self.stack2_subset - self.stack2).depth, 1) + assert (self.stack2_subset - self.stack2) == + self.ta1.inverted() + + assert (self.stack2_subset - self.stack2).depth == 1 assert_raises(ValueError, self.stack1.__sub__, self.stack2) @@ -498,7 +498,7 @@ def test_bbox_intersection(): # r3 contains r2 assert_bbox_eq(inter(r1, r3), r3) # no intersection - assert_equal(inter(r1, r4), None) + assert inter(r1, r4) is None # single point assert_bbox_eq(inter(r1, r5), bbox_from_ext(1, 1, 1, 1)) @@ -508,11 +508,11 @@ def test_bbox_as_strings(): assert_bbox_eq(b, eval(repr(b), {'Bbox': mtrans.Bbox})) asdict = eval(str(b), {'Bbox': dict}) for k, v in asdict.items(): - assert_equal(getattr(b, k), v) + assert getattr(b, k) == v fmt = '.1f' asdict = eval(format(b, fmt), {'Bbox': dict}) for k, v in asdict.items(): - assert_equal(eval(format(getattr(b, k), fmt)), v) + assert eval(format(getattr(b, k), fmt)) == v def test_transform_single_point(): diff --git a/lib/matplotlib/tests/test_type1font.py b/lib/matplotlib/tests/test_type1font.py index 90edf56accdc..e298a19f6d3d 100644 --- a/lib/matplotlib/tests/test_type1font.py +++ b/lib/matplotlib/tests/test_type1font.py @@ -16,11 +16,13 @@ def test_Type1Font(): condensed = font.transform({'extend': 0.5}) with open(filename, 'rb') as f: rawdata = f.read() - assert_equal(font.parts[0], rawdata[0x0006:0x10c5]) - assert_equal(font.parts[1], rawdata[0x10cb:0x897f]) - assert_equal(font.parts[2], rawdata[0x8985:0x8ba6]) - assert_equal(font.parts[1:], slanted.parts[1:]) - assert_equal(font.parts[1:], condensed.parts[1:]) + + rawdata = open(filename, 'rb').read() + assert font.parts[0] == rawdata[0x0006:0x10c5] + assert font.parts[1] == rawdata[0x10cb:0x897f] + assert font.parts[2] == rawdata[0x8985:0x8ba6] + assert font.parts[1:] == slanted.parts[1:] + assert font.parts[1:] == condensed.parts[1:] differ = difflib.Differ() diff = list(differ.compare( From 5f433fb98dba5e05bb29b01d3ba0554a3648fc68 Mon Sep 17 00:00:00 2001 From: Jason King Date: Thu, 5 Nov 2015 12:30:49 +1100 Subject: [PATCH 006/174] fixing up problems with assert, and the use of messages. Also added tox.ini --- lib/matplotlib/tests/test_coding_standards.py | 2 +- lib/matplotlib/tests/test_mlab.py | 32 +++++++++---------- lib/matplotlib/tests/test_style.py | 3 +- tox.ini | 4 +++ 4 files changed, 23 insertions(+), 18 deletions(-) diff --git a/lib/matplotlib/tests/test_coding_standards.py b/lib/matplotlib/tests/test_coding_standards.py index 6734fde7b6e6..d000b05249d1 100644 --- a/lib/matplotlib/tests/test_coding_standards.py +++ b/lib/matplotlib/tests/test_coding_standards.py @@ -140,7 +140,7 @@ def assert_pep8_conformance(module=matplotlib, exclude_files=None, "{0}".format('\n'.join(reporter._global_deferred_print))) else: msg = "Found code syntax errors (and warnings)." - assert_equal(result.total_errors, 0, msg) + assert result.total_errors == 0, msg # If we've been using the exclusions reporter, check that we didn't # exclude files unnecessarily. diff --git a/lib/matplotlib/tests/test_mlab.py b/lib/matplotlib/tests/test_mlab.py index 0f92f3963dc4..c4df96a70a8d 100644 --- a/lib/matplotlib/tests/test_mlab.py +++ b/lib/matplotlib/tests/test_mlab.py @@ -14,7 +14,7 @@ import matplotlib.mlab as mlab import matplotlib.cbook as cbook from matplotlib.testing.decorators import knownfailureif, CleanupTestCase - +import pytest try: from mpl_toolkits.natgrid import _natgrid @@ -123,23 +123,23 @@ def calc_window_target(self, x, NFFT, noverlap=0): def test_stride_windows_2D_ValueError(self): x = np.arange(10)[np.newaxis] - pytest.raises(ValueError, mlab.stride_windows( x, 5)) + pytest.raises(ValueError, mlab.stride_windows, x, 5) def test_stride_windows_0D_ValueError(self): x = np.array(0) - pytest.raises(ValueError, mlab.stride_windows( x, 5)) + pytest.raises(ValueError, mlab.stride_windows, x, 5) def test_stride_windows_noverlap_gt_n_ValueError(self): x = np.arange(10) - pytest.raises(ValueError, mlab.stride_windows(x, 2, 3) + pytest.raises(ValueError, mlab.stride_windows, x, 2, 3) def test_stride_windows_noverlap_eq_n_ValueError(self): x = np.arange(10) - pytest.raises(ValueError, mlab.stride_windows(x, 2, 2)) + pytest.raises(ValueError, mlab.stride_windows, x, 2, 2) def test_stride_windows_n_gt_lenx_ValueError(self): x = np.arange(10) - pytest.raises(ValueError, mlab.stride_windows(x, 11)) + pytest.raises(ValueError, mlab.stride_windows, x, 11) def test_stride_windows_n_lt_1_ValueError(self): x = np.arange(10) @@ -254,7 +254,7 @@ def test_stride_windows_n13_noverlapn3_axis0(self): assert yt.shape == y.shape assert_array_equal(yt, y) assert (13, 6) == y.shape - assert_true(self.get_base(y) is x) + assert self.get_base(y) is x def test_stride_windows_n13_noverlapn3_axis1(self): x = np.arange(100) @@ -337,7 +337,7 @@ def test_rec2csv_bad_shape_ValueError(self): (str('y'), np.float)]) # the bad recarray should trigger a ValueError for having ndim > 1. - pytest.raises(ValueError, mlab.rec2csv( bad, self.fd)) + 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,8 +399,8 @@ def test_window_hanning_ones(self): def test_apply_window_1D_axis1_ValueError(self): x = self.sig_rand window = mlab.window_hanning - pytest.raises(ValueError, mlab.apply_window( x, window, axis=1, - return_window=False)) + 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 @@ -2790,11 +2790,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 +2844,17 @@ def test_kde_bandwidth_method(self): class gaussian_kde_custom_tests(object): def test_no_data(self): """Pass no data into the GaussianKDE class.""" - pytest.raises(ValueError, mlab.GaussianKDE,([])) + pytest.raises(ValueError, mlab.GaussianKDE, []) def test_single_dataset_element(self): """Pass a single dataset element into the GaussianKDE class.""" - pytest.raises(ValueError, mlab.GaussianKDE([42])) + 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]]) - pytest.raises(np.linalg.LinAlgError, mlab.GaussianKDE(x1, "silverman")) + 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 @@ -2995,7 +2995,7 @@ def test_contiguous_regions(): # No True in mask assert mlab.contiguous_regions([False]*5) == [] # Empty mask - assert (mlab.contiguous_regions([]) == [] + assert mlab.contiguous_regions([]) == [] def test_psd_onesided_norm(): diff --git a/lib/matplotlib/tests/test_style.py b/lib/matplotlib/tests/test_style.py index 8957b0706c65..9d65324ee360 100644 --- a/lib/matplotlib/tests/test_style.py +++ b/lib/matplotlib/tests/test_style.py @@ -16,6 +16,7 @@ from matplotlib.style.core import USER_LIBRARY_PATHS, STYLE_EXTENSION from matplotlib.externals import six +import pytest PARAM = 'image.cmap' VALUE = 'pink' @@ -133,7 +134,7 @@ def test_context_with_badparam(): with style.context({PARAM: other_value}): assert mpl.rcParams[PARAM] == other_value x = style.context([d]) - assert_raises(KeyError, x.__enter__) + pytest.raises(KeyError, x.__enter__()) assert mpl.rcParams[PARAM] == other_value diff --git a/tox.ini b/tox.ini index 97af758fa7ac..36291d307e96 100644 --- a/tox.ini +++ b/tox.ini @@ -15,3 +15,7 @@ deps = pytest mock numpy + +[pytest] +norecursedirs = .git build +testpaths = tests \ No newline at end of file From cfb8d7147774b535e3a5ef34adaa7b0853d4b941 Mon Sep 17 00:00:00 2001 From: Jason King Date: Thu, 5 Nov 2015 12:36:34 +1100 Subject: [PATCH 007/174] flake8 failures --- lib/matplotlib/tests/test_artist.py | 10 +++++----- lib/matplotlib/tests/test_cbook.py | 24 ++++++++++++++---------- 2 files changed, 19 insertions(+), 15 deletions(-) diff --git a/lib/matplotlib/tests/test_artist.py b/lib/matplotlib/tests/test_artist.py index ae732cae0273..ba824157e310 100644 --- a/lib/matplotlib/tests/test_artist.py +++ b/lib/matplotlib/tests/test_artist.py @@ -154,13 +154,13 @@ def test_remove(): im = ax.imshow(np.arange(36).reshape(6, 6)) ln, = ax.plot(range(5)) - assert fig.stale == True - assert ax.stale == True + assert fig.stale + assert ax.stale fig.canvas.draw() - assert fig.stale == False - assert ax.stale == False - assert ln.stale == False + assert not fig.stale + assert not ax.stale + assert not ln.stale assert im in ax.mouseover_set assert ln not in ax.mouseover_set diff --git a/lib/matplotlib/tests/test_cbook.py b/lib/matplotlib/tests/test_cbook.py index a649defe2009..7685f3e55e9f 100644 --- a/lib/matplotlib/tests/test_cbook.py +++ b/lib/matplotlib/tests/test_cbook.py @@ -21,20 +21,20 @@ def test_is_string_like(): y = np.arange(10) - assert cbook.is_string_like(y) == False + assert not cbook.is_string_like(y) y.shape = 10, 1 - assert cbook.is_string_like(y) == False + assert not cbook.is_string_like(y) y.shape = 1, 10 - assert cbook.is_string_like(y) == False + assert not cbook.is_string_like(y) assert cbook.is_string_like("hello world") - assert cbook.is_string_like(10) == False + assert not cbook.is_string_like(10) y = ['a', 'b', 'c'] - assert cbook.is_string_like(y) == False + assert not cbook.is_string_like(y) y = np.array(y) - assert 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) @@ -371,10 +371,14 @@ def test_to_midstep(): def test_step_fails(): - pytest.raises(ValueError, cbook._step_validation(np.arange(12).reshape(3, 4), 'a')) - pytest.raises(ValueError, cbook._step_validation(np.arange(12), 'a')) - pytest.raises(ValueError, cbook._step_validation(np.arange(12))) - pytest.raises(ValueError, cbook._step_validation(np.arange(12), np.arange(3))) + pytest.raises(ValueError, + cbook._step_validation(np.arange(12).reshape(3, 4), 'a')) + pytest.raises(ValueError, + cbook._step_validation(np.arange(12), 'a')) + pytest.raises(ValueError, + cbook._step_validation(np.arange(12))) + pytest.raises(ValueError, + cbook._step_validation(np.arange(12), np.arange(3))) def test_grouper(): From 89d3366e1c15c75c2fa4dfbca6af29cafc001d78 Mon Sep 17 00:00:00 2001 From: Jason King Date: Thu, 5 Nov 2015 12:44:30 +1100 Subject: [PATCH 008/174] flake8 doesn't like blank lines at ends of files. aren't you picky flake8. Its always about you isn't it. --- lib/matplotlib/tests/test_ticker.py | 1 + lib/matplotlib/tests/test_transforms.py | 13 ++++++------- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/lib/matplotlib/tests/test_ticker.py b/lib/matplotlib/tests/test_ticker.py index 578c73e640cf..ea2b3a54a965 100644 --- a/lib/matplotlib/tests/test_ticker.py +++ b/lib/matplotlib/tests/test_ticker.py @@ -366,6 +366,7 @@ def test_formatstrformatter(): tmp_form = mticker.StrMethodFormatter('{x:05d}') assert '00002' == tmp_form(2) + if __name__ == '__main__': import nose nose.runmodule(argv=['-s', '--with-doctest'], exit=False) diff --git a/lib/matplotlib/tests/test_transforms.py b/lib/matplotlib/tests/test_transforms.py index e2f0196055f2..aedc070e9c9a 100644 --- a/lib/matplotlib/tests/test_transforms.py +++ b/lib/matplotlib/tests/test_transforms.py @@ -569,13 +569,12 @@ def test_invalid_arguments(): # raises a ValueError, and a wrong shape with a possible number # of dimensions is caught by our CALL_CPP macro, which always # raises the less precise RuntimeError. - assert_raises(ValueError, t.transform, 1) - assert_raises(ValueError, t.transform, [[[1]]]) - assert_raises(RuntimeError, t.transform, []) - assert_raises(RuntimeError, t.transform, [1]) - assert_raises(RuntimeError, t.transform, [[1]]) - assert_raises(RuntimeError, t.transform, [[1, 2, 3]]) - + pytest.raises(ValueError, t.transform(1)) + pytest.raises(ValueError, t.transform([[[1]]])) + pytest.raises(RuntimeError, t.transform([])) + pytest.raises(RuntimeError, t.transform([1])) + pytest.raises(RuntimeError, t.transform([[1]])) + pytest.raises(RuntimeError, t.transform([[1, 2, 3]])) def test_transformed_path(): points = [(0, 0), (1, 0), (1, 1), (0, 1)] From 887e482d55f924eacdb5eb8cbaa960487a74ed05 Mon Sep 17 00:00:00 2001 From: Jason King Date: Thu, 5 Nov 2015 13:02:12 +1100 Subject: [PATCH 009/174] flake8 fixes --- .../tests/test_labeled_data_unpacking.py | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/lib/matplotlib/tests/test_labeled_data_unpacking.py b/lib/matplotlib/tests/test_labeled_data_unpacking.py index 5ad2244c6583..640a09643806 100644 --- a/lib/matplotlib/tests/test_labeled_data_unpacking.py +++ b/lib/matplotlib/tests/test_labeled_data_unpacking.py @@ -51,13 +51,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) @@ -126,7 +130,7 @@ def f(): func(None, x="a", y="b") # This sets a label although the function can't handle it. - assert_raises(TypeError, f) + pytest.raises(TypeError, f()) def test_function_call_without_data(): From 8f16316742072b6118951e5435da9acf48de7d03 Mon Sep 17 00:00:00 2001 From: Jason King Date: Thu, 5 Nov 2015 13:40:49 +1100 Subject: [PATCH 010/174] fixed syntax errors --- lib/matplotlib/tests/test_rcparams.py | 2 +- lib/matplotlib/tests/test_transforms.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/matplotlib/tests/test_rcparams.py b/lib/matplotlib/tests/test_rcparams.py index 754933db85f2..4290160598ad 100644 --- a/lib/matplotlib/tests/test_rcparams.py +++ b/lib/matplotlib/tests/test_rcparams.py @@ -260,7 +260,7 @@ def _validation_fail_helper(validator, arg, exception_type): if sys.version_info[:2] < (2, 7): raise nose.SkipTest("assert_raises as context manager not " "supported with Python < 2.7") - ptest.raise(exception_type,validator(arg)) + pytest.raise(exception_type,validator(arg)) diff --git a/lib/matplotlib/tests/test_transforms.py b/lib/matplotlib/tests/test_transforms.py index aedc070e9c9a..8492cd5e9324 100644 --- a/lib/matplotlib/tests/test_transforms.py +++ b/lib/matplotlib/tests/test_transforms.py @@ -288,7 +288,7 @@ def test_transform_shortcuts(self): self.assertEqual(self.stack1 - self.stack2_subset, self.ta1) self.assertEqual(self.stack2 - self.stack2_subset, self.ta1) - assert (self.stack2_subset - self.stack2) == + assert self.stack2_subset - self.stack2 == self.ta1.inverted() assert (self.stack2_subset - self.stack2).depth == 1 From b56297f7aaffcc4dd751415fb40e62f42dc4819e Mon Sep 17 00:00:00 2001 From: Jason King Date: Thu, 5 Nov 2015 13:43:13 +1100 Subject: [PATCH 011/174] just have it on one line --- lib/matplotlib/tests/test_transforms.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/lib/matplotlib/tests/test_transforms.py b/lib/matplotlib/tests/test_transforms.py index 8492cd5e9324..8590b6b67435 100644 --- a/lib/matplotlib/tests/test_transforms.py +++ b/lib/matplotlib/tests/test_transforms.py @@ -288,8 +288,7 @@ def test_transform_shortcuts(self): self.assertEqual(self.stack1 - self.stack2_subset, self.ta1) self.assertEqual(self.stack2 - self.stack2_subset, self.ta1) - assert self.stack2_subset - self.stack2 == - self.ta1.inverted() + assert self.stack2_subset - self.stack2 == self.ta1.inverted() assert (self.stack2_subset - self.stack2).depth == 1 From df4e413d211648325decdb44dd8fb627876441ac Mon Sep 17 00:00:00 2001 From: Jason King Date: Thu, 5 Nov 2015 13:56:23 +1100 Subject: [PATCH 012/174] fix errors highlighted in travis CI logs --- lib/matplotlib/tests/test_axes.py | 23 +++++++++++---------- lib/matplotlib/tests/test_collections.py | 2 +- lib/matplotlib/tests/test_dates.py | 3 +-- lib/matplotlib/tests/test_font_manager.py | 2 +- lib/matplotlib/tests/test_patheffects.py | 3 +-- lib/matplotlib/tests/test_simplification.py | 2 +- 6 files changed, 17 insertions(+), 18 deletions(-) diff --git a/lib/matplotlib/tests/test_axes.py b/lib/matplotlib/tests/test_axes.py index e3d1154ed364..95e6efdabe96 100644 --- a/lib/matplotlib/tests/test_axes.py +++ b/lib/matplotlib/tests/test_axes.py @@ -25,6 +25,7 @@ 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 @@ -120,22 +121,22 @@ def test_twinx_cla(): ax2 = ax.twinx() ax3 = ax2.twiny() plt.draw() - assert ax2.xaxis.get_visible() == False - assert x2.patch.get_visible() == False + assert not ax2.xaxis.get_visible() + assert not x2.patch.get_visible() ax2.cla() ax3.cla() - assert ax2.xaxis.get_visible() == False - assert ax2.patch.get_visible() == False - assert ax2.yaxis.get_visible() == True + assert not ax2.xaxis.get_visible() + assert not ax2.patch.get_visible() + assert ax2.yaxis.get_visible() - assert ax3.xaxis.get_visible() == True - assert ax3.patch.get_visible() == False - assert ax3.yaxis.get_visible() == False + assert ax3.xaxis.get_visible() + assert not ax3.patch.get_visible() + assert not ax3.yaxis.get_visible() - assert ax.xaxis.get_visible() == True - assert ax.patch.get_visible() == True - assert ax.yaxis.get_visible() == True + 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']) diff --git a/lib/matplotlib/tests/test_collections.py b/lib/matplotlib/tests/test_collections.py index a6c7a19221a7..764f824d7449 100644 --- a/lib/matplotlib/tests/test_collections.py +++ b/lib/matplotlib/tests/test_collections.py @@ -266,7 +266,7 @@ def test__EventCollection__set_orientation(): new_orientation = 'vertical' coll.set_orientation(new_orientation) assert new_orientation == coll.get_orientation() - assert_ not coll.is_horizontal() + assert not coll.is_horizontal() check_segments(coll, props['positions'], props['linelength'], diff --git a/lib/matplotlib/tests/test_dates.py b/lib/matplotlib/tests/test_dates.py index 14f1d43d428e..cc43f13807dd 100644 --- a/lib/matplotlib/tests/test_dates.py +++ b/lib/matplotlib/tests/test_dates.py @@ -197,8 +197,7 @@ 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 locale_formatter.strftime(dt) == - expanded_formatter.strftime(dt) + assert locale_formatter.strftime(dt) == expanded_formatter.strftime(dt) except (ImportError, AttributeError): pass diff --git a/lib/matplotlib/tests/test_font_manager.py b/lib/matplotlib/tests/test_font_manager.py index 91deaca845dc..9aea89bb3092 100644 --- a/lib/matplotlib/tests/test_font_manager.py +++ b/lib/matplotlib/tests/test_font_manager.py @@ -46,5 +46,5 @@ def test_json_serialization(): {'family': 'Bitstream Vera Sans', 'weight': 700}, {'family': 'no such font family'}): fp = FontProperties(**prop) - assertfontManager.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_patheffects.py b/lib/matplotlib/tests/test_patheffects.py index 8be45f8a79c1..1e10a31ea2e9 100644 --- a/lib/matplotlib/tests/test_patheffects.py +++ b/lib/matplotlib/tests/test_patheffects.py @@ -101,8 +101,7 @@ 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 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(): diff --git a/lib/matplotlib/tests/test_simplification.py b/lib/matplotlib/tests/test_simplification.py index df16d0de3e5f..426b4ff3df13 100644 --- a/lib/matplotlib/tests/test_simplification.py +++ b/lib/matplotlib/tests/test_simplification.py @@ -161,7 +161,7 @@ def test_start_with_moveto(): assert segs[0][1] == Path.MOVETO @cleanup -@raises(OverflowError) +@pytest.mark.xfail(raises=OverflowError) def test_throw_rendering_complexity_exceeded(): rcParams['path.simplify'] = False xx = np.arange(200000) From defa65d4d31b690939e9e137dcaa5f4360df67e9 Mon Sep 17 00:00:00 2001 From: Jason King Date: Thu, 5 Nov 2015 14:16:13 +1100 Subject: [PATCH 013/174] fixing reported test failures, reported by pytest on travis. --- lib/matplotlib/tests/test_axes.py | 5 +++-- lib/matplotlib/tests/test_compare_images.py | 4 ++-- lib/matplotlib/tests/test_path.py | 4 +++- lib/matplotlib/tests/test_subplots.py | 11 ++++++----- lib/matplotlib/tests/test_text.py | 4 ++-- lib/matplotlib/tests/test_triangulation.py | 1 + 6 files changed, 17 insertions(+), 12 deletions(-) diff --git a/lib/matplotlib/tests/test_axes.py b/lib/matplotlib/tests/test_axes.py index 95e6efdabe96..7679c8eb76c7 100644 --- a/lib/matplotlib/tests/test_axes.py +++ b/lib/matplotlib/tests/test_axes.py @@ -4069,8 +4069,9 @@ def test_square_plot(): ax.plot(x, y, 'mo') ax.axis('square') xlim, ylim = ax.get_xlim(), ax.get_ylim() - assert np.diff(xlim) == np.diff(ylim) == True - assert ax.get_aspect() == 'equal' == True + assert np.diff(xlim) + assert np.diff(ylim) + assert ax.get_aspect() == 'equal' @cleanup diff --git a/lib/matplotlib/tests/test_compare_images.py b/lib/matplotlib/tests/test_compare_images.py index f9ee9159f204..d903a29d78c0 100644 --- a/lib/matplotlib/tests/test_compare_images.py +++ b/lib/matplotlib/tests/test_compare_images.py @@ -37,9 +37,9 @@ 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 results is not None assert_almost_equal(expect_rms, results['rms'], places=4) diff --git a/lib/matplotlib/tests/test_path.py b/lib/matplotlib/tests/test_path.py index 2c4b036c237c..f94a82832cdc 100644 --- a/lib/matplotlib/tests/test_path.py +++ b/lib/matplotlib/tests/test_path.py @@ -11,6 +11,8 @@ from matplotlib.testing.decorators import image_comparison import matplotlib.pyplot as plt from matplotlib import transforms +import pytest + def test_readonly_path(): @@ -19,7 +21,7 @@ def test_readonly_path(): def modify_vertices(): path.vertices = path.vertices * 2.0 - assert_raises(AttributeError, modify_vertices) + pytest.raises(AttributeError, modify_vertices) def test_point_in_path(): diff --git a/lib/matplotlib/tests/test_subplots.py b/lib/matplotlib/tests/test_subplots.py index d588f7b4b13b..b0ec71d06b2b 100644 --- a/lib/matplotlib/tests/test_subplots.py +++ b/lib/matplotlib/tests/test_subplots.py @@ -8,6 +8,7 @@ import numpy import matplotlib.pyplot as plt from matplotlib.testing.decorators import image_comparison, cleanup +import pytest from nose.tools import assert_raises @@ -104,17 +105,17 @@ def test_shared(): def test_exceptions(): # TODO should this test more options? - assert_raises(ValueError, plt.subplots, 2, 2, sharex='blah') - assert_raises(ValueError, plt.subplots, 2, 2, sharey='blah') + pytest.raises(ValueError, plt.subplots, 2, 2, sharex='blah') + pytest.raises(ValueError, plt.subplots, 2, 2, sharey='blah') # We filter warnings in this test which are genuine since # the pount of this test is to ensure that this raises. with warnings.catch_warnings(): warnings.filterwarnings('ignore', message='.*sharex\ argument\ to\ subplots', category=UserWarning) - assert_raises(ValueError, plt.subplots, 2, 2, -1) - assert_raises(ValueError, plt.subplots, 2, 2, 0) - assert_raises(ValueError, plt.subplots, 2, 2, 5) + pytest.raises(ValueError, plt.subplots, 2, 2, -1) + pytest.raises(ValueError, plt.subplots, 2, 2, 0) + pytest.raises(ValueError, plt.subplots, 2, 2, 5) @image_comparison(baseline_images=['subplots_offset_text'], remove_text=False) diff --git a/lib/matplotlib/tests/test_text.py b/lib/matplotlib/tests/test_text.py index f975ca597037..bf28c9c247eb 100644 --- a/lib/matplotlib/tests/test_text.py +++ b/lib/matplotlib/tests/test_text.py @@ -16,6 +16,7 @@ from matplotlib.figure import Figure from matplotlib.text import Annotation, Text from matplotlib.backends.backend_agg import RendererAgg +import pytest @image_comparison(baseline_images=['font_styles']) @@ -291,8 +292,7 @@ def test_get_rotation_raises(): if sys.version_info[:2] < (2, 7): raise SkipTest("assert_raises as context manager " "not supported with Python < 2.7") - with assert_raises(ValueError): - text.get_rotation('hozirontal') + pytest.raises(ValueError, text.get_rotation, 'hozirontal') def test_get_rotation_none(): diff --git a/lib/matplotlib/tests/test_triangulation.py b/lib/matplotlib/tests/test_triangulation.py index 1c08228fd907..d448fb1d0398 100644 --- a/lib/matplotlib/tests/test_triangulation.py +++ b/lib/matplotlib/tests/test_triangulation.py @@ -13,6 +13,7 @@ from matplotlib.testing.decorators import cleanup, image_comparison import matplotlib.cm as cm from matplotlib.path import Path +import pytest def test_delaunay(): From b8b39094af5691fc65fd4504792ebc2e14563596 Mon Sep 17 00:00:00 2001 From: Jason King Date: Thu, 5 Nov 2015 14:51:43 +1100 Subject: [PATCH 014/174] fixing pytest failures. Interesting that assert can't seem to handle splitting off 'a == b' into seperate lines. Other changes seem to be missing import pytest statements. --- lib/matplotlib/tests/test_colors.py | 1 + lib/matplotlib/tests/test_dates.py | 3 +- lib/matplotlib/tests/test_font_manager.py | 3 +- .../tests/test_labeled_data_unpacking.py | 150 ++++++------------ lib/matplotlib/tests/test_rcparams.py | 4 +- lib/matplotlib/tests/test_simplification.py | 1 + lib/matplotlib/tests/test_ticker.py | 1 + 7 files changed, 54 insertions(+), 109 deletions(-) diff --git a/lib/matplotlib/tests/test_colors.py b/lib/matplotlib/tests/test_colors.py index 6cbbe4125a0c..261c3234551f 100644 --- a/lib/matplotlib/tests/test_colors.py +++ b/lib/matplotlib/tests/test_colors.py @@ -16,6 +16,7 @@ import matplotlib.pyplot as plt from matplotlib.testing.decorators import (image_comparison, cleanup, knownfailureif) +import pytest def test_colormap_endian(): diff --git a/lib/matplotlib/tests/test_dates.py b/lib/matplotlib/tests/test_dates.py index cc43f13807dd..fdce84b4e416 100644 --- a/lib/matplotlib/tests/test_dates.py +++ b/lib/matplotlib/tests/test_dates.py @@ -215,8 +215,7 @@ def test_date_formatter_callable(): formatter = mdates.AutoDateFormatter(locator) formatter.scaled[-10] = callable_formatting_function - assert formatter([datetime.datetime(2014, 12, 25)]) == - ['25-12//2014'] + assert formatter([datetime.datetime(2014, 12, 25)]) == ['25-12//2014'] def test_drange(): diff --git a/lib/matplotlib/tests/test_font_manager.py b/lib/matplotlib/tests/test_font_manager.py index 9aea89bb3092..323f3c6c0860 100644 --- a/lib/matplotlib/tests/test_font_manager.py +++ b/lib/matplotlib/tests/test_font_manager.py @@ -46,5 +46,4 @@ def test_json_serialization(): {'family': 'Bitstream Vera Sans', 'weight': 700}, {'family': 'no such font family'}): fp = FontProperties(**prop) - assert 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_labeled_data_unpacking.py b/lib/matplotlib/tests/test_labeled_data_unpacking.py index 640a09643806..8eaaff56d4f2 100644 --- a/lib/matplotlib/tests/test_labeled_data_unpacking.py +++ b/lib/matplotlib/tests/test_labeled_data_unpacking.py @@ -136,54 +136,36 @@ def f(): def test_function_call_without_data(): """test without data -> no replacements""" for func in all_funcs: - 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" + 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 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" + 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 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" + 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(): @@ -196,18 +178,12 @@ def test_function_call_with_pandas_data(): data = pd.DataFrame({"a": [1, 2], "b": [8, 9], "w": ["NOT", "NOT"]}) for func in all_funcs: - 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" + 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(): @@ -219,21 +195,12 @@ 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 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" + 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): @@ -249,27 +216,14 @@ 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 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" + 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 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(): @@ -281,14 +235,10 @@ 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 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" + 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(): @@ -322,10 +272,8 @@ def funcy(ax, *args, **kwargs): func = unpack_labeled_data(replace_all_args=True, replace_names=["w"], label_namer="y")(funcy) - 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" + 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", @@ -333,12 +281,9 @@ def funcy(ax, *args, **kwargs): "label", "w"])( funcy) - 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" + 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(): @@ -408,9 +353,8 @@ def funcy(ax, *args, **kwargs): # no arbitrary long args with data def f(): - assert funcy(None, "x", "y", "c", "x", "y", "x", "y", data=data) == - "('X', 'Y', 'c', 'X', 'Y', 'X', 'Y') | {}" - pytest.raises(ValueError, f()) + assert funcy(None, "x", "y", "c", "x", "y", "x", "y", data=data) == "('X', 'Y', 'c', 'X', 'Y', 'X', 'Y') | {}" + pytest.raises(ValueError, f) # In the two arg case, if a valid color spec is in data, we warn but use # it as data... diff --git a/lib/matplotlib/tests/test_rcparams.py b/lib/matplotlib/tests/test_rcparams.py index 4290160598ad..3f168efbf573 100644 --- a/lib/matplotlib/tests/test_rcparams.py +++ b/lib/matplotlib/tests/test_rcparams.py @@ -29,7 +29,7 @@ validate_cycler, validate_hatch, validate_hist_bins) - +import pytest mpl.rc('text', usetex=False) mpl.rc('lines', linewidth=22) @@ -260,7 +260,7 @@ def _validation_fail_helper(validator, arg, exception_type): if sys.version_info[:2] < (2, 7): raise nose.SkipTest("assert_raises as context manager not " "supported with Python < 2.7") - pytest.raise(exception_type,validator(arg)) + pytest.raises(exception_type,validator, arg) diff --git a/lib/matplotlib/tests/test_simplification.py b/lib/matplotlib/tests/test_simplification.py index 426b4ff3df13..36c865804230 100644 --- a/lib/matplotlib/tests/test_simplification.py +++ b/lib/matplotlib/tests/test_simplification.py @@ -7,6 +7,7 @@ import matplotlib from matplotlib.testing.decorators import image_comparison, knownfailureif, cleanup import matplotlib.pyplot as plt +import pytest from pylab import * import numpy as np diff --git a/lib/matplotlib/tests/test_ticker.py b/lib/matplotlib/tests/test_ticker.py index ea2b3a54a965..031e37a144fc 100644 --- a/lib/matplotlib/tests/test_ticker.py +++ b/lib/matplotlib/tests/test_ticker.py @@ -12,6 +12,7 @@ from matplotlib.testing.decorators import cleanup import warnings +import pytest def test_MaxNLocator(): From 5fd4351c392414e26fe7870582ec0784bde4d8fd Mon Sep 17 00:00:00 2001 From: Jason King Date: Thu, 5 Nov 2015 18:36:51 +1100 Subject: [PATCH 015/174] fixing syntax failures --- lib/matplotlib/tests/test_dates.py | 3 +-- lib/matplotlib/tests/test_labeled_data_unpacking.py | 4 ++-- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/lib/matplotlib/tests/test_dates.py b/lib/matplotlib/tests/test_dates.py index fdce84b4e416..770bc06d5185 100644 --- a/lib/matplotlib/tests/test_dates.py +++ b/lib/matplotlib/tests/test_dates.py @@ -334,8 +334,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 list(map(str, mdates.num2date(locator()))) == - expected + assert list(map(str, mdates.num2date(locator()))) == expected @image_comparison(baseline_images=['date_inverted_limit'], diff --git a/lib/matplotlib/tests/test_labeled_data_unpacking.py b/lib/matplotlib/tests/test_labeled_data_unpacking.py index 8eaaff56d4f2..14baa31c7c10 100644 --- a/lib/matplotlib/tests/test_labeled_data_unpacking.py +++ b/lib/matplotlib/tests/test_labeled_data_unpacking.py @@ -137,7 +137,7 @@ def test_function_call_without_data(): """test without data -> no replacements""" for func in all_funcs: 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="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: " @@ -216,7 +216,7 @@ 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 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, 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: " From 47c968bb1508f905afa3ba7bea9124bd55595e7b Mon Sep 17 00:00:00 2001 From: Jason King Date: Thu, 5 Nov 2015 20:53:53 +1100 Subject: [PATCH 016/174] Force travis to install pytest, and plugins Need to stop running nose through code, and start running pytest from shell. --- .travis.yml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/.travis.yml b/.travis.yml index d63ed602c0e2..402e8da05b93 100644 --- a/.travis.yml +++ b/.travis.yml @@ -78,6 +78,14 @@ install: # Always install from pypi - pip install $PRE pep8 cycler coveralls coverage - '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-flake8 for docs + - pip install pytest-flake8 + # 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 From 1b509c1a247def123a822a072a423e155a6c3fcd Mon Sep 17 00:00:00 2001 From: Jason King Date: Fri, 6 Nov 2015 12:22:29 +1100 Subject: [PATCH 017/174] get travis to run py.test instead of nose. also supply pep8 with list of files and warnings to ignore. --- .travis.yml | 8 +++++--- tox.ini | 6 +++++- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/.travis.yml b/.travis.yml index 402e8da05b93..0416a10a4dfa 100644 --- a/.travis.yml +++ b/.travis.yml @@ -83,8 +83,8 @@ install: # 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-flake8 for docs - - pip install pytest-flake8 + # 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 @@ -119,7 +119,9 @@ 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 $NOSE_ARGS $TEST_ARGS + py.test --pep8 --cov=matplotlib ./lib/matplotlib/tests + else cd doc python make.py html --small --warningsaserrors diff --git a/tox.ini b/tox.ini index 36291d307e96..c67253b5bfa1 100644 --- a/tox.ini +++ b/tox.ini @@ -18,4 +18,8 @@ deps = [pytest] norecursedirs = .git build -testpaths = tests \ No newline at end of file +testpaths = tests + +[pep8] +ignore=E111,E114,E115,E116,E121,E122,E123,E124,E125,E126,E127,E128,E129,E131,E265,E266,W503 +exclude=_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 \ No newline at end of file From 432e9e8d847ce86e40085f3a719a305c226f1aaa Mon Sep 17 00:00:00 2001 From: Jason King Date: Fri, 6 Nov 2015 12:38:16 +1100 Subject: [PATCH 018/174] small pep8 fix to force travis to build no response after previous patch from travis. come on travis, wake up. --- lib/matplotlib/tests/test_skew.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/matplotlib/tests/test_skew.py b/lib/matplotlib/tests/test_skew.py index 3ccc150896df..2070a470e876 100644 --- a/lib/matplotlib/tests/test_skew.py +++ b/lib/matplotlib/tests/test_skew.py @@ -106,7 +106,7 @@ class SkewXAxes(Axes): name = 'skewx' def _init_axis(self): - #Taken from Axes and modified to use our modified X-axis + # Taken from Axes and modified to use our modified X-axis self.xaxis = SkewXAxis(self) self.spines['top'].register_axis(self.xaxis) self.spines['bottom'].register_axis(self.xaxis) @@ -128,7 +128,7 @@ def _set_lim_and_transforms(self): """ rot = 30 - #Get the standard transform setup from the Axes base class + # Get the standard transform setup from the Axes base class Axes._set_lim_and_transforms(self) # Need to put the skew in the middle, after the scale and limits, From 60b038ccfbff224fa22994b2ca1fd4cabc6c8bf2 Mon Sep 17 00:00:00 2001 From: Jason King Date: Sat, 7 Nov 2015 00:14:23 +1100 Subject: [PATCH 019/174] lets see if indenting a comment fixes the problem --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 0416a10a4dfa..29b1e2108cf9 100644 --- a/.travis.yml +++ b/.travis.yml @@ -119,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 $NOSE_ARGS $TEST_ARGS py.test --pep8 --cov=matplotlib ./lib/matplotlib/tests else From 2984d4414f9531f309de4eaf0258fca5deb8b82c Mon Sep 17 00:00:00 2001 From: Jason King Date: Sat, 7 Nov 2015 21:25:11 +1100 Subject: [PATCH 020/174] give py.test the install location of the module, rather than the download location. hopefully that will fix the path problems. --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 29b1e2108cf9..fc4aebe22c5d 100644 --- a/.travis.yml +++ b/.travis.yml @@ -121,7 +121,7 @@ script: 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 py.test --pep8 --cov=matplotlib ./lib/matplotlib/tests - + py.test --pep8 --cov=matplotlib `python -c "import os ; import inspect ; import matplotlib; print( os.path.dirname(inspect.getfile(matplotlib)) )"` else cd doc python make.py html --small --warningsaserrors From e27451df25be371250c8cf1794869501476c2b57 Mon Sep 17 00:00:00 2001 From: Jason King Date: Sat, 7 Nov 2015 21:31:59 +1100 Subject: [PATCH 021/174] forgot to remove the bad py.test call. --- .travis.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index fc4aebe22c5d..8114aa0456d8 100644 --- a/.travis.yml +++ b/.travis.yml @@ -120,7 +120,6 @@ 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 - py.test --pep8 --cov=matplotlib ./lib/matplotlib/tests py.test --pep8 --cov=matplotlib `python -c "import os ; import inspect ; import matplotlib; print( os.path.dirname(inspect.getfile(matplotlib)) )"` else cd doc From 784fdf8dadbf3e78ccb5e0dd858d4ae8b15695e9 Mon Sep 17 00:00:00 2001 From: Jason King Date: Sat, 7 Nov 2015 22:30:48 +1100 Subject: [PATCH 022/174] force pytest-pep8 to ignore the pep8 warnings that matplotlib has already specified. Which might make the output log shorter than 4 megs. --- tox.ini | 1 + 1 file changed, 1 insertion(+) diff --git a/tox.ini b/tox.ini index c67253b5bfa1..150ea308d756 100644 --- a/tox.ini +++ b/tox.ini @@ -19,6 +19,7 @@ deps = [pytest] norecursedirs = .git build testpaths = tests +pep8ignore = E111 E114 E115 E116 E121 E122 E123 E124 E125 E126 E127 E128 E129 E131 E265 E266 W503 [pep8] ignore=E111,E114,E115,E116,E121,E122,E123,E124,E125,E126,E127,E128,E129,E131,E265,E266,W503 From f035db746fe32b5ba84aa5564958c9a65019fc96 Mon Sep 17 00:00:00 2001 From: Jason King Date: Sat, 7 Nov 2015 23:55:47 +1100 Subject: [PATCH 023/174] temporarily adding more items to be ignored by pep8, just to see how much smaller it makes the log. --- tox.ini | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tox.ini b/tox.ini index 150ea308d756..89e89e7b66a3 100644 --- a/tox.ini +++ b/tox.ini @@ -19,7 +19,7 @@ deps = [pytest] norecursedirs = .git build testpaths = tests -pep8ignore = E111 E114 E115 E116 E121 E122 E123 E124 E125 E126 E127 E128 E129 E131 E265 E266 W503 +pep8ignore = E111 E114 E115 E116 E121 E122 E123 E124 E125 E126 E127 E128 E129 E131 E265 E266 W503 E241 E401 E231 E203 E226 [pep8] ignore=E111,E114,E115,E116,E121,E122,E123,E124,E125,E126,E127,E128,E129,E131,E265,E266,W503 From 1e7b62cc6a674a69c69be45c8201e5cd4f62548b Mon Sep 17 00:00:00 2001 From: Jason King Date: Sun, 8 Nov 2015 10:44:47 +1100 Subject: [PATCH 024/174] trying out --pyargs as requested, also removing pep checks, there's too many, output log too large to see the end. --- .travis.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 8114aa0456d8..231565f9a8ea 100644 --- a/.travis.yml +++ b/.travis.yml @@ -120,7 +120,8 @@ 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 - py.test --pep8 --cov=matplotlib `python -c "import os ; import inspect ; import matplotlib; print( os.path.dirname(inspect.getfile(matplotlib)) )"` + # py.test --pep8 --cov=matplotlib `python -c "import os ; import inspect ; import matplotlib; print( os.path.dirname(inspect.getfile(matplotlib)) )"` + py.test --cov=matplotlib --pyargs matplotlib else cd doc python make.py html --small --warningsaserrors From 56d99ed34ca229f08e2df4f4b826e97c9bf311ce Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 9 Nov 2015 00:22:31 +1100 Subject: [PATCH 025/174] tests.py should now act more like the old nose version did, using pytest. also fixed up problem in test_labeled_data_unpacking, relating to '==' on two lines. --- lib/matplotlib/__init__.py | 11 +++++----- .../tests/test_labeled_data_unpacking.py | 6 ++---- tests.py | 21 ++++++++++++------- 3 files changed, 21 insertions(+), 17 deletions(-) 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/tests/test_labeled_data_unpacking.py b/lib/matplotlib/tests/test_labeled_data_unpacking.py index 14baa31c7c10..4d1e582fbe96 100644 --- a/lib/matplotlib/tests/test_labeled_data_unpacking.py +++ b/lib/matplotlib/tests/test_labeled_data_unpacking.py @@ -346,10 +346,8 @@ def funcy(ax, *args, **kwargs): # the normal case... data = {"x": "X", "hy1": "Y"} - assert funcy(None, "x", "hy1", data=data) == - "('X', 'Y') | {}" - assert 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(): diff --git a/tests.py b/tests.py index cf5c82f3bc0e..86c932b4db41 100755 --- a/tests.py +++ b/tests.py @@ -16,12 +16,13 @@ import matplotlib matplotlib.use('agg') -import nose +# import nose +import pytest from matplotlib import default_test_modules def run(extra_args): - from nose.plugins import multiprocess + # from nose.plugins import multiprocess env = matplotlib._get_nose_env() @@ -30,13 +31,17 @@ def run(extra_args): # Nose doesn't automatically instantiate all of the plugins in the # child processes, so we have to provide the multiprocess plugin with # a list. - plugins = matplotlib._get_extra_test_plugins() - multiprocess._instantiate_plugins = plugins + # plugins = matplotlib._get_extra_test_plugins() + # multiprocess._instantiate_plugins = plugins - nose.main(addplugins=[x() for x in plugins], - defaultTest=default_test_modules, - argv=sys.argv + extra_args, - env=env) + # nose.main(addplugins=[x() for x in plugins], + # defaultTest=default_test_modules, + # argv=sys.argv + extra_args, + # env=env) + + argv = sys.argv + extra_args + for test_module in default_test_modules: + pytest.main(' '.join(argv[1:]) + ' ' + " --pyargs %s" % test_module) if __name__ == '__main__': extra_args = [] From 7d38aa3159d3dff992565eb18ae620563785946a Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 9 Nov 2015 10:23:35 +1100 Subject: [PATCH 026/174] lets try the 'gdb python tests.py' method again. --- .travis.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index 231565f9a8ea..0cc3d71d06c8 100644 --- a/.travis.yml +++ b/.travis.yml @@ -119,9 +119,9 @@ 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 $NOSE_ARGS $TEST_ARGS # py.test --pep8 --cov=matplotlib `python -c "import os ; import inspect ; import matplotlib; print( os.path.dirname(inspect.getfile(matplotlib)) )"` - py.test --cov=matplotlib --pyargs matplotlib + # py.test --cov=matplotlib --pyargs matplotlib else cd doc python make.py html --small --warningsaserrors From 7bbc04ad2b7bb3a9dbabdc8bb72ec18962f4e45e Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 9 Nov 2015 10:41:13 +1100 Subject: [PATCH 027/174] the switches that nose needed , make pytest fail, so lets remove them for now. --- tests.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests.py b/tests.py index 86c932b4db41..6f7ef108fcce 100755 --- a/tests.py +++ b/tests.py @@ -41,7 +41,7 @@ def run(extra_args): argv = sys.argv + extra_args for test_module in default_test_modules: - pytest.main(' '.join(argv[1:]) + ' ' + " --pyargs %s" % test_module) + pytest.main(" --pyargs %s" % test_module) if __name__ == '__main__': extra_args = [] From 05da48a02152a724a892837eb20ae7d20ed750aa Mon Sep 17 00:00:00 2001 From: pizzathief Date: Mon, 9 Nov 2015 12:53:14 +1100 Subject: [PATCH 028/174] pytest.main doesn't like --pyargs now? it used to.. --- tests.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests.py b/tests.py index 6f7ef108fcce..4ef04a865de9 100755 --- a/tests.py +++ b/tests.py @@ -41,7 +41,7 @@ def run(extra_args): argv = sys.argv + extra_args for test_module in default_test_modules: - pytest.main(" --pyargs %s" % test_module) + pytest.main(test_module) if __name__ == '__main__': extra_args = [] From 98b1e69024c4993b84d84f365d937f6a472b4150 Mon Sep 17 00:00:00 2001 From: Jason King Date: Fri, 13 Nov 2015 22:25:26 +1100 Subject: [PATCH 029/174] Adding in all tests to the list, including argv[1:] --- tests.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/tests.py b/tests.py index 4ef04a865de9..46799cabc3b0 100755 --- a/tests.py +++ b/tests.py @@ -40,8 +40,7 @@ def run(extra_args): # env=env) argv = sys.argv + extra_args - for test_module in default_test_modules: - pytest.main(test_module) + pytest.main(['--pyargs'] + argv[1:] + default_test_modules) if __name__ == '__main__': extra_args = [] From 6853e712581776673023dc88e9721afcc697a5f1 Mon Sep 17 00:00:00 2001 From: Jason King Date: Fri, 13 Nov 2015 22:42:21 +1100 Subject: [PATCH 030/174] seems --processes=2 and --process-timeout=300 need to be swallowed, otherwise something complains --- tests.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests.py b/tests.py index 46799cabc3b0..7cc599ff07a3 100755 --- a/tests.py +++ b/tests.py @@ -40,7 +40,7 @@ def run(extra_args): # env=env) argv = sys.argv + extra_args - pytest.main(['--pyargs'] + argv[1:] + default_test_modules) + pytest.main(['--pyargs'] + default_test_modules) if __name__ == '__main__': extra_args = [] From 105a15dde6211a8b406de87c2970c691b2e1a23a Mon Sep 17 00:00:00 2001 From: Jason King Date: Fri, 13 Nov 2015 23:12:40 +1100 Subject: [PATCH 031/174] replace assert_raises with pytest.raises --- lib/matplotlib/tests/test_rcparams.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/lib/matplotlib/tests/test_rcparams.py b/lib/matplotlib/tests/test_rcparams.py index 3f168efbf573..18f86739d6cb 100644 --- a/lib/matplotlib/tests/test_rcparams.py +++ b/lib/matplotlib/tests/test_rcparams.py @@ -121,7 +121,7 @@ def test_rcparams_update(): 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', @@ -134,7 +134,7 @@ def test_rcparams_init(): if sys.version_info[:2] < (2, 7): raise nose.SkipTest("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)', @@ -180,11 +180,11 @@ def test_Bug_2543_newer_python(): if sys.version_info[:2] < (2, 7): raise nose.SkipTest("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 From 5482cc767548ee7fa258c47cbb02d27595d3e88e Mon Sep 17 00:00:00 2001 From: Jason King Date: Fri, 13 Nov 2015 23:13:50 +1100 Subject: [PATCH 032/174] another assert_raises to replace with pytest.raises --- lib/matplotlib/tests/test_rcparams.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/matplotlib/tests/test_rcparams.py b/lib/matplotlib/tests/test_rcparams.py index 18f86739d6cb..92394b0d7bab 100644 --- a/lib/matplotlib/tests/test_rcparams.py +++ b/lib/matplotlib/tests/test_rcparams.py @@ -406,7 +406,7 @@ def test_rcparams_reset_after_fail(): assert mpl.rcParams['text.usetex'] is False - with assert_raises(KeyError): + with pytest.raises(KeyError): with mpl.rc_context(rc=OrderedDict([('text.usetex', True),('test.blah', True)])): pass From 4a8caad96019bea4b48a9ee836cc82f5bbf86913 Mon Sep 17 00:00:00 2001 From: Jason King Date: Fri, 13 Nov 2015 23:16:35 +1100 Subject: [PATCH 033/174] replace assert_raises with pytest.raises --- lib/matplotlib/tests/test_dates.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/lib/matplotlib/tests/test_dates.py b/lib/matplotlib/tests/test_dates.py index 770bc06d5185..9797dc9cca62 100644 --- a/lib/matplotlib/tests/test_dates.py +++ b/lib/matplotlib/tests/test_dates.py @@ -19,6 +19,7 @@ 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 +106,7 @@ 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') + pytest.raises(RuntimeError, fig.savefig, 'junk.png') @image_comparison(baseline_images=['RRuleLocator_bounds'], extensions=['png']) @@ -263,7 +264,7 @@ def test_empty_date_with_year_formatter(): ax.xaxis.set_major_formatter(yearFmt) with tempfile.TemporaryFile() as fh: - assert_raises(ValueError, fig.savefig, fh) + pytest.raises(ValueError, fig.savefig, fh) def test_auto_date_locator(): From 8985c357ae16547b922cee38a977676e11264cb9 Mon Sep 17 00:00:00 2001 From: Jason King Date: Sat, 14 Nov 2015 10:24:54 +1100 Subject: [PATCH 034/174] Fixing errors that appear before testing starts Likely caused by me. --- lib/matplotlib/tests/test_labeled_data_unpacking.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/lib/matplotlib/tests/test_labeled_data_unpacking.py b/lib/matplotlib/tests/test_labeled_data_unpacking.py index 4d1e582fbe96..2f037543583b 100644 --- a/lib/matplotlib/tests/test_labeled_data_unpacking.py +++ b/lib/matplotlib/tests/test_labeled_data_unpacking.py @@ -358,5 +358,4 @@ def f(): # it as data... data = {"x": "X", "y": "Y", "ro": "!!"} with assert_produces_warning(RuntimeWarning): - assert funcy(None, "y", "ro", data=data) == - "('Y', '!!') | {}" + assert funcy(None, "y", "ro", data=data) == "('Y', '!!') | {}" From 789f864bcfb9ae095f3d496070d0a554769ba2f6 Mon Sep 17 00:00:00 2001 From: Jason King Date: Sat, 14 Nov 2015 10:51:23 +1100 Subject: [PATCH 035/174] replaced a nose function for known failing tests --- lib/matplotlib/tests/test_animation.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/lib/matplotlib/tests/test_animation.py b/lib/matplotlib/tests/test_animation.py index 2a62cfb7a2ac..08271272cffb 100644 --- a/lib/matplotlib/tests/test_animation.py +++ b/lib/matplotlib/tests/test_animation.py @@ -10,9 +10,10 @@ from nose import with_setup from matplotlib import pyplot as plt from matplotlib import animation -from matplotlib.testing.noseclasses import KnownFailureTest +# from matplotlib.testing.noseclasses import KnownFailureTest from matplotlib.testing.decorators import cleanup from matplotlib.testing.decorators import CleanupTest +import pytest class NullMovieWriter(animation.AbstractMovieWriter): @@ -109,7 +110,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 +135,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: From 4900796253c9a4295392a80dbbad840ff67fcb1b Mon Sep 17 00:00:00 2001 From: Jason King Date: Sat, 14 Nov 2015 11:09:46 +1100 Subject: [PATCH 036/174] updating basic tests that are know to fail with pytest decorators --- lib/matplotlib/tests/test_basic.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/matplotlib/tests/test_basic.py b/lib/matplotlib/tests/test_basic.py index f960be09fe6e..dbff048af882 100644 --- a/lib/matplotlib/tests/test_basic.py +++ b/lib/matplotlib/tests/test_basic.py @@ -7,13 +7,14 @@ from matplotlib.testing.decorators import knownfailureif from pylab import * +import pytest def test_simple(): assert 1 + 1 == 2 -@knownfailureif(True) +@pytest.mark.xfail def test_simple_knownfail(): # Test the known fail mechanism. assert 1 + 1 == 3 From 06335762a004a658ab3224fc7bec4a7f51d94032 Mon Sep 17 00:00:00 2001 From: Jason King Date: Wed, 18 Nov 2015 21:32:31 +1100 Subject: [PATCH 037/174] add the ability to only run pep8 tests. remove commented out means of running tests from .travis.yml --- .travis.yml | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/.travis.yml b/.travis.yml index 0cc3d71d06c8..4bb7ec526456 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" @@ -119,9 +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 - # py.test --pep8 --cov=matplotlib `python -c "import os ; import inspect ; import matplotlib; print( os.path.dirname(inspect.getfile(matplotlib)) )"` - # py.test --cov=matplotlib --pyargs matplotlib + gdb -return-child-result -batch -ex r -ex bt --args python tests.py $TEST_ARGS else cd doc python make.py html --small --warningsaserrors From 47ef9f025630bbb27de07847cbb587a0543eabd7 Mon Sep 17 00:00:00 2001 From: Jason King Date: Wed, 18 Nov 2015 21:35:14 +1100 Subject: [PATCH 038/174] ass civerage report as standard --- tests.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests.py b/tests.py index 7cc599ff07a3..c8139a8506ad 100755 --- a/tests.py +++ b/tests.py @@ -40,7 +40,7 @@ def run(extra_args): # env=env) argv = sys.argv + extra_args - pytest.main(['--pyargs'] + default_test_modules) + pytest.main(['--pyargs', '--cov=matplotlib'] + default_test_modules) if __name__ == '__main__': extra_args = [] From 2a7637cffa907cf819a1d9573cffbbc00b799d10 Mon Sep 17 00:00:00 2001 From: Jason King Date: Wed, 18 Nov 2015 22:23:46 +1100 Subject: [PATCH 039/174] no need for the nose pep8 tests, so remove from tests.py --- tests.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/tests.py b/tests.py index c8139a8506ad..9371aa9f3b25 100755 --- a/tests.py +++ b/tests.py @@ -46,11 +46,12 @@ def run(extra_args): extra_args = [] if '--no-pep8' in sys.argv: - default_test_modules.remove('matplotlib.tests.test_coding_standards') - sys.argv.remove('--no-pep8') + # default_test_modules.remove('matplotlib.tests.test_coding_standards') + # sys.argv.remove('--no-pep8') + pass elif '--pep8' in sys.argv: - default_test_modules = ['matplotlib.tests.test_coding_standards'] - sys.argv.remove('--pep8') + default_test_modules = ['--pep8 -m pep8'] + # sys.argv.remove('--pep8') if '--no-network' in sys.argv: from matplotlib.testing import disable_internet disable_internet.turn_off_internet() From 08ae5ef396d297acff1c36cae47f6f2b4ce9df2a Mon Sep 17 00:00:00 2001 From: Jason King Date: Wed, 25 Nov 2015 22:01:00 +1100 Subject: [PATCH 040/174] pep8 and non-pep8 tests act better now. taking out the code coverage module, its in the way for the moment. --- tests.py | 31 ++++++++----------------------- 1 file changed, 8 insertions(+), 23 deletions(-) diff --git a/tests.py b/tests.py index 9371aa9f3b25..2e966860b2ae 100755 --- a/tests.py +++ b/tests.py @@ -22,36 +22,21 @@ def run(extra_args): - # from nose.plugins import multiprocess - - env = matplotlib._get_nose_env() - matplotlib._init_tests() - # Nose doesn't automatically instantiate all of the plugins in the - # child processes, so we have to provide the multiprocess plugin with - # a list. - # plugins = matplotlib._get_extra_test_plugins() - # multiprocess._instantiate_plugins = plugins - - # nose.main(addplugins=[x() for x in plugins], - # defaultTest=default_test_modules, - # argv=sys.argv + extra_args, - # env=env) - argv = sys.argv + extra_args - pytest.main(['--pyargs', '--cov=matplotlib'] + default_test_modules) + # pytest.main(['--pyargs', '--cov=matplotlib'] + default_test_modules) + print(argv + ['--pyargs'] + default_test_modules) + pytest.main(argv + ['--pyargs'] + default_test_modules) if __name__ == '__main__': + # extra_args = ['--cov=matplotlib'] extra_args = [] - if '--no-pep8' in sys.argv: - # default_test_modules.remove('matplotlib.tests.test_coding_standards') - # sys.argv.remove('--no-pep8') - pass - elif '--pep8' in sys.argv: - default_test_modules = ['--pep8 -m pep8'] - # sys.argv.remove('--pep8') + if '--pep8' in sys.argv: + extra_args.extend(['--pep8']) + extra_args.extend(['-m pep8']) + sys.argv.remove('--pep8') if '--no-network' in sys.argv: from matplotlib.testing import disable_internet disable_internet.turn_off_internet() From bd0c06183bf2e5bf974b4c96daf9efc01d249447 Mon Sep 17 00:00:00 2001 From: Jason King Date: Fri, 27 Nov 2015 18:38:35 +1100 Subject: [PATCH 041/174] remove more of the nose infrastructure --- lib/matplotlib/testing/decorators.py | 9 +++++---- lib/matplotlib/tests/test_animation.py | 1 - lib/matplotlib/tests/test_coding_standards.py | 4 ++-- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/lib/matplotlib/testing/decorators.py b/lib/matplotlib/testing/decorators.py index a73dbd150504..030304c6bba7 100644 --- a/lib/matplotlib/testing/decorators.py +++ b/lib/matplotlib/testing/decorators.py @@ -23,10 +23,11 @@ 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 +import pytest def knownfailureif(fail_condition, msg=None, known_exception_class=None ): @@ -59,7 +60,7 @@ def failer(*args, **kwargs): # 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. + 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': @@ -245,7 +246,7 @@ 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 diff --git a/lib/matplotlib/tests/test_animation.py b/lib/matplotlib/tests/test_animation.py index 08271272cffb..ff957a39c3a2 100644 --- a/lib/matplotlib/tests/test_animation.py +++ b/lib/matplotlib/tests/test_animation.py @@ -10,7 +10,6 @@ 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 diff --git a/lib/matplotlib/tests/test_coding_standards.py b/lib/matplotlib/tests/test_coding_standards.py index d000b05249d1..9224feb8c82d 100644 --- a/lib/matplotlib/tests/test_coding_standards.py +++ b/lib/matplotlib/tests/test_coding_standards.py @@ -6,7 +6,7 @@ from nose.tools import assert_equal from nose.plugins.skip import SkipTest -from matplotlib.testing.noseclasses import KnownFailureTest +import pytest try: import pep8 @@ -261,7 +261,7 @@ def test_pep8_conformance_examples(): fp, tail = os.path.split(fp) if mpldir is None: - raise KnownFailureTest("can not find the examples, set env " + raise pytest.xfail("can not find the examples, set env " "MPL_REPO_DIR to point to the top-level path " "of the source tree") From 42e7ae1c315beb9610ba33b87a20354e16d81d4e Mon Sep 17 00:00:00 2001 From: Jason King Date: Sun, 13 Dec 2015 11:13:16 +1100 Subject: [PATCH 042/174] Pass the exit code of pytest.main back to the shell. --- tests.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/tests.py b/tests.py index 2e966860b2ae..eb45aa3a98f3 100755 --- a/tests.py +++ b/tests.py @@ -27,7 +27,7 @@ def run(extra_args): argv = sys.argv + extra_args # pytest.main(['--pyargs', '--cov=matplotlib'] + default_test_modules) print(argv + ['--pyargs'] + default_test_modules) - pytest.main(argv + ['--pyargs'] + default_test_modules) + return pytest.main(argv + ['--pyargs'] + default_test_modules) if __name__ == '__main__': # extra_args = ['--cov=matplotlib'] @@ -43,4 +43,5 @@ def run(extra_args): extra_args.extend(['--eval-attr="not network"']) sys.argv.remove('--no-network') - run(extra_args) + returnvar = run(extra_args) + sys.exit(returnvar) From 86820be27b1b520ba06c9525988b490357cbd3f8 Mon Sep 17 00:00:00 2001 From: Jason King Date: Sun, 13 Dec 2015 14:38:20 +1100 Subject: [PATCH 043/174] replace nose decorator with pytest code. --- lib/matplotlib/tests/test_cbook.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/matplotlib/tests/test_cbook.py b/lib/matplotlib/tests/test_cbook.py index 7685f3e55e9f..39a6edd6540a 100644 --- a/lib/matplotlib/tests/test_cbook.py +++ b/lib/matplotlib/tests/test_cbook.py @@ -80,9 +80,9 @@ def setUp(self): self.arr_colors = ['r', 'g', 'b', 'c', 'm', 'y'] self.arr_rgba = mcolors.colorConverter.to_rgba_array(self.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) From 37c67c2d6b6e0b24f8d40e2cdf79f61abaad7a7a Mon Sep 17 00:00:00 2001 From: Jason King Date: Sun, 13 Dec 2015 14:54:22 +1100 Subject: [PATCH 044/174] whoops, deleted an 'a' from a variable while doing nose -> pytest transform. --- lib/matplotlib/tests/test_axes.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/matplotlib/tests/test_axes.py b/lib/matplotlib/tests/test_axes.py index 7679c8eb76c7..fb0e05a89f03 100644 --- a/lib/matplotlib/tests/test_axes.py +++ b/lib/matplotlib/tests/test_axes.py @@ -122,7 +122,7 @@ def test_twinx_cla(): ax3 = ax2.twiny() plt.draw() assert not ax2.xaxis.get_visible() - assert not x2.patch.get_visible() + assert not ax2.patch.get_visible() ax2.cla() ax3.cla() From 84359ac181c69778a4a204c70a9891a42da4006d Mon Sep 17 00:00:00 2001 From: Jason King Date: Sun, 13 Dec 2015 16:25:39 +1100 Subject: [PATCH 045/174] fix up a bunch of pytest.raises calls. I changed func,x,y into func(x,y) by mistake, and hadn't changed a few back. --- lib/matplotlib/tests/test_cbook.py | 12 ++++++------ lib/matplotlib/tests/test_mlab.py | 22 +++++++++++----------- 2 files changed, 17 insertions(+), 17 deletions(-) diff --git a/lib/matplotlib/tests/test_cbook.py b/lib/matplotlib/tests/test_cbook.py index 39a6edd6540a..a7771cfd96dd 100644 --- a/lib/matplotlib/tests/test_cbook.py +++ b/lib/matplotlib/tests/test_cbook.py @@ -255,15 +255,15 @@ def test_results_withlabels(self): 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): diff --git a/lib/matplotlib/tests/test_mlab.py b/lib/matplotlib/tests/test_mlab.py index c4df96a70a8d..673c052328c3 100644 --- a/lib/matplotlib/tests/test_mlab.py +++ b/lib/matplotlib/tests/test_mlab.py @@ -143,23 +143,23 @@ def test_stride_windows_n_gt_lenx_ValueError(self): def test_stride_windows_n_lt_1_ValueError(self): x = np.arange(10) - pytest.raises(ValueError, mlab.stride_windows(x, 0)) + pytest.raises(ValueError, mlab.stride_windows, x, 0) def test_stride_repeat_2D_ValueError(self): x = np.arange(10)[np.newaxis] - pytest.raises(ValueError, mlab.stride_repeat(x, 5)) + pytest.raises(ValueError, mlab.stride_repeat, x, 5) def test_stride_repeat_axis_lt_0_ValueError(self): x = np.array(0) - pytest.raises(ValueError, mlab.stride_repeat(x, 5, axis=-1)) + pytest.raises(ValueError, mlab.stride_repeat, x, 5, axis=-1) def test_stride_repeat_axis_gt_1_ValueError(self): x = np.array(0) - pytest.raises(ValueError, mlab.stride_repeat(x, 5, axis=2)) + pytest.raises(ValueError, mlab.stride_repeat, x, 5, axis=2) def test_stride_repeat_n_lt_1_ValueError(self): x = np.arange(10) - pytest.raises(ValueError, mlab.stride_repeat(x, 0)) + pytest.raises(ValueError, mlab.stride_repeat, x, 0) def test_stride_repeat_n1_axis0(self): x = np.arange(10) @@ -1588,7 +1588,7 @@ def test_psd_detrend_mean_func_offset(self): assert_allclose(spec_g, spec_c, atol=1e-08) # these should not be almost equal pytest.raises(AssertionError, - assert_allclose(spec_b, spec_c, atol=1e-08)) + assert_allclose,spec_b, spec_c, atol=1e-08) def test_psd_detrend_mean_str_offset(self): if self.NFFT_density is None: @@ -1624,7 +1624,7 @@ def test_psd_detrend_mean_str_offset(self): assert_allclose(spec_g, spec_c, atol=1e-08) # these should not be almost equal pytest.raises(AssertionError, - assert_allclose(spec_b, spec_c, atol=1e-08)) + assert_allclose, spec_b, spec_c, atol=1e-08) def test_psd_detrend_linear_func_trend(self): if self.NFFT_density is None: @@ -1660,7 +1660,7 @@ def test_psd_detrend_linear_func_trend(self): assert_allclose(spec_g, spec_c, atol=1e-08) # these should not be almost equal pytest.raises(AssertionError, - assert_allclose(spec_b, spec_c, atol=1e-08)) + assert_allclose, spec_b, spec_c, atol=1e-08) def test_psd_detrend_linear_str_trend(self): if self.NFFT_density is None: @@ -1696,7 +1696,7 @@ def test_psd_detrend_linear_str_trend(self): assert_allclose(spec_g, spec_c, atol=1e-08) # these should not be almost equal pytest.raises(AssertionError, - assert_allclose(spec_b, spec_c, atol=1e-08)) + assert_allclose, spec_b, spec_c, atol=1e-08) def test_psd_window_hanning(self): if self.NFFT_density is None: @@ -1740,7 +1740,7 @@ def test_psd_window_hanning(self): assert_allclose(spec_g, spec_c, atol=1e-08) # these should not be almost equal pytest.raises(AssertionError, - assert_allclose(spec_b, spec_c, atol=1e-08)) + assert_allclose, spec_b, spec_c, atol=1e-08) def test_psd_window_hanning_detrend_linear(self): if self.NFFT_density is None: @@ -1789,7 +1789,7 @@ def test_psd_window_hanning_detrend_linear(self): assert_allclose(spec_g, spec_c, atol=1e-08) # these should not be almost equal pytest.raises(AssertionError, - assert_allclose(spec_b, spec_c, atol=1e-08)) + assert_allclose, spec_b, spec_c, atol=1e-08) def test_psd_windowarray(self): freqs = self.freqs_density From c76bef97cd2efc0db40f717b518673c6e810a1a6 Mon Sep 17 00:00:00 2001 From: Jason King Date: Sun, 13 Dec 2015 17:10:13 +1100 Subject: [PATCH 046/174] found 'assert_less' calls to replace --- lib/matplotlib/tests/test_spines.py | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/lib/matplotlib/tests/test_spines.py b/lib/matplotlib/tests/test_spines.py index 3c436ce3ef0f..fe7654e2a24d 100644 --- a/lib/matplotlib/tests/test_spines.py +++ b/lib/matplotlib/tests/test_spines.py @@ -71,11 +71,9 @@ def test_label_without_ticks(): spine = ax.spines['left'] spinebbox = spine.get_transform().transform_path( spine.get_path()).get_extents() - assert (ax.yaxis.label.get_position()[0] < spinebbox.xmin, - "Y-Axis label not left of the spine") + assert ax.yaxis.label.get_position()[0] < spinebbox.xmin, "Y-Axis label not left of the spine" spine = ax.spines['bottom'] spinebbox = spine.get_transform().transform_path( spine.get_path()).get_extents() - assert (ax.xaxis.label.get_position()[1] < spinebbox.ymin, - "X-Axis label not below the spine") + assert ax.xaxis.label.get_position()[1] < spinebbox.ymin, "X-Axis label not below the spine" From 2e58461bbde55c82eb60a2adef79b8eb6deaa5a2 Mon Sep 17 00:00:00 2001 From: Jason King Date: Sun, 13 Dec 2015 17:15:33 +1100 Subject: [PATCH 047/174] found a space and comma char that had attempted an escape of the facility. slammed back in the file where they belong. --- lib/matplotlib/tests/test_lines.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/matplotlib/tests/test_lines.py b/lib/matplotlib/tests/test_lines.py index 268fde346f2f..3440a2db1827 100644 --- a/lib/matplotlib/tests/test_lines.py +++ b/lib/matplotlib/tests/test_lines.py @@ -116,7 +116,7 @@ def test_valid_linestyles(): "not supported with Python < 2.7") line = mpl.lines.Line2D([], []) - pytest.raises(ValueErrorline.set_linestyle('aardvark')) + pytest.raises(ValueError, line.set_linestyle, 'aardvark') @image_comparison(baseline_images=['line_collection_dashes'], remove_text=True) From 517b232f53812567b311e08b1fdca20a2580f21c Mon Sep 17 00:00:00 2001 From: Jason King Date: Sun, 13 Dec 2015 17:19:20 +1100 Subject: [PATCH 048/174] found some assert_equal statements to convert. --- lib/matplotlib/tests/test_axes.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/lib/matplotlib/tests/test_axes.py b/lib/matplotlib/tests/test_axes.py index fb0e05a89f03..2a5e32758d17 100644 --- a/lib/matplotlib/tests/test_axes.py +++ b/lib/matplotlib/tests/test_axes.py @@ -4182,12 +4182,12 @@ 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') + pytest.raises(ValueError, ax.get_title, loc='foo') + pytest.raises(ValueError, ax.set_title, 'fail', loc='foo') @image_comparison(baseline_images=["loglog"], remove_text=True, From 9aee1fc53841a70ef46f1df0be822908920cc809 Mon Sep 17 00:00:00 2001 From: Jason King Date: Sun, 13 Dec 2015 17:22:16 +1100 Subject: [PATCH 049/174] converted assert_raises calls to pytest.raises. --- lib/matplotlib/tests/test_labeled_data_unpacking.py | 2 +- lib/matplotlib/tests/test_triangulation.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/matplotlib/tests/test_labeled_data_unpacking.py b/lib/matplotlib/tests/test_labeled_data_unpacking.py index 2f037543583b..306f8a42955e 100644 --- a/lib/matplotlib/tests/test_labeled_data_unpacking.py +++ b/lib/matplotlib/tests/test_labeled_data_unpacking.py @@ -251,7 +251,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(): diff --git a/lib/matplotlib/tests/test_triangulation.py b/lib/matplotlib/tests/test_triangulation.py index d448fb1d0398..1960b5428291 100644 --- a/lib/matplotlib/tests/test_triangulation.py +++ b/lib/matplotlib/tests/test_triangulation.py @@ -1029,7 +1029,7 @@ def test_tricontourf_decreasing_levels(): y = [0.0, 0.0, 1.0] z = [0.2, 0.4, 0.6] plt.figure() - assert_raises(ValueError, plt.tricontourf, x, y, z, [1.0, 0.0]) + pytest.raises(ValueError, plt.tricontourf, x, y, z, [1.0, 0.0]) if __name__ == '__main__': From 91f30325dff549675399773b3a34a82594257744 Mon Sep 17 00:00:00 2001 From: Jason King Date: Sun, 13 Dec 2015 17:47:31 +1100 Subject: [PATCH 050/174] more assert_raises calls to replace --- lib/matplotlib/tests/test_labeled_data_unpacking.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/matplotlib/tests/test_labeled_data_unpacking.py b/lib/matplotlib/tests/test_labeled_data_unpacking.py index 306f8a42955e..8aee140e54d8 100644 --- a/lib/matplotlib/tests/test_labeled_data_unpacking.py +++ b/lib/matplotlib/tests/test_labeled_data_unpacking.py @@ -74,12 +74,12 @@ def f(): # z is unknown unpack_labeled_data(replace_names=["x", "y", "z"])(func_args) - assert_raises(AssertionError, f) + pytest.raises(AssertionError, f) def f(): unpack_labeled_data(replace_names=["x", "y"])(func_no_ax_args) - assert_raises(AssertionError, f) + pytest.raises(AssertionError, f) # no replacements at all -> all ok... unpack_labeled_data(replace_names=[], label_namer=None)(func) @@ -91,12 +91,12 @@ def f(): def f(): unpack_labeled_data(label_namer="z")(func) - assert_raises(AssertionError, f) + pytest.raises(AssertionError, f) def f(): unpack_labeled_data(label_namer="z")(func_args) - assert_raises(AssertionError, f) + 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) From 86f7264285782c275498e6bcef4b23b34388fff8 Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 14 Dec 2015 10:13:23 +1100 Subject: [PATCH 051/174] Thanks to QuLogic , using decorator form of pytest.raises for various function calls. --- lib/matplotlib/tests/test_axes.py | 42 +++++++++++++++++++------------ 1 file changed, 26 insertions(+), 16 deletions(-) diff --git a/lib/matplotlib/tests/test_axes.py b/lib/matplotlib/tests/test_axes.py index 2a5e32758d17..8e0972866b06 100644 --- a/lib/matplotlib/tests/test_axes.py +++ b/lib/matplotlib/tests/test_axes.py @@ -1727,7 +1727,8 @@ def test_bxp_bad_widths(): fig, ax = plt.subplots() ax.set_yscale('log') - pytest.raises(ValueError, ax.bxp(logstats, widths=[1])) + with pytest.raises(ValueError): + ax.bxp(logstats, widths=[1]) @cleanup @@ -1739,7 +1740,8 @@ def test_bxp_bad_positions(): fig, ax = plt.subplots() ax.set_yscale('log') - pytest.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) @@ -1895,7 +1897,8 @@ def test_boxplot_bad_medians_1(): x = np.linspace(-7, 7, 140) x = np.hstack([-25, x, 25]) fig, ax = plt.subplots() - pytest.raises(ValueError, ax.boxplot(x, usermedians=[1, 2])) + with pytest.raises(ValueError): + ax.boxplot(x, usermedians=[1, 2]) @cleanup @@ -1903,7 +1906,8 @@ def test_boxplot_bad_medians_2(): x = np.linspace(-7, 7, 140) x = np.hstack([-25, x, 25]) fig, ax = plt.subplots() - pytest.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 @@ -1911,8 +1915,8 @@ def test_boxplot_bad_ci_1(): x = np.linspace(-7, 7, 140) x = np.hstack([-25, x, 25]) fig, ax = plt.subplots() - pytest.raises(ValueError, ax.boxplot([x, x], - conf_intervals=[[1, 2]])) + with pytest.raises(ValueError): + ax.boxplot([x, x], conf_intervals=[[1, 2]]) @cleanup @@ -1920,8 +1924,8 @@ def test_boxplot_bad_ci_2(): x = np.linspace(-7, 7, 140) x = np.hstack([-25, x, 25]) fig, ax = plt.subplots() - pytest.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'], @@ -2104,7 +2108,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)] - pytest.raises(ValueError, ax.violinplot(data, positions=range(5))) + with pytest.raises(ValueError): + ax.violinplot(data, positions=range(5)) @cleanup @@ -2113,8 +2118,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)] - pytest.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 @@ -2196,9 +2201,12 @@ def test_errorbar_shape(): yerr = np.vstack((yerr1, 2*yerr1)).T xerr = 0.1 + yerr - pytest.raises(ValueError, ax.errorbar(x, y, yerr=yerr, fmt='o')) - pytest.raises(ValueError, ax.errorbar(x, y, xerr=xerr, fmt='o')) - pytest.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']) @@ -4077,8 +4085,10 @@ def test_square_plot(): @cleanup def test_no_None(): fig, ax = plt.subplots() - pytest.raises(ValueError, plt.plot(None)) - pytest.raises(ValueError, plt.plot(None, None)) + with pytest.raises(ValueError): + plt.plot(None) + with pytest.raises(ValueError): + plt.plot(None, None) @cleanup From f7e74010b0d8d0d064fe358c453b39b4d6056d31 Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 14 Dec 2015 10:51:07 +1100 Subject: [PATCH 052/174] more conversions of pytest.raises to use 'with' instead. --- .../tests/test_labeled_data_unpacking.py | 3 ++- lib/matplotlib/tests/test_style.py | 3 ++- lib/matplotlib/tests/test_transforms.py | 27 ++++++++++++------- 3 files changed, 22 insertions(+), 11 deletions(-) diff --git a/lib/matplotlib/tests/test_labeled_data_unpacking.py b/lib/matplotlib/tests/test_labeled_data_unpacking.py index 8aee140e54d8..ad548d193914 100644 --- a/lib/matplotlib/tests/test_labeled_data_unpacking.py +++ b/lib/matplotlib/tests/test_labeled_data_unpacking.py @@ -130,7 +130,8 @@ def f(): func(None, x="a", y="b") # This sets a label although the function can't handle it. - pytest.raises(TypeError, f()) + with pytest.raises(TypeError): + f() def test_function_call_without_data(): diff --git a/lib/matplotlib/tests/test_style.py b/lib/matplotlib/tests/test_style.py index 9d65324ee360..2634bddd7dc6 100644 --- a/lib/matplotlib/tests/test_style.py +++ b/lib/matplotlib/tests/test_style.py @@ -134,7 +134,8 @@ def test_context_with_badparam(): with style.context({PARAM: other_value}): assert mpl.rcParams[PARAM] == other_value x = style.context([d]) - pytest.raises(KeyError, x.__enter__()) + with pytest.raises(KeyError): + x.__enter__() assert mpl.rcParams[PARAM] == other_value diff --git a/lib/matplotlib/tests/test_transforms.py b/lib/matplotlib/tests/test_transforms.py index 8590b6b67435..ff83335771a0 100644 --- a/lib/matplotlib/tests/test_transforms.py +++ b/lib/matplotlib/tests/test_transforms.py @@ -292,7 +292,8 @@ def test_transform_shortcuts(self): assert (self.stack2_subset - self.stack2).depth == 1 - assert_raises(ValueError, self.stack1.__sub__, self.stack2) + with pytest.raises(ValueError): + self.stack1.__sub__(self.stack2) aff1 = self.ta1 + (self.ta2 + self.ta3) aff2 = self.ta2 + self.ta3 @@ -546,10 +547,12 @@ def test_transform_angles(): assert_array_almost_equal(angles, new_angles) # points missing a 2nd dimension - assert_raises(ValueError, t.transform_angles, angles, points[0:2, 0:1]) + with pytest.raises(ValueError): + t.transform_angles(angles, points[0:2, 0:1]) # Number of angles != Number of points - assert_raises(ValueError, t.transform_angles, angles, points[0:2, :]) + with pytest.raises(ValueError): + t.transform_angles(angles, points[0:2, :]) def test_nonsingular(): @@ -568,12 +571,18 @@ def test_invalid_arguments(): # raises a ValueError, and a wrong shape with a possible number # of dimensions is caught by our CALL_CPP macro, which always # raises the less precise RuntimeError. - pytest.raises(ValueError, t.transform(1)) - pytest.raises(ValueError, t.transform([[[1]]])) - pytest.raises(RuntimeError, t.transform([])) - pytest.raises(RuntimeError, t.transform([1])) - pytest.raises(RuntimeError, t.transform([[1]])) - pytest.raises(RuntimeError, t.transform([[1, 2, 3]])) + with pytest.raises(ValueError): + t.transform(1) + with pytest.raises(ValueError): + t.transform([[[1]]]) + with pytest.raises(RuntimeError): + t.transform([]) + with pytest.raises(RuntimeError): + t.transform([1]) + with pytest.raises(RuntimeError): + t.transform([[1]]) + with pytest.raises(RuntimeError): + t.transform([[1, 2, 3]]) def test_transformed_path(): points = [(0, 0), (1, 0), (1, 1), (0, 1)] From 6f935ce70636fa6237c248ceab38ba847ee600fc Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 14 Dec 2015 12:14:22 +1100 Subject: [PATCH 053/174] change nose method for calling test class methods. ie 'def setUp' to 'def setup_class' --- lib/matplotlib/tests/test_cbook.py | 26 ++++++++++++++------------ 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/lib/matplotlib/tests/test_cbook.py b/lib/matplotlib/tests/test_cbook.py index a7771cfd96dd..511bdbf5363b 100644 --- a/lib/matplotlib/tests/test_cbook.py +++ b/lib/matplotlib/tests/test_cbook.py @@ -65,20 +65,22 @@ def test_restrict_dict(): 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) def test_bad_first_arg(self): with pytest.raises(ValueError): From 72ddc43d477d14bd5b564f3d3dc436269add748e Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 14 Dec 2015 13:28:59 +1100 Subject: [PATCH 054/174] fixing pep8 failures. --- lib/matplotlib/tests/test_image.py | 66 ++++++--- .../tests/test_labeled_data_unpacking.py | 138 ++++++++++++------ lib/matplotlib/tests/test_legend.py | 6 +- lib/matplotlib/tests/test_lines.py | 2 +- lib/matplotlib/tests/test_mathtext.py | 16 +- lib/matplotlib/tests/test_rcparams.py | 10 +- lib/matplotlib/tests/test_simplification.py | 27 +++- lib/matplotlib/tests/test_spines.py | 6 +- lib/matplotlib/tests/test_subplots.py | 6 +- lib/matplotlib/tests/test_tightlayout.py | 1 + lib/matplotlib/tests/test_triangulation.py | 2 +- lib/mpl_toolkits/tests/test_axes_grid1.py | 6 +- lib/mpl_toolkits/tests/test_mplot3d.py | 10 +- 13 files changed, 201 insertions(+), 95 deletions(-) diff --git a/lib/matplotlib/tests/test_image.py b/lib/matplotlib/tests/test_image.py index 9ffa6d9d1e5e..fb9fda5fcbc1 100644 --- a/lib/matplotlib/tests/test_image.py +++ b/lib/matplotlib/tests/test_image.py @@ -43,6 +43,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 +64,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 +82,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,6 +93,7 @@ def test_image_python_io(): buffer.seek(0) plt.imread(buffer) + @knownfailureif(not HAS_PIL) def test_imread_pil_uint16(): img = plt.imread(os.path.join(os.path.dirname(__file__), @@ -106,6 +110,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 +140,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 +246,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 +257,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 +274,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 +302,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 +333,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 +345,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 +357,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 +375,29 @@ 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 +434,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 @@ -476,7 +499,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))) diff --git a/lib/matplotlib/tests/test_labeled_data_unpacking.py b/lib/matplotlib/tests/test_labeled_data_unpacking.py index ad548d193914..637f9ceb6ccd 100644 --- a/lib/matplotlib/tests/test_labeled_data_unpacking.py +++ b/lib/matplotlib/tests/test_labeled_data_unpacking.py @@ -137,36 +137,54 @@ def f(): def test_function_call_without_data(): """test without data -> no replacements""" for func in all_funcs: - 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" + 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 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" + 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 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" + 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(): @@ -179,12 +197,18 @@ def test_function_call_with_pandas_data(): data = pd.DataFrame({"a": [1, 2], "b": [8, 9], "w": ["NOT", "NOT"]}) for func in all_funcs: - 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" + 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(): @@ -196,12 +220,18 @@ 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 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" + 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): @@ -217,14 +247,20 @@ 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 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" + 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 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(): @@ -236,10 +272,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 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" + 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(): @@ -273,8 +313,10 @@ def funcy(ax, *args, **kwargs): func = unpack_labeled_data(replace_all_args=True, replace_names=["w"], label_namer="y")(funcy) - 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" + 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", @@ -282,9 +324,12 @@ def funcy(ax, *args, **kwargs): "label", "w"])( funcy) - 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" + 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(): @@ -352,7 +397,8 @@ def funcy(ax, *args, **kwargs): # no arbitrary long args with data def f(): - assert funcy(None, "x", "y", "c", "x", "y", "x", "y", data=data) == "('X', 'Y', 'c', 'X', 'Y', 'X', 'Y') | {}" + assert funcy(None, "x", "y", "c", "x", "y", "x", "y", data=data) == \ + "('X', 'Y', 'c', 'X', 'Y', 'X', 'Y') | {}" pytest.raises(ValueError, f) # In the two arg case, if a valid color spec is in data, we warn but use diff --git a/lib/matplotlib/tests/test_legend.py b/lib/matplotlib/tests/test_legend.py index e66a6fd86a70..1c18a5364fd3 100644 --- a/lib/matplotlib/tests/test_legend.py +++ b/lib/matplotlib/tests/test_legend.py @@ -109,7 +109,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 +123,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() diff --git a/lib/matplotlib/tests/test_lines.py b/lib/matplotlib/tests/test_lines.py index 3440a2db1827..af7e38d280c8 100644 --- a/lib/matplotlib/tests/test_lines.py +++ b/lib/matplotlib/tests/test_lines.py @@ -59,7 +59,7 @@ 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 + slowdown_threshold = 2 # trying to avoid false positive failures assert slowdown_factor < slowdown_threshold diff --git a/lib/matplotlib/tests/test_mathtext.py b/lib/matplotlib/tests/test_mathtext.py index eeac74ad3878..d0f41f90f9ce 100644 --- a/lib/matplotlib/tests/test_mathtext.py +++ b/lib/matplotlib/tests/test_mathtext.py @@ -88,17 +88,17 @@ 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"$\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'$\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}$', @@ -108,6 +108,7 @@ 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)) diff --git a/lib/matplotlib/tests/test_rcparams.py b/lib/matplotlib/tests/test_rcparams.py index 92394b0d7bab..15cf20730227 100644 --- a/lib/matplotlib/tests/test_rcparams.py +++ b/lib/matplotlib/tests/test_rcparams.py @@ -178,7 +178,8 @@ 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 nose.SkipTest( + "assert_raises as context manager not supported with Python < 2.7") from matplotlib.rcsetup import validate_bool_maybe_none, validate_bool with pytest.raises(ValueError): validate_bool_maybe_none("blah") @@ -263,7 +264,6 @@ def _validation_fail_helper(validator, arg, exception_type): pytest.raises(exception_type,validator, arg) - def test_validators(): validation_tests = ( {'validator': validate_bool, @@ -400,14 +400,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 SkipTest("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 pytest.raises(KeyError): - with mpl.rc_context(rc=OrderedDict([('text.usetex', True),('test.blah', True)])): + with mpl.rc_context(rc=OrderedDict([('text.usetex', True), + ('test.blah', True)])): pass assert mpl.rcParams['text.usetex'] is False diff --git a/lib/matplotlib/tests/test_simplification.py b/lib/matplotlib/tests/test_simplification.py index 36c865804230..6b507dc194a4 100644 --- a/lib/matplotlib/tests/test_simplification.py +++ b/lib/matplotlib/tests/test_simplification.py @@ -5,7 +5,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 import pytest @@ -32,6 +32,7 @@ def test_clipping(): 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]) @@ -42,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]) @@ -53,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) @@ -69,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) @@ -85,11 +90,13 @@ 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.MOVETO, Path.CURVE3, Path.CURVE3, Path.CURVE3, + Path.CURVE3, Path.CURVE3, Path.CURVE3, Path.CLOSEPOLY]), fc="none") fig = plt.figure() @@ -98,6 +105,7 @@ 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() @@ -106,6 +114,7 @@ def test_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() @@ -120,6 +129,7 @@ def test_fft_peaks(): assert len(simplified) == 20 + @cleanup def test_start_with_moveto(): # Should be entirely clipped away to a single MOVETO @@ -156,11 +166,13 @@ def test_start_with_moveto(): verts = np.fromstring(decodebytes(data), dtype=' Date: Mon, 14 Dec 2015 14:02:18 +1100 Subject: [PATCH 055/174] more pep8 fixes. --- lib/matplotlib/tests/test_bbox_tight.py | 8 +++--- lib/matplotlib/tests/test_collections.py | 2 +- lib/matplotlib/tests/test_dates.py | 3 ++- lib/matplotlib/tests/test_dviread.py | 2 +- lib/matplotlib/tests/test_font_manager.py | 3 ++- lib/matplotlib/tests/test_image.py | 3 ++- .../tests/test_labeled_data_unpacking.py | 25 +++++++++++-------- lib/matplotlib/tests/test_pickle.py | 1 + lib/matplotlib/tests/test_simplification.py | 4 ++- 9 files changed, 31 insertions(+), 20 deletions(-) diff --git a/lib/matplotlib/tests/test_bbox_tight.py b/lib/matplotlib/tests/test_bbox_tight.py index 7e05e5fd5432..d7d2af651606 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 diff --git a/lib/matplotlib/tests/test_collections.py b/lib/matplotlib/tests/test_collections.py index 764f824d7449..e0f33e190b97 100644 --- a/lib/matplotlib/tests/test_collections.py +++ b/lib/matplotlib/tests/test_collections.py @@ -110,7 +110,7 @@ def test__EventCollection__get_linelength(): check to make sure the default linelength matches the input linelength ''' _, coll, props = generate_EventCollection_plot() - assert props['linelength'] == coll.get_linelength() + assert props['linelength'] == coll.get_linelength() @cleanup diff --git a/lib/matplotlib/tests/test_dates.py b/lib/matplotlib/tests/test_dates.py index 9797dc9cca62..b5ff383e881e 100644 --- a/lib/matplotlib/tests/test_dates.py +++ b/lib/matplotlib/tests/test_dates.py @@ -198,7 +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 locale_formatter.strftime(dt) == expanded_formatter.strftime(dt) + assert locale_formatter.strftime(dt) == \ + expanded_formatter.strftime(dt) except (ImportError, AttributeError): pass diff --git a/lib/matplotlib/tests/test_dviread.py b/lib/matplotlib/tests/test_dviread.py index 1d585a77b644..3444e913fe00 100644 --- a/lib/matplotlib/tests/test_dviread.py +++ b/lib/matplotlib/tests/test_dviread.py @@ -72,4 +72,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_font_manager.py b/lib/matplotlib/tests/test_font_manager.py index 323f3c6c0860..6eed66993fef 100644 --- a/lib/matplotlib/tests/test_font_manager.py +++ b/lib/matplotlib/tests/test_font_manager.py @@ -46,4 +46,5 @@ def test_json_serialization(): {'family': 'Bitstream Vera Sans', 'weight': 700}, {'family': 'no such font family'}): fp = FontProperties(**prop) - assert 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_image.py b/lib/matplotlib/tests/test_image.py index fb9fda5fcbc1..6c08f5a258d4 100644 --- a/lib/matplotlib/tests/test_image.py +++ b/lib/matplotlib/tests/test_image.py @@ -375,7 +375,8 @@ def test_image_composite_alpha(): ax.set_ylim([5, 0]) -@image_comparison(baseline_images=['rasterize_10dpi'], extensions=['pdf','svg'], +@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. diff --git a/lib/matplotlib/tests/test_labeled_data_unpacking.py b/lib/matplotlib/tests/test_labeled_data_unpacking.py index 637f9ceb6ccd..6b70e4b12fd9 100644 --- a/lib/matplotlib/tests/test_labeled_data_unpacking.py +++ b/lib/matplotlib/tests/test_labeled_data_unpacking.py @@ -247,16 +247,21 @@ 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 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" + 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 func_varags_replace_all(None, "a", "b", w="x", data=data) == \ diff --git a/lib/matplotlib/tests/test_pickle.py b/lib/matplotlib/tests/test_pickle.py index 682421d35023..61cc7add9647 100644 --- a/lib/matplotlib/tests/test_pickle.py +++ b/lib/matplotlib/tests/test_pickle.py @@ -279,6 +279,7 @@ def test_transform(): assert obj.wrapper._child == obj.composite # Check child -> parent links of TransformWrapper. assert list(obj.wrapper._parents.values()) == [obj.composite2] + # Check input and output dimensions are set as expected. 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_simplification.py b/lib/matplotlib/tests/test_simplification.py index 6b507dc194a4..3a90251c4836 100644 --- a/lib/matplotlib/tests/test_simplification.py +++ b/lib/matplotlib/tests/test_simplification.py @@ -22,6 +22,7 @@ # 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) @@ -94,7 +95,8 @@ def test_sine_plus_noise(): @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([(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") From 571fbbd4bb07ffd4625de72b3f47787d0711f563 Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 14 Dec 2015 14:58:03 +1100 Subject: [PATCH 056/174] another testing class that needed changes for pytest. --- lib/matplotlib/tests/test_cbook.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/lib/matplotlib/tests/test_cbook.py b/lib/matplotlib/tests/test_cbook.py index 511bdbf5363b..229f2ef5ade9 100644 --- a/lib/matplotlib/tests/test_cbook.py +++ b/lib/matplotlib/tests/test_cbook.py @@ -269,9 +269,10 @@ def test_bad_dims(self): 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) From 50b0e0af04721b64b27c09f2d82b42646cc604a8 Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 14 Dec 2015 15:25:22 +1100 Subject: [PATCH 057/174] more pep8 failures to hide under the rug. --- lib/matplotlib/tests/test_axes.py | 137 +++++++++++------- lib/matplotlib/tests/test_delaunay.py | 49 +++++-- .../tests/test_labeled_data_unpacking.py | 30 ++-- 3 files changed, 138 insertions(+), 78 deletions(-) diff --git a/lib/matplotlib/tests/test_axes.py b/lib/matplotlib/tests/test_axes.py index 8e0972866b06..e1a2f23ad579 100644 --- a/lib/matplotlib/tests/test_axes.py +++ b/lib/matplotlib/tests/test_axes.py @@ -32,6 +32,7 @@ # 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', @@ -105,7 +106,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])) @@ -139,7 +141,8 @@ def test_twinx_cla(): 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 @@ -322,26 +325,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 @@ -428,7 +432,7 @@ def test_polar_units(): y1 = [y*km for y in y1] plt.polar(x2, y1, color="blue", thetaunits="rad", runits="km") assert isinstance(plt.gca().get_xaxis().get_major_formatter(), - units.UnitDblFormatter) == True + units.UnitDblFormatter) == True @image_comparison(baseline_images=['polar_rmin']) @@ -524,7 +528,7 @@ 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() @@ -592,7 +596,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: @@ -620,7 +627,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) @@ -679,8 +686,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) @@ -688,8 +697,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']) @@ -884,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) @@ -1111,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) @@ -1143,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'], @@ -1316,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 @@ -1353,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) @@ -1754,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)) @@ -1795,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]) @@ -1802,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(): @@ -2181,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() @@ -2285,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) @@ -2376,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) @@ -2399,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) @@ -2436,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 @@ -2568,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 @@ -2585,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 @@ -2623,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']) @@ -3632,8 +3658,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) @@ -3813,7 +3839,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, @@ -3899,10 +3925,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'], diff --git a/lib/matplotlib/tests/test_delaunay.py b/lib/matplotlib/tests/test_delaunay.py index 82284513fec9..b63a935761dd 100644 --- a/lib/matplotlib/tests/test_delaunay.py +++ b/lib/matplotlib/tests/test_delaunay.py @@ -1,6 +1,8 @@ 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 @@ -13,21 +15,24 @@ # 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 @@ -46,37 +51,44 @@ def exponential(x, y): 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 +98,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 +109,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 +150,8 @@ 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 +159,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 +186,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 +230,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_labeled_data_unpacking.py b/lib/matplotlib/tests/test_labeled_data_unpacking.py index 6b70e4b12fd9..4cd3b614abe5 100644 --- a/lib/matplotlib/tests/test_labeled_data_unpacking.py +++ b/lib/matplotlib/tests/test_labeled_data_unpacking.py @@ -220,18 +220,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 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" + 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): From 4408d108615c8c7adb3f5de726054108bd2c4b22 Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 14 Dec 2015 22:06:28 +1100 Subject: [PATCH 058/174] another pytest.raises to fix. --- lib/matplotlib/tests/test_axes.py | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/lib/matplotlib/tests/test_axes.py b/lib/matplotlib/tests/test_axes.py index e1a2f23ad579..8e1f67ee68db 100644 --- a/lib/matplotlib/tests/test_axes.py +++ b/lib/matplotlib/tests/test_axes.py @@ -857,12 +857,14 @@ def test_pcolorargs(): Z = np.sqrt(X**2 + Y**2)/5 _, ax = plt.subplots() - pytest.raises(TypeError, ax.pcolormesh(y, x, Z)) - pytest.raises(TypeError, ax.pcolormesh(X, Y, Z.T)) - pytest.raises(TypeError, ax.pcolormesh(x, y, Z[:-1, :-1], - shading="gouraud")) - pytest.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']) From 4e87b7240077016c92708b4c63124998c98cce7a Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 14 Dec 2015 22:23:42 +1100 Subject: [PATCH 059/174] lets try not comparing the equivilance of empty dicts, but rather something more booleanated. --- lib/matplotlib/tests/test_cbook.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/matplotlib/tests/test_cbook.py b/lib/matplotlib/tests/test_cbook.py index 229f2ef5ade9..86127e7e1f5a 100644 --- a/lib/matplotlib/tests/test_cbook.py +++ b/lib/matplotlib/tests/test_cbook.py @@ -278,12 +278,12 @@ def connect(self, s, func): return self.callbacks.connect(s, func) def is_empty(self): - assert self.callbacks._func_cid_map() == {} - assert self.callbacks.callbacks() == {} + assert not self.callbacks._func_cid_map() + assert not self.callbacks.callbacks() def is_not_empty(self): - assert self.callbacks._func_cid_map() != {} - assert 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 From 6d3bb584fe061041be8d63fa8216093a1394e11b Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 14 Dec 2015 22:24:46 +1100 Subject: [PATCH 060/174] if commenting out the nose pep8 functions work, then they can all be removed later. --- lib/matplotlib/tests/test_coding_standards.py | 387 +++++++++--------- 1 file changed, 191 insertions(+), 196 deletions(-) diff --git a/lib/matplotlib/tests/test_coding_standards.py b/lib/matplotlib/tests/test_coding_standards.py index 9224feb8c82d..c233c9e01fdc 100644 --- a/lib/matplotlib/tests/test_coding_standards.py +++ b/lib/matplotlib/tests/test_coding_standards.py @@ -86,199 +86,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 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) - - -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 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 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) From 4bfbf26dc44ac443be82d1e4702d0293cd53b5df Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 14 Dec 2015 22:30:29 +1100 Subject: [PATCH 061/174] pep8 fixes. --- lib/matplotlib/tests/test_axes.py | 1 + lib/matplotlib/tests/test_delaunay.py | 1 - 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/matplotlib/tests/test_axes.py b/lib/matplotlib/tests/test_axes.py index 8e1f67ee68db..87e3f845d63e 100644 --- a/lib/matplotlib/tests/test_axes.py +++ b/lib/matplotlib/tests/test_axes.py @@ -534,6 +534,7 @@ def test_hexbin_empty(): ax = plt.gca() ax.hexbin([], []) + @cleanup def test_hexbin_pickable(): # From #1973: Test that picking a hexbin collection works diff --git a/lib/matplotlib/tests/test_delaunay.py b/lib/matplotlib/tests/test_delaunay.py index b63a935761dd..c924a7ad3fd1 100644 --- a/lib/matplotlib/tests/test_delaunay.py +++ b/lib/matplotlib/tests/test_delaunay.py @@ -17,7 +17,6 @@ from matplotlib.delaunay.triangulate import Triangulation - def constant(x, y): return np.ones(x.shape, x.dtype) constant.title = 'Constant' From 1ffc9c29ebe25a3081b7905c7fab59c8429ac1f0 Mon Sep 17 00:00:00 2001 From: Jason King Date: Tue, 15 Dec 2015 10:40:50 +1100 Subject: [PATCH 062/174] fix typos found QuLogic --- lib/matplotlib/tests/test_cbook.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/matplotlib/tests/test_cbook.py b/lib/matplotlib/tests/test_cbook.py index 86127e7e1f5a..ef63306902fd 100644 --- a/lib/matplotlib/tests/test_cbook.py +++ b/lib/matplotlib/tests/test_cbook.py @@ -278,11 +278,11 @@ def connect(self, s, func): return self.callbacks.connect(s, func) def is_empty(self): - assert not self.callbacks._func_cid_map() - assert not self.callbacks.callbacks() + assert not self.callbacks._func_cid_map + assert not self.callbacks.callbacks def is_not_empty(self): - assert self.callbacks._func_cid_map() + assert self.callbacks._func_cid_map assert self.callbacks.callbacks def test_callback_complete(self): From 389ebc3dc07a8927e05451b4b9b4968e414d33a9 Mon Sep 17 00:00:00 2001 From: Jason King Date: Tue, 15 Dec 2015 11:30:25 +1100 Subject: [PATCH 063/174] removing (and moving) import code in tests.py --- lib/matplotlib/tests/test_delaunay.py | 8 +++++--- tests.py | 5 ++--- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/lib/matplotlib/tests/test_delaunay.py b/lib/matplotlib/tests/test_delaunay.py index c924a7ad3fd1..84cc5e742fac 100644 --- a/lib/matplotlib/tests/test_delaunay.py +++ b/lib/matplotlib/tests/test_delaunay.py @@ -46,7 +46,7 @@ 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' @@ -149,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) diff --git a/tests.py b/tests.py index eb45aa3a98f3..be5bc211a39c 100755 --- a/tests.py +++ b/tests.py @@ -12,13 +12,12 @@ import os import sys import time +import pytest +from matplotlib import default_test_modules import matplotlib matplotlib.use('agg') -# import nose -import pytest -from matplotlib import default_test_modules def run(extra_args): From 1f1c2a6fb8ff28a8996cfb3d55191fec8317845d Mon Sep 17 00:00:00 2001 From: Jason King Date: Tue, 15 Dec 2015 12:49:57 +1100 Subject: [PATCH 064/174] replacing new nose calls with plain asserts --- lib/matplotlib/tests/test_ticker.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/matplotlib/tests/test_ticker.py b/lib/matplotlib/tests/test_ticker.py index 031e37a144fc..040fd567c951 100644 --- a/lib/matplotlib/tests/test_ticker.py +++ b/lib/matplotlib/tests/test_ticker.py @@ -163,7 +163,7 @@ def test_SymmetricalLogLocator_set_params(): def _logfe_helper(formatter, base, locs, i, expected_result): vals = base**locs labels = [formatter(x, pos) for (x, pos) in zip(vals, i)] - nose.tools.assert_equal(labels, expected_result) + assert labels == expected_result def test_LogFormatterExponent(): @@ -208,7 +208,7 @@ def get_view_interval(self): def _pprint_helper(value, domain, expected): fmt = mticker.LogFormatter() label = fmt.pprint_val(value, domain) - nose.tools.assert_equal(label, expected) + assert label == expected def test_logformatter_pprint(): From 01df45590daf7325d66d64e2c42685194ac7e335 Mon Sep 17 00:00:00 2001 From: Jason King Date: Wed, 16 Dec 2015 09:50:50 +1100 Subject: [PATCH 065/174] exclude files from pep8 checking --- tox.ini | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/tox.ini b/tox.ini index 89e89e7b66a3..bd1b68bfaac0 100644 --- a/tox.ini +++ b/tox.ini @@ -19,8 +19,24 @@ deps = [pytest] norecursedirs = .git build testpaths = tests -pep8ignore = E111 E114 E115 E116 E121 E122 E123 E124 E125 E126 E127 E128 E129 E131 E265 E266 W503 E241 E401 E231 E203 E226 - +pep8ignore = + *.py E111 E114 E115 E116 E121 E122 E123 E124 E125 E126 E127 E128 E129 E131 E265 E266 W503 E241 E401 E231 E203 E226 + _delaunay.py ALL + _image.py ALL + _tri.py ALL + _backend_agg.py ALL + _tkagg.py ALL + ft2font.py ALL + _cntr.py ALL + _contour.py ALL + _png.py ALL + _path.py ALL + ttconv.py ALL + _gtkagg.py ALL + _backend_gdk.py ALL + pyparsing* ALL + _qhull.py ALL + _macosx.py ALL [pep8] ignore=E111,E114,E115,E116,E121,E122,E123,E124,E125,E126,E127,E128,E129,E131,E265,E266,W503 exclude=_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 \ No newline at end of file From bb3ab51a43bcaaf3fca76dddfe289b45b599a442 Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 21 Dec 2015 21:45:14 +1100 Subject: [PATCH 066/174] add support for running a single test module, instead of all of them depends on detecting the module in default_test_modules --- tests.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/tests.py b/tests.py index be5bc211a39c..b3af44b80f6f 100755 --- a/tests.py +++ b/tests.py @@ -26,7 +26,15 @@ def run(extra_args): argv = sys.argv + extra_args # pytest.main(['--pyargs', '--cov=matplotlib'] + default_test_modules) print(argv + ['--pyargs'] + default_test_modules) - return pytest.main(argv + ['--pyargs'] + default_test_modules) + + # if a specific test module is in argv, run that instead of all tests + for argument in sys.argv: + if argument in default_test_modules: + # might need to insert a "--pyargs" into argv before passing + # to pytest.main + return pytest.main(argv) + else: + return pytest.main(argv + ['--pyargs'] + default_test_modules) if __name__ == '__main__': # extra_args = ['--cov=matplotlib'] From 73e93830c1c0351dd13d5235b750c8ed961b248c Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 28 Dec 2015 14:36:44 +1100 Subject: [PATCH 067/174] The "_name.py" files in exclude_files might need globbing to be handled properly (ie ignored) So lets try that and see what it does. --- tox.ini | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/tox.ini b/tox.ini index bd1b68bfaac0..270c54361df7 100644 --- a/tox.ini +++ b/tox.ini @@ -21,22 +21,22 @@ norecursedirs = .git build testpaths = tests pep8ignore = *.py E111 E114 E115 E116 E121 E122 E123 E124 E125 E126 E127 E128 E129 E131 E265 E266 W503 E241 E401 E231 E203 E226 - _delaunay.py ALL - _image.py ALL - _tri.py ALL - _backend_agg.py ALL - _tkagg.py ALL + *_delaunay.py ALL + *_image.py ALL + *_tri.py ALL + *_backend_agg.py ALL + *_tkagg.py ALL ft2font.py ALL - _cntr.py ALL - _contour.py ALL - _png.py ALL - _path.py ALL + *_cntr.py ALL + *_contour.py ALL + *_png.py ALL + *_path.py ALL ttconv.py ALL - _gtkagg.py ALL - _backend_gdk.py ALL + *_gtkagg.py ALL + *_backend_gdk.py ALL pyparsing* ALL - _qhull.py ALL - _macosx.py ALL + *_qhull.py ALL + *_macosx.py ALL [pep8] ignore=E111,E114,E115,E116,E121,E122,E123,E124,E125,E126,E127,E128,E129,E131,E265,E266,W503 exclude=_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 \ No newline at end of file From 5f3255be46165674c36b779b8b0a170be6e7d3c1 Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 28 Dec 2015 16:13:00 +1100 Subject: [PATCH 068/174] pep8 failures --- tests.py | 1 - 1 file changed, 1 deletion(-) diff --git a/tests.py b/tests.py index b3af44b80f6f..5cb72273c416 100755 --- a/tests.py +++ b/tests.py @@ -19,7 +19,6 @@ matplotlib.use('agg') - def run(extra_args): matplotlib._init_tests() From f4826c33856857e48c70660fff7767dbb7467090 Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 28 Dec 2015 16:41:41 +1100 Subject: [PATCH 069/174] pep8 was demanding that lambdas be replaced with proper functions. --- lib/matplotlib/tests/test_subplots.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/lib/matplotlib/tests/test_subplots.py b/lib/matplotlib/tests/test_subplots.py index 5e5f9986de91..4c075344397b 100644 --- a/lib/matplotlib/tests/test_subplots.py +++ b/lib/matplotlib/tests/test_subplots.py @@ -25,7 +25,8 @@ def check_shared(results, f, axs): # 'x': a1._shared_x_axes, # 'y': a1._shared_y_axes, # } - tostr = lambda r: "not " if r else "" + def tostr(r): + return "not " if r else "" for i1 in xrange(len(axs)): for i2 in xrange(i1 + 1, len(axs)): for i3 in xrange(len(shared)): @@ -36,7 +37,8 @@ def check_shared(results, f, axs): def check_visible(result, f, axs): - tostr = lambda v: "invisible" if v else "visible" + def tostr(v): + return "invisible" if v else "visible" for (ax, vx, vy) in zip(axs, result['x'], result['y']): for l in ax.get_xticklabels(): assert l.get_visible() == vx, \ From 08ce37b909677d3678881522dedc7e5ed6b60e2f Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 28 Dec 2015 16:42:46 +1100 Subject: [PATCH 070/174] This is hopefully an acceptable solution to the problem with test_mathtext.py. Namely that there was a lot of complicated strings that I didn't want to touch, that were failing pep8 Line-too-long tests. --- tox.ini | 1 + 1 file changed, 1 insertion(+) diff --git a/tox.ini b/tox.ini index 270c54361df7..568eaeefecb8 100644 --- a/tox.ini +++ b/tox.ini @@ -37,6 +37,7 @@ pep8ignore = pyparsing* ALL *_qhull.py ALL *_macosx.py ALL + *_mathtext.py E501 [pep8] ignore=E111,E114,E115,E116,E121,E122,E123,E124,E125,E126,E127,E128,E129,E131,E265,E266,W503 exclude=_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 \ No newline at end of file From f705680f3b9d946e3639452b94d4dae780654334 Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 28 Dec 2015 17:01:30 +1100 Subject: [PATCH 071/174] pep8 failures --- lib/matplotlib/tests/test_mathtext.py | 2 +- lib/matplotlib/tests/test_subplots.py | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/matplotlib/tests/test_mathtext.py b/lib/matplotlib/tests/test_mathtext.py index d0f41f90f9ce..99cd11935a39 100644 --- a/lib/matplotlib/tests/test_mathtext.py +++ b/lib/matplotlib/tests/test_mathtext.py @@ -90,7 +90,7 @@ 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"$? ! &$", # github issue #466 r'$\operatorname{cos} x$', # github issue #553 r'$\sum _{\genfrac{}{}{0}{}{0\leq i\leq m}{0 Date: Mon, 28 Dec 2015 17:58:08 +1100 Subject: [PATCH 072/174] remove assert_not_equal --- lib/matplotlib/tests/test_pickle.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/matplotlib/tests/test_pickle.py b/lib/matplotlib/tests/test_pickle.py index 61cc7add9647..6e9477d6a3a6 100644 --- a/lib/matplotlib/tests/test_pickle.py +++ b/lib/matplotlib/tests/test_pickle.py @@ -191,7 +191,7 @@ def test_complete(): fig = pickle.load(result_fh) # make sure there is now a figure manager - assert_not_equal(plt._pylab_helpers.Gcf.figs, {}) + assert not plt._pylab_helpers.Gcf.figs assert fig.get_label() == 'Figure with a label?' From 4a62ad99cff330256b61d22999bee5635e745756 Mon Sep 17 00:00:00 2001 From: Jason King Date: Thu, 31 Dec 2015 20:58:27 +1100 Subject: [PATCH 073/174] lets try '--ignore'ing the numpy tests dir --- tests.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests.py b/tests.py index 5cb72273c416..e0a007ba92af 100755 --- a/tests.py +++ b/tests.py @@ -33,7 +33,8 @@ def run(extra_args): # to pytest.main return pytest.main(argv) else: - return pytest.main(argv + ['--pyargs'] + default_test_modules) + return pytest.main(argv + ['--pyargs'] + default_test_modules + + '--ignore=site-packages/numpy/testing/.') if __name__ == '__main__': # extra_args = ['--cov=matplotlib'] From df2ebeb9021e5e4c522bb41a801786b56decd9db Mon Sep 17 00:00:00 2001 From: Jason King Date: Thu, 31 Dec 2015 21:19:34 +1100 Subject: [PATCH 074/174] Don't code at night on holidays with bad specs. --- tests.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests.py b/tests.py index e0a007ba92af..c71815882e6e 100755 --- a/tests.py +++ b/tests.py @@ -34,7 +34,7 @@ def run(extra_args): return pytest.main(argv) else: return pytest.main(argv + ['--pyargs'] + default_test_modules + - '--ignore=site-packages/numpy/testing/.') + ['--ignore=site-packages/numpy/testing/.']) if __name__ == '__main__': # extra_args = ['--cov=matplotlib'] From 1e122733385599cbdc0affe700eaebc2b70a2959 Mon Sep 17 00:00:00 2001 From: Jason King Date: Fri, 1 Jan 2016 19:28:54 +1100 Subject: [PATCH 075/174] try norecursedirs to get pytest to stop looking in numpy --- tox.ini | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tox.ini b/tox.ini index 568eaeefecb8..47b63f160ef5 100644 --- a/tox.ini +++ b/tox.ini @@ -17,7 +17,7 @@ deps = numpy [pytest] -norecursedirs = .git build +norecursedirs = .git build numpy testpaths = tests pep8ignore = *.py E111 E114 E115 E116 E121 E122 E123 E124 E125 E126 E127 E128 E129 E131 E265 E266 W503 E241 E401 E231 E203 E226 From 47e0c4b7e002ce6948ab1e8f528f7d5e6f8fdeca Mon Sep 17 00:00:00 2001 From: Jason King Date: Sat, 2 Jan 2016 13:44:52 +1100 Subject: [PATCH 076/174] found cases of 'import nose' , and also, use of a decorator called 'knownfailureif' removed, and replaced with pytest versions if necessary. --- lib/matplotlib/testing/decorators.py | 1 - lib/matplotlib/tests/test_artist.py | 5 ----- lib/matplotlib/tests/test_axes.py | 5 ++--- lib/matplotlib/tests/test_backend_pdf.py | 3 +-- lib/matplotlib/tests/test_backend_ps.py | 9 ++++---- lib/matplotlib/tests/test_backend_qt4.py | 26 ++++++++++++------------ lib/matplotlib/tests/test_backend_qt5.py | 26 ++++++++++++------------ lib/matplotlib/tests/test_backend_svg.py | 4 ---- lib/matplotlib/tests/test_basic.py | 2 -- lib/matplotlib/tests/test_collections.py | 4 ---- lib/matplotlib/tests/test_colors.py | 4 ++-- lib/matplotlib/tests/test_contour.py | 4 ---- lib/matplotlib/tests/test_delaunay.py | 2 +- lib/matplotlib/tests/test_image.py | 14 +++++++------ lib/matplotlib/tests/test_mathtext.py | 2 +- lib/matplotlib/tests/test_mlab.py | 4 ++-- lib/matplotlib/tests/test_patheffects.py | 5 ++--- lib/matplotlib/tests/test_rcparams.py | 2 +- lib/matplotlib/tests/test_subplots.py | 5 ----- lib/matplotlib/tests/test_tightlayout.py | 2 +- lib/mpl_toolkits/tests/test_mplot3d.py | 1 - 21 files changed, 51 insertions(+), 79 deletions(-) diff --git a/lib/matplotlib/testing/decorators.py b/lib/matplotlib/testing/decorators.py index 030304c6bba7..1abae20047f9 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 diff --git a/lib/matplotlib/tests/test_artist.py b/lib/matplotlib/tests/test_artist.py index ba824157e310..df1f43ce9592 100644 --- a/lib/matplotlib/tests/test_artist.py +++ b/lib/matplotlib/tests/test_artist.py @@ -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 87e3f845d63e..0a5ea04a50a2 100644 --- a/lib/matplotlib/tests/test_axes.py +++ b/lib/matplotlib/tests/test_axes.py @@ -4367,10 +4367,9 @@ def test_pandas_indexing_hist(): if __name__ == '__main__': - import nose import sys - args = ['-s', '--with-doctest'] + args = ['--doctest-modules'] argv = sys.argv argv = argv[:1] + args + argv[1:] - nose.runmodule(argv=argv, exit=False) + pytest.main(argv) 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_ps.py b/lib/matplotlib/tests/test_backend_ps.py index ab346a4d0a41..52f29bcf3a4e 100644 --- a/lib/matplotlib/tests/test_backend_ps.py +++ b/lib/matplotlib/tests/test_backend_ps.py @@ -7,19 +7,18 @@ 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") - -needs_tex = knownfailureif( +needs_tex = pytest.mark.xfail( not matplotlib.checkdep_tex(), "This test needs a TeX installation") diff --git a/lib/matplotlib/tests/test_backend_qt4.py b/lib/matplotlib/tests/test_backend_qt4.py index 5dfdfdf6cf46..2429c8c3f7d9 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) @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) 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) 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) 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) 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) 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) 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) 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) 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) 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) 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) 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..1c059b15ba19 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) @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) 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) 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) 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) 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) 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) 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) 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) 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) 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) 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) 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..086e1f8779b5 100644 --- a/lib/matplotlib/tests/test_backend_svg.py +++ b/lib/matplotlib/tests/test_backend_svg.py @@ -183,7 +183,3 @@ 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 dbff048af882..cd7745087c07 100644 --- a/lib/matplotlib/tests/test_basic.py +++ b/lib/matplotlib/tests/test_basic.py @@ -3,9 +3,7 @@ from matplotlib.externals import six -from nose.tools import assert_equal -from matplotlib.testing.decorators import knownfailureif from pylab import * import pytest diff --git a/lib/matplotlib/tests/test_collections.py b/lib/matplotlib/tests/test_collections.py index e0f33e190b97..dd2b8a5eb0b0 100644 --- a/lib/matplotlib/tests/test_collections.py +++ b/lib/matplotlib/tests/test_collections.py @@ -616,7 +616,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_colors.py b/lib/matplotlib/tests/test_colors.py index 261c3234551f..5d51cc1bf601 100644 --- a/lib/matplotlib/tests/test_colors.py +++ b/lib/matplotlib/tests/test_colors.py @@ -15,7 +15,7 @@ import matplotlib.cbook as cbook import matplotlib.pyplot as plt from matplotlib.testing.decorators import (image_comparison, - cleanup, knownfailureif) + cleanup) import pytest @@ -397,7 +397,7 @@ def test_light_source_shading_default(): assert_array_almost_equal(rgb, expect, decimal=2) -@knownfailureif((V(np.__version__) <= V('1.9.0') +@pytest.mark.xfail((V(np.__version__) <= V('1.9.0') and V(np.__version__) >= V('1.7.0'))) # Numpy 1.9.1 fixed a bug in masked arrays which resulted in # additional elements being masked when calculating the gradient thus diff --git a/lib/matplotlib/tests/test_contour.py b/lib/matplotlib/tests/test_contour.py index 1abe239b3b5d..ee39cc59437e 100644 --- a/lib/matplotlib/tests/test_contour.py +++ b/lib/matplotlib/tests/test_contour.py @@ -310,7 +310,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_delaunay.py b/lib/matplotlib/tests/test_delaunay.py index 84cc5e742fac..b31c9afbba30 100644 --- a/lib/matplotlib/tests/test_delaunay.py +++ b/lib/matplotlib/tests/test_delaunay.py @@ -8,7 +8,7 @@ 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(): diff --git a/lib/matplotlib/tests/test_image.py b/lib/matplotlib/tests/test_image.py index 6c08f5a258d4..e3eb2bb49982 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 @@ -94,7 +95,7 @@ def test_image_python_io(): plt.imread(buffer) -@knownfailureif(not HAS_PIL) +@pytest.mark.xfail(not HAS_PIL) def test_imread_pil_uint16(): img = plt.imread(os.path.join(os.path.dirname(__file__), 'baseline_images', 'test_image', 'uint16.tif')) @@ -479,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) @cleanup def test_jpeg_alpha(): plt.figure(figsize=(1, 1), dpi=300) diff --git a/lib/matplotlib/tests/test_mathtext.py b/lib/matplotlib/tests/test_mathtext.py index 99cd11935a39..02edbb76479f 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 diff --git a/lib/matplotlib/tests/test_mlab.py b/lib/matplotlib/tests/test_mlab.py index 673c052328c3..109e8b0a04c3 100644 --- a/lib/matplotlib/tests/test_mlab.py +++ b/lib/matplotlib/tests/test_mlab.py @@ -13,7 +13,7 @@ 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: @@ -2751,7 +2751,7 @@ def get_z(x, y): np.ma.getmask(correct_zi_masked)) -@knownfailureif(not HAS_NATGRID) +@pytest.mark.xfail(not HAS_NATGRID) def test_griddata_nn(): # z is a linear function of x and y. def get_z(x, y): diff --git a/lib/matplotlib/tests/test_patheffects.py b/lib/matplotlib/tests/test_patheffects.py index 1e10a31ea2e9..e1d1e3381d55 100644 --- a/lib/matplotlib/tests/test_patheffects.py +++ b/lib/matplotlib/tests/test_patheffects.py @@ -5,8 +5,7 @@ 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 @@ -85,7 +84,7 @@ def test_patheffect3(): @cleanup -@knownfailureif(True) +@pytest.mark.xfail(True) def test_PathEffect_points_to_pixels(): fig = plt.figure(dpi=150) p1, = plt.plot(range(10)) diff --git a/lib/matplotlib/tests/test_rcparams.py b/lib/matplotlib/tests/test_rcparams.py index 15cf20730227..ad202ffae095 100644 --- a/lib/matplotlib/tests/test_rcparams.py +++ b/lib/matplotlib/tests/test_rcparams.py @@ -13,7 +13,7 @@ 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 diff --git a/lib/matplotlib/tests/test_subplots.py b/lib/matplotlib/tests/test_subplots.py index 21a08ba1d429..7ffe0a10b7be 100644 --- a/lib/matplotlib/tests/test_subplots.py +++ b/lib/matplotlib/tests/test_subplots.py @@ -140,8 +140,3 @@ def test_subplots(): test_shared() # - are exceptions thrown correctly test_exceptions() - - -if __name__ == "__main__": - import nose - nose.runmodule(argv=['-s', '--with-doctest'], exit=False) diff --git a/lib/matplotlib/tests/test_tightlayout.py b/lib/matplotlib/tests/test_tightlayout.py index c55ff6ba01fa..a1b428b04900 100644 --- a/lib/matplotlib/tests/test_tightlayout.py +++ b/lib/matplotlib/tests/test_tightlayout.py @@ -6,7 +6,7 @@ import numpy as np -from matplotlib.testing.decorators import image_comparison, knownfailureif +from matplotlib.testing.decorators import image_comparison import matplotlib.pyplot as plt from nose.tools import assert_raises from numpy.testing import assert_array_equal diff --git a/lib/mpl_toolkits/tests/test_mplot3d.py b/lib/mpl_toolkits/tests/test_mplot3d.py index e2b73105089d..e1343618a7e3 100644 --- a/lib/mpl_toolkits/tests/test_mplot3d.py +++ b/lib/mpl_toolkits/tests/test_mplot3d.py @@ -1,5 +1,4 @@ import sys -import nose from nose.tools import assert_raises from mpl_toolkits.mplot3d import Axes3D, axes3d from matplotlib import cm From d04ab5ca4f497a7596a00729d172afa2dc1b5599 Mon Sep 17 00:00:00 2001 From: Jason King Date: Sat, 2 Jan 2016 15:43:32 +1100 Subject: [PATCH 077/174] needed to specify 'reason=' for xfail to work --- lib/matplotlib/tests/test_backend_ps.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/matplotlib/tests/test_backend_ps.py b/lib/matplotlib/tests/test_backend_ps.py index 52f29bcf3a4e..81e4c4237c25 100644 --- a/lib/matplotlib/tests/test_backend_ps.py +++ b/lib/matplotlib/tests/test_backend_ps.py @@ -16,11 +16,11 @@ 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 = 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): From 57b2f17196e8869f4c29f82c3a29581b43a7867f Mon Sep 17 00:00:00 2001 From: Jason King Date: Sat, 2 Jan 2016 15:47:06 +1100 Subject: [PATCH 078/174] need to specify a 'reason=' to use pytest.maek.xfail --- lib/matplotlib/tests/test_image.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/matplotlib/tests/test_image.py b/lib/matplotlib/tests/test_image.py index e3eb2bb49982..8ef51d9fa27e 100644 --- a/lib/matplotlib/tests/test_image.py +++ b/lib/matplotlib/tests/test_image.py @@ -95,7 +95,7 @@ def test_image_python_io(): plt.imread(buffer) -@pytest.mark.xfail(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')) @@ -481,7 +481,7 @@ def test_nonuniformimage_setnorm(): im.set_norm(plt.Normalize()) -@pytest.mark.xfail(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) From 636728fc1018c641acaf858d01d08baaf09771db Mon Sep 17 00:00:00 2001 From: Jason King Date: Sat, 2 Jan 2016 17:07:30 +1100 Subject: [PATCH 079/174] don't need knownfailureif --- lib/matplotlib/testing/decorators.py | 76 ++++++++++++++-------------- 1 file changed, 38 insertions(+), 38 deletions(-) diff --git a/lib/matplotlib/testing/decorators.py b/lib/matplotlib/testing/decorators.py index 1abae20047f9..29752a49bb7a 100644 --- a/lib/matplotlib/testing/decorators.py +++ b/lib/matplotlib/testing/decorators.py @@ -29,44 +29,44 @@ 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 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): From b0a342d7ed0549a57170eca0402f502fe9e0b093 Mon Sep 17 00:00:00 2001 From: Jason King Date: Sat, 2 Jan 2016 17:08:25 +1100 Subject: [PATCH 080/174] pytest xfail needs a 'reason' --- lib/matplotlib/tests/test_colors.py | 3 ++- lib/matplotlib/tests/test_mlab.py | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/lib/matplotlib/tests/test_colors.py b/lib/matplotlib/tests/test_colors.py index 5d51cc1bf601..bf88626da6a1 100644 --- a/lib/matplotlib/tests/test_colors.py +++ b/lib/matplotlib/tests/test_colors.py @@ -398,7 +398,8 @@ def test_light_source_shading_default(): @pytest.mark.xfail((V(np.__version__) <= V('1.9.0') - and V(np.__version__) >= V('1.7.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. diff --git a/lib/matplotlib/tests/test_mlab.py b/lib/matplotlib/tests/test_mlab.py index 109e8b0a04c3..65bee3e3d3cc 100644 --- a/lib/matplotlib/tests/test_mlab.py +++ b/lib/matplotlib/tests/test_mlab.py @@ -2751,7 +2751,8 @@ def get_z(x, y): np.ma.getmask(correct_zi_masked)) -@pytest.mark.xfail(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): From 78587c10d887adf369af5d574b3ae30f930ff157 Mon Sep 17 00:00:00 2001 From: Jason King Date: Sat, 2 Jan 2016 17:13:26 +1100 Subject: [PATCH 081/174] fixing up small pytest issues --- lib/matplotlib/tests/test_mlab.py | 2 +- lib/matplotlib/tests/test_patheffects.py | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/matplotlib/tests/test_mlab.py b/lib/matplotlib/tests/test_mlab.py index 65bee3e3d3cc..f7b0f667a60d 100644 --- a/lib/matplotlib/tests/test_mlab.py +++ b/lib/matplotlib/tests/test_mlab.py @@ -2751,7 +2751,7 @@ def get_z(x, y): np.ma.getmask(correct_zi_masked)) -@pytest.mark.xfail(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. diff --git a/lib/matplotlib/tests/test_patheffects.py b/lib/matplotlib/tests/test_patheffects.py index e1d1e3381d55..9029ed02dcbd 100644 --- a/lib/matplotlib/tests/test_patheffects.py +++ b/lib/matplotlib/tests/test_patheffects.py @@ -8,6 +8,7 @@ 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 09e559a3c49e64e255b5d3247c0fa2a2406929ca Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 4 Jan 2016 12:49:25 +1100 Subject: [PATCH 082/174] don't need the nose make_decorator function any more. --- lib/matplotlib/testing/decorators.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/matplotlib/testing/decorators.py b/lib/matplotlib/testing/decorators.py index 29752a49bb7a..6ce53687cc16 100644 --- a/lib/matplotlib/testing/decorators.py +++ b/lib/matplotlib/testing/decorators.py @@ -410,5 +410,5 @@ def backend_switcher(*args, **kwargs): plt.switch_backend(prev_backend) return result - return nose.tools.make_decorator(func)(backend_switcher) + return func(backend_switcher) return switch_backend_decorator From 8c3f2f11dc4fe082718b9f779d5e5ae8d540841e Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 4 Jan 2016 15:01:37 +1100 Subject: [PATCH 083/174] to please the pep8 gods, we sacrifice this line break. some rain would be good. --- lib/matplotlib/tests/test_backend_svg.py | 1 - 1 file changed, 1 deletion(-) diff --git a/lib/matplotlib/tests/test_backend_svg.py b/lib/matplotlib/tests/test_backend_svg.py index 086e1f8779b5..35989214aeaf 100644 --- a/lib/matplotlib/tests/test_backend_svg.py +++ b/lib/matplotlib/tests/test_backend_svg.py @@ -182,4 +182,3 @@ def test_determinism_notex(): def test_determinism_tex(): # unique filename to allow for parallel testing _test_determinism('determinism_tex.svg', usetex=True) - From 62983b5a62fce983f68c4ea59e5f3fd4666b9a10 Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 4 Jan 2016 22:28:39 +1100 Subject: [PATCH 084/174] replace a knownfailureif call, and fix up pytest xfail calls --- lib/matplotlib/tests/test_backend_qt5.py | 24 ++++++++++++------------ lib/matplotlib/tests/test_backend_svg.py | 5 +++-- 2 files changed, 15 insertions(+), 14 deletions(-) diff --git a/lib/matplotlib/tests/test_backend_qt5.py b/lib/matplotlib/tests/test_backend_qt5.py index 1c059b15ba19..f77bc6713734 100644 --- a/lib/matplotlib/tests/test_backend_qt5.py +++ b/lib/matplotlib/tests/test_backend_qt5.py @@ -34,7 +34,7 @@ @cleanup -@pytest.mark.xfail(not HAS_QT) +@pytest.mark.xfail(not HAS_QT, reason='pyq5 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 -@pytest.mark.xfail(not HAS_QT) +@pytest.mark.xfail(not HAS_QT, reason='pyq5 version 5 not installed') def test_shift(): assert_correct_key(QtCore.Qt.Key_A, ShiftModifier, @@ -83,7 +83,7 @@ def test_shift(): @cleanup -@pytest.mark.xfail(not HAS_QT) +@pytest.mark.xfail(not HAS_QT, reason='pyq5 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 -@pytest.mark.xfail(not HAS_QT) +@pytest.mark.xfail(not HAS_QT, reason='pyq5 version 5 not installed') def test_control(): assert_correct_key(QtCore.Qt.Key_A, ControlModifier, @@ -99,7 +99,7 @@ def test_control(): @cleanup -@pytest.mark.xfail(not HAS_QT) +@pytest.mark.xfail(not HAS_QT, reason='pyq5 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 -@pytest.mark.xfail(not HAS_QT) +@pytest.mark.xfail(not HAS_QT, reason='pyq5 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 -@pytest.mark.xfail(not HAS_QT) +@pytest.mark.xfail(not HAS_QT, reason='pyq5 version 5 not installed') def test_alt_control(): assert_correct_key(ControlKey, AltModifier, @@ -123,7 +123,7 @@ def test_alt_control(): @cleanup -@pytest.mark.xfail(not HAS_QT) +@pytest.mark.xfail(not HAS_QT, reason='pyq5 version 5 not installed') def test_control_alt(): assert_correct_key(AltKey, ControlModifier, @@ -131,7 +131,7 @@ def test_control_alt(): @cleanup -@pytest.mark.xfail(not HAS_QT) +@pytest.mark.xfail(not HAS_QT, reason='pyq5 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 -@pytest.mark.xfail(not HAS_QT) +@pytest.mark.xfail(not HAS_QT, reason='pyq5 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 -@pytest.mark.xfail(not HAS_QT) +@pytest.mark.xfail(not HAS_QT, reason='pyq5 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 -@pytest.mark.xfail(not HAS_QT) +@pytest.mark.xfail(not HAS_QT, reason='pyq5 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 35989214aeaf..046ee9477f7c 100644 --- a/lib/matplotlib/tests/test_backend_svg.py +++ b/lib/matplotlib/tests/test_backend_svg.py @@ -9,10 +9,11 @@ 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") From e83807f270118f299883e300ead15dfcc3b20e79 Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 4 Jan 2016 22:38:40 +1100 Subject: [PATCH 085/174] make_decorator seems to be described here. https://ipython.org/ipython-doc/1/api/generated/IPython. testing.decorators.html So lets try just returning the decorator instead of whats there now. --- lib/matplotlib/testing/decorators.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/matplotlib/testing/decorators.py b/lib/matplotlib/testing/decorators.py index 6ce53687cc16..5a6c39938a47 100644 --- a/lib/matplotlib/testing/decorators.py +++ b/lib/matplotlib/testing/decorators.py @@ -410,5 +410,5 @@ def backend_switcher(*args, **kwargs): plt.switch_backend(prev_backend) return result - return func(backend_switcher) + return backend_switcher return switch_backend_decorator From 22ee9786dfd72e9ee10158ed4b0ed0356239adb3 Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 4 Jan 2016 22:53:25 +1100 Subject: [PATCH 086/174] resolve the oeo8 allergy to blank lines, --- lib/matplotlib/tests/test_collections.py | 1 - 1 file changed, 1 deletion(-) diff --git a/lib/matplotlib/tests/test_collections.py b/lib/matplotlib/tests/test_collections.py index dd2b8a5eb0b0..f72e92b8a3d9 100644 --- a/lib/matplotlib/tests/test_collections.py +++ b/lib/matplotlib/tests/test_collections.py @@ -615,4 +615,3 @@ def test_size_in_xy(): ax.set_xlim(0, 30) ax.set_ylim(0, 30) - From ea7c57fd913c6b1120c55b4ab1d89ae97803090f Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 4 Jan 2016 22:58:57 +1100 Subject: [PATCH 087/174] fix up xfail calls --- lib/matplotlib/tests/test_backend_qt4.py | 24 ++++++++++++------------ lib/matplotlib/tests/test_backend_svg.py | 2 +- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/lib/matplotlib/tests/test_backend_qt4.py b/lib/matplotlib/tests/test_backend_qt4.py index 2429c8c3f7d9..c6f3ef91740a 100644 --- a/lib/matplotlib/tests/test_backend_qt4.py +++ b/lib/matplotlib/tests/test_backend_qt4.py @@ -40,7 +40,7 @@ @cleanup -@pytest.mark.xfail(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 -@pytest.mark.xfail(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 -@pytest.mark.xfail(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 -@pytest.mark.xfail(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 -@pytest.mark.xfail(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 -@pytest.mark.xfail(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 -@pytest.mark.xfail(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 -@pytest.mark.xfail(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 -@pytest.mark.xfail(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 -@pytest.mark.xfail(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 -@pytest.mark.xfail(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 -@pytest.mark.xfail(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_svg.py b/lib/matplotlib/tests/test_backend_svg.py index 046ee9477f7c..0b7e9ab82544 100644 --- a/lib/matplotlib/tests/test_backend_svg.py +++ b/lib/matplotlib/tests/test_backend_svg.py @@ -15,7 +15,7 @@ needs_tex = pytest.mark.xfail( not matplotlib.checkdep_tex(), - "This test needs a TeX installation") + reason="This test needs a TeX installation") @cleanup From 3008a224614473c1fe8f5b0d54a4ca7524a772a9 Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 4 Jan 2016 23:02:39 +1100 Subject: [PATCH 088/174] another zfail reason fix --- lib/matplotlib/tests/test_patheffects.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/matplotlib/tests/test_patheffects.py b/lib/matplotlib/tests/test_patheffects.py index 9029ed02dcbd..5cbea26102b4 100644 --- a/lib/matplotlib/tests/test_patheffects.py +++ b/lib/matplotlib/tests/test_patheffects.py @@ -85,7 +85,7 @@ def test_patheffect3(): @cleanup -@pytest.mark.xfail(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)) From 49d231506ba02cb4a67ff3a3f0c7c450f7eb581e Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 4 Jan 2016 23:04:18 +1100 Subject: [PATCH 089/174] typo --- lib/matplotlib/tests/test_backend_qt5.py | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/lib/matplotlib/tests/test_backend_qt5.py b/lib/matplotlib/tests/test_backend_qt5.py index f77bc6713734..3006aa88c59b 100644 --- a/lib/matplotlib/tests/test_backend_qt5.py +++ b/lib/matplotlib/tests/test_backend_qt5.py @@ -34,7 +34,7 @@ @cleanup -@pytest.mark.xfail(not HAS_QT, reason='pyq5 version 5 not installed') +@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 -@pytest.mark.xfail(not HAS_QT, reason='pyq5 version 5 not installed') +@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 -@pytest.mark.xfail(not HAS_QT, reason='pyq5 version 5 not installed') +@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 -@pytest.mark.xfail(not HAS_QT, reason='pyq5 version 5 not installed') +@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 -@pytest.mark.xfail(not HAS_QT, reason='pyq5 version 5 not installed') +@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 -@pytest.mark.xfail(not HAS_QT, reason='pyq5 version 5 not installed') +@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 -@pytest.mark.xfail(not HAS_QT, reason='pyq5 version 5 not installed') +@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 -@pytest.mark.xfail(not HAS_QT, reason='pyq5 version 5 not installed') +@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 -@pytest.mark.xfail(not HAS_QT, reason='pyq5 version 5 not installed') +@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 -@pytest.mark.xfail(not HAS_QT, reason='pyq5 version 5 not installed') +@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 -@pytest.mark.xfail(not HAS_QT, reason='pyq5 version 5 not installed') +@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 -@pytest.mark.xfail(not HAS_QT, reason='pyq5 version 5 not installed') +@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, From a1f31a84eb08130a9f0ffaf273ea2ca8e9c4078a Mon Sep 17 00:00:00 2001 From: Jason King Date: Tue, 5 Jan 2016 11:39:31 +1100 Subject: [PATCH 090/174] don't import from nose , and don't need knownfailure --- lib/matplotlib/testing/noseclasses.py | 84 +++++++++++++-------------- 1 file changed, 42 insertions(+), 42 deletions(-) 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 From e812aac8fc82c444c66c8e7bb73632c28fdca92e Mon Sep 17 00:00:00 2001 From: Jason King Date: Tue, 5 Jan 2016 11:40:06 +1100 Subject: [PATCH 091/174] remove knownfailureif reference --- lib/matplotlib/testing/decorators.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/matplotlib/testing/decorators.py b/lib/matplotlib/testing/decorators.py index 5a6c39938a47..038137ca24ac 100644 --- a/lib/matplotlib/testing/decorators.py +++ b/lib/matplotlib/testing/decorators.py @@ -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(): From 4fff1464ee4cc7b8b7867fed53fa8dd61f0a72ef Mon Sep 17 00:00:00 2001 From: Jason King Date: Fri, 8 Jan 2016 12:14:50 +1100 Subject: [PATCH 092/174] An attempt to make a image_comparison decorator that doesn't fail while being used on test_pickle.test_complete() --- lib/matplotlib/testing/decorators.py | 30 ++++++++++++++++++++++++++++ lib/matplotlib/tests/test_pickle.py | 9 ++++++--- 2 files changed, 36 insertions(+), 3 deletions(-) diff --git a/lib/matplotlib/testing/decorators.py b/lib/matplotlib/testing/decorators.py index 038137ca24ac..04bb81fca9ab 100644 --- a/lib/matplotlib/testing/decorators.py +++ b/lib/matplotlib/testing/decorators.py @@ -252,6 +252,35 @@ def do_test(): 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 + 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 +367,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*. diff --git a/lib/matplotlib/tests/test_pickle.py b/lib/matplotlib/tests/test_pickle.py index 6e9477d6a3a6..5464b2fc31b3 100644 --- a/lib/matplotlib/tests/test_pickle.py +++ b/lib/matplotlib/tests/test_pickle.py @@ -10,7 +10,8 @@ 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, + image_comparison_2 import matplotlib.pyplot as plt import matplotlib.transforms as mtransforms @@ -128,7 +129,7 @@ def test_simple(): @cleanup -@image_comparison(baseline_images=['multi_pickle'], +@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)) @@ -191,7 +192,9 @@ def test_complete(): fig = pickle.load(result_fh) # make sure there is now a figure manager - assert not 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 fig.get_label() == 'Figure with a label?' From 738da3e33216fc57ae8b29f328399ee2fe3bc69c Mon Sep 17 00:00:00 2001 From: Jason King Date: Fri, 8 Jan 2016 12:55:00 +1100 Subject: [PATCH 093/174] fix up indentation for import --- lib/matplotlib/tests/test_pickle.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/matplotlib/tests/test_pickle.py b/lib/matplotlib/tests/test_pickle.py index 5464b2fc31b3..1b4b66c72159 100644 --- a/lib/matplotlib/tests/test_pickle.py +++ b/lib/matplotlib/tests/test_pickle.py @@ -11,7 +11,7 @@ import numpy as np from matplotlib.testing.decorators import cleanup, image_comparison, - image_comparison_2 + image_comparison_2 import matplotlib.pyplot as plt import matplotlib.transforms as mtransforms From da60028e8d8f8e085eb0fe55812e7ac4acb6e8c1 Mon Sep 17 00:00:00 2001 From: Jason King Date: Fri, 8 Jan 2016 13:13:42 +1100 Subject: [PATCH 094/174] another fix for indentation. kinda non-dry'y --- lib/matplotlib/tests/test_pickle.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/matplotlib/tests/test_pickle.py b/lib/matplotlib/tests/test_pickle.py index 1b4b66c72159..6998e5dec19f 100644 --- a/lib/matplotlib/tests/test_pickle.py +++ b/lib/matplotlib/tests/test_pickle.py @@ -10,8 +10,8 @@ from nose.tools import assert_equal, assert_not_equal import numpy as np -from matplotlib.testing.decorators import cleanup, image_comparison, - image_comparison_2 +from matplotlib.testing.decorators import cleanup, image_comparison +from matplotlib.testing.decorators import image_comparison_2 import matplotlib.pyplot as plt import matplotlib.transforms as mtransforms From 726cc928394a5878b06b7fd271ffb3e54df50223 Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 11 Jan 2016 23:02:54 +1100 Subject: [PATCH 095/174] removed mentions of 'import nose' --- conftest.py | 0 lib/matplotlib/tests/test_animation.py | 1 - lib/matplotlib/tests/test_backend_pgf.py | 15 ++++++------ lib/matplotlib/tests/test_coding_standards.py | 7 ++---- lib/matplotlib/tests/test_compare_images.py | 2 +- lib/matplotlib/tests/test_contour.py | 6 ++--- lib/matplotlib/tests/test_cycles.py | 23 +++++++++++-------- lib/matplotlib/tests/test_dviread.py | 16 ++++++------- .../tests/test_labeled_data_unpacking.py | 4 +--- lib/matplotlib/tests/test_mlab.py | 3 +-- lib/matplotlib/tests/test_rcparams.py | 13 ++++------- lib/matplotlib/tests/test_style.py | 8 ++----- lib/matplotlib/tests/test_text.py | 4 +--- lib/matplotlib/tests/test_type1font.py | 5 ++-- lib/mpl_toolkits/tests/test_mplot3d.py | 22 +++++++----------- 15 files changed, 54 insertions(+), 75 deletions(-) create mode 100644 conftest.py diff --git a/conftest.py b/conftest.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/lib/matplotlib/tests/test_animation.py b/lib/matplotlib/tests/test_animation.py index ff957a39c3a2..52c9a9843ddf 100644 --- a/lib/matplotlib/tests/test_animation.py +++ b/lib/matplotlib/tests/test_animation.py @@ -7,7 +7,6 @@ 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.decorators import cleanup diff --git a/lib/matplotlib/tests/test_backend_pgf.py b/lib/matplotlib/tests/test_backend_pgf.py index 28be98c8f3cb..db19121907be 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} diff --git a/lib/matplotlib/tests/test_coding_standards.py b/lib/matplotlib/tests/test_coding_standards.py index c233c9e01fdc..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 -import pytest +# import pytest try: import pep8 @@ -102,7 +99,7 @@ def get_file_results(self): # """ # # if not HAS_PEP8: -# raise SkipTest('The pep8 tool is required for this test') +# 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. diff --git a/lib/matplotlib/tests/test_compare_images.py b/lib/matplotlib/tests/test_compare_images.py index d903a29d78c0..37c064d8a3b2 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 diff --git a/lib/matplotlib/tests/test_contour.py b/lib/matplotlib/tests/test_contour.py index ee39cc59437e..07d5cecf131d 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,12 @@ 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]) + 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 diff --git a/lib/matplotlib/tests/test_cycles.py b/lib/matplotlib/tests/test_cycles.py index 5cec742f29ba..a842d8caa558 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,14 +172,18 @@ 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') + 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') if __name__ == '__main__': diff --git a/lib/matplotlib/tests/test_dviread.py b/lib/matplotlib/tests/test_dviread.py index 3444e913fe00..6ece9961b95f 100644 --- a/lib/matplotlib/tests/test_dviread.py +++ b/lib/matplotlib/tests/test_dviread.py @@ -3,7 +3,6 @@ from matplotlib.externals import six -from nose.tools import assert_equal, with_setup import matplotlib.dviread as dr import os.path import json @@ -11,17 +10,18 @@ original_find_tex_file = dr.find_tex_file - -def setup_PsfontsMap(): - dr.find_tex_file = lambda x: x - - 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) + -@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') diff --git a/lib/matplotlib/tests/test_labeled_data_unpacking.py b/lib/matplotlib/tests/test_labeled_data_unpacking.py index 4cd3b614abe5..9c43aa799737 100644 --- a/lib/matplotlib/tests/test_labeled_data_unpacking.py +++ b/lib/matplotlib/tests/test_labeled_data_unpacking.py @@ -1,7 +1,5 @@ from __future__ import (absolute_import, division, print_function) -from nose.tools import (assert_raises, assert_equal) -from nose.plugins.skip import SkipTest import pytest try: @@ -192,7 +190,7 @@ 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"]}) diff --git a/lib/matplotlib/tests/test_mlab.py b/lib/matplotlib/tests/test_mlab.py index f7b0f667a60d..67bb54833f78 100644 --- a/lib/matplotlib/tests/test_mlab.py +++ b/lib/matplotlib/tests/test_mlab.py @@ -8,8 +8,7 @@ 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 diff --git a/lib/matplotlib/tests/test_rcparams.py b/lib/matplotlib/tests/test_rcparams.py index ad202ffae095..31b71660c6bf 100644 --- a/lib/matplotlib/tests/test_rcparams.py +++ b/lib/matplotlib/tests/test_rcparams.py @@ -15,9 +15,6 @@ from matplotlib.tests import assert_str_equal 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, @@ -116,7 +113,7 @@ 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)} @@ -132,7 +129,7 @@ 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 pytest.raises(ValueError): with warnings.catch_warnings(): @@ -178,7 +175,7 @@ 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( + 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 pytest.raises(ValueError): @@ -259,7 +256,7 @@ def _validation_test_helper(validator, arg, 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") pytest.raises(exception_type,validator, arg) @@ -400,7 +397,7 @@ 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" + raise pytest.skip("Test can only be run in Python >= 2.7" " as it requires OrderedDict") with mpl.rc_context(rc={'text.usetex': False}): diff --git a/lib/matplotlib/tests/test_style.py b/lib/matplotlib/tests/test_style.py index 2634bddd7dc6..7a7a3f309683 100644 --- a/lib/matplotlib/tests/test_style.py +++ b/lib/matplotlib/tests/test_style.py @@ -7,10 +7,6 @@ import tempfile from contextlib import contextmanager -from nose import SkipTest -from nose.tools import assert_raises -from nose.plugins.attrib import attr - import matplotlib as mpl from matplotlib import style from matplotlib.style.core import USER_LIBRARY_PATHS, STYLE_EXTENSION @@ -58,7 +54,7 @@ def test_use(): assert mpl.rcParams[PARAM] == VALUE -@attr('network') +@pytest.mark.network def test_use_url(): with temp_style('test', DUMMY_SETTINGS): with style.context('https://gist.github.com/adrn/6590261/raw'): @@ -126,7 +122,7 @@ def test_context_with_badparam(): from collections import OrderedDict else: m = "Test can only be run in Python >= 2.7 as it requires OrderedDict" - raise SkipTest(m) + raise pytest.skip(m) original_value = 'gray' other_value = 'blue' diff --git a/lib/matplotlib/tests/test_text.py b/lib/matplotlib/tests/test_text.py index bf28c9c247eb..11d9b3c527bd 100644 --- a/lib/matplotlib/tests/test_text.py +++ b/lib/matplotlib/tests/test_text.py @@ -6,8 +6,6 @@ import numpy as np from numpy.testing import assert_almost_equal -from nose.tools import eq_, assert_raises -from nose.plugins.skip import SkipTest from matplotlib.transforms import Bbox import matplotlib @@ -290,7 +288,7 @@ def test_get_rotation_raises(): from matplotlib import text import sys if sys.version_info[:2] < (2, 7): - raise SkipTest("assert_raises as context manager " + raise pytest.skip("assert_raises as context manager " "not supported with Python < 2.7") pytest.raises(ValueError, text.get_rotation, 'hozirontal') diff --git a/lib/matplotlib/tests/test_type1font.py b/lib/matplotlib/tests/test_type1font.py index e298a19f6d3d..640ae45061b0 100644 --- a/lib/matplotlib/tests/test_type1font.py +++ b/lib/matplotlib/tests/test_type1font.py @@ -3,7 +3,6 @@ from matplotlib.externals import six -from nose.tools import assert_equal, assert_in import matplotlib.type1font as t1f import os.path import difflib @@ -41,7 +40,7 @@ def test_Type1Font(): # Alters ItalicAngle '- /ItalicAngle 0 def', '+ /ItalicAngle -45.0 def'): - assert_in(line, diff, 'diff to slanted font must contain %s' % line) + assert line in diff, 'diff to slanted font must contain %s' % line diff = list(differ.compare(font.parts[0].decode('latin-1').splitlines(), condensed.parts[0].decode('latin-1').splitlines())) @@ -55,4 +54,4 @@ def test_Type1Font(): # Alters FontMatrix '- /FontMatrix [0.001 0 0 0.001 0 0 ]readonly def', '+ /FontMatrix [0.0005 0.0 0.0 0.001 0.0 0.0]readonly def'): - assert_in(line, diff, 'diff to condensed font must contain %s' % line) + assert line in diff, 'diff to condensed font must contain %s' % line diff --git a/lib/mpl_toolkits/tests/test_mplot3d.py b/lib/mpl_toolkits/tests/test_mplot3d.py index e1343618a7e3..87b405e2020d 100644 --- a/lib/mpl_toolkits/tests/test_mplot3d.py +++ b/lib/mpl_toolkits/tests/test_mplot3d.py @@ -1,10 +1,10 @@ import sys -from nose.tools import assert_raises from mpl_toolkits.mplot3d import Axes3D, axes3d from matplotlib import cm from matplotlib.testing.decorators import image_comparison, cleanup import matplotlib.pyplot as plt import numpy as np +import pytest @image_comparison(baseline_images=['bar3d'], remove_text=True) @@ -194,13 +194,13 @@ def test_wireframe3dzerorstride(): @cleanup def test_wireframe3dzerostrideraises(): - if sys.version_info[:2] < (2, 7): - raise nose.SkipTest("assert_raises as context manager " - "not supported with Python < 2.7") + # if sys.version_info[:2] < (2, 7): + # raise nose.SkipTest("assert_raises as context manager " + # "not supported with Python < 2.7") fig = plt.figure() ax = fig.add_subplot(111, projection='3d') X, Y, Z = axes3d.get_test_data(0.05) - with assert_raises(ValueError): + with pytest.raises(ValueError): ax.plot_wireframe(X, Y, Z, rstride=0, cstride=0) @@ -287,16 +287,15 @@ def test_quiver3d_pivot_tail(): @image_comparison(baseline_images=['axes3d_labelpad'], extensions=['png']) def test_axes3d_labelpad(): - from nose.tools import assert_equal from matplotlib import rcParams fig = plt.figure() ax = Axes3D(fig) # labelpad respects rcParams - assert_equal(ax.xaxis.labelpad, rcParams['axes.labelpad']) + assert ax.xaxis.labelpad == rcParams['axes.labelpad'] # labelpad can be set in set_label ax.set_xlabel('X LABEL', labelpad=10) - assert_equal(ax.xaxis.labelpad, 10) + assert ax.xaxis.labelpad == 10 ax.set_ylabel('Y LABEL') ax.set_zlabel('Z LABEL') # or manually @@ -326,9 +325,4 @@ def test_plotsurface_1d_raises(): fig = plt.figure(figsize=(14,6)) ax = fig.add_subplot(1, 2, 1, projection='3d') - assert_raises(ValueError, ax.plot_surface, X, Y, z) - - -if __name__ == '__main__': - import nose - nose.runmodule(argv=['-s', '--with-doctest'], exit=False) + pytest.raises(ValueError, ax.plot_surface, X, Y, z) From f17a2dbd12234c29dcf6c332db7dfa3e70c8f155 Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 11 Jan 2016 23:19:03 +1100 Subject: [PATCH 096/174] more nose lines to change --- .../sphinxext/tests/test_tinypages.py | 27 +++++++++---------- lib/matplotlib/tests/test_dviread.py | 1 + 2 files changed, 14 insertions(+), 14 deletions(-) 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/tests/test_dviread.py b/lib/matplotlib/tests/test_dviread.py index 6ece9961b95f..58b9fbb5522f 100644 --- a/lib/matplotlib/tests/test_dviread.py +++ b/lib/matplotlib/tests/test_dviread.py @@ -6,6 +6,7 @@ import matplotlib.dviread as dr import os.path import json +import pytest original_find_tex_file = dr.find_tex_file From 683546ea791e8975e9d8676aac8cfc63e2c398aa Mon Sep 17 00:00:00 2001 From: Jason King Date: Tue, 12 Jan 2016 00:03:26 +1100 Subject: [PATCH 097/174] regex assertions to convert --- .../tests/test_labeled_data_unpacking.py | 58 +++++++++---------- 1 file changed, 27 insertions(+), 31 deletions(-) diff --git a/lib/matplotlib/tests/test_labeled_data_unpacking.py b/lib/matplotlib/tests/test_labeled_data_unpacking.py index 9c43aa799737..522119d3dc64 100644 --- a/lib/matplotlib/tests/test_labeled_data_unpacking.py +++ b/lib/matplotlib/tests/test_labeled_data_unpacking.py @@ -2,15 +2,7 @@ import pytest -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 re from ..testing import assert_produces_warning from .. import unpack_labeled_data @@ -342,38 +334,44 @@ def funcy(ax, *args, **kwargs): 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.match(funcy.__doc__) + assert not all_positional.match(funcy.__doc__) + assert not all_arguments.match(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.match(funcy.__doc__) + assert not all_positional_all_keyword.match(funcy.__doc__) + assert not all_arguments.match(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.match(funcy.__doc__) + assert all_arguments.match(funcy.__doc__) + assert not all_positional_all_keyword.match(funcy.__doc__) @unpack_labeled_data(replace_names=["x", "bar"]) def funcy(ax, x, y, z, bar=None): @@ -381,13 +379,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.match(funcy.__doc__) + assert x_string.match(funcy.__doc__) + assert bar_string.match(funcy.__doc__) + assert not all_positional_all_keyword.match(funcy.__doc__) + assert not all_positional.match(funcy.__doc__) def test_positional_parameter_names_as_function(): From 63eae4b2e8f03de054590a3ba39c1c16218b1ae2 Mon Sep 17 00:00:00 2001 From: Jason King Date: Tue, 12 Jan 2016 00:04:41 +1100 Subject: [PATCH 098/174] replaced nose.assert_almost_equal with the numpy one, but had to change places= to decimal= --- lib/matplotlib/tests/test_compare_images.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/matplotlib/tests/test_compare_images.py b/lib/matplotlib/tests/test_compare_images.py index 37c064d8a3b2..043dff50f77a 100644 --- a/lib/matplotlib/tests/test_compare_images.py +++ b/lib/matplotlib/tests/test_compare_images.py @@ -40,7 +40,7 @@ def image_comparison_expect_rms(im1, im2, tol, expect_rms): assert results is None else: assert results is not None - assert_almost_equal(expect_rms, results['rms'], places=4) + assert_almost_equal(expect_rms, results['rms'], decimal=4) def test_image_compare_basic(): From 6c46f42d37e8ec17b26197135ead89d6af16b353 Mon Sep 17 00:00:00 2001 From: Jason King Date: Tue, 12 Jan 2016 00:05:20 +1100 Subject: [PATCH 099/174] basic nose replacement stuff --- lib/matplotlib/tests/test_backend_svg.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/lib/matplotlib/tests/test_backend_svg.py b/lib/matplotlib/tests/test_backend_svg.py index 0b7e9ab82544..00513dd8d4ee 100644 --- a/lib/matplotlib/tests/test_backend_svg.py +++ b/lib/matplotlib/tests/test_backend_svg.py @@ -156,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', @@ -169,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 From c4a824e4df5c78a227365596273d58366bc6004b Mon Sep 17 00:00:00 2001 From: Jason King Date: Fri, 15 Jan 2016 00:34:33 +1100 Subject: [PATCH 100/174] fix up test failures caused through rebase --- lib/matplotlib/tests/test_animation.py | 12 ++++++------ lib/matplotlib/tests/test_lines.py | 5 +---- 2 files changed, 7 insertions(+), 10 deletions(-) diff --git a/lib/matplotlib/tests/test_animation.py b/lib/matplotlib/tests/test_animation.py index 52c9a9843ddf..3dd5b6e42b81 100644 --- a/lib/matplotlib/tests/test_animation.py +++ b/lib/matplotlib/tests/test_animation.py @@ -64,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') diff --git a/lib/matplotlib/tests/test_lines.py b/lib/matplotlib/tests/test_lines.py index af7e38d280c8..b2b7a13d9715 100644 --- a/lib/matplotlib/tests/test_lines.py +++ b/lib/matplotlib/tests/test_lines.py @@ -8,15 +8,12 @@ import itertools import matplotlib as mpl import matplotlib.lines as mlines -import nose -from nose.tools import assert_true, assert_raises -import pytest 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 From ac14548dac5f3b7af0b66570ffb7d7361f2409bb Mon Sep 17 00:00:00 2001 From: Jason King Date: Fri, 15 Jan 2016 20:33:31 +1100 Subject: [PATCH 101/174] add in the ability to filter out numpy files from consideration while searching for tests to run --- lib/matplotlib/ignorenumpytests.py | 29 +++++++++++++++++++++++++++++ setup.py | 6 +++++- tests.py | 1 + 3 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 lib/matplotlib/ignorenumpytests.py 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/setup.py b/setup.py index 2570f157152b..d906ab286f82 100644 --- a/setup.py +++ b/setup.py @@ -292,7 +292,11 @@ def run(self): package_data=package_data, classifiers=classifiers, download_url="http://matplotlib.org/users/installing.html", - + entry_points = { + 'pytest11': [ + 'ignorenumpytests = matplotlib.ignorenumpytests', + ] + }, # List third-party Python packages that we require install_requires=install_requires, setup_requires=setup_requires, diff --git a/tests.py b/tests.py index c71815882e6e..5a3b7c771306 100755 --- a/tests.py +++ b/tests.py @@ -33,6 +33,7 @@ def run(extra_args): # to pytest.main return pytest.main(argv) else: + pytest.main(['--traceconfig']) return pytest.main(argv + ['--pyargs'] + default_test_modules + ['--ignore=site-packages/numpy/testing/.']) From 3f45e425aadf24b62ab71120666b1a387faaf463 Mon Sep 17 00:00:00 2001 From: Jason King Date: Sun, 17 Jan 2016 22:40:18 +1100 Subject: [PATCH 102/174] fix up test_mlab.py raises and nose import lines --- lib/matplotlib/tests/test_mlab.py | 104 ++++++++++++++---------------- 1 file changed, 47 insertions(+), 57 deletions(-) diff --git a/lib/matplotlib/tests/test_mlab.py b/lib/matplotlib/tests/test_mlab.py index 67bb54833f78..bd2e3d61e762 100644 --- a/lib/matplotlib/tests/test_mlab.py +++ b/lib/matplotlib/tests/test_mlab.py @@ -404,19 +404,19 @@ def test_apply_window_1D_axis1_ValueError(self): def test_apply_window_1D_els_wrongsize_ValueError(self): x = self.sig_rand window = mlab.window_hanning(np.ones(x.shape[0]-1)) - pytest.raises(ValueError, mlab.apply_window(x, window)) + pytest.raises(ValueError, mlab.apply_windowx, window) def test_apply_window_0D_ValueError(self): x = np.array(0) window = mlab.window_hanning - pytest.raises(ValueError, mlab.apply_window(x, window, axis=1, - return_window=False)) + pytest.raises(ValueError, mlab.apply_windowx, 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 - pytest.raises(ValueError, mlab.apply_window(x, window, axis=1, - return_window=False)) + pytest.raises(ValueError, mlab.apply_windowx, window, axis=1, + return_window=False) def test_apply_window_hanning_1D(self): x = self.sig_rand @@ -1095,43 +1095,43 @@ def test_demean_2D_axism1(self): def test_detrend_bad_key_str_ValueError(self): input = self.sig_slope[np.newaxis] - pytest.raises(ValueError, mlab.detrend(input, key='spam')) + pytest.raises(ValueError, mlab.detrend, input, key='spam') def test_detrend_bad_key_var_ValueError(self): input = self.sig_slope[np.newaxis] - pytest.raises(ValueError, mlab.detrend(input, key=5)) + pytest.raises(ValueError, mlab.detrend, input, key=5) def test_detrend_mean_0D_d0_ValueError(self): input = 5.5 - pytest.raises(ValueError, mlab.detrend_mean(input, axis=0)) + pytest.raises(ValueError, mlab.detrend_mean, input, axis=0) def test_detrend_0D_d0_ValueError(self): input = 5.5 - pytest.raises(ValueError, mlab.detrend(input, axis=0)) + pytest.raises(ValueError, mlab.detrend, input, axis=0) def test_detrend_mean_1D_d1_ValueError(self): input = self.sig_slope - pytest.raises(ValueError, mlab.detrend_mean(input, axis=1)) + pytest.raises(ValueError, mlab.detrend_mean, input, axis=1) def test_detrend_1D_d1_ValueError(self): input = self.sig_slope - pytest.raises(ValueError, mlab.detrend(input, axis=1)) + pytest.raises(ValueError, mlab.detrend, input, axis=1) def test_demean_1D_d1_ValueError(self): input = self.sig_slope - pytest.raises(ValueError, mlab.demean(input, axis=1)) + pytest.raises(ValueError, mlab.demean, input, axis=1) def test_detrend_mean_2D_d2_ValueError(self): input = self.sig_slope[np.newaxis] - pytest.raises(ValueError, mlab.detrend_mean(input, axis=2)) + pytest.raises(ValueError, mlab.detrend_mean, input, axis=2) def test_detrend_2D_d2_ValueError(self): input = self.sig_slope[np.newaxis] - pytest.raises(ValueError, mlab.detrend(input, axis=2)) + pytest.raises(ValueError, mlab.detrend, input, axis=2) def test_demean_2D_d2_ValueError(self): input = self.sig_slope[np.newaxis] - pytest.raises(ValueError, mlab.demean(input, axis=2)) + pytest.raises(ValueError, mlab.demean, input, axis=2) def test_detrend_linear_0D_zeros(self): input = 0. @@ -1195,7 +1195,7 @@ def test_detrend_linear_1d_slope_off_list(self): def test_detrend_linear_2D_ValueError(self): input = self.sig_slope[np.newaxis] - pytest.raises(ValueError, mlab.detrend_linear(input)) + pytest.raises(ValueError, mlab.detrend_linear, input) def test_detrend_str_linear_2d_slope_off_axis0(self): arri = [self.sig_off, @@ -1430,58 +1430,58 @@ 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 - pytest.raises(ValueError, mlab._spectral_helper( - x=self.y, y=self.y+1, mode='complex')) + 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 - pytest.raises(ValueError, mlab._spectral_helper( - x=self.y, y=self.y+1, mode='magnitude')) + 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 - pytest.raises(ValueError, mlab._spectral_helper( - x=self.y, y=self.y+1, mode='angle')) + 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 - pytest.raises(ValueError, mlab._spectral_helper( - x=self.y, y=self.y+1, mode='phase')) + 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 - pytest.raises(ValueError, mlab._spectral_helper( - x=self.y, mode='spam')) + 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 - pytest.raises(ValueError, mlab._spectral_helper( - x=self.y, y=self.y, sides='eggs')) + 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 - pytest.raises(ValueError, mlab._spectral_helper( - x=self.y, y=self.y, NFFT=10, noverlap=20)) + 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 - pytest.raises(ValueError, mlab._spectral_helper( - x=self.y, NFFT=10, noverlap=10)) + 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 - pytest.raises(ValueError, mlab._spectral_helper( - x=self.y, y=self.y, NFFT=10, window=np.ones(9))) + 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 - pytest.raises(ValueError, mlab._single_spectrum_helper( - x=self.y, mode='default')) + 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 - pytest.raises(ValueError, mlab._single_spectrum_helper( - x=self.y, mode='psd')) + pytest.raises(ValueError, mlab._single_spectrum_helper, + x=self.y, mode='psd') def test_spectral_helper_psd(self): freqs = self.freqs_density @@ -2771,10 +2771,10 @@ def get_z(x, y): np.testing.assert_array_almost_equal(zi, correct_zi, 5) # Decreasing xi or yi should raise ValueError. - pytest.raises(ValueError, mlab.griddata(x, y, z, xi[::-1], yi, - interp='nn')) - pytest.raises(ValueError, mlab.griddata(x, y, z, xi, yi[::-1], - interp='nn')) + pytest.raises(ValueError, mlab.griddata, x, y, z, xi[::-1], yi, + interp='nn') + 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) @@ -2868,7 +2868,7 @@ 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]]) - pytest.raises(np.linalg.LinAlgError, mlab.GaussianKDE(x1, "scott")) + 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 +2881,7 @@ 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 """ - pytest.raises(ValueError, mlab.GaussianKDE([], bw_method=5)) + pytest.raises(ValueError, mlab.GaussianKDE, [], bw_method=5) def test_scalar_covariance_dataset(self): """Use a dataset and test a scalar's cov factor @@ -2921,7 +2921,7 @@ def test_wrong_bw_method(self): np.random.seed(8765678) n_basesample = 50 data = np.random.randn(n_basesample) - pytest.raises(ValueError, mlab.GaussianKDE(data, bw_method="invalid")) + pytest.raises(ValueError, mlab.GaussianKDE, data, bw_method="invalid") class gaussian_kde_evaluate_tests(object): @@ -2947,7 +2947,7 @@ def test_evaluate_inv_dim(self): multidim_data = np.random.randn(n_basesample) kde = mlab.GaussianKDE(multidim_data) x2 = [[1], [2], [3]] - pytest.raises(ValueError, kde.evaluate(x2)) + pytest.raises(ValueError, kde.evaluate, x2) def test_evaluate_dim_and_num(self): """ Tests if evaluated against a one by one array""" @@ -2963,7 +2963,7 @@ 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) - pytest.raises(ValueError, kde.evaluate(x2)) + pytest.raises(ValueError, kde.evaluate, x2) def test_evaluate_equal_dim_and_num_lt(self): """Test when line 3810 fails""" @@ -3008,13 +3008,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) From 38c29c62f5b8978659dc528d4b29eb91f71e31af Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 18 Jan 2016 10:02:34 +1100 Subject: [PATCH 103/174] fix test_apply_window_*D* function calls in test_mlab.py --- lib/matplotlib/tests/test_mlab.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/matplotlib/tests/test_mlab.py b/lib/matplotlib/tests/test_mlab.py index bd2e3d61e762..c9fa040d28ae 100644 --- a/lib/matplotlib/tests/test_mlab.py +++ b/lib/matplotlib/tests/test_mlab.py @@ -404,18 +404,18 @@ def test_apply_window_1D_axis1_ValueError(self): def test_apply_window_1D_els_wrongsize_ValueError(self): x = self.sig_rand window = mlab.window_hanning(np.ones(x.shape[0]-1)) - pytest.raises(ValueError, mlab.apply_windowx, window) + pytest.raises(ValueError, mlab.apply_window, x, window) def test_apply_window_0D_ValueError(self): x = np.array(0) window = mlab.window_hanning - pytest.raises(ValueError, mlab.apply_windowx, window, axis=1, + 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 - pytest.raises(ValueError, mlab.apply_windowx, window, axis=1, + pytest.raises(ValueError, mlab.apply_window, x, window, axis=1, return_window=False) def test_apply_window_hanning_1D(self): From fc4e02574c979189b0661b64193711a8f2dc4969 Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 18 Jan 2016 10:09:06 +1100 Subject: [PATCH 104/174] fix test_LogLocator in test_ticker.py --- lib/matplotlib/tests/test_ticker.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/matplotlib/tests/test_ticker.py b/lib/matplotlib/tests/test_ticker.py index 040fd567c951..26e0a4b16e49 100644 --- a/lib/matplotlib/tests/test_ticker.py +++ b/lib/matplotlib/tests/test_ticker.py @@ -53,7 +53,7 @@ def test_AutoMinorLocator(): def test_LogLocator(): loc = mticker.LogLocator(numticks=5) - pytest.raises(ValueError, loc.tick_values(0, 1000)) + pytest.raises(ValueError, loc.tick_values, 0, 1000) test_value = np.array([1.00000000e-05, 1.00000000e-03, 1.00000000e-01, 1.00000000e+01, 1.00000000e+03, 1.00000000e+05, From ade18905e9fc6cb946a0c25894d7b82a6ea53b0a Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 18 Jan 2016 10:11:28 +1100 Subject: [PATCH 105/174] fix lack of pytest import in test_transforms.py --- lib/matplotlib/tests/test_transforms.py | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/matplotlib/tests/test_transforms.py b/lib/matplotlib/tests/test_transforms.py index ff83335771a0..e36548a8edef 100644 --- a/lib/matplotlib/tests/test_transforms.py +++ b/lib/matplotlib/tests/test_transforms.py @@ -21,6 +21,7 @@ import matplotlib.pyplot as plt import matplotlib.path as mpath import matplotlib.patches as mpatches +import pytest @cleanup From 1cbd24ae11b053d431a15ec31666a48e6909fbc3 Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 18 Jan 2016 10:29:22 +1100 Subject: [PATCH 106/174] remove __name__ == '__main__' from many test files --- lib/matplotlib/tests/test_arrow_patches.py | 5 ----- lib/matplotlib/tests/test_axes.py | 9 --------- lib/matplotlib/tests/test_backend_pgf.py | 5 ----- lib/matplotlib/tests/test_backend_ps.py | 5 ----- lib/matplotlib/tests/test_basic.py | 5 ----- lib/matplotlib/tests/test_bbox_tight.py | 4 ---- lib/matplotlib/tests/test_colorbar.py | 5 ----- lib/matplotlib/tests/test_colors.py | 5 ----- lib/matplotlib/tests/test_compare_images.py | 5 ----- lib/matplotlib/tests/test_cycles.py | 5 ----- lib/matplotlib/tests/test_dates.py | 5 ----- lib/matplotlib/tests/test_image.py | 5 ----- lib/matplotlib/tests/test_legend.py | 5 ----- lib/matplotlib/tests/test_lines.py | 4 ---- lib/matplotlib/tests/test_mathtext.py | 5 ----- lib/matplotlib/tests/test_offsetbox.py | 3 --- lib/matplotlib/tests/test_patches.py | 5 ----- lib/matplotlib/tests/test_path.py | 5 ----- lib/matplotlib/tests/test_patheffects.py | 5 ----- lib/matplotlib/tests/test_pickle.py | 6 ------ lib/matplotlib/tests/test_quiver.py | 5 ----- lib/matplotlib/tests/test_rcparams.py | 4 ---- lib/matplotlib/tests/test_sankey.py | 5 ----- lib/matplotlib/tests/test_simplification.py | 5 ----- lib/matplotlib/tests/test_skew.py | 4 ---- lib/matplotlib/tests/test_streamplot.py | 5 ----- lib/matplotlib/tests/test_style.py | 5 ----- lib/matplotlib/tests/test_ticker.py | 5 ----- lib/matplotlib/tests/test_transforms.py | 5 ----- lib/matplotlib/tests/test_triangulation.py | 5 ----- lib/mpl_toolkits/tests/test_axes_grid1.py | 5 ----- 31 files changed, 154 deletions(-) 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_axes.py b/lib/matplotlib/tests/test_axes.py index 0a5ea04a50a2..e5c787d44c7b 100644 --- a/lib/matplotlib/tests/test_axes.py +++ b/lib/matplotlib/tests/test_axes.py @@ -4364,12 +4364,3 @@ def test_pandas_indexing_hist(): ser_2 = ser_1.iloc[1:] fig, axes = plt.subplots() axes.hist(ser_2) - - -if __name__ == '__main__': - import sys - - args = ['--doctest-modules'] - argv = sys.argv - argv = argv[:1] + args + argv[1:] - pytest.main(argv) diff --git a/lib/matplotlib/tests/test_backend_pgf.py b/lib/matplotlib/tests/test_backend_pgf.py index db19121907be..2813e7079d5b 100644 --- a/lib/matplotlib/tests/test_backend_pgf.py +++ b/lib/matplotlib/tests/test_backend_pgf.py @@ -190,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 81e4c4237c25..add7617fdfc7 100644 --- a/lib/matplotlib/tests/test_backend_ps.py +++ b/lib/matplotlib/tests/test_backend_ps.py @@ -129,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_basic.py b/lib/matplotlib/tests/test_basic.py index cd7745087c07..5495af8bb99b 100644 --- a/lib/matplotlib/tests/test_basic.py +++ b/lib/matplotlib/tests/test_basic.py @@ -46,8 +46,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 d7d2af651606..875318b5a76f 100644 --- a/lib/matplotlib/tests/test_bbox_tight.py +++ b/lib/matplotlib/tests/test_bbox_tight.py @@ -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_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 bf88626da6a1..bced0209f9d6 100644 --- a/lib/matplotlib/tests/test_colors.py +++ b/lib/matplotlib/tests/test_colors.py @@ -536,8 +536,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 043dff50f77a..e90b0b631b1a 100644 --- a/lib/matplotlib/tests/test_compare_images.py +++ b/lib/matplotlib/tests/test_compare_images.py @@ -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_cycles.py b/lib/matplotlib/tests/test_cycles.py index a842d8caa558..ba46eb209dbc 100644 --- a/lib/matplotlib/tests/test_cycles.py +++ b/lib/matplotlib/tests/test_cycles.py @@ -184,8 +184,3 @@ def test_invalid_input_forms(): ax.set_prop_cycle('linewidth', {'1': 1, '2': 2}) with pytest.raises(TypeError, ValueError): ax.set_prop_cycle(linewidth=1, color='r') - - -if __name__ == '__main__': - import nose - nose.runmodule(argv=['-s', '--with-doctest'], exit=False) diff --git a/lib/matplotlib/tests/test_dates.py b/lib/matplotlib/tests/test_dates.py index b5ff383e881e..ff4ed52ae514 100644 --- a/lib/matplotlib/tests/test_dates.py +++ b/lib/matplotlib/tests/test_dates.py @@ -352,8 +352,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_image.py b/lib/matplotlib/tests/test_image.py index 8ef51d9fa27e..607145bc2cd8 100644 --- a/lib/matplotlib/tests/test_image.py +++ b/lib/matplotlib/tests/test_image.py @@ -542,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_legend.py b/lib/matplotlib/tests/test_legend.py index 1c18a5364fd3..cf51522eed65 100644 --- a/lib/matplotlib/tests/test_legend.py +++ b/lib/matplotlib/tests/test_legend.py @@ -261,8 +261,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 b2b7a13d9715..f0008d009b84 100644 --- a/lib/matplotlib/tests/test_lines.py +++ b/lib/matplotlib/tests/test_lines.py @@ -159,7 +159,3 @@ def test_nan_is_sorted(): 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]) - - -if __name__ == '__main__': - nose.runmodule(argv=['-s', '--with-doctest'], exit=False) diff --git a/lib/matplotlib/tests/test_mathtext.py b/lib/matplotlib/tests/test_mathtext.py index 02edbb76479f..658c2a3473c6 100644 --- a/lib/matplotlib/tests/test_mathtext.py +++ b/lib/matplotlib/tests/test_mathtext.py @@ -249,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_offsetbox.py b/lib/matplotlib/tests/test_offsetbox.py index 57496b7a856d..ffc5cd2f7dd6 100644 --- a/lib/matplotlib/tests/test_offsetbox.py +++ b/lib/matplotlib/tests/test_offsetbox.py @@ -81,6 +81,3 @@ def test_offsetbox_clip_children(): assert not fig.stale da.clip_children = True assert fig.stale - -if __name__ == '__main__': - nose.runmodule(argv=['-s', '--with-doctest'], exit=False) 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 f94a82832cdc..29805d731059 100644 --- a/lib/matplotlib/tests/test_path.py +++ b/lib/matplotlib/tests/test_path.py @@ -149,8 +149,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 5cbea26102b4..50f20b18d298 100644 --- a/lib/matplotlib/tests/test_patheffects.py +++ b/lib/matplotlib/tests/test_patheffects.py @@ -126,8 +126,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 6998e5dec19f..561afd62b5c9 100644 --- a/lib/matplotlib/tests/test_pickle.py +++ b/lib/matplotlib/tests/test_pickle.py @@ -285,9 +285,3 @@ def test_transform(): # Check input and output dimensions are set as expected. assert (obj.wrapper.input_dims == obj.composite.input_dims) assert (obj.wrapper.output_dims == obj.composite.output_dims) - - - -if __name__ == '__main__': - import nose - nose.runmodule(argv=['-s']) 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 31b71660c6bf..c2f003fad958 100644 --- a/lib/matplotlib/tests/test_rcparams.py +++ b/lib/matplotlib/tests/test_rcparams.py @@ -410,7 +410,3 @@ def test_rcparams_reset_after_fail(): 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 3a90251c4836..852053c382c4 100644 --- a/lib/matplotlib/tests/test_simplification.py +++ b/lib/matplotlib/tests/test_simplification.py @@ -228,8 +228,3 @@ def test_clipping_with_nans(): ax = fig.add_subplot(111) ax.plot(x, y) ax.set_ylim(-0.25, 0.25) - - -if __name__=='__main__': - import nose - nose.runmodule(argv=['-s','--with-doctest'], exit=False) diff --git a/lib/matplotlib/tests/test_skew.py b/lib/matplotlib/tests/test_skew.py index 2070a470e876..8bd2b9144526 100644 --- a/lib/matplotlib/tests/test_skew.py +++ b/lib/matplotlib/tests/test_skew.py @@ -189,7 +189,3 @@ def test_skew_rectange(): alpha=0.5, facecolor='coral')) plt.subplots_adjust(wspace=0, left=0, right=1, bottom=0) - -if __name__ == '__main__': - import nose - nose.runmodule(argv=['-s', '--with-doctest'], exit=False) diff --git a/lib/matplotlib/tests/test_streamplot.py b/lib/matplotlib/tests/test_streamplot.py index a9c94a3fe0e6..3a6bcad38f12 100644 --- a/lib/matplotlib/tests/test_streamplot.py +++ b/lib/matplotlib/tests/test_streamplot.py @@ -59,8 +59,3 @@ def test_streamplot_limits(): # datalim. assert_array_almost_equal(ax.dataLim.bounds, (20, 30, 15, 6), decimal=1) - - -if __name__=='__main__': - import nose - nose.runmodule() diff --git a/lib/matplotlib/tests/test_style.py b/lib/matplotlib/tests/test_style.py index 7a7a3f309683..e5320db7a513 100644 --- a/lib/matplotlib/tests/test_style.py +++ b/lib/matplotlib/tests/test_style.py @@ -133,8 +133,3 @@ def test_context_with_badparam(): with pytest.raises(KeyError): x.__enter__() assert mpl.rcParams[PARAM] == other_value - - -if __name__ == '__main__': - from numpy import testing - testing.run_module_suite() diff --git a/lib/matplotlib/tests/test_ticker.py b/lib/matplotlib/tests/test_ticker.py index 26e0a4b16e49..b9bf4912f328 100644 --- a/lib/matplotlib/tests/test_ticker.py +++ b/lib/matplotlib/tests/test_ticker.py @@ -366,8 +366,3 @@ def test_formatstrformatter(): # test str.format() style formatter tmp_form = mticker.StrMethodFormatter('{x:05d}') assert '00002' == tmp_form(2) - - -if __name__ == '__main__': - import nose - nose.runmodule(argv=['-s', '--with-doctest'], exit=False) diff --git a/lib/matplotlib/tests/test_transforms.py b/lib/matplotlib/tests/test_transforms.py index e36548a8edef..8002a20cf357 100644 --- a/lib/matplotlib/tests/test_transforms.py +++ b/lib/matplotlib/tests/test_transforms.py @@ -624,8 +624,3 @@ def test_transformed_patch_path(): patch.set_radius(0.5) assert np.allclose(tpatch.get_fully_transformed_path().vertices, points) - - -if __name__ == '__main__': - import nose - nose.runmodule(argv=['-s', '--with-doctest'], exit=False) diff --git a/lib/matplotlib/tests/test_triangulation.py b/lib/matplotlib/tests/test_triangulation.py index 88e0b2ab2056..ed8af0369576 100644 --- a/lib/matplotlib/tests/test_triangulation.py +++ b/lib/matplotlib/tests/test_triangulation.py @@ -1030,8 +1030,3 @@ def test_tricontourf_decreasing_levels(): z = [0.2, 0.4, 0.6] plt.figure() pytest.raises(ValueError, plt.tricontourf, x, y, z, [1.0, 0.0]) - - -if __name__ == '__main__': - import nose - nose.runmodule(argv=['-s', '--with-doctest'], exit=False) diff --git a/lib/mpl_toolkits/tests/test_axes_grid1.py b/lib/mpl_toolkits/tests/test_axes_grid1.py index 5ef80dbb4970..7ebeff947d9d 100644 --- a/lib/mpl_toolkits/tests/test_axes_grid1.py +++ b/lib/mpl_toolkits/tests/test_axes_grid1.py @@ -154,8 +154,3 @@ def get_demo_image(): pad=0.1, borderpad=0.5, sep=5, frameon=False) ax.add_artist(asb) - - -if __name__ == '__main__': - import nose - nose.runmodule(argv=['-s', '--with-doctest'], exit=False) From 373fa15198fca1689c7a9e38e6328b78628b4983 Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 18 Jan 2016 10:45:17 +1100 Subject: [PATCH 107/174] PEP8 E301 in test_docstring_addition --- lib/matplotlib/tests/test_labeled_data_unpacking.py | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/matplotlib/tests/test_labeled_data_unpacking.py b/lib/matplotlib/tests/test_labeled_data_unpacking.py index 522119d3dc64..f259a0bfbdfc 100644 --- a/lib/matplotlib/tests/test_labeled_data_unpacking.py +++ b/lib/matplotlib/tests/test_labeled_data_unpacking.py @@ -346,6 +346,7 @@ def test_docstring_addition(): re.compile(r".*'x'.*") bar_string = \ re.compile(r".*'bar'.*") + @unpack_labeled_data() def funcy(ax, *args, **kwargs): """Funcy does nothing""" From ca9828a05f3f310e5f723275055923493858d945 Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 18 Jan 2016 10:47:08 +1100 Subject: [PATCH 108/174] PEP8 E302 in test_transforms.py, test_transformed_path --- lib/matplotlib/tests/test_transforms.py | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/matplotlib/tests/test_transforms.py b/lib/matplotlib/tests/test_transforms.py index 8002a20cf357..a05b3c48760d 100644 --- a/lib/matplotlib/tests/test_transforms.py +++ b/lib/matplotlib/tests/test_transforms.py @@ -585,6 +585,7 @@ def test_invalid_arguments(): with pytest.raises(RuntimeError): t.transform([[1, 2, 3]]) + def test_transformed_path(): points = [(0, 0), (1, 0), (1, 1), (0, 1)] codes = [Path.MOVETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY] From fa1e601406190f7b0f27d1abfefde0882e32e308 Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 18 Jan 2016 10:48:31 +1100 Subject: [PATCH 109/174] PEP8 E261 in test_mathtext.py, math_tests[] --- lib/matplotlib/tests/test_mathtext.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/matplotlib/tests/test_mathtext.py b/lib/matplotlib/tests/test_mathtext.py index 658c2a3473c6..c6361d793a83 100644 --- a/lib/matplotlib/tests/test_mathtext.py +++ b/lib/matplotlib/tests/test_mathtext.py @@ -104,8 +104,8 @@ 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 ] From 534ab6f311d7f825d5e9dfdc80a028e823628cfa Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 18 Jan 2016 11:24:16 +1100 Subject: [PATCH 110/174] PEP8 E712 in test_figure.py, test_fignum_exists --- lib/matplotlib/tests/test_figure.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/matplotlib/tests/test_figure.py b/lib/matplotlib/tests/test_figure.py index 36eb7bb89e5c..31f68b9514ec 100644 --- a/lib/matplotlib/tests/test_figure.py +++ b/lib/matplotlib/tests/test_figure.py @@ -47,8 +47,8 @@ def test_fignum_exists(): assert plt.fignum_exists(4) plt.close('one') plt.close(4) - assert plt.fignum_exists('one') == False - assert plt.fignum_exists(4) == False + assert not plt.fignum_exists('one') + assert not plt.fignum_exists(4) @image_comparison(baseline_images=['figure_today']) From db2d85b03bcf8d935b1246a76d76ef78dcf4c9ab Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 18 Jan 2016 11:28:50 +1100 Subject: [PATCH 111/174] PEP8 E302 test_dviread.py around setup_PsfontsMap --- lib/matplotlib/tests/test_dviread.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/lib/matplotlib/tests/test_dviread.py b/lib/matplotlib/tests/test_dviread.py index 58b9fbb5522f..ac7f7d5cbc46 100644 --- a/lib/matplotlib/tests/test_dviread.py +++ b/lib/matplotlib/tests/test_dviread.py @@ -11,12 +11,15 @@ original_find_tex_file = dr.find_tex_file + 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) From c4ea6d4367e77b9b0eabad080dfe0c0e0609270b Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 18 Jan 2016 11:43:04 +1100 Subject: [PATCH 112/174] PEP8 E712 in test_axes.py --- lib/matplotlib/tests/test_axes.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/lib/matplotlib/tests/test_axes.py b/lib/matplotlib/tests/test_axes.py index e5c787d44c7b..720264c700bb 100644 --- a/lib/matplotlib/tests/test_axes.py +++ b/lib/matplotlib/tests/test_axes.py @@ -432,7 +432,7 @@ def test_polar_units(): y1 = [y*km for y in y1] plt.polar(x2, y1, color="blue", thetaunits="rad", runits="km") assert isinstance(plt.gca().get_xaxis().get_major_formatter(), - units.UnitDblFormatter) == True + units.UnitDblFormatter) @image_comparison(baseline_images=['polar_rmin']) @@ -4081,11 +4081,11 @@ 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 From a2291a1876cb1fe8e92af13f86706004eb5c20e9 Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 18 Jan 2016 11:44:15 +1100 Subject: [PATCH 113/174] PEP8 E712 in test_artist.py , test_remove --- lib/matplotlib/tests/test_artist.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/matplotlib/tests/test_artist.py b/lib/matplotlib/tests/test_artist.py index df1f43ce9592..ecf8e4ff1571 100644 --- a/lib/matplotlib/tests/test_artist.py +++ b/lib/matplotlib/tests/test_artist.py @@ -174,8 +174,8 @@ def test_remove(): assert art.figure is None assert im not in ax.mouseover_set - assert fig.stale == True - assert ax.stale == True + assert fig.stale + assert ax.stale @image_comparison(baseline_images=["default_edges"], remove_text=True, From 65b42bdd76783f9dff216ee2858c4ff23d10bc80 Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 18 Jan 2016 12:39:28 +1100 Subject: [PATCH 114/174] PEP8 W293 in test_labeled_data_unpacking.py, test_docstring_addition --- lib/matplotlib/tests/test_labeled_data_unpacking.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/matplotlib/tests/test_labeled_data_unpacking.py b/lib/matplotlib/tests/test_labeled_data_unpacking.py index f259a0bfbdfc..684ae1524610 100644 --- a/lib/matplotlib/tests/test_labeled_data_unpacking.py +++ b/lib/matplotlib/tests/test_labeled_data_unpacking.py @@ -346,7 +346,7 @@ def test_docstring_addition(): re.compile(r".*'x'.*") bar_string = \ re.compile(r".*'bar'.*") - + @unpack_labeled_data() def funcy(ax, *args, **kwargs): """Funcy does nothing""" From 8a22e2a5db356df5fa3070fe00013197be9aff73 Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 18 Jan 2016 12:49:19 +1100 Subject: [PATCH 115/174] fix bad pytest raises calls in test_triangulation.py --- lib/matplotlib/tests/test_triangulation.py | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/lib/matplotlib/tests/test_triangulation.py b/lib/matplotlib/tests/test_triangulation.py index ed8af0369576..90b01bc86aaa 100644 --- a/lib/matplotlib/tests/test_triangulation.py +++ b/lib/matplotlib/tests/test_triangulation.py @@ -85,7 +85,7 @@ def test_delaunay_points_in_line(): # that delaunay code fails gracefully. x = np.linspace(0.0, 10.0, 11) y = np.linspace(0.0, 10.0, 11) - pytest.raises(RuntimeError, mtri.Triangulation(x, y)) + pytest.raises(RuntimeError, mtri.Triangulation, x, y) # Add an extra point not on the line and the triangulation is OK. x = np.append(x, 2.0) @@ -95,16 +95,16 @@ def test_delaunay_points_in_line(): def test_delaunay_insufficient_points(): # Triangulation should raise a ValueError if passed less than 3 points. - pytest.raises(ValueError, mtri.Triangulation([], [])) - pytest.raises(ValueError, mtri.Triangulation([1], [5])) - pytest.raises(ValueError, mtri.Triangulation([1, 2], [5, 6])) + pytest.raises(ValueError, mtri.Triangulation, [], []) + pytest.raises(ValueError, mtri.Triangulation, [1], [5]) + pytest.raises(ValueError, mtri.Triangulation, [1, 2], [5, 6]) # Triangulation should also raise a ValueError if passed duplicate points # such that there are less than 3 unique points. - pytest.raises(ValueError, mtri.Triangulation([1, 2, 1], [5, 6, 5])) - pytest.raises(ValueError, mtri.Triangulation([1, 2, 2], [5, 6, 6])) - pytest.raises(ValueError, mtri.Triangulation([1, 1, 1, 2, 1, 2], - [5, 5, 5, 6, 5, 6])) + pytest.raises(ValueError, mtri.Triangulation, [1, 2, 1], [5, 6, 5]) + pytest.raises(ValueError, mtri.Triangulation, [1, 2, 2], [5, 6, 6]) + pytest.raises(ValueError, mtri.Triangulation, [1, 1, 1, 2, 1, 2], + [5, 5, 5, 6, 5, 6]) def test_delaunay_robust(): From 6ed71fa7a24d00d9a958c65250d9b1b94cf7b0b4 Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 18 Jan 2016 13:36:15 +1100 Subject: [PATCH 116/174] fix bad pytest.raises calls in test_cbook.py test_step_fails --- lib/matplotlib/tests/test_cbook.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/matplotlib/tests/test_cbook.py b/lib/matplotlib/tests/test_cbook.py index ef63306902fd..5328f8838a42 100644 --- a/lib/matplotlib/tests/test_cbook.py +++ b/lib/matplotlib/tests/test_cbook.py @@ -375,13 +375,13 @@ def test_to_midstep(): def test_step_fails(): pytest.raises(ValueError, - cbook._step_validation(np.arange(12).reshape(3, 4), 'a')) + cbook._step_validation, np.arange(12).reshape(3, 4), 'a') pytest.raises(ValueError, - cbook._step_validation(np.arange(12), 'a')) + cbook._step_validation, np.arange(12), 'a') pytest.raises(ValueError, - cbook._step_validation(np.arange(12))) + cbook._step_validation, np.arange(12)) pytest.raises(ValueError, - cbook._step_validation(np.arange(12), np.arange(3))) + cbook._step_validation, np.arange(12), np.arange(3)) def test_grouper(): From f78c07509e404c0b4c4908f403921c957dd89df3 Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 18 Jan 2016 13:37:13 +1100 Subject: [PATCH 117/174] fix bad assert calls in test_pickle.py , test_transform --- lib/matplotlib/tests/test_pickle.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/matplotlib/tests/test_pickle.py b/lib/matplotlib/tests/test_pickle.py index 561afd62b5c9..3cce5e497c9f 100644 --- a/lib/matplotlib/tests/test_pickle.py +++ b/lib/matplotlib/tests/test_pickle.py @@ -283,5 +283,5 @@ def test_transform(): # Check child -> parent links of TransformWrapper. assert list(obj.wrapper._parents.values()) == [obj.composite2] # Check input and output dimensions are set as expected. - assert (obj.wrapper.input_dims == obj.composite.input_dims) - assert (obj.wrapper.output_dims == obj.composite.output_dims) + assert obj.wrapper.input_dims == obj.composite.input_dims + assert obj.wrapper.output_dims == obj.composite.output_dims From 1d7b37c6e6bd8ba4880b74a042d189822964aa37 Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 18 Jan 2016 13:38:26 +1100 Subject: [PATCH 118/174] fix bad pytest.raises calls in test_colors.py, test_colors_no_float --- lib/matplotlib/tests/test_colors.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/matplotlib/tests/test_colors.py b/lib/matplotlib/tests/test_colors.py index bced0209f9d6..a39bb1fb26cd 100644 --- a/lib/matplotlib/tests/test_colors.py +++ b/lib/matplotlib/tests/test_colors.py @@ -312,8 +312,8 @@ def gray_from_float_rgb(): def gray_from_float_rgba(): return mcolors.colorConverter.to_rgba(0.4) - pytest.raises(ValueError, gray_from_float_rgb()) - pytest.raises(ValueError, gray_from_float_rgba()) + pytest.raises(ValueError, gray_from_float_rgb) + pytest.raises(ValueError, gray_from_float_rgba) @image_comparison(baseline_images=['light_source_shading_topo'], From 90bbe2569df9b16e2f3aec40f434ab98109c4c52 Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 18 Jan 2016 14:18:50 +1100 Subject: [PATCH 119/174] fix pytest.raises call in test_colors.py test_cmap_and_norm_from_levels_and_colors2 --- lib/matplotlib/tests/test_colors.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/matplotlib/tests/test_colors.py b/lib/matplotlib/tests/test_colors.py index a39bb1fb26cd..dd74a4502684 100644 --- a/lib/matplotlib/tests/test_colors.py +++ b/lib/matplotlib/tests/test_colors.py @@ -282,7 +282,7 @@ def test_cmap_and_norm_from_levels_and_colors2(): 'Wih extend={0!r} and data ' 'value={1!r}'.format(extend, d_val)) - pytest.raises(ValueError, mcolors.from_levels_and_colors(levels, colors)) + pytest.raises(ValueError, mcolors.from_levels_and_colors, levels, colors) def test_rgb_hsv_round_trip(): From ee30e1092335a1a35cf6ba77f723936b45672895 Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 18 Jan 2016 16:08:54 +1100 Subject: [PATCH 120/174] fix rebase omission, test_transform in test_pickle.py was using list() instead of list comprehension --- lib/matplotlib/tests/test_pickle.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/matplotlib/tests/test_pickle.py b/lib/matplotlib/tests/test_pickle.py index 3cce5e497c9f..563fd74bd447 100644 --- a/lib/matplotlib/tests/test_pickle.py +++ b/lib/matplotlib/tests/test_pickle.py @@ -281,7 +281,7 @@ def test_transform(): # Check parent -> child links of TransformWrapper. assert obj.wrapper._child == obj.composite # Check child -> parent links of TransformWrapper. - assert list(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 obj.wrapper.input_dims == obj.composite.input_dims assert obj.wrapper.output_dims == obj.composite.output_dims From 35520a4a13be0526cbb0b797d9f43a64c30c50b1 Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 18 Jan 2016 20:45:38 +1100 Subject: [PATCH 121/174] fix user searh, not match in test_labeled_data_unpacking, test_docstring_addition --- .../tests/test_labeled_data_unpacking.py | 28 +++++++++---------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/lib/matplotlib/tests/test_labeled_data_unpacking.py b/lib/matplotlib/tests/test_labeled_data_unpacking.py index 684ae1524610..f85a0970d8a2 100644 --- a/lib/matplotlib/tests/test_labeled_data_unpacking.py +++ b/lib/matplotlib/tests/test_labeled_data_unpacking.py @@ -352,27 +352,27 @@ def funcy(ax, *args, **kwargs): """Funcy does nothing""" pass - assert all_positional_all_keyword.match(funcy.__doc__) - assert not all_positional.match(funcy.__doc__) - assert not all_arguments.match(funcy.__doc__) + 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 all_positional.match(funcy.__doc__) - assert not all_positional_all_keyword.match(funcy.__doc__) - assert not all_arguments.match(funcy.__doc__) + 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 all_positional.match(funcy.__doc__) - assert all_arguments.match(funcy.__doc__) - assert not all_positional_all_keyword.match(funcy.__doc__) + 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): @@ -380,11 +380,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 all_arguments_with_following_names.match(funcy.__doc__) - assert x_string.match(funcy.__doc__) - assert bar_string.match(funcy.__doc__) - assert not all_positional_all_keyword.match(funcy.__doc__) - assert not all_positional.match(funcy.__doc__) + 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(): From b3c7dda345ce12ed3e35ce81d96f51dacafa276b Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 18 Jan 2016 21:34:36 +1100 Subject: [PATCH 122/174] fix test_invalid_input_forms in test_cycles.py --- lib/matplotlib/tests/test_cycles.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/lib/matplotlib/tests/test_cycles.py b/lib/matplotlib/tests/test_cycles.py index ba46eb209dbc..8c25bd7e0b57 100644 --- a/lib/matplotlib/tests/test_cycles.py +++ b/lib/matplotlib/tests/test_cycles.py @@ -172,15 +172,15 @@ def test_cycle_reset(): @cleanup def test_invalid_input_forms(): fig, ax = plt.subplots() - with pytest.raises(TypeError, ValueError): + with pytest.raises((TypeError, ValueError)): ax.set_prop_cycle(1) - with pytest.raises(TypeError, ValueError): + with pytest.raises((TypeError, ValueError)): ax.set_prop_cycle([1, 2]) - with pytest.raises(TypeError, ValueError): + with pytest.raises((TypeError, ValueError)): ax.set_prop_cycle('color', 'fish') - with pytest.raises(TypeError, ValueError): + with pytest.raises((TypeError, ValueError)): ax.set_prop_cycle('linewidth', 1) - with pytest.raises(TypeError, ValueError): + with pytest.raises((TypeError, ValueError)): ax.set_prop_cycle('linewidth', {'1': 1, '2': 2}) - with pytest.raises(TypeError, ValueError): + with pytest.raises((TypeError, ValueError)): ax.set_prop_cycle(linewidth=1, color='r') From 331428f1cf73219f39bc567bd098037f6706f299 Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 18 Jan 2016 22:33:44 +1100 Subject: [PATCH 123/174] fix nose skiptest references, test_axes.py --- lib/matplotlib/tests/test_axes.py | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/lib/matplotlib/tests/test_axes.py b/lib/matplotlib/tests/test_axes.py index 720264c700bb..ceb71c15f147 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, pytest.raises, assert_false, assert_true -from nose.plugins.skip import SkipTest - import datetime import numpy as np @@ -4341,7 +4337,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)))) @@ -4358,7 +4354,7 @@ 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:] From ea38ba6be10f4c24a2dd571fff46c8db91b3d777 Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 18 Jan 2016 22:34:59 +1100 Subject: [PATCH 124/174] remove nose import references, many files --- lib/matplotlib/tests/test_collections.py | 1 - lib/matplotlib/tests/test_dates.py | 1 - lib/matplotlib/tests/test_font_manager.py | 1 - lib/matplotlib/tests/test_gridspec.py | 7 +++---- lib/matplotlib/tests/test_legend.py | 1 - lib/matplotlib/tests/test_path.py | 2 -- lib/matplotlib/tests/test_patheffects.py | 1 - lib/matplotlib/tests/test_pickle.py | 1 - lib/matplotlib/tests/test_simplification.py | 1 - lib/matplotlib/tests/test_subplots.py | 2 -- lib/matplotlib/tests/test_table.py | 1 - lib/matplotlib/tests/test_tightlayout.py | 1 - lib/matplotlib/tests/test_transforms.py | 1 - 13 files changed, 3 insertions(+), 18 deletions(-) diff --git a/lib/matplotlib/tests/test_collections.py b/lib/matplotlib/tests/test_collections.py index f72e92b8a3d9..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 diff --git a/lib/matplotlib/tests/test_dates.py b/lib/matplotlib/tests/test_dates.py index ff4ed52ae514..08da86538e15 100644 --- a/lib/matplotlib/tests/test_dates.py +++ b/lib/matplotlib/tests/test_dates.py @@ -14,7 +14,6 @@ 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 diff --git a/lib/matplotlib/tests/test_font_manager.py b/lib/matplotlib/tests/test_font_manager.py index 6eed66993fef..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 diff --git a/lib/matplotlib/tests/test_gridspec.py b/lib/matplotlib/tests/test_gridspec.py index 57616397f5e3..49284d950703 100644 --- a/lib/matplotlib/tests/test_gridspec.py +++ b/lib/matplotlib/tests/test_gridspec.py @@ -1,8 +1,7 @@ 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_legend.py b/lib/matplotlib/tests/test_legend.py index cf51522eed65..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 diff --git a/lib/matplotlib/tests/test_path.py b/lib/matplotlib/tests/test_path.py index 29805d731059..267b1fe30e4d 100644 --- a/lib/matplotlib/tests/test_path.py +++ b/lib/matplotlib/tests/test_path.py @@ -7,14 +7,12 @@ 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(): path = Path.unit_circle() diff --git a/lib/matplotlib/tests/test_patheffects.py b/lib/matplotlib/tests/test_patheffects.py index 50f20b18d298..5ad6bb218318 100644 --- a/lib/matplotlib/tests/test_patheffects.py +++ b/lib/matplotlib/tests/test_patheffects.py @@ -15,7 +15,6 @@ from unittest import mock except ImportError: import mock -from nose.tools import assert_equal @image_comparison(baseline_images=['patheffect1'], remove_text=True) diff --git a/lib/matplotlib/tests/test_pickle.py b/lib/matplotlib/tests/test_pickle.py index 563fd74bd447..ced3bc1aa2b6 100644 --- a/lib/matplotlib/tests/test_pickle.py +++ b/lib/matplotlib/tests/test_pickle.py @@ -7,7 +7,6 @@ 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 diff --git a/lib/matplotlib/tests/test_simplification.py b/lib/matplotlib/tests/test_simplification.py index 852053c382c4..b08890f7c23f 100644 --- a/lib/matplotlib/tests/test_simplification.py +++ b/lib/matplotlib/tests/test_simplification.py @@ -13,7 +13,6 @@ import numpy as np from matplotlib import patches, path, transforms -from nose.tools import raises import io nan = np.nan diff --git a/lib/matplotlib/tests/test_subplots.py b/lib/matplotlib/tests/test_subplots.py index 7ffe0a10b7be..9acbc8bb1454 100644 --- a/lib/matplotlib/tests/test_subplots.py +++ b/lib/matplotlib/tests/test_subplots.py @@ -10,8 +10,6 @@ from matplotlib.testing.decorators import image_comparison, cleanup import pytest -from nose.tools import assert_raises - def check_shared(results, f, axs): """ diff --git a/lib/matplotlib/tests/test_table.py b/lib/matplotlib/tests/test_table.py index 2aa3ff5b9563..d19f15f9cc83 100644 --- a/lib/matplotlib/tests/test_table.py +++ b/lib/matplotlib/tests/test_table.py @@ -9,7 +9,6 @@ from matplotlib.table import CustomCell from matplotlib.path import Path -from nose.tools import assert_equal @image_comparison(baseline_images=['table_zorder'], diff --git a/lib/matplotlib/tests/test_tightlayout.py b/lib/matplotlib/tests/test_tightlayout.py index a1b428b04900..7bbe9b150c37 100644 --- a/lib/matplotlib/tests/test_tightlayout.py +++ b/lib/matplotlib/tests/test_tightlayout.py @@ -8,7 +8,6 @@ from matplotlib.testing.decorators import image_comparison import matplotlib.pyplot as plt -from nose.tools import assert_raises from numpy.testing import assert_array_equal from matplotlib.offsetbox import AnchoredOffsetbox, DrawingArea from matplotlib.patches import Rectangle diff --git a/lib/matplotlib/tests/test_transforms.py b/lib/matplotlib/tests/test_transforms.py index a05b3c48760d..6ed4abf01114 100644 --- a/lib/matplotlib/tests/test_transforms.py +++ b/lib/matplotlib/tests/test_transforms.py @@ -6,7 +6,6 @@ import unittest -from nose.tools import assert_equal, assert_raises import numpy.testing as np_test from numpy.testing import assert_almost_equal, assert_array_equal from numpy.testing import assert_array_almost_equal From 2cb6b8c41f58a7a50390fe5938bb9a64250a1e02 Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 18 Jan 2016 23:29:35 +1100 Subject: [PATCH 125/174] PEP8 E302 at test_gridspec.py --- lib/matplotlib/tests/test_gridspec.py | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/matplotlib/tests/test_gridspec.py b/lib/matplotlib/tests/test_gridspec.py index 49284d950703..26f3db89e448 100644 --- a/lib/matplotlib/tests/test_gridspec.py +++ b/lib/matplotlib/tests/test_gridspec.py @@ -1,6 +1,7 @@ import matplotlib.gridspec as gridspec import numpy + def test_equal(): gs = gridspec.GridSpec(2, 1) assert gs[0, 0] == gs[0, 0] From accbcf2f4891320c87f9d7423a92427c2a3bf344 Mon Sep 17 00:00:00 2001 From: Jason King Date: Tue, 19 Jan 2016 12:26:34 +1100 Subject: [PATCH 126/174] doc convert nose docs to pytest, testing.rst --- doc/devel/testing.rst | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/doc/devel/testing.rst b/doc/devel/testing.rst index 8bbe720de771..e38131f358ed 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,12 @@ 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 +58,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 +118,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 +209,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 +217,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) From a4ddff3264cdd4bac4ec9137e5220c83c0fafe5b Mon Sep 17 00:00:00 2001 From: Jason King Date: Tue, 19 Jan 2016 18:56:21 +1100 Subject: [PATCH 127/174] fix remove nose install from travis --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 4bb7ec526456..fa9785a0a7f8 100644 --- a/.travis.yml +++ b/.travis.yml @@ -77,7 +77,7 @@ 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? From bd5828f9e29b824639f80510b379d04409e7c001 Mon Sep 17 00:00:00 2001 From: Jason King Date: Tue, 19 Jan 2016 19:18:42 +1100 Subject: [PATCH 128/174] fix syntax error (newline) in testing.rst --- doc/devel/testing.rst | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/doc/devel/testing.rst b/doc/devel/testing.rst index e38131f358ed..9c63a4f6b7e2 100644 --- a/doc/devel/testing.rst +++ b/doc/devel/testing.rst @@ -33,8 +33,7 @@ Optionally you can install: - `pep8 `_ to test coding standards - - `pytest-cov `_ for coverage stats - in pytest + - `pytest-cov `_ for coverage stats in pytest - `pytest-pep8 `_ for pep8 conformance in pytest From 930c52952aa5e05fa86a5a545b62193564924ce1 Mon Sep 17 00:00:00 2001 From: Jason King Date: Wed, 20 Jan 2016 08:31:07 +1100 Subject: [PATCH 129/174] fix numpy pytest errors. don't put pylab in default namespace This might not be the point of using pylab this way in a test however --- lib/matplotlib/tests/test_basic.py | 3 ++- lib/matplotlib/tests/test_simplification.py | 15 ++++++++------- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/lib/matplotlib/tests/test_basic.py b/lib/matplotlib/tests/test_basic.py index 5495af8bb99b..c34b954d7bf4 100644 --- a/lib/matplotlib/tests/test_basic.py +++ b/lib/matplotlib/tests/test_basic.py @@ -4,7 +4,8 @@ from matplotlib.externals import six -from pylab import * +import pylab +import sys import pytest diff --git a/lib/matplotlib/tests/test_simplification.py b/lib/matplotlib/tests/test_simplification.py index b08890f7c23f..cc42eed96f36 100644 --- a/lib/matplotlib/tests/test_simplification.py +++ b/lib/matplotlib/tests/test_simplification.py @@ -9,7 +9,7 @@ import matplotlib.pyplot as plt import pytest -from pylab import * +import pylab import numpy as np from matplotlib import patches, path, transforms @@ -25,7 +25,7 @@ @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) @@ -111,7 +111,7 @@ def test_simplify_curve(): 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)) @@ -119,9 +119,10 @@ def test_hatch(): @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() @@ -177,7 +178,7 @@ def test_start_with_moveto(): @cleanup @pytest.mark.xfail(raises=OverflowError) def test_throw_rendering_complexity_exceeded(): - rcParams['path.simplify'] = False + pylab.rcParams['path.simplify'] = False xx = np.arange(200000) yy = np.random.rand(200000) yy[1000] = np.nan @@ -187,7 +188,7 @@ def test_throw_rendering_complexity_exceeded(): try: fig.savefig(io.BytesIO()) finally: - rcParams['path.simplify'] = True + pylab.rcParams['path.simplify'] = True @image_comparison(baseline_images=['clipper_edge'], remove_text=True) From ae9715c6492ddbb55665b5d1f02dffdd9b216eb2 Mon Sep 17 00:00:00 2001 From: Jason King Date: Sat, 31 Oct 2015 23:12:09 +1100 Subject: [PATCH 130/174] ENH: use pytest instead of nose. --- lib/matplotlib/tests/test_artist.py | 1 + lib/matplotlib/tests/test_axes.py | 56 ++++++++++++++------------ lib/matplotlib/tests/test_colors.py | 1 + lib/matplotlib/tests/test_figure.py | 5 --- lib/matplotlib/tests/test_lines.py | 14 +++---- lib/matplotlib/tests/test_mlab.py | 5 ++- lib/matplotlib/tests/test_offsetbox.py | 3 +- lib/matplotlib/tests/test_rcparams.py | 4 ++ tox.ini | 2 +- 9 files changed, 50 insertions(+), 41 deletions(-) diff --git a/lib/matplotlib/tests/test_artist.py b/lib/matplotlib/tests/test_artist.py index ecf8e4ff1571..9b777fb94950 100644 --- a/lib/matplotlib/tests/test_artist.py +++ b/lib/matplotlib/tests/test_artist.py @@ -206,3 +206,4 @@ def test_properties(): warnings.simplefilter("always") ln.properties() assert len(w) == 0 + diff --git a/lib/matplotlib/tests/test_axes.py b/lib/matplotlib/tests/test_axes.py index ceb71c15f147..ae268ed49acc 100644 --- a/lib/matplotlib/tests/test_axes.py +++ b/lib/matplotlib/tests/test_axes.py @@ -5,6 +5,10 @@ from six.moves import xrange from itertools import chain import io + +# from nose.tools import assert_equal, pytest.raises, assert_false, assert_true +from nose.plugins.skip import SkipTest + import datetime import numpy as np @@ -356,7 +360,7 @@ def test_shaped_data(): plt.plot(y2) plt.subplot(413) - pytest.raises(ValueError, plt.plot(y1, y2)) + pytest.raises(ValueError, plt.plot, y1, y2) plt.subplot(414) plt.plot(xdata[:, 1], xdata[1, :], 'o') @@ -2199,6 +2203,7 @@ 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() @@ -3026,17 +3031,17 @@ def test_specgram_angle_freqs(): spec13 = ax13.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='twosided', mode='angle') - pytest.raises(ValueError, ax11.specgram(y, NFFT=NFFT, Fs=Fs, + pytest.raises(ValueError, ax11.specgram, y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='default', - mode='phase', scale='dB')) + mode='phase', scale='dB') - pytest.raises(ValueError, ax12.specgram(y, NFFT=NFFT, Fs=Fs, + pytest.raises(ValueError, ax12.specgram, y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='onesided', - mode='phase', scale='dB')) + mode='phase', scale='dB') - pytest.raises(ValueError, ax13.specgram(y, NFFT=NFFT, Fs=Fs, + pytest.raises(ValueError, ax13.specgram, y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='twosided', - mode='phase', scale='dB')) + mode='phase', scale='dB') @image_comparison(baseline_images=['specgram_angle_noise'], @@ -3073,17 +3078,17 @@ def test_specgram_noise_angle(): spec13 = ax13.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='twosided', mode='angle') - pytest.raises(ValueError, ax11.specgram(y, NFFT=NFFT, Fs=Fs, + pytest.raises(ValueError, ax11.specgram, y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='default', - mode='phase', scale='dB')) + mode='phase', scale='dB') - pytest.raises(ValueError, ax12.specgram(y, NFFT=NFFT, Fs=Fs, + pytest.raises(ValueError, ax12.specgram, y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='onesided', - mode='phase', scale='dB')) + mode='phase', scale='dB') - pytest.raises(ValueError, ax13.specgram(y, NFFT=NFFT, Fs=Fs, + pytest.raises(ValueError, ax13.specgram, y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='twosided', - mode='phase', scale='dB')) + mode='phase', scale='dB') @image_comparison(baseline_images=['specgram_phase_freqs'], @@ -3128,17 +3133,17 @@ def test_specgram_freqs_phase(): spec13 = ax13.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='twosided', mode='phase') - pytest.raises(ValueError, ax11.specgram(y, NFFT=NFFT, Fs=Fs, + pytest.raises(ValueError, ax11.specgram, y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='default', - mode='phase', scale='dB')) + mode='phase', scale='dB') - pytest.raises(ValueError, ax12.specgram(y, NFFT=NFFT, Fs=Fs, + pytest.raises(ValueError, ax12.specgram, y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='onesided', - mode='phase', scale='dB')) + mode='phase', scale='dB') - pytest.raises(ValueError, ax13.specgram(y, NFFT=NFFT, Fs=Fs, + pytest.raises(ValueError, ax13.specgram, y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='twosided', - mode='phase', scale='dB')) + mode='phase', scale='dB') @image_comparison(baseline_images=['specgram_phase_noise'], @@ -3178,17 +3183,17 @@ def test_specgram_noise_phase(): pad_to=pad_to, sides='twosided', mode='phase', ) - pytest.raises(ValueError, ax11.specgram(y, NFFT=NFFT, Fs=Fs, + pytest.raises(ValueError, ax11.specgram, y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='default', - mode='phase', scale='dB')) + mode='phase', scale='dB') - pytest.raises(ValueError, ax12.specgram(y, NFFT=NFFT, Fs=Fs, + pytest.raises(ValueError, ax12.specgram, y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='onesided', - mode='phase', scale='dB')) + mode='phase', scale='dB') - pytest.raises(ValueError, ax13.specgram(y, NFFT=NFFT, Fs=Fs, + pytest.raises(ValueError, ax13.specgram, y, NFFT=NFFT, Fs=Fs, noverlap=noverlap, pad_to=pad_to, sides='twosided', - mode='phase', scale='dB')) + mode='phase', scale='dB') @image_comparison(baseline_images=['psd_freqs'], remove_text=True, @@ -4360,3 +4365,4 @@ def test_pandas_indexing_hist(): ser_2 = ser_1.iloc[1:] fig, axes = plt.subplots() axes.hist(ser_2) + diff --git a/lib/matplotlib/tests/test_colors.py b/lib/matplotlib/tests/test_colors.py index dd74a4502684..0d99205dbf1e 100644 --- a/lib/matplotlib/tests/test_colors.py +++ b/lib/matplotlib/tests/test_colors.py @@ -536,3 +536,4 @@ def _azimuth2math(azimuth, elevation): theta = np.radians((90 - azimuth) % 360) phi = np.radians(90 - elevation) return theta, phi + diff --git a/lib/matplotlib/tests/test_figure.py b/lib/matplotlib/tests/test_figure.py index 31f68b9514ec..b1219a7b046d 100644 --- a/lib/matplotlib/tests/test_figure.py +++ b/lib/matplotlib/tests/test_figure.py @@ -202,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_lines.py b/lib/matplotlib/tests/test_lines.py index f0008d009b84..c1768ba5b13b 100644 --- a/lib/matplotlib/tests/test_lines.py +++ b/lib/matplotlib/tests/test_lines.py @@ -112,8 +112,9 @@ def test_valid_linestyles(): raise nose.SkipTest("assert_raises as context manager " "not supported with Python < 2.7") - line = mpl.lines.Line2D([], []) - pytest.raises(ValueError, line.set_linestyle, 'aardvark') + line = mlines.Line2D([], []) + with assert_raises(ValueError): + line.set_linestyle('aardvark') @image_comparison(baseline_images=['line_collection_dashes'], remove_text=True) @@ -154,8 +155,7 @@ def test_marker_fill_styles(): def test_nan_is_sorted(): - # Exercises issue from PR #2744 (NaN throwing warning in _is_sorted) - line = mpl.lines.Line2D([],[]) - 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]) + 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])) diff --git a/lib/matplotlib/tests/test_mlab.py b/lib/matplotlib/tests/test_mlab.py index c9fa040d28ae..1cb83d7ba234 100644 --- a/lib/matplotlib/tests/test_mlab.py +++ b/lib/matplotlib/tests/test_mlab.py @@ -2790,11 +2790,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(): @@ -3008,3 +3008,4 @@ 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) + diff --git a/lib/matplotlib/tests/test_offsetbox.py b/lib/matplotlib/tests/test_offsetbox.py index ffc5cd2f7dd6..fc67c70bd59a 100644 --- a/lib/matplotlib/tests/test_offsetbox.py +++ b/lib/matplotlib/tests/test_offsetbox.py @@ -80,4 +80,5 @@ def test_offsetbox_clip_children(): fig.canvas.draw() assert not fig.stale da.clip_children = True - assert fig.stale + assert_true(fig.stale) + diff --git a/lib/matplotlib/tests/test_rcparams.py b/lib/matplotlib/tests/test_rcparams.py index c2f003fad958..80105140dbe1 100644 --- a/lib/matplotlib/tests/test_rcparams.py +++ b/lib/matplotlib/tests/test_rcparams.py @@ -15,6 +15,9 @@ from matplotlib.tests import assert_str_equal 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, @@ -410,3 +413,4 @@ def test_rcparams_reset_after_fail(): pass assert mpl.rcParams['text.usetex'] is False + diff --git a/tox.ini b/tox.ini index 47b63f160ef5..164f44168d24 100644 --- a/tox.ini +++ b/tox.ini @@ -40,4 +40,4 @@ pep8ignore = *_mathtext.py E501 [pep8] ignore=E111,E114,E115,E116,E121,E122,E123,E124,E125,E126,E127,E128,E129,E131,E265,E266,W503 -exclude=_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 \ No newline at end of file +exclude=_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 From edabe746d4cd18b5baa06d40242f96d765409189 Mon Sep 17 00:00:00 2001 From: Jason King Date: Wed, 4 Nov 2015 21:44:58 +1100 Subject: [PATCH 131/174] pytest.raises(), not pytest.raise() --- lib/matplotlib/tests/test_colors.py | 1 - lib/matplotlib/tests/test_lines.py | 9 ++++++--- lib/matplotlib/tests/test_mlab.py | 1 - lib/matplotlib/tests/test_ticker.py | 1 - 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/lib/matplotlib/tests/test_colors.py b/lib/matplotlib/tests/test_colors.py index 0d99205dbf1e..dd74a4502684 100644 --- a/lib/matplotlib/tests/test_colors.py +++ b/lib/matplotlib/tests/test_colors.py @@ -536,4 +536,3 @@ def _azimuth2math(azimuth, elevation): theta = np.radians((90 - azimuth) % 360) phi = np.radians(90 - elevation) return theta, phi - diff --git a/lib/matplotlib/tests/test_lines.py b/lib/matplotlib/tests/test_lines.py index c1768ba5b13b..300369ee841f 100644 --- a/lib/matplotlib/tests/test_lines.py +++ b/lib/matplotlib/tests/test_lines.py @@ -10,6 +10,7 @@ import matplotlib.lines as mlines from timeit import repeat import numpy as np + import matplotlib.pyplot as plt from matplotlib.testing.decorators import cleanup, image_comparison import sys @@ -155,7 +156,9 @@ 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])) + 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_mlab.py b/lib/matplotlib/tests/test_mlab.py index 1cb83d7ba234..1fbe41fe186f 100644 --- a/lib/matplotlib/tests/test_mlab.py +++ b/lib/matplotlib/tests/test_mlab.py @@ -3008,4 +3008,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) - diff --git a/lib/matplotlib/tests/test_ticker.py b/lib/matplotlib/tests/test_ticker.py index b9bf4912f328..96bb38900fff 100644 --- a/lib/matplotlib/tests/test_ticker.py +++ b/lib/matplotlib/tests/test_ticker.py @@ -12,7 +12,6 @@ from matplotlib.testing.decorators import cleanup import warnings -import pytest def test_MaxNLocator(): From 23d6fae156eea78f4b4083bfd1a1c71adcc66421 Mon Sep 17 00:00:00 2001 From: Jason King Date: Wed, 4 Nov 2015 22:43:15 +1100 Subject: [PATCH 132/174] pytest.raises() calls needed some massaging --- lib/matplotlib/tests/test_axes.py | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/lib/matplotlib/tests/test_axes.py b/lib/matplotlib/tests/test_axes.py index ae268ed49acc..3273bb1f2a11 100644 --- a/lib/matplotlib/tests/test_axes.py +++ b/lib/matplotlib/tests/test_axes.py @@ -3662,8 +3662,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) @@ -3843,7 +3843,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, @@ -3929,11 +3929,10 @@ 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'], @@ -4365,4 +4364,3 @@ def test_pandas_indexing_hist(): ser_2 = ser_1.iloc[1:] fig, axes = plt.subplots() axes.hist(ser_2) - From f27909a12982ada7bd1fbba8a916d21be98ee684 Mon Sep 17 00:00:00 2001 From: Jason King Date: Thu, 5 Nov 2015 12:30:49 +1100 Subject: [PATCH 133/174] fixing up problems with assert, and the use of messages. Also added tox.ini --- lib/matplotlib/tests/test_coding_standards.py | 6 ++++++ lib/matplotlib/tests/test_mlab.py | 6 +++--- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/lib/matplotlib/tests/test_coding_standards.py b/lib/matplotlib/tests/test_coding_standards.py index 60f21b096ca7..9d90f5dbbc46 100644 --- a/lib/matplotlib/tests/test_coding_standards.py +++ b/lib/matplotlib/tests/test_coding_standards.py @@ -151,6 +151,12 @@ def get_file_results(self): # 'tests or do not point to a file:\n ' # '{0}'.format('\n '.join(unexpectedly_good))) + 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. + """ # def test_pep8_conformance_installed_files(): # exclude_files = ['_delaunay.py', diff --git a/lib/matplotlib/tests/test_mlab.py b/lib/matplotlib/tests/test_mlab.py index 1fbe41fe186f..63258f0bea7b 100644 --- a/lib/matplotlib/tests/test_mlab.py +++ b/lib/matplotlib/tests/test_mlab.py @@ -1623,7 +1623,7 @@ def test_psd_detrend_mean_str_offset(self): assert_allclose(spec_g, spec_c, atol=1e-08) # these should not be almost equal pytest.raises(AssertionError, - assert_allclose, spec_b, spec_c, atol=1e-08) + assert_allclose(spec_b, spec_c, atol=1e-08)) def test_psd_detrend_linear_func_trend(self): if self.NFFT_density is None: @@ -2790,11 +2790,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(): From a02334765d734fac2bf9b4ff1c753ae392476fbe Mon Sep 17 00:00:00 2001 From: Jason King Date: Thu, 5 Nov 2015 13:56:23 +1100 Subject: [PATCH 134/174] fix errors highlighted in travis CI logs --- lib/matplotlib/tests/test_dates.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/matplotlib/tests/test_dates.py b/lib/matplotlib/tests/test_dates.py index 08da86538e15..844c7e8f63fa 100644 --- a/lib/matplotlib/tests/test_dates.py +++ b/lib/matplotlib/tests/test_dates.py @@ -335,7 +335,8 @@ 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 list(map(str, mdates.num2date(locator()))) == expected + assert list(map(str, mdates.num2date(locator()))) == + expected @image_comparison(baseline_images=['date_inverted_limit'], From dd8111b950783cdd02f42ba1bc1c8e41a80eb98e Mon Sep 17 00:00:00 2001 From: Jason King Date: Thu, 5 Nov 2015 14:51:43 +1100 Subject: [PATCH 135/174] fixing pytest failures. Interesting that assert can't seem to handle splitting off 'a == b' into seperate lines. Other changes seem to be missing import pytest statements. --- lib/matplotlib/tests/test_ticker.py | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/matplotlib/tests/test_ticker.py b/lib/matplotlib/tests/test_ticker.py index 96bb38900fff..b9bf4912f328 100644 --- a/lib/matplotlib/tests/test_ticker.py +++ b/lib/matplotlib/tests/test_ticker.py @@ -12,6 +12,7 @@ from matplotlib.testing.decorators import cleanup import warnings +import pytest def test_MaxNLocator(): From 9f53f57a8c0be3fd6a0da3bc40119f797c267ba0 Mon Sep 17 00:00:00 2001 From: Jason King Date: Thu, 5 Nov 2015 18:36:51 +1100 Subject: [PATCH 136/174] fixing syntax failures --- lib/matplotlib/tests/test_dates.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/lib/matplotlib/tests/test_dates.py b/lib/matplotlib/tests/test_dates.py index 844c7e8f63fa..08da86538e15 100644 --- a/lib/matplotlib/tests/test_dates.py +++ b/lib/matplotlib/tests/test_dates.py @@ -335,8 +335,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 list(map(str, mdates.num2date(locator()))) == - expected + assert list(map(str, mdates.num2date(locator()))) == expected @image_comparison(baseline_images=['date_inverted_limit'], From eefe67df21ec0172be1a309282d8c2f4d79f2c9b Mon Sep 17 00:00:00 2001 From: Jason King Date: Sat, 7 Nov 2015 22:30:48 +1100 Subject: [PATCH 137/174] force pytest-pep8 to ignore the pep8 warnings that matplotlib has already specified. Which might make the output log shorter than 4 megs. --- tox.ini | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tox.ini b/tox.ini index 164f44168d24..568eaeefecb8 100644 --- a/tox.ini +++ b/tox.ini @@ -17,7 +17,7 @@ deps = numpy [pytest] -norecursedirs = .git build numpy +norecursedirs = .git build testpaths = tests pep8ignore = *.py E111 E114 E115 E116 E121 E122 E123 E124 E125 E126 E127 E128 E129 E131 E265 E266 W503 E241 E401 E231 E203 E226 @@ -40,4 +40,4 @@ pep8ignore = *_mathtext.py E501 [pep8] ignore=E111,E114,E115,E116,E121,E122,E123,E124,E125,E126,E127,E128,E129,E131,E265,E266,W503 -exclude=_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 +exclude=_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 \ No newline at end of file From 2661e32871624a74653d884530f81e486db1f9e4 Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 9 Nov 2015 10:41:13 +1100 Subject: [PATCH 138/174] the switches that nose needed , make pytest fail, so lets remove them for now. --- tests.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/tests.py b/tests.py index 5a3b7c771306..74d03a575c0e 100755 --- a/tests.py +++ b/tests.py @@ -12,12 +12,14 @@ import os import sys import time -import pytest -from matplotlib import default_test_modules import matplotlib matplotlib.use('agg') +# import nose +import pytest +from matplotlib import default_test_modules + def run(extra_args): matplotlib._init_tests() From f404baa75395ac351eed5258af9f59ed417b5f24 Mon Sep 17 00:00:00 2001 From: Jason King Date: Fri, 13 Nov 2015 23:13:50 +1100 Subject: [PATCH 139/174] another assert_raises to replace with pytest.raises --- lib/matplotlib/tests/test_rcparams.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/matplotlib/tests/test_rcparams.py b/lib/matplotlib/tests/test_rcparams.py index 80105140dbe1..6db28890550f 100644 --- a/lib/matplotlib/tests/test_rcparams.py +++ b/lib/matplotlib/tests/test_rcparams.py @@ -13,7 +13,7 @@ import matplotlib as mpl import matplotlib.pyplot as plt from matplotlib.tests import assert_str_equal -from matplotlib.testing.decorators import cleanup +from matplotlib.testing.decorators import cleanup, knownfailureif import matplotlib.colors as mcolors # from nose.tools import assert_true, assert_raises, assert_equal # from nose.plugins.skip import SkipTest From 53457e97e0e83401edab27a4bb8d0049f6836711 Mon Sep 17 00:00:00 2001 From: Jason King Date: Sat, 14 Nov 2015 10:51:23 +1100 Subject: [PATCH 140/174] replaced a nose function for known failing tests --- lib/matplotlib/tests/test_animation.py | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/matplotlib/tests/test_animation.py b/lib/matplotlib/tests/test_animation.py index 3dd5b6e42b81..451b1cbfebbd 100644 --- a/lib/matplotlib/tests/test_animation.py +++ b/lib/matplotlib/tests/test_animation.py @@ -9,6 +9,7 @@ from numpy.testing import assert_equal 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 From 0f9fae8f7545c03f6f0c2e980a09b7c38e9db0d6 Mon Sep 17 00:00:00 2001 From: Jason King Date: Fri, 27 Nov 2015 18:38:35 +1100 Subject: [PATCH 141/174] remove more of the nose infrastructure --- lib/matplotlib/tests/test_animation.py | 1 - lib/matplotlib/tests/test_coding_standards.py | 74 ++----------------- 2 files changed, 7 insertions(+), 68 deletions(-) diff --git a/lib/matplotlib/tests/test_animation.py b/lib/matplotlib/tests/test_animation.py index 451b1cbfebbd..3dd5b6e42b81 100644 --- a/lib/matplotlib/tests/test_animation.py +++ b/lib/matplotlib/tests/test_animation.py @@ -9,7 +9,6 @@ from numpy.testing import assert_equal 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 diff --git a/lib/matplotlib/tests/test_coding_standards.py b/lib/matplotlib/tests/test_coding_standards.py index 9d90f5dbbc46..540d8e202c95 100644 --- a/lib/matplotlib/tests/test_coding_standards.py +++ b/lib/matplotlib/tests/test_coding_standards.py @@ -83,73 +83,13 @@ 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 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 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 From cd961ccad1a08b5ac5f385d21ded303617a77dca Mon Sep 17 00:00:00 2001 From: Jason King Date: Sun, 13 Dec 2015 16:25:39 +1100 Subject: [PATCH 142/174] fix up a bunch of pytest.raises calls. I changed func,x,y into func(x,y) by mistake, and hadn't changed a few back. --- lib/matplotlib/tests/test_mlab.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/matplotlib/tests/test_mlab.py b/lib/matplotlib/tests/test_mlab.py index 63258f0bea7b..c9fa040d28ae 100644 --- a/lib/matplotlib/tests/test_mlab.py +++ b/lib/matplotlib/tests/test_mlab.py @@ -1623,7 +1623,7 @@ def test_psd_detrend_mean_str_offset(self): assert_allclose(spec_g, spec_c, atol=1e-08) # these should not be almost equal pytest.raises(AssertionError, - assert_allclose(spec_b, spec_c, atol=1e-08)) + assert_allclose, spec_b, spec_c, atol=1e-08) def test_psd_detrend_linear_func_trend(self): if self.NFFT_density is None: From de69032e8b7ee307f36fe05f56f633d77c9db93e Mon Sep 17 00:00:00 2001 From: Jason King Date: Sun, 13 Dec 2015 17:22:16 +1100 Subject: [PATCH 143/174] converted assert_raises calls to pytest.raises. --- lib/matplotlib/tests/test_triangulation.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/matplotlib/tests/test_triangulation.py b/lib/matplotlib/tests/test_triangulation.py index 90b01bc86aaa..d195fce20d4a 100644 --- a/lib/matplotlib/tests/test_triangulation.py +++ b/lib/matplotlib/tests/test_triangulation.py @@ -277,7 +277,7 @@ def test_trifinder(): trifinder = triang.get_trifinder() xs = [-0.2, 0.2, 0.8, 1.2] - ys = [0.5, 0.5, 0.5, 0.5] + ys = [ 0.5, 0.5, 0.5, 0.5] tris = trifinder(xs, ys) assert_array_equal(tris, [-1, 0, 1, -1]) From 42185f8a2e9a0f4dbc8f1ce0ceb58668f0f22f50 Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 14 Dec 2015 13:28:59 +1100 Subject: [PATCH 144/174] fixing pep8 failures. --- lib/matplotlib/tests/test_image.py | 6 ++---- lib/matplotlib/tests/test_simplification.py | 2 +- lib/matplotlib/tests/test_triangulation.py | 2 +- 3 files changed, 4 insertions(+), 6 deletions(-) diff --git a/lib/matplotlib/tests/test_image.py b/lib/matplotlib/tests/test_image.py index 607145bc2cd8..fd6eb5e1b02f 100644 --- a/lib/matplotlib/tests/test_image.py +++ b/lib/matplotlib/tests/test_image.py @@ -12,10 +12,8 @@ from matplotlib.transforms import Bbox from matplotlib import rcParams, rc_context import matplotlib.pyplot as plt -from numpy.testing import assert_array_equal, assert_array_almost_equal -import pytest -import io -import os + +from numpy.testing import assert_array_equal try: from PIL import Image diff --git a/lib/matplotlib/tests/test_simplification.py b/lib/matplotlib/tests/test_simplification.py index cc42eed96f36..350be67954c3 100644 --- a/lib/matplotlib/tests/test_simplification.py +++ b/lib/matplotlib/tests/test_simplification.py @@ -9,7 +9,7 @@ import matplotlib.pyplot as plt import pytest -import pylab +from pylab import * import numpy as np from matplotlib import patches, path, transforms diff --git a/lib/matplotlib/tests/test_triangulation.py b/lib/matplotlib/tests/test_triangulation.py index d195fce20d4a..90b01bc86aaa 100644 --- a/lib/matplotlib/tests/test_triangulation.py +++ b/lib/matplotlib/tests/test_triangulation.py @@ -277,7 +277,7 @@ def test_trifinder(): trifinder = triang.get_trifinder() xs = [-0.2, 0.2, 0.8, 1.2] - ys = [ 0.5, 0.5, 0.5, 0.5] + ys = [0.5, 0.5, 0.5, 0.5] tris = trifinder(xs, ys) assert_array_equal(tris, [-1, 0, 1, -1]) From cd81fbf2eab3a70d5b8dc2f89a850f9d733e6642 Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 14 Dec 2015 15:25:22 +1100 Subject: [PATCH 145/174] more pep8 failures to hide under the rug. --- lib/matplotlib/tests/test_axes.py | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/lib/matplotlib/tests/test_axes.py b/lib/matplotlib/tests/test_axes.py index 3273bb1f2a11..581bb9f4c156 100644 --- a/lib/matplotlib/tests/test_axes.py +++ b/lib/matplotlib/tests/test_axes.py @@ -3662,8 +3662,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) @@ -3843,7 +3843,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, @@ -3929,10 +3929,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'], From 523bb864a793eaf8a036152b7755585d0950fc73 Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 14 Dec 2015 22:24:46 +1100 Subject: [PATCH 146/174] if commenting out the nose pep8 functions work, then they can all be removed later. --- lib/matplotlib/tests/test_coding_standards.py | 82 +++++++++++++++---- 1 file changed, 68 insertions(+), 14 deletions(-) diff --git a/lib/matplotlib/tests/test_coding_standards.py b/lib/matplotlib/tests/test_coding_standards.py index 540d8e202c95..cbe2400e5840 100644 --- a/lib/matplotlib/tests/test_coding_standards.py +++ b/lib/matplotlib/tests/test_coding_standards.py @@ -83,20 +83,74 @@ 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. - """ +# 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 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', From 859f8d5534f7d712f0e6b2450b684cc52bcd7172 Mon Sep 17 00:00:00 2001 From: Jason King Date: Tue, 15 Dec 2015 11:30:25 +1100 Subject: [PATCH 147/174] removing (and moving) import code in tests.py --- tests.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/tests.py b/tests.py index 74d03a575c0e..11a7de31b354 100755 --- a/tests.py +++ b/tests.py @@ -12,13 +12,12 @@ import os import sys import time +import pytest +from matplotlib import default_test_modules import matplotlib matplotlib.use('agg') -# import nose -import pytest -from matplotlib import default_test_modules def run(extra_args): From ad48b37ccd02db16fcc785c687f2ec7e96509c5d Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 28 Dec 2015 16:13:00 +1100 Subject: [PATCH 148/174] pep8 failures --- tests.py | 1 - 1 file changed, 1 deletion(-) diff --git a/tests.py b/tests.py index 11a7de31b354..5a3b7c771306 100755 --- a/tests.py +++ b/tests.py @@ -19,7 +19,6 @@ matplotlib.use('agg') - def run(extra_args): matplotlib._init_tests() From 9a0b134846eca44b3db5e8c69efdf18b3ca3d995 Mon Sep 17 00:00:00 2001 From: Jason King Date: Fri, 1 Jan 2016 19:28:54 +1100 Subject: [PATCH 149/174] try norecursedirs to get pytest to stop looking in numpy --- tox.ini | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tox.ini b/tox.ini index 568eaeefecb8..47b63f160ef5 100644 --- a/tox.ini +++ b/tox.ini @@ -17,7 +17,7 @@ deps = numpy [pytest] -norecursedirs = .git build +norecursedirs = .git build numpy testpaths = tests pep8ignore = *.py E111 E114 E115 E116 E121 E122 E123 E124 E125 E126 E127 E128 E129 E131 E265 E266 W503 E241 E401 E231 E203 E226 From 23cee6a3014a8a23cf1d009a5d1c5f70449de638 Mon Sep 17 00:00:00 2001 From: Jason King Date: Sat, 2 Jan 2016 13:44:52 +1100 Subject: [PATCH 150/174] found cases of 'import nose' , and also, use of a decorator called 'knownfailureif' removed, and replaced with pytest versions if necessary. --- lib/matplotlib/tests/test_artist.py | 1 - lib/matplotlib/tests/test_axes.py | 1 - lib/matplotlib/tests/test_image.py | 6 ++++-- lib/matplotlib/tests/test_rcparams.py | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/lib/matplotlib/tests/test_artist.py b/lib/matplotlib/tests/test_artist.py index 9b777fb94950..ecf8e4ff1571 100644 --- a/lib/matplotlib/tests/test_artist.py +++ b/lib/matplotlib/tests/test_artist.py @@ -206,4 +206,3 @@ def test_properties(): warnings.simplefilter("always") ln.properties() assert len(w) == 0 - diff --git a/lib/matplotlib/tests/test_axes.py b/lib/matplotlib/tests/test_axes.py index 581bb9f4c156..62f9beb6f500 100644 --- a/lib/matplotlib/tests/test_axes.py +++ b/lib/matplotlib/tests/test_axes.py @@ -2203,7 +2203,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() diff --git a/lib/matplotlib/tests/test_image.py b/lib/matplotlib/tests/test_image.py index fd6eb5e1b02f..607145bc2cd8 100644 --- a/lib/matplotlib/tests/test_image.py +++ b/lib/matplotlib/tests/test_image.py @@ -12,8 +12,10 @@ 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 diff --git a/lib/matplotlib/tests/test_rcparams.py b/lib/matplotlib/tests/test_rcparams.py index 6db28890550f..80105140dbe1 100644 --- a/lib/matplotlib/tests/test_rcparams.py +++ b/lib/matplotlib/tests/test_rcparams.py @@ -13,7 +13,7 @@ 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 From c59a7b01b7c2e982d3dba7e792d5fc585b2d4696 Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 4 Jan 2016 12:49:25 +1100 Subject: [PATCH 151/174] don't need the nose make_decorator function any more. --- lib/matplotlib/testing/decorators.py | 32 +--------------------------- 1 file changed, 1 insertion(+), 31 deletions(-) diff --git a/lib/matplotlib/testing/decorators.py b/lib/matplotlib/testing/decorators.py index 04bb81fca9ab..3c7b176caadf 100644 --- a/lib/matplotlib/testing/decorators.py +++ b/lib/matplotlib/testing/decorators.py @@ -252,35 +252,6 @@ def do_test(): 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 - 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'): @@ -367,7 +338,6 @@ 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*. @@ -440,5 +410,5 @@ def backend_switcher(*args, **kwargs): plt.switch_backend(prev_backend) return result - return backend_switcher + return nose.tools.make_decorator(func)(backend_switcher) return switch_backend_decorator From 43fd3e26f4d2b82536795ceb9726e46c99ee2587 Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 4 Jan 2016 22:38:40 +1100 Subject: [PATCH 152/174] make_decorator seems to be described here. https://ipython.org/ipython-doc/1/api/generated/IPython. testing.decorators.html So lets try just returning the decorator instead of whats there now. --- lib/matplotlib/testing/decorators.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/matplotlib/testing/decorators.py b/lib/matplotlib/testing/decorators.py index 3c7b176caadf..038137ca24ac 100644 --- a/lib/matplotlib/testing/decorators.py +++ b/lib/matplotlib/testing/decorators.py @@ -410,5 +410,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 From 108522a79b74ea6109dda45db8fb1bf3fad134ac Mon Sep 17 00:00:00 2001 From: Jason King Date: Fri, 8 Jan 2016 12:14:50 +1100 Subject: [PATCH 153/174] An attempt to make a image_comparison decorator that doesn't fail while being used on test_pickle.test_complete() --- lib/matplotlib/testing/decorators.py | 30 ++++++++++++++++++++++++++++ lib/matplotlib/tests/test_pickle.py | 4 ++-- 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/lib/matplotlib/testing/decorators.py b/lib/matplotlib/testing/decorators.py index 038137ca24ac..04bb81fca9ab 100644 --- a/lib/matplotlib/testing/decorators.py +++ b/lib/matplotlib/testing/decorators.py @@ -252,6 +252,35 @@ def do_test(): 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 + 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 +367,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*. diff --git a/lib/matplotlib/tests/test_pickle.py b/lib/matplotlib/tests/test_pickle.py index ced3bc1aa2b6..f70ec25c8667 100644 --- a/lib/matplotlib/tests/test_pickle.py +++ b/lib/matplotlib/tests/test_pickle.py @@ -9,8 +9,8 @@ import numpy as np -from matplotlib.testing.decorators import cleanup, image_comparison -from matplotlib.testing.decorators import image_comparison_2 +from matplotlib.testing.decorators import cleanup, image_comparison, + image_comparison_2 import matplotlib.pyplot as plt import matplotlib.transforms as mtransforms From 90221b908489d69874c812f15da6da6776dbeee0 Mon Sep 17 00:00:00 2001 From: Jason King Date: Fri, 8 Jan 2016 12:55:00 +1100 Subject: [PATCH 154/174] fix up indentation for import --- lib/matplotlib/tests/test_pickle.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/matplotlib/tests/test_pickle.py b/lib/matplotlib/tests/test_pickle.py index f70ec25c8667..dd7698ad8050 100644 --- a/lib/matplotlib/tests/test_pickle.py +++ b/lib/matplotlib/tests/test_pickle.py @@ -10,7 +10,7 @@ import numpy as np from matplotlib.testing.decorators import cleanup, image_comparison, - image_comparison_2 + image_comparison_2 import matplotlib.pyplot as plt import matplotlib.transforms as mtransforms From 6f74d88db975da01fa22485b7c7f6efd57751ba5 Mon Sep 17 00:00:00 2001 From: Jason King Date: Fri, 8 Jan 2016 13:13:42 +1100 Subject: [PATCH 155/174] another fix for indentation. kinda non-dry'y --- lib/matplotlib/tests/test_pickle.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/matplotlib/tests/test_pickle.py b/lib/matplotlib/tests/test_pickle.py index dd7698ad8050..ced3bc1aa2b6 100644 --- a/lib/matplotlib/tests/test_pickle.py +++ b/lib/matplotlib/tests/test_pickle.py @@ -9,8 +9,8 @@ import numpy as np -from matplotlib.testing.decorators import cleanup, image_comparison, - image_comparison_2 +from matplotlib.testing.decorators import cleanup, image_comparison +from matplotlib.testing.decorators import image_comparison_2 import matplotlib.pyplot as plt import matplotlib.transforms as mtransforms From 0ba73236bce2068c371fc34d6acaca929576e24c Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 11 Jan 2016 23:02:54 +1100 Subject: [PATCH 156/174] removed mentions of 'import nose' --- lib/matplotlib/tests/test_coding_standards.py | 2 +- lib/matplotlib/tests/test_cycles.py | 12 ++++++------ lib/matplotlib/tests/test_dviread.py | 2 ++ lib/matplotlib/tests/test_rcparams.py | 3 --- 4 files changed, 9 insertions(+), 10 deletions(-) diff --git a/lib/matplotlib/tests/test_coding_standards.py b/lib/matplotlib/tests/test_coding_standards.py index cbe2400e5840..60f21b096ca7 100644 --- a/lib/matplotlib/tests/test_coding_standards.py +++ b/lib/matplotlib/tests/test_coding_standards.py @@ -99,7 +99,7 @@ def get_file_results(self): # """ # # if not HAS_PEP8: -# raise SkipTest('The pep8 tool is required for this test') +# 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. diff --git a/lib/matplotlib/tests/test_cycles.py b/lib/matplotlib/tests/test_cycles.py index 8c25bd7e0b57..ba46eb209dbc 100644 --- a/lib/matplotlib/tests/test_cycles.py +++ b/lib/matplotlib/tests/test_cycles.py @@ -172,15 +172,15 @@ def test_cycle_reset(): @cleanup def test_invalid_input_forms(): fig, ax = plt.subplots() - with pytest.raises((TypeError, ValueError)): + with pytest.raises(TypeError, ValueError): ax.set_prop_cycle(1) - with pytest.raises((TypeError, ValueError)): + with pytest.raises(TypeError, ValueError): ax.set_prop_cycle([1, 2]) - with pytest.raises((TypeError, ValueError)): + with pytest.raises(TypeError, ValueError): ax.set_prop_cycle('color', 'fish') - with pytest.raises((TypeError, ValueError)): + with pytest.raises(TypeError, ValueError): ax.set_prop_cycle('linewidth', 1) - with pytest.raises((TypeError, ValueError)): + with pytest.raises(TypeError, ValueError): ax.set_prop_cycle('linewidth', {'1': 1, '2': 2}) - with pytest.raises((TypeError, ValueError)): + with pytest.raises(TypeError, ValueError): ax.set_prop_cycle(linewidth=1, color='r') diff --git a/lib/matplotlib/tests/test_dviread.py b/lib/matplotlib/tests/test_dviread.py index ac7f7d5cbc46..4cecf14ce3dc 100644 --- a/lib/matplotlib/tests/test_dviread.py +++ b/lib/matplotlib/tests/test_dviread.py @@ -24,6 +24,8 @@ def fin(): teardown_PsfontsMap() request.addfinalizer(fin) +def teardown_PsfontsMap(): + dr.find_tex_file = original_find_tex_file def test_PsfontsMap(setup_PsfontsMap): filename = os.path.join( diff --git a/lib/matplotlib/tests/test_rcparams.py b/lib/matplotlib/tests/test_rcparams.py index 80105140dbe1..54cc152bed85 100644 --- a/lib/matplotlib/tests/test_rcparams.py +++ b/lib/matplotlib/tests/test_rcparams.py @@ -15,9 +15,6 @@ from matplotlib.tests import assert_str_equal 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, From 39612f6f90306cc6dae9d6f209013c4857e744c3 Mon Sep 17 00:00:00 2001 From: Jason King Date: Fri, 15 Jan 2016 00:34:33 +1100 Subject: [PATCH 157/174] fix up test failures caused through rebase --- lib/matplotlib/tests/test_lines.py | 1 - 1 file changed, 1 deletion(-) diff --git a/lib/matplotlib/tests/test_lines.py b/lib/matplotlib/tests/test_lines.py index 300369ee841f..de083871918c 100644 --- a/lib/matplotlib/tests/test_lines.py +++ b/lib/matplotlib/tests/test_lines.py @@ -10,7 +10,6 @@ import matplotlib.lines as mlines from timeit import repeat import numpy as np - import matplotlib.pyplot as plt from matplotlib.testing.decorators import cleanup, image_comparison import sys From 336d1eb4614815f3cb3f25bbe1e6c80ab818a621 Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 18 Jan 2016 10:29:22 +1100 Subject: [PATCH 158/174] remove __name__ == '__main__' from many test files --- lib/matplotlib/tests/test_lines.py | 1 - lib/matplotlib/tests/test_offsetbox.py | 3 +-- lib/matplotlib/tests/test_rcparams.py | 1 - 3 files changed, 1 insertion(+), 4 deletions(-) diff --git a/lib/matplotlib/tests/test_lines.py b/lib/matplotlib/tests/test_lines.py index de083871918c..8db3c6219506 100644 --- a/lib/matplotlib/tests/test_lines.py +++ b/lib/matplotlib/tests/test_lines.py @@ -160,4 +160,3 @@ def test_nan_is_sorted(): 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_offsetbox.py b/lib/matplotlib/tests/test_offsetbox.py index fc67c70bd59a..ffc5cd2f7dd6 100644 --- a/lib/matplotlib/tests/test_offsetbox.py +++ b/lib/matplotlib/tests/test_offsetbox.py @@ -80,5 +80,4 @@ def test_offsetbox_clip_children(): fig.canvas.draw() assert not fig.stale da.clip_children = True - assert_true(fig.stale) - + assert fig.stale diff --git a/lib/matplotlib/tests/test_rcparams.py b/lib/matplotlib/tests/test_rcparams.py index 54cc152bed85..c2f003fad958 100644 --- a/lib/matplotlib/tests/test_rcparams.py +++ b/lib/matplotlib/tests/test_rcparams.py @@ -410,4 +410,3 @@ def test_rcparams_reset_after_fail(): pass assert mpl.rcParams['text.usetex'] is False - From 7d9fdf6b4c90b71bc6d8aec6b9edbed0da4f92b0 Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 18 Jan 2016 21:34:36 +1100 Subject: [PATCH 159/174] fix test_invalid_input_forms in test_cycles.py --- lib/matplotlib/tests/test_cycles.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/lib/matplotlib/tests/test_cycles.py b/lib/matplotlib/tests/test_cycles.py index ba46eb209dbc..8c25bd7e0b57 100644 --- a/lib/matplotlib/tests/test_cycles.py +++ b/lib/matplotlib/tests/test_cycles.py @@ -172,15 +172,15 @@ def test_cycle_reset(): @cleanup def test_invalid_input_forms(): fig, ax = plt.subplots() - with pytest.raises(TypeError, ValueError): + with pytest.raises((TypeError, ValueError)): ax.set_prop_cycle(1) - with pytest.raises(TypeError, ValueError): + with pytest.raises((TypeError, ValueError)): ax.set_prop_cycle([1, 2]) - with pytest.raises(TypeError, ValueError): + with pytest.raises((TypeError, ValueError)): ax.set_prop_cycle('color', 'fish') - with pytest.raises(TypeError, ValueError): + with pytest.raises((TypeError, ValueError)): ax.set_prop_cycle('linewidth', 1) - with pytest.raises(TypeError, ValueError): + with pytest.raises((TypeError, ValueError)): ax.set_prop_cycle('linewidth', {'1': 1, '2': 2}) - with pytest.raises(TypeError, ValueError): + with pytest.raises((TypeError, ValueError)): ax.set_prop_cycle(linewidth=1, color='r') From 606907b3f305e2bc6499a29ffbbb2611307a0b1a Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 18 Jan 2016 22:33:44 +1100 Subject: [PATCH 160/174] fix nose skiptest references, test_axes.py --- lib/matplotlib/tests/test_axes.py | 4 ---- 1 file changed, 4 deletions(-) diff --git a/lib/matplotlib/tests/test_axes.py b/lib/matplotlib/tests/test_axes.py index 62f9beb6f500..49c817a68e7d 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, pytest.raises, assert_false, assert_true -from nose.plugins.skip import SkipTest - import datetime import numpy as np From db5f5e5295e343f1bb730956c7ae3f064efd02d3 Mon Sep 17 00:00:00 2001 From: Jason King Date: Wed, 20 Jan 2016 08:31:07 +1100 Subject: [PATCH 161/174] fix numpy pytest errors. don't put pylab in default namespace This might not be the point of using pylab this way in a test however --- lib/matplotlib/tests/test_simplification.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/matplotlib/tests/test_simplification.py b/lib/matplotlib/tests/test_simplification.py index 350be67954c3..cc42eed96f36 100644 --- a/lib/matplotlib/tests/test_simplification.py +++ b/lib/matplotlib/tests/test_simplification.py @@ -9,7 +9,7 @@ import matplotlib.pyplot as plt import pytest -from pylab import * +import pylab import numpy as np from matplotlib import patches, path, transforms From 37418d852c09e4e25b0e450fdd6c5b42f3ae4653 Mon Sep 17 00:00:00 2001 From: Jason King Date: Wed, 20 Jan 2016 10:35:33 +1100 Subject: [PATCH 162/174] PEP8 E502 at test_simplification.py, test_fft_peaks --- lib/matplotlib/tests/test_simplification.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/matplotlib/tests/test_simplification.py b/lib/matplotlib/tests/test_simplification.py index cc42eed96f36..82c3e6be899f 100644 --- a/lib/matplotlib/tests/test_simplification.py +++ b/lib/matplotlib/tests/test_simplification.py @@ -121,7 +121,7 @@ def test_fft_peaks(): fig = plt.figure() t = pylab.arange(65536) ax = fig.add_subplot(111) - p1 = ax.plot(abs(pylab.numpy.fft( \ + p1 = ax.plot(abs(pylab.numpy.fft( pylab.sin(2*pylab.pi*.01*t)*pylab.blackman(len(t))))) path = p1[0].get_path() From 01b92150ca31084a2a093b41ea046a815c619c47 Mon Sep 17 00:00:00 2001 From: Jason King Date: Thu, 21 Jan 2016 11:20:53 +1100 Subject: [PATCH 163/174] remove @cleanup operator from test_complete. Its causing a pytest failure, and I can't figure out why. Test seems to work ok without it. --- lib/matplotlib/tests/test_pickle.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/lib/matplotlib/tests/test_pickle.py b/lib/matplotlib/tests/test_pickle.py index ced3bc1aa2b6..a3f9a0c67c4c 100644 --- a/lib/matplotlib/tests/test_pickle.py +++ b/lib/matplotlib/tests/test_pickle.py @@ -9,8 +9,7 @@ import numpy as np -from matplotlib.testing.decorators import cleanup, image_comparison -from matplotlib.testing.decorators import image_comparison_2 +from matplotlib.testing.decorators import cleanup, image_comparison_2 import matplotlib.pyplot as plt import matplotlib.transforms as mtransforms @@ -127,7 +126,10 @@ def test_simple(): pickle.dump(fig, BytesIO(), pickle.HIGHEST_PROTOCOL) -@cleanup +# 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(): From b9c0ee7f54390ac93f51a4ecbc033485954e39f9 Mon Sep 17 00:00:00 2001 From: Jason King Date: Fri, 22 Jan 2016 23:38:33 +1100 Subject: [PATCH 164/174] PEP8 E302 around teardown_PsfontsMap, test_dviread.py --- lib/matplotlib/tests/test_dviread.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lib/matplotlib/tests/test_dviread.py b/lib/matplotlib/tests/test_dviread.py index 4cecf14ce3dc..15b69f2bb650 100644 --- a/lib/matplotlib/tests/test_dviread.py +++ b/lib/matplotlib/tests/test_dviread.py @@ -24,9 +24,11 @@ def fin(): teardown_PsfontsMap() request.addfinalizer(fin) + def teardown_PsfontsMap(): dr.find_tex_file = original_find_tex_file + def test_PsfontsMap(setup_PsfontsMap): filename = os.path.join( os.path.dirname(__file__), From e002e488565fed3c6dac034fb3c6fe023a8f89d8 Mon Sep 17 00:00:00 2001 From: Jason King Date: Fri, 22 Jan 2016 23:56:51 +1100 Subject: [PATCH 165/174] fix lack of _func error in image_comparison_2, decorators.py most likely human error with a long rebase process --- lib/matplotlib/testing/decorators.py | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/matplotlib/testing/decorators.py b/lib/matplotlib/testing/decorators.py index 04bb81fca9ab..5f02bb358034 100644 --- a/lib/matplotlib/testing/decorators.py +++ b/lib/matplotlib/testing/decorators.py @@ -276,6 +276,7 @@ def compare_images_decorator(func): 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 From 25f77bc1d9bdfaea295b6011524c1e9bc22659da Mon Sep 17 00:00:00 2001 From: Jason King Date: Sat, 23 Jan 2016 00:11:27 +1100 Subject: [PATCH 166/174] fix assert_raises call in test_valid_linestyles, test_lines.py human error that got through a long rebase procedure. --- lib/matplotlib/tests/test_lines.py | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/lib/matplotlib/tests/test_lines.py b/lib/matplotlib/tests/test_lines.py index 8db3c6219506..3bbdb3232ec7 100644 --- a/lib/matplotlib/tests/test_lines.py +++ b/lib/matplotlib/tests/test_lines.py @@ -108,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') From 19965132256a8d6b90a65c6daa74507d4e8fa4da Mon Sep 17 00:00:00 2001 From: Jason King Date: Sat, 23 Jan 2016 00:39:04 +1100 Subject: [PATCH 167/174] fix syntax error (another newline) in testing.rst, rst files are not python! --- doc/devel/testing.rst | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/doc/devel/testing.rst b/doc/devel/testing.rst index 9c63a4f6b7e2..c7d7b724fbaf 100644 --- a/doc/devel/testing.rst +++ b/doc/devel/testing.rst @@ -35,8 +35,7 @@ Optionally you can install: - `pytest-cov `_ for coverage stats in pytest - - `pytest-pep8 `_ for pep8 - conformance in pytest + - `pytest-pep8 `_ for pep8 conformance in pytest Building matplotlib for image comparison tests ---------------------------------------------- From 07313dbd0accc1771c5c7353b3a88c2ccfb46c6f Mon Sep 17 00:00:00 2001 From: Jason King Date: Sat, 23 Jan 2016 09:55:11 +1100 Subject: [PATCH 168/174] doc lets remove pytest targets in rst for now --- doc/devel/testing.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc/devel/testing.rst b/doc/devel/testing.rst index c7d7b724fbaf..de1358135ba6 100644 --- a/doc/devel/testing.rst +++ b/doc/devel/testing.rst @@ -3,7 +3,7 @@ Testing ======= -Matplotlib has a testing infrastructure based on pytest_, 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 pytest testing infrastructure are in :mod:`matplotlib.testing`. (There is other old testing cruft around, @@ -16,7 +16,7 @@ Requirements The following software is required to run the tests: - - pytest_ + - pytest - `mock `_, when running python versions < 3.3 From 280be1bea08abea5363fa25a6f4fa1d50a01bfcc Mon Sep 17 00:00:00 2001 From: Jason King Date: Sat, 23 Jan 2016 13:32:28 +1100 Subject: [PATCH 169/174] convert pytest.raises(error,f,x,y) calls to with pytest.raises --- lib/matplotlib/tests/test_axes.py | 45 +++-- lib/matplotlib/tests/test_cbook.py | 16 +- lib/matplotlib/tests/test_colors.py | 9 +- lib/matplotlib/tests/test_contour.py | 3 +- lib/matplotlib/tests/test_dates.py | 6 +- .../tests/test_labeled_data_unpacking.py | 15 +- lib/matplotlib/tests/test_mlab.py | 182 ++++++++++-------- lib/matplotlib/tests/test_path.py | 3 +- lib/matplotlib/tests/test_rcparams.py | 3 +- lib/matplotlib/tests/test_subplots.py | 15 +- lib/matplotlib/tests/test_text.py | 3 +- lib/matplotlib/tests/test_ticker.py | 3 +- lib/matplotlib/tests/test_triangulation.py | 25 ++- lib/mpl_toolkits/tests/test_mplot3d.py | 3 +- 14 files changed, 203 insertions(+), 128 deletions(-) diff --git a/lib/matplotlib/tests/test_axes.py b/lib/matplotlib/tests/test_axes.py index 49c817a68e7d..eafec267c2d4 100644 --- a/lib/matplotlib/tests/test_axes.py +++ b/lib/matplotlib/tests/test_axes.py @@ -356,7 +356,8 @@ def test_shaped_data(): plt.plot(y2) plt.subplot(413) - pytest.raises(ValueError, plt.plot, y1, y2) + with pytest.raises(ValueError): + plt.plot(y1, y2) plt.subplot(414) plt.plot(xdata[:, 1], xdata[1, :], 'o') @@ -3026,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') - pytest.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') - pytest.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') - pytest.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') @@ -3073,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') - pytest.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') - pytest.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') - pytest.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') @@ -3128,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') - pytest.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') - pytest.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') - pytest.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') @@ -3178,15 +3188,18 @@ def test_specgram_noise_phase(): pad_to=pad_to, sides='twosided', mode='phase', ) - pytest.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') - pytest.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') - pytest.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') @@ -4222,8 +4235,10 @@ def test_title_location_roundtrip(): assert 'right' == ax.get_title(loc='right') assert 'aardvark' == ax.get_title() - pytest.raises(ValueError, ax.get_title, loc='foo') - pytest.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, diff --git a/lib/matplotlib/tests/test_cbook.py b/lib/matplotlib/tests/test_cbook.py index 5328f8838a42..bfdda8f0982e 100644 --- a/lib/matplotlib/tests/test_cbook.py +++ b/lib/matplotlib/tests/test_cbook.py @@ -374,14 +374,14 @@ def test_to_midstep(): def test_step_fails(): - pytest.raises(ValueError, - cbook._step_validation, np.arange(12).reshape(3, 4), 'a') - pytest.raises(ValueError, - cbook._step_validation, np.arange(12), 'a') - pytest.raises(ValueError, - cbook._step_validation, np.arange(12)) - pytest.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_colors.py b/lib/matplotlib/tests/test_colors.py index dd74a4502684..bd17ea1e4da6 100644 --- a/lib/matplotlib/tests/test_colors.py +++ b/lib/matplotlib/tests/test_colors.py @@ -282,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)) - pytest.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(): @@ -312,8 +313,10 @@ def gray_from_float_rgb(): def gray_from_float_rgba(): return mcolors.colorConverter.to_rgba(0.4) - pytest.raises(ValueError, gray_from_float_rgb) - pytest.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'], diff --git a/lib/matplotlib/tests/test_contour.py b/lib/matplotlib/tests/test_contour.py index 07d5cecf131d..9ae8224968b6 100644 --- a/lib/matplotlib/tests/test_contour.py +++ b/lib/matplotlib/tests/test_contour.py @@ -284,7 +284,8 @@ def test_contourf_decreasing_levels(): # github issue 5477. z = [[0.1, 0.3], [0.5, 0.7]] plt.figure() - pytest.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: diff --git a/lib/matplotlib/tests/test_dates.py b/lib/matplotlib/tests/test_dates.py index 08da86538e15..ed2ecceb1522 100644 --- a/lib/matplotlib/tests/test_dates.py +++ b/lib/matplotlib/tests/test_dates.py @@ -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()) - pytest.raises(RuntimeError, fig.savefig, 'junk.png') + with pytest.raises(RuntimeError): + fig.savefig('junk.png') @image_comparison(baseline_images=['RRuleLocator_bounds'], extensions=['png']) @@ -264,7 +265,8 @@ def test_empty_date_with_year_formatter(): ax.xaxis.set_major_formatter(yearFmt) with tempfile.TemporaryFile() as fh: - pytest.raises(ValueError, fig.savefig, fh) + with pytest.raises(ValueError): + fig.savefig(fh) def test_auto_date_locator(): diff --git a/lib/matplotlib/tests/test_labeled_data_unpacking.py b/lib/matplotlib/tests/test_labeled_data_unpacking.py index f85a0970d8a2..d898d0841e10 100644 --- a/lib/matplotlib/tests/test_labeled_data_unpacking.py +++ b/lib/matplotlib/tests/test_labeled_data_unpacking.py @@ -64,12 +64,14 @@ def f(): # z is unknown unpack_labeled_data(replace_names=["x", "y", "z"])(func_args) - pytest.raises(AssertionError, f) + with pytest.raises(AssertionError): + f() def f(): unpack_labeled_data(replace_names=["x", "y"])(func_no_ax_args) - pytest.raises(AssertionError, f) + with pytest.raises(AssertionError): + f() # no replacements at all -> all ok... unpack_labeled_data(replace_names=[], label_namer=None)(func) @@ -81,12 +83,14 @@ def f(): def f(): unpack_labeled_data(label_namer="z")(func) - pytest.raises(AssertionError, f) + with pytest.raises(AssertionError): + f() def f(): unpack_labeled_data(label_namer="z")(func_args) - pytest.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) @@ -405,7 +409,8 @@ def funcy(ax, *args, **kwargs): def f(): assert funcy(None, "x", "y", "c", "x", "y", "x", "y", data=data) == \ "('X', 'Y', 'c', 'X', 'Y', 'X', 'Y') | {}" - pytest.raises(ValueError, f) + with pytest.raises(AssertionError): + f() # In the two arg case, if a valid color spec is in data, we warn but use # it as data... diff --git a/lib/matplotlib/tests/test_mlab.py b/lib/matplotlib/tests/test_mlab.py index c9fa040d28ae..d68fe84368c6 100644 --- a/lib/matplotlib/tests/test_mlab.py +++ b/lib/matplotlib/tests/test_mlab.py @@ -122,43 +122,53 @@ def calc_window_target(self, x, NFFT, noverlap=0): def test_stride_windows_2D_ValueError(self): x = np.arange(10)[np.newaxis] - pytest.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) - pytest.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) - pytest.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) - pytest.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) - pytest.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) - pytest.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] - pytest.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) - pytest.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) - pytest.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) - pytest.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) @@ -336,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. - pytest.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') @@ -398,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 - pytest.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)) - pytest.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 - pytest.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 - pytest.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 @@ -1095,43 +1107,53 @@ def test_demean_2D_axism1(self): def test_detrend_bad_key_str_ValueError(self): input = self.sig_slope[np.newaxis] - pytest.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] - pytest.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 - pytest.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 - pytest.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 - pytest.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 - pytest.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 - pytest.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] - pytest.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] - pytest.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] - pytest.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. @@ -1195,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] - pytest.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, @@ -1430,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 - pytest.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 - pytest.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 - pytest.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 - pytest.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 - pytest.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 - pytest.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 - pytest.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 - pytest.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 - pytest.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 - pytest.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 - pytest.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 @@ -1586,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 - pytest.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: @@ -1622,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 - pytest.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: @@ -1658,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 - pytest.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: @@ -1694,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 - pytest.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: @@ -1738,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 - pytest.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: @@ -1787,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 - pytest.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 @@ -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. - pytest.raises(ValueError, mlab.griddata, x, y, z, xi[::-1], yi, - interp='nn') - pytest.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) @@ -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.""" - pytest.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.""" - pytest.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]]) - pytest.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]]) - pytest.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 """ - pytest.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 @@ -2921,7 +2950,8 @@ def test_wrong_bw_method(self): np.random.seed(8765678) n_basesample = 50 data = np.random.randn(n_basesample) - pytest.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]] - pytest.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) - pytest.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""" diff --git a/lib/matplotlib/tests/test_path.py b/lib/matplotlib/tests/test_path.py index 267b1fe30e4d..44888ea5aa22 100644 --- a/lib/matplotlib/tests/test_path.py +++ b/lib/matplotlib/tests/test_path.py @@ -19,7 +19,8 @@ def test_readonly_path(): def modify_vertices(): path.vertices = path.vertices * 2.0 - pytest.raises(AttributeError, modify_vertices) + with pytest.raises(AttributeError): + modify_vertices() def test_point_in_path(): diff --git a/lib/matplotlib/tests/test_rcparams.py b/lib/matplotlib/tests/test_rcparams.py index c2f003fad958..70a469c00678 100644 --- a/lib/matplotlib/tests/test_rcparams.py +++ b/lib/matplotlib/tests/test_rcparams.py @@ -258,7 +258,8 @@ def _validation_fail_helper(validator, arg, exception_type): if sys.version_info[:2] < (2, 7): raise pytest.skip("assert_raises as context manager not " "supported with Python < 2.7") - pytest.raises(exception_type,validator, arg) + with pytest.raises(exception_type): + validator(arg) def test_validators(): diff --git a/lib/matplotlib/tests/test_subplots.py b/lib/matplotlib/tests/test_subplots.py index 9acbc8bb1454..2b2562a52449 100644 --- a/lib/matplotlib/tests/test_subplots.py +++ b/lib/matplotlib/tests/test_subplots.py @@ -106,17 +106,22 @@ def test_shared(): def test_exceptions(): # TODO should this test more options? - pytest.raises(ValueError, plt.subplots, 2, 2, sharex='blah') - pytest.raises(ValueError, plt.subplots, 2, 2, sharey='blah') + with pytest.raises(ValueError): + plt.subplots(2, 2, sharex='blah') + with pytest.raises(ValueError): + plt.subplots(2, 2, sharey='blah') # We filter warnings in this test which are genuine since # the pount of this test is to ensure that this raises. with warnings.catch_warnings(): warnings.filterwarnings('ignore', message='.*sharex\ argument\ to\ subplots', category=UserWarning) - pytest.raises(ValueError, plt.subplots, 2, 2, -1) - pytest.raises(ValueError, plt.subplots, 2, 2, 0) - pytest.raises(ValueError, plt.subplots, 2, 2, 5) + with pytest.raises(ValueError): + plt.subplots(2, 2, -1) + with pytest.raises(ValueError): + plt.subplots(2, 2, 0) + with pytest.raises(ValueError): + plt.subplots(2, 2, 5) @image_comparison(baseline_images=['subplots_offset_text'], remove_text=False) diff --git a/lib/matplotlib/tests/test_text.py b/lib/matplotlib/tests/test_text.py index 11d9b3c527bd..cddda99c547b 100644 --- a/lib/matplotlib/tests/test_text.py +++ b/lib/matplotlib/tests/test_text.py @@ -290,7 +290,8 @@ def test_get_rotation_raises(): if sys.version_info[:2] < (2, 7): raise pytest.skip("assert_raises as context manager " "not supported with Python < 2.7") - pytest.raises(ValueError, text.get_rotation, 'hozirontal') + with pytest.raises(ValueError): + text.get_rotation('hozirontal') def test_get_rotation_none(): diff --git a/lib/matplotlib/tests/test_ticker.py b/lib/matplotlib/tests/test_ticker.py index b9bf4912f328..8e595a12bf29 100644 --- a/lib/matplotlib/tests/test_ticker.py +++ b/lib/matplotlib/tests/test_ticker.py @@ -53,7 +53,8 @@ def test_AutoMinorLocator(): def test_LogLocator(): loc = mticker.LogLocator(numticks=5) - pytest.raises(ValueError, loc.tick_values, 0, 1000) + with pytest.raises(ValueError): + loc.tick_values(0, 1000) test_value = np.array([1.00000000e-05, 1.00000000e-03, 1.00000000e-01, 1.00000000e+01, 1.00000000e+03, 1.00000000e+05, diff --git a/lib/matplotlib/tests/test_triangulation.py b/lib/matplotlib/tests/test_triangulation.py index 90b01bc86aaa..795b465fee1b 100644 --- a/lib/matplotlib/tests/test_triangulation.py +++ b/lib/matplotlib/tests/test_triangulation.py @@ -85,7 +85,8 @@ def test_delaunay_points_in_line(): # that delaunay code fails gracefully. x = np.linspace(0.0, 10.0, 11) y = np.linspace(0.0, 10.0, 11) - pytest.raises(RuntimeError, mtri.Triangulation, x, y) + with pytest.raises(RuntimeError): + mtri.Triangulation(x, y) # Add an extra point not on the line and the triangulation is OK. x = np.append(x, 2.0) @@ -95,16 +96,21 @@ def test_delaunay_points_in_line(): def test_delaunay_insufficient_points(): # Triangulation should raise a ValueError if passed less than 3 points. - pytest.raises(ValueError, mtri.Triangulation, [], []) - pytest.raises(ValueError, mtri.Triangulation, [1], [5]) - pytest.raises(ValueError, mtri.Triangulation, [1, 2], [5, 6]) + with pytest.raises(ValueError): + mtri.Triangulation([], []) + with pytest.raises(ValueError): + mtri.Triangulation([1], [5]) + with pytest.raises(ValueError): + mtri.Triangulation([1, 2], [5, 6]) # Triangulation should also raise a ValueError if passed duplicate points # such that there are less than 3 unique points. - pytest.raises(ValueError, mtri.Triangulation, [1, 2, 1], [5, 6, 5]) - pytest.raises(ValueError, mtri.Triangulation, [1, 2, 2], [5, 6, 6]) - pytest.raises(ValueError, mtri.Triangulation, [1, 1, 1, 2, 1, 2], - [5, 5, 5, 6, 5, 6]) + with pytest.raises(ValueError): + mtri.Triangulation([1, 2, 1], [5, 6, 5]) + with pytest.raises(ValueError): + mtri.Triangulation([1, 2, 2], [5, 6, 6]) + with pytest.raises(ValueError): + mtri.Triangulation([1, 1, 1, 2, 1, 2], [5, 5, 5, 6, 5, 6]) def test_delaunay_robust(): @@ -1029,4 +1035,5 @@ def test_tricontourf_decreasing_levels(): y = [0.0, 0.0, 1.0] z = [0.2, 0.4, 0.6] plt.figure() - pytest.raises(ValueError, plt.tricontourf, x, y, z, [1.0, 0.0]) + with pytest.raises(ValueError): + plt.tricontourf(x, y, z, [1.0, 0.0]) diff --git a/lib/mpl_toolkits/tests/test_mplot3d.py b/lib/mpl_toolkits/tests/test_mplot3d.py index 87b405e2020d..e5a9638f33d3 100644 --- a/lib/mpl_toolkits/tests/test_mplot3d.py +++ b/lib/mpl_toolkits/tests/test_mplot3d.py @@ -325,4 +325,5 @@ def test_plotsurface_1d_raises(): fig = plt.figure(figsize=(14,6)) ax = fig.add_subplot(1, 2, 1, projection='3d') - pytest.raises(ValueError, ax.plot_surface, X, Y, z) + with pytest.raises(ValueError): + ax.plot_surface(X, Y, z) From a135e566a7779d576555de2c78268d584a60e7b3 Mon Sep 17 00:00:00 2001 From: Jason King Date: Sat, 23 Jan 2016 14:02:53 +1100 Subject: [PATCH 170/174] fix test_positional_parameter_names_as_function , seems getting a ValueError is also valid for this test, due to the number of function arguments --- lib/matplotlib/tests/test_labeled_data_unpacking.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/matplotlib/tests/test_labeled_data_unpacking.py b/lib/matplotlib/tests/test_labeled_data_unpacking.py index d898d0841e10..a5110266cbb0 100644 --- a/lib/matplotlib/tests/test_labeled_data_unpacking.py +++ b/lib/matplotlib/tests/test_labeled_data_unpacking.py @@ -409,7 +409,7 @@ def funcy(ax, *args, **kwargs): def f(): assert funcy(None, "x", "y", "c", "x", "y", "x", "y", data=data) == \ "('X', 'Y', 'c', 'X', 'Y', 'X', 'Y') | {}" - with pytest.raises(AssertionError): + with pytest.raises((AssertionError, ValueError)): f() # In the two arg case, if a valid color spec is in data, we warn but use From e52e0fc5a25a7aa71deb0e34dcf9ce58a238ca78 Mon Sep 17 00:00:00 2001 From: Jason King Date: Sat, 23 Jan 2016 14:04:37 +1100 Subject: [PATCH 171/174] PEP8 E201 in test_stride_windows_0D_ValueError, test_mlab.py --- lib/matplotlib/tests/test_mlab.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/matplotlib/tests/test_mlab.py b/lib/matplotlib/tests/test_mlab.py index d68fe84368c6..179006bbdcd2 100644 --- a/lib/matplotlib/tests/test_mlab.py +++ b/lib/matplotlib/tests/test_mlab.py @@ -128,7 +128,7 @@ def test_stride_windows_2D_ValueError(self): def test_stride_windows_0D_ValueError(self): x = np.array(0) with pytest.raises(ValueError): - mlab.stride_windows( x, 5) + mlab.stride_windows(x, 5) def test_stride_windows_noverlap_gt_n_ValueError(self): x = np.arange(10) From d2f4e6b8d5ba048f8c5e33e7561ae98638d8078d Mon Sep 17 00:00:00 2001 From: Jason King Date: Mon, 8 Feb 2016 13:00:09 +1100 Subject: [PATCH 172/174] as requested, push a simple change to test appveyor --- tox.ini | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tox.ini b/tox.ini index 47b63f160ef5..2f6bf5795692 100644 --- a/tox.ini +++ b/tox.ini @@ -3,6 +3,8 @@ # test suite on all supported python versions. To use it, "pip install tox" # and then run "tox" from this directory. +# Please delete this line at your convenience. just to force a rebuild + [tox] envlist = py26, py27, py31, py32 From bf19dadab1404580d56e4cb0388725ae3a6715b4 Mon Sep 17 00:00:00 2001 From: Jason King Date: Wed, 10 Feb 2016 12:26:35 +1100 Subject: [PATCH 173/174] trying to get pytest to recognise dynamically created test functions that have the image_comparison decorator. After asking on irc, seems this is the way to do it. Just checking in what I have so I can rebase again. --- lib/matplotlib/tests/conftest.py | 108 +++++++++++++++++++++++++++++++ 1 file changed, 108 insertions(+) create mode 100644 lib/matplotlib/tests/conftest.py 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 From f1111938bc65d8e57ebb99c31d7f043d25a3736d Mon Sep 17 00:00:00 2001 From: Jason King Date: Wed, 10 Feb 2016 12:29:01 +1100 Subject: [PATCH 174/174] make tests.py handle single modules better --- tests.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/tests.py b/tests.py index 5a3b7c771306..0d8d9343597f 100755 --- a/tests.py +++ b/tests.py @@ -24,14 +24,15 @@ def run(extra_args): argv = sys.argv + extra_args # pytest.main(['--pyargs', '--cov=matplotlib'] + default_test_modules) - print(argv + ['--pyargs'] + default_test_modules) + print(argv) + print(['--pyargs'] + default_test_modules) # if a specific test module is in argv, run that instead of all tests for argument in sys.argv: if argument in default_test_modules: # might need to insert a "--pyargs" into argv before passing # to pytest.main - return pytest.main(argv) + return pytest.main(['--pyargs'] + argv[1:]) else: pytest.main(['--traceconfig']) return pytest.main(argv + ['--pyargs'] + default_test_modules +