From 17fe952cc82637f478d2fcd800a3e0f4800ae091 Mon Sep 17 00:00:00 2001 From: Elliott Sales de Andrade Date: Thu, 20 Oct 2016 04:28:05 -0400 Subject: [PATCH 1/4] TST: Run nose2pytest on a few files. --- lib/matplotlib/tests/test_animation.py | 32 +++++------ lib/matplotlib/tests/test_axes.py | 78 +++++++++++++------------- lib/matplotlib/tests/test_cbook.py | 71 ++++++++++++----------- lib/matplotlib/tests/test_rcparams.py | 20 +++---- lib/matplotlib/tests/test_ticker.py | 69 +++++++++++------------ 5 files changed, 132 insertions(+), 138 deletions(-) diff --git a/lib/matplotlib/tests/test_animation.py b/lib/matplotlib/tests/test_animation.py index bcef70acfae2..c22eda508914 100644 --- a/lib/matplotlib/tests/test_animation.py +++ b/lib/matplotlib/tests/test_animation.py @@ -7,8 +7,6 @@ import sys import tempfile import numpy as np -from numpy.testing import assert_equal -from nose.tools import assert_false, assert_true import matplotlib as mpl from matplotlib import pyplot as plt from matplotlib import animation @@ -67,12 +65,12 @@ def animate(i): anim.save(filename, 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') @@ -174,23 +172,23 @@ def test_movie_writer_registry(): ffmpeg_path = mpl.rcParams['animation.ffmpeg_path'] # Not sure about the first state as there could be some writer # which set rcparams - #assert_false(animation.writers._dirty) - assert_true(len(animation.writers._registered) > 0) + # assert not animation.writers._dirty + assert len(animation.writers._registered) > 0 animation.writers.list() # resets dirty state - assert_false(animation.writers._dirty) + assert not animation.writers._dirty mpl.rcParams['animation.ffmpeg_path'] = u"not_available_ever_xxxx" - assert_true(animation.writers._dirty) + assert animation.writers._dirty animation.writers.list() # resets - assert_false(animation.writers._dirty) - assert_false(animation.writers.is_available("ffmpeg")) + assert not animation.writers._dirty + assert not animation.writers.is_available("ffmpeg") # something which is guaranteed to be available in path # and exits immediately bin = u"true" if sys.platform != 'win32' else u"where" mpl.rcParams['animation.ffmpeg_path'] = bin - assert_true(animation.writers._dirty) + assert animation.writers._dirty animation.writers.list() # resets - assert_false(animation.writers._dirty) - assert_true(animation.writers.is_available("ffmpeg")) + assert not animation.writers._dirty + assert animation.writers.is_available("ffmpeg") mpl.rcParams['animation.ffmpeg_path'] = ffmpeg_path diff --git a/lib/matplotlib/tests/test_axes.py b/lib/matplotlib/tests/test_axes.py index f1624d53ff1b..25382ff1ddb5 100644 --- a/lib/matplotlib/tests/test_axes.py +++ b/lib/matplotlib/tests/test_axes.py @@ -7,7 +7,7 @@ from distutils.version import LooseVersion import io -from nose.tools import assert_equal, assert_raises, assert_false, assert_true +from nose.tools import assert_raises from nose.plugins.skip import SkipTest import datetime @@ -129,22 +129,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 not ax2.xaxis.get_visible() + assert not ax2.patch.get_visible() ax2.cla() ax3.cla() - assert_false(ax2.xaxis.get_visible()) - assert_false(ax2.patch.get_visible()) - assert_true(ax2.yaxis.get_visible()) + assert not ax2.xaxis.get_visible() + assert not ax2.patch.get_visible() + assert ax2.yaxis.get_visible() - assert_true(ax3.xaxis.get_visible()) - assert_false(ax3.patch.get_visible()) - assert_false(ax3.yaxis.get_visible()) + assert ax3.xaxis.get_visible() + assert not ax3.patch.get_visible() + assert not ax3.yaxis.get_visible() - assert_true(ax.xaxis.get_visible()) - assert_true(ax.patch.get_visible()) - assert_true(ax.yaxis.get_visible()) + assert ax.xaxis.get_visible() + assert ax.patch.get_visible() + assert ax.yaxis.get_visible() @image_comparison(baseline_images=["minorticks_on_rcParams_both"], extensions=['png']) @@ -420,7 +420,6 @@ 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 units.register() pi = np.pi @@ -445,7 +444,7 @@ def test_polar_units(): # make sure runits and theta units work y1 = [y*km for y in y1] plt.polar(x2, y1, color="blue", thetaunits="rad", runits="km") - assert_true(isinstance(plt.gca().get_xaxis().get_major_formatter(), units.UnitDblFormatter)) + assert isinstance(plt.gca().get_xaxis().get_major_formatter(), units.UnitDblFormatter) @image_comparison(baseline_images=['polar_rmin']) @@ -2671,7 +2670,7 @@ def test_eventplot(): linelengths=linelengths) num_collections = len(colls) - np.testing.assert_equal(num_collections, num_datasets) + assert num_collections == num_datasets # Reuse testcase from above for a labeled data test data = {"pos": data, "c": colors, "lo": lineoffsets, "ll": linelengths} @@ -2680,7 +2679,7 @@ def test_eventplot(): colls = axobj.eventplot("pos", colors="c", lineoffsets="lo", linelengths="ll", data=data) num_collections = len(colls) - np.testing.assert_equal(num_collections, num_datasets) + assert num_collections == num_datasets @image_comparison(baseline_images=['test_eventplot_defaults'], extensions=['png'], remove_text=True) @@ -2727,9 +2726,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) - for wi in w)) + assert len(w) == 3 + assert all(issubclass(wi.category, IgnoredKeywordWarning) for wi in w) @cleanup @@ -2870,7 +2868,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 (5, 1, 0, None) == ax.get_subplotspec().get_geometry() @image_comparison(baseline_images=['specgram_freqs', @@ -3825,7 +3823,7 @@ def test_rcparam_grid_minor(): matplotlib.rcParams['axes.grid.which'] = locator fig = plt.figure() ax = fig.add_subplot(1, 1, 1) - assert((ax.xaxis._gridOnMajor, ax.xaxis._gridOnMinor) == result) + assert (ax.xaxis._gridOnMajor, ax.xaxis._gridOnMinor) == result matplotlib.rcParams['axes.grid'] = orig_grid matplotlib.rcParams['axes.grid.which'] = orig_locator @@ -4043,17 +4041,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 @@ -4074,7 +4072,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 @@ -4089,7 +4087,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 'lime' == line.get_color() @cleanup @@ -4120,7 +4118,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 (1, 0.5) == ax.yaxis.offsetText.get_position() @image_comparison(baseline_images=['rc_spines'], extensions=['png'], @@ -4209,11 +4207,11 @@ def test_rc_major_minor_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 @@ -4224,8 +4222,8 @@ 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) + assert ax.get_aspect() == 'equal' @cleanup @@ -4254,15 +4252,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 @@ -4336,9 +4334,9 @@ 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') diff --git a/lib/matplotlib/tests/test_cbook.py b/lib/matplotlib/tests/test_cbook.py index 7560f5ebf861..f5c73d36bca4 100644 --- a/lib/matplotlib/tests/test_cbook.py +++ b/lib/matplotlib/tests/test_cbook.py @@ -11,8 +11,7 @@ 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) +from nose.tools import raises, assert_raises import matplotlib.cbook as cbook import matplotlib.colors as mcolors @@ -21,20 +20,20 @@ def test_is_string_like(): y = np.arange(10) - assert_equal(cbook.is_string_like(y), False) + assert not cbook.is_string_like(y) y.shape = 10, 1 - assert_equal(cbook.is_string_like(y), False) + assert not cbook.is_string_like(y) y.shape = 1, 10 - assert_equal(cbook.is_string_like(y), False) + assert not cbook.is_string_like(y) assert cbook.is_string_like("hello world") - assert_equal(cbook.is_string_like(10), False) + assert not cbook.is_string_like(10) y = ['a', 'b', 'c'] - assert_equal(cbook.is_string_like(y), False) + assert not cbook.is_string_like(y) y = np.array(y) - assert_equal(cbook.is_string_like(y), False) + assert not cbook.is_string_like(y) y = np.array(y, dtype=object) assert cbook.is_string_like(y) @@ -59,17 +58,17 @@ def test_is_hashable(): 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 d2 == {} 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 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): @@ -117,11 +116,11 @@ def test_rgba(self): def test_allequal(): - assert(cbook.allequal([1, 1, 1])) - assert(not cbook.allequal([1, 1, 0])) - assert(cbook.allequal([])) - assert(cbook.allequal(('a', 'a'))) - assert(not cbook.allequal(('a', 'b'))) + assert cbook.allequal([1, 1, 1]) + assert not cbook.allequal([1, 1, 0]) + assert cbook.allequal([]) + assert cbook.allequal(('a', 'a')) + assert not cbook.allequal(('a', 'b')) class Test_boxplot_stats(object): @@ -176,17 +175,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] @@ -257,11 +256,11 @@ def test_results_withlabels(self): results = cbook.boxplot_stats(self.data, labels=labels) res = results[0] for lab, res in zip(labels, results): - assert_equal(res['label'], lab) + assert res['label'] == lab results = cbook.boxplot_stats(self.data) for res in results: - assert('label' not in res) + assert 'label' not in res @raises(ValueError) def test_label_error(self): @@ -279,12 +278,12 @@ def test_boxplot_stats_autorange_false(self): bstats_false = cbook.boxplot_stats(x, autorange=False) bstats_true = cbook.boxplot_stats(x, autorange=True) - assert_equal(bstats_false[0]['whislo'], 0) - assert_equal(bstats_false[0]['whishi'], 0) + assert bstats_false[0]['whislo'] == 0 + assert bstats_false[0]['whishi'] == 0 assert_array_almost_equal(bstats_false[0]['fliers'], [-25, 25]) - assert_equal(bstats_true[0]['whislo'], -25) - assert_equal(bstats_true[0]['whishi'], 25) + assert bstats_true[0]['whislo'] == -25 + assert bstats_true[0]['whishi'] == 25 assert_array_almost_equal(bstats_true[0]['fliers'], []) @@ -297,12 +296,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 @@ -313,15 +312,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) == 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_rcparams.py b/lib/matplotlib/tests/test_rcparams.py index 51a9e12124f7..745641637813 100644 --- a/lib/matplotlib/tests/test_rcparams.py +++ b/lib/matplotlib/tests/test_rcparams.py @@ -15,7 +15,7 @@ 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.tools import assert_raises import nose from itertools import chain import numpy as np @@ -157,13 +157,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" with assert_raises(ValueError): validate_bool_maybe_none("blah") @@ -180,7 +180,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(): @@ -225,12 +225,12 @@ 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): @@ -368,7 +368,7 @@ def test_validators(): def test_keymaps(): key_list = [k for k in mpl.rcParams if 'keymap' in k] for k in key_list: - assert(isinstance(mpl.rcParams[k], list)) + assert isinstance(mpl.rcParams[k], list) def test_rcparams_reset_after_fail(): diff --git a/lib/matplotlib/tests/test_ticker.py b/lib/matplotlib/tests/test_ticker.py index 117e7034fee1..fa8c7b9c636c 100644 --- a/lib/matplotlib/tests/test_ticker.py +++ b/lib/matplotlib/tests/test_ticker.py @@ -2,8 +2,7 @@ unicode_literals) import six -import nose.tools -from nose.tools import assert_equal, assert_raises +from nose.tools import assert_raises from numpy.testing import assert_almost_equal import numpy as np import matplotlib @@ -82,8 +81,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(): @@ -95,10 +94,10 @@ def test_LogLocator_set_params(): """ loc = mticker.LogLocator() loc.set_params(numticks=7, numdecs=8, subs=[2.0], base=4) - nose.tools.assert_equal(loc.numticks, 7) - nose.tools.assert_equal(loc.numdecs, 8) - nose.tools.assert_equal(loc._base, 4) - nose.tools.assert_equal(list(loc._subs), [2.0]) + assert loc.numticks == 7 + assert loc.numdecs == 8 + assert loc._base == 4 + assert list(loc._subs) == [2.0] def test_NullLocator_set_params(): @@ -110,7 +109,7 @@ def test_NullLocator_set_params(): with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") loc.set_params() - nose.tools.assert_equal(len(w), 1) + assert len(w) == 1 def test_MultipleLocator_set_params(): @@ -121,7 +120,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(): @@ -131,7 +130,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(): @@ -142,7 +141,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(): @@ -153,8 +152,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(): @@ -167,8 +166,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 @cleanup @@ -180,7 +179,7 @@ def check_offset_for(left, right, offset): ax.set_xlim(left, right) # Update ticks. next(ax.get_xaxis().iter_ticks()) - assert_equal(formatter.offset, offset) + assert formatter.offset == offset test_data = [(123, 189, 0), (-189, -123, 0), @@ -226,7 +225,7 @@ def _sub_labels(axis, subs=()): coefs = minor_tlocs / 10**(np.floor(np.log10(minor_tlocs))) label_expected = [np.round(c) in subs for c in coefs] label_test = [fmt(x) != '' for x in minor_tlocs] - assert_equal(label_test, label_expected) + assert label_test == label_expected @cleanup @@ -263,7 +262,7 @@ def test_LogFormatter_sublabel(): 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(): @@ -286,7 +285,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]) @@ -333,13 +332,13 @@ def test_LogFormatterSciNotation(): formatter.sublabel = set([1, 2, 5, 1.2]) for value, expected in test_cases[base]: with matplotlib.rc_context({'text.usetex': False}): - nose.tools.assert_equal(formatter(value), expected) + assert formatter(value) == expected 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(): @@ -486,26 +485,26 @@ 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) def _percent_format_helper(xmax, decimals, symbol, x, display_range, expected): formatter = mticker.PercentFormatter(xmax, decimals, symbol) - nose.tools.assert_equal(formatter.format_pct(x, display_range), expected) + assert formatter.format_pct(x, display_range) == expected # test str.format() style formatter with `pos` tmp_form = mticker.StrMethodFormatter('{x:03d}-{pos:02d}') - nose.tools.assert_equal('002-01', tmp_form(2, 1)) + assert '002-01' == tmp_form(2, 1) def test_percentformatter(): @@ -544,16 +543,16 @@ def test_EngFormatter_formatting(): Should not raise exceptions. """ unitless = mticker.EngFormatter() - nose.tools.assert_equal(unitless(0.1), u'100 m') - nose.tools.assert_equal(unitless(1), u'1') - nose.tools.assert_equal(unitless(999.9), u'999.9') - nose.tools.assert_equal(unitless(1001), u'1.001 k') + assert unitless(0.1) == u'100 m' + assert unitless(1) == u'1' + assert unitless(999.9) == u'999.9' + assert unitless(1001) == u'1.001 k' with_unit = mticker.EngFormatter(unit=u's') - nose.tools.assert_equal(with_unit(0.1), u'100 ms') - nose.tools.assert_equal(with_unit(1), u'1 s') - nose.tools.assert_equal(with_unit(999.9), u'999.9 s') - nose.tools.assert_equal(with_unit(1001), u'1.001 ks') + assert with_unit(0.1) == u'100 ms' + assert with_unit(1) == u'1 s' + assert with_unit(999.9) == u'999.9 s' + assert with_unit(1001) == u'1.001 ks' if __name__ == '__main__': import nose From ba30f11c0e1bc84dff2597ecf97239442d61ac79 Mon Sep 17 00:00:00 2001 From: Elliott Sales de Andrade Date: Thu, 20 Oct 2016 19:20:33 -0400 Subject: [PATCH 2/4] TST: Parametrize tests that were using yield. --- lib/matplotlib/tests/test_animation.py | 27 +-- lib/matplotlib/tests/test_axes.py | 76 +++++---- lib/matplotlib/tests/test_cbook.py | 103 ++++++----- lib/matplotlib/tests/test_rcparams.py | 102 +++++------ lib/matplotlib/tests/test_ticker.py | 225 ++++++++++++------------- 5 files changed, 273 insertions(+), 260 deletions(-) diff --git a/lib/matplotlib/tests/test_animation.py b/lib/matplotlib/tests/test_animation.py index c22eda508914..492c252aa79e 100644 --- a/lib/matplotlib/tests/test_animation.py +++ b/lib/matplotlib/tests/test_animation.py @@ -6,7 +6,10 @@ import os import sys import tempfile + import numpy as np +import pytest + import matplotlib as mpl from matplotlib import pyplot as plt from matplotlib import animation @@ -91,23 +94,25 @@ def isAvailable(self): return True -WRITER_OUTPUT = dict(ffmpeg='mp4', ffmpeg_file='mp4', - mencoder='mp4', mencoder_file='mp4', - avconv='mp4', avconv_file='mp4', - imagemagick='gif', imagemagick_file='gif', - null='null') +WRITER_OUTPUT = [ + ('ffmpeg', 'mp4'), + ('ffmpeg_file', 'mp4'), + ('mencoder', 'mp4'), + ('mencoder_file', 'mp4'), + ('avconv', 'mp4'), + ('avconv_file', 'mp4'), + ('imagemagick', 'gif'), + ('imagemagick_file', 'gif'), + ('null', 'null') +] # Smoke test for saving animations. In the future, we should probably # design more sophisticated tests which compare resulting frames a-la # matplotlib.testing.image_comparison -def test_save_animation_smoketest(): - for writer, extension in six.iteritems(WRITER_OUTPUT): - yield check_save_animation, writer, extension - - @cleanup -def check_save_animation(writer, extension='mp4'): +@pytest.mark.parametrize('writer, extension', WRITER_OUTPUT) +def test_save_animation_smoketest(writer, extension): try: # for ImageMagick the rcparams must be patched to account for # 'convert' being a built in MS tool, not the imagemagick diff --git a/lib/matplotlib/tests/test_axes.py b/lib/matplotlib/tests/test_axes.py index 25382ff1ddb5..7694828a01be 100644 --- a/lib/matplotlib/tests/test_axes.py +++ b/lib/matplotlib/tests/test_axes.py @@ -18,6 +18,7 @@ from numpy import ma from numpy import arange from cycler import cycler +import pytest import warnings @@ -4269,13 +4270,7 @@ def test_violin_point_mass(): plt.violinplot(np.array([0, 0])) -def _eb_succes_helper(ax, x, y, xerr=None, yerr=None): - eb = ax.errorbar(x, y, xerr=xerr, yerr=yerr) - eb.remove() - - -@cleanup -def test_errorbar_inputs_shotgun(): +def generate_errorbar_inputs(): base_xy = cycler('x', [np.arange(5)]) + cycler('y', [np.ones((5, ))]) err_cycler = cycler('err', [1, [1, 1, 1, 1, 1], @@ -4296,15 +4291,17 @@ def test_errorbar_inputs_shotgun(): yerr_only = base_xy * yerr_cy both_err = base_xy * yerr_cy * xerr_cy - test_cyclers = xerr_only, yerr_only, both_err, empty + test_cyclers = chain(xerr_only, yerr_only, both_err, empty) + + return test_cyclers + +@cleanup +@pytest.mark.parametrize('kwargs', generate_errorbar_inputs()) +def test_errorbar_inputs_shotgun(kwargs): ax = plt.gca() - # should do this as a generative test, but @cleanup seems to break that - # for p in chain(*test_cyclers): - # yield (_eb_succes_helper, ax) + tuple(p.get(k, None) for - # k in ['x', 'y', 'xerr', 'yerr']) - for p in chain(*test_cyclers): - _eb_succes_helper(ax, **p) + eb = ax.errorbar(**kwargs) + eb.remove() @cleanup @@ -4386,8 +4383,8 @@ def test_axes_margins(): assert ax.get_ybound() == (-0.5, 9.5) -@cleanup -def test_remove_shared_axes(): +@pytest.fixture(params=['x', 'y']) +def shared_axis_remover(request): def _helper_x(ax): ax2 = ax.twinx() ax2.remove() @@ -4402,26 +4399,43 @@ def _helper_y(ax): r = ax.yaxis.get_major_locator()() assert r[-1] > 14 + if request.param == 'x': + return _helper_x + elif request.param == 'y': + return _helper_y + else: + assert False, 'Request param %s is invalid.' % (request.param, ) + + +@pytest.fixture(params=['gca', 'subplots', 'subplots_shared', 'add_axes']) +def shared_axes_generator(request): # test all of the ways to get fig/ax sets - fig = plt.figure() - ax = fig.gca() - yield _helper_x, ax - yield _helper_y, ax + if request.param == 'gca': + fig = plt.figure() + ax = fig.gca() + elif request.param == 'subplots': + fig, ax = plt.subplots() + elif request.param == 'subplots_shared': + fig, ax_lst = plt.subplots(2, 2, sharex='all', sharey='all') + ax = ax_lst[0][0] + elif request.param == 'add_axes': + fig = plt.figure() + ax = fig.add_axes([.1, .1, .8, .8]) + else: + assert False, 'Request param %s is invalid.' % (request.param, ) - fig, ax = plt.subplots() - yield _helper_x, ax - yield _helper_y, ax + return fig, ax - fig, ax_lst = plt.subplots(2, 2, sharex='all', sharey='all') - ax = ax_lst[0][0] - yield _helper_x, ax - yield _helper_y, ax - fig = plt.figure() - ax = fig.add_axes([.1, .1, .8, .8]) - yield _helper_x, ax - yield _helper_y, ax +@cleanup +def test_remove_shared_axes(shared_axes_generator, shared_axis_remover): + # test all of the ways to get fig/ax sets + fig, ax = shared_axes_generator + shared_axis_remover(ax) + +@cleanup +def test_remove_shared_axes_relim(): fig, ax_lst = plt.subplots(2, 2, sharex='all', sharey='all') ax = ax_lst[0][0] orig_xlim = ax_lst[0][1].get_xlim() diff --git a/lib/matplotlib/tests/test_cbook.py b/lib/matplotlib/tests/test_cbook.py index f5c73d36bca4..5960467b65eb 100644 --- a/lib/matplotlib/tests/test_cbook.py +++ b/lib/matplotlib/tests/test_cbook.py @@ -12,6 +12,7 @@ from numpy.testing.utils import (assert_array_equal, assert_approx_equal, assert_array_almost_equal) from nose.tools import raises, assert_raises +import pytest import matplotlib.cbook as cbook import matplotlib.colors as mcolors @@ -343,65 +344,61 @@ def test_sanitize_sequence(): assert k == cbook.sanitize_sequence(k) -def _kwarg_norm_helper(inp, expected, kwargs_to_norm, warn_count=0): - +fail_mapping = ( + ({'a': 1}, {'forbidden': ('a')}), + ({'a': 1}, {'required': ('b')}), + ({'a': 1, 'b': 2}, {'required': ('a'), 'allowed': ()}) +) + +warn_passing_mapping = ( + ({'a': 1, 'b': 2}, {'a': 1}, {'alias_mapping': {'a': ['b']}}, 1), + ({'a': 1, 'b': 2}, {'a': 1}, + {'alias_mapping': {'a': ['b']}, 'allowed': ('a',)}, 1), + ({'a': 1, 'b': 2}, {'a': 2}, {'alias_mapping': {'a': ['a', 'b']}}, 1), + ({'a': 1, 'b': 2, 'c': 3}, {'a': 1, 'c': 3}, + {'alias_mapping': {'a': ['b']}, 'required': ('a', )}, 1), +) + +pass_mapping = ( + ({'a': 1, 'b': 2}, {'a': 1, 'b': 2}, {}), + ({'b': 2}, {'a': 2}, {'alias_mapping': {'a': ['a', 'b']}}), + ({'b': 2}, {'a': 2}, + {'alias_mapping': {'a': ['b']}, 'forbidden': ('b', )}), + ({'a': 1, 'c': 3}, {'a': 1, 'c': 3}, + {'required': ('a', ), 'allowed': ('c', )}), + ({'a': 1, 'c': 3}, {'a': 1, 'c': 3}, + {'required': ('a', 'c'), 'allowed': ('c', )}), + ({'a': 1, 'c': 3}, {'a': 1, 'c': 3}, + {'required': ('a', 'c'), 'allowed': ('a', 'c')}), + ({'a': 1, 'c': 3}, {'a': 1, 'c': 3}, + {'required': ('a', 'c'), 'allowed': ()}), + ({'a': 1, 'c': 3}, {'a': 1, 'c': 3}, {'required': ('a', 'c')}), + ({'a': 1, 'c': 3}, {'a': 1, 'c': 3}, {'allowed': ('a', 'c')}), +) + + +@pytest.mark.parametrize('inp, kwargs_to_norm', fail_mapping) +def test_normalize_kwargs_fail(inp, kwargs_to_norm): + with pytest.raises(TypeError): + cbook.normalize_kwargs(inp, **kwargs_to_norm) + + +@pytest.mark.parametrize('inp, expected, kwargs_to_norm, warn_count', + warn_passing_mapping) +def test_normalize_kwargs_warn(inp, expected, kwargs_to_norm, warn_count): with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") assert expected == cbook.normalize_kwargs(inp, **kwargs_to_norm) assert len(w) == warn_count -def _kwarg_norm_fail_helper(inp, kwargs_to_norm): - assert_raises(TypeError, cbook.normalize_kwargs, inp, **kwargs_to_norm) - - -def test_normalize_kwargs(): - fail_mapping = ( - ({'a': 1}, {'forbidden': ('a')}), - ({'a': 1}, {'required': ('b')}), - ({'a': 1, 'b': 2}, {'required': ('a'), 'allowed': ()}) - ) - - for inp, kwargs in fail_mapping: - yield _kwarg_norm_fail_helper, inp, kwargs - - warn_passing_mapping = ( - ({'a': 1, 'b': 2}, {'a': 1}, {'alias_mapping': {'a': ['b']}}, 1), - ({'a': 1, 'b': 2}, {'a': 1}, {'alias_mapping': {'a': ['b']}, - 'allowed': ('a',)}, 1), - ({'a': 1, 'b': 2}, {'a': 2}, {'alias_mapping': {'a': ['a', 'b']}}, 1), - - ({'a': 1, 'b': 2, 'c': 3}, {'a': 1, 'c': 3}, - {'alias_mapping': {'a': ['b']}, 'required': ('a', )}, 1), - - ) - - for inp, exp, kwargs, wc in warn_passing_mapping: - yield _kwarg_norm_helper, inp, exp, kwargs, wc - - pass_mapping = ( - ({'a': 1, 'b': 2}, {'a': 1, 'b': 2}, {}), - ({'b': 2}, {'a': 2}, {'alias_mapping': {'a': ['a', 'b']}}), - ({'b': 2}, {'a': 2}, {'alias_mapping': {'a': ['b']}, - 'forbidden': ('b', )}), - - ({'a': 1, 'c': 3}, {'a': 1, 'c': 3}, {'required': ('a', ), - 'allowed': ('c', )}), - - ({'a': 1, 'c': 3}, {'a': 1, 'c': 3}, {'required': ('a', 'c'), - 'allowed': ('c', )}), - ({'a': 1, 'c': 3}, {'a': 1, 'c': 3}, {'required': ('a', 'c'), - 'allowed': ('a', 'c')}), - ({'a': 1, 'c': 3}, {'a': 1, 'c': 3}, {'required': ('a', 'c'), - 'allowed': ()}), - - ({'a': 1, 'c': 3}, {'a': 1, 'c': 3}, {'required': ('a', 'c')}), - ({'a': 1, 'c': 3}, {'a': 1, 'c': 3}, {'allowed': ('a', 'c')}), - - ) - - for inp, exp, kwargs in pass_mapping: - yield _kwarg_norm_helper, inp, exp, kwargs +@pytest.mark.parametrize('inp, expected, kwargs_to_norm', + pass_mapping) +def test_normalize_kwargs_pass(inp, expected, kwargs_to_norm): + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + assert expected == cbook.normalize_kwargs(inp, **kwargs_to_norm) + assert len(w) == 0 def test_to_prestep(): diff --git a/lib/matplotlib/tests/test_rcparams.py b/lib/matplotlib/tests/test_rcparams.py index 745641637813..62d7d7928e89 100644 --- a/lib/matplotlib/tests/test_rcparams.py +++ b/lib/matplotlib/tests/test_rcparams.py @@ -9,6 +9,7 @@ from collections import OrderedDict from cycler import cycler, Cycler +import pytest import matplotlib as mpl import matplotlib.pyplot as plt @@ -174,8 +175,33 @@ def test_Bug_2543(): mpl.rcParams['svg.fonttype'] = True +legend_color_tests = [ + ('face', {'color': 'r'}, mcolors.to_rgba('r')), + ('face', {'color': 'inherit', 'axes.facecolor': 'r'}, + mcolors.to_rgba('r')), + ('face', {'color': 'g', 'axes.facecolor': 'r'}, mcolors.to_rgba('g')), + ('edge', {'color': 'r'}, mcolors.to_rgba('r')), + ('edge', {'color': 'inherit', 'axes.edgecolor': 'r'}, + mcolors.to_rgba('r')), + ('edge', {'color': 'g', 'axes.facecolor': 'r'}, mcolors.to_rgba('g')) +] +legend_color_test_ids = [ + 'same facecolor', + 'inherited facecolor', + 'different facecolor', + 'same edgecolor', + 'inherited edgecolor', + 'different facecolor', +] + + @cleanup -def _legend_rcparam_helper(param_dict, target, get_func): +@pytest.mark.parametrize('color_type, param_dict, target', legend_color_tests, + ids=legend_color_test_ids) +def test_legend_colors(color_type, param_dict, target): + param_dict['legend.%scolor' % (color_type, )] = param_dict.pop('color') + get_func = 'get_%scolor' % (color_type, ) + with mpl.rc_context(param_dict): _, ax = plt.subplots() ax.plot(range(3), label='test') @@ -183,32 +209,6 @@ def _legend_rcparam_helper(param_dict, target, get_func): assert getattr(leg.legendPatch, get_func)() == target -def test_legend_facecolor(): - get_func = 'get_facecolor' - rcparam = 'legend.facecolor' - test_values = [({rcparam: 'r'}, - mcolors.to_rgba('r')), - ({rcparam: 'inherit', 'axes.facecolor': 'r'}, - mcolors.to_rgba('r')), - ({rcparam: 'g', 'axes.facecolor': 'r'}, - mcolors.to_rgba('g'))] - for rc_dict, target in test_values: - yield _legend_rcparam_helper, rc_dict, target, get_func - - -def test_legend_edgecolor(): - get_func = 'get_edgecolor' - rcparam = 'legend.edgecolor' - test_values = [({rcparam: 'r'}, - mcolors.to_rgba('r')), - ({rcparam: 'inherit', 'axes.edgecolor': 'r'}, - mcolors.to_rgba('r')), - ({rcparam: 'g', 'axes.facecolor': 'r'}, - mcolors.to_rgba('g'))] - for rc_dict, target in test_values: - yield _legend_rcparam_helper, rc_dict, target, get_func - - def test_Issue_1713(): utf32_be = os.path.join(os.path.dirname(__file__), 'test_utf32_be_rcparams.rc') @@ -222,23 +222,7 @@ def test_Issue_1713(): assert rc.get('timezone') == 'UTC' -def _validation_test_helper(validator, arg, target): - res = validator(arg) - if isinstance(target, np.ndarray): - assert np.all(res == target) - elif not isinstance(target, Cycler): - assert res == target - else: - # Cyclers can't simply be asserted equal. They don't implement __eq__ - assert list(res) == list(target) - - -def _validation_fail_helper(validator, arg, exception_type): - with assert_raises(exception_type): - validator(arg) - - -def test_validators(): +def generate_validator_testcases(valid): validation_tests = ( {'validator': validate_bool, 'success': chain(((_, True) for _ in @@ -359,10 +343,32 @@ def test_validators(): for validator_dict in validation_tests: validator = validator_dict['validator'] - for arg, target in validator_dict['success']: - yield _validation_test_helper, validator, arg, target - for arg, error_type in validator_dict['fail']: - yield _validation_fail_helper, validator, arg, error_type + if valid: + for arg, target in validator_dict['success']: + yield validator, arg, target + else: + for arg, error_type in validator_dict['fail']: + yield validator, arg, error_type + + +@pytest.mark.parametrize('validator, arg, target', + generate_validator_testcases(True)) +def test_validator_valid(validator, arg, target): + res = validator(arg) + if isinstance(target, np.ndarray): + assert np.all(res == target) + elif not isinstance(target, Cycler): + assert res == target + else: + # Cyclers can't simply be asserted equal. They don't implement __eq__ + assert list(res) == list(target) + + +@pytest.mark.parametrize('validator, arg, exception_type', + generate_validator_testcases(False)) +def test_validator_invalid(validator, arg, exception_type): + with assert_raises(exception_type): + validator(arg) def test_keymaps(): diff --git a/lib/matplotlib/tests/test_ticker.py b/lib/matplotlib/tests/test_ticker.py index fa8c7b9c636c..bb012a6f4971 100644 --- a/lib/matplotlib/tests/test_ticker.py +++ b/lib/matplotlib/tests/test_ticker.py @@ -2,9 +2,12 @@ unicode_literals) import six + from nose.tools import assert_raises from numpy.testing import assert_almost_equal import numpy as np +import pytest + import matplotlib import matplotlib.pyplot as plt import matplotlib.ticker as mticker @@ -171,50 +174,50 @@ def test_SymmetricalLogLocator_set_params(): @cleanup -def test_ScalarFormatter_offset_value(): +@pytest.mark.parametrize('left, right, offset', + [(123, 189, 0), + (-189, -123, 0), + (12341, 12349, 12340), + (-12349, -12341, -12340), + (99999.5, 100010.5, 100000), + (-100010.5, -99999.5, -100000), + (99990.5, 100000.5, 100000), + (-100000.5, -99990.5, -100000), + (1233999, 1234001, 1234000), + (-1234001, -1233999, -1234000), + (1, 1, 1), + (123, 123, 120), + # Test cases courtesy of @WeatherGod + (.4538, .4578, .45), + (3789.12, 3783.1, 3780), + (45124.3, 45831.75, 45000), + (0.000721, 0.0007243, 0.00072), + (12592.82, 12591.43, 12590), + (9., 12., 0), + (900., 1200., 0), + (1900., 1200., 0), + (0.99, 1.01, 1), + (9.99, 10.01, 10), + (99.99, 100.01, 100), + (5.99, 6.01, 6), + (15.99, 16.01, 16), + (-0.452, 0.492, 0), + (-0.492, 0.492, 0), + (12331.4, 12350.5, 12300), + (-12335.3, 12335.3, 0)]) +def test_ScalarFormatter_offset_value(left, right, offset): fig, ax = plt.subplots() formatter = ax.get_xaxis().get_major_formatter() - def check_offset_for(left, right, offset): - ax.set_xlim(left, right) - # Update ticks. - next(ax.get_xaxis().iter_ticks()) - assert formatter.offset == offset - - test_data = [(123, 189, 0), - (-189, -123, 0), - (12341, 12349, 12340), - (-12349, -12341, -12340), - (99999.5, 100010.5, 100000), - (-100010.5, -99999.5, -100000), - (99990.5, 100000.5, 100000), - (-100000.5, -99990.5, -100000), - (1233999, 1234001, 1234000), - (-1234001, -1233999, -1234000), - (1, 1, 1), - (123, 123, 120), - # Test cases courtesy of @WeatherGod - (.4538, .4578, .45), - (3789.12, 3783.1, 3780), - (45124.3, 45831.75, 45000), - (0.000721, 0.0007243, 0.00072), - (12592.82, 12591.43, 12590), - (9., 12., 0), - (900., 1200., 0), - (1900., 1200., 0), - (0.99, 1.01, 1), - (9.99, 10.01, 10), - (99.99, 100.01, 100), - (5.99, 6.01, 6), - (15.99, 16.01, 16), - (-0.452, 0.492, 0), - (-0.492, 0.492, 0), - (12331.4, 12350.5, 12300), - (-12335.3, 12335.3, 0)] - - for left, right, offset in test_data: - yield check_offset_for, left, right, offset - yield check_offset_for, right, left, offset + ax.set_xlim(left, right) + # Update ticks. + next(ax.get_xaxis().iter_ticks()) + assert formatter.offset == offset + + ax.set_xlim(right, left) + # Update ticks. + next(ax.get_xaxis().iter_ticks()) + assert formatter.offset == offset def _sub_labels(axis, subs=()): @@ -259,50 +262,45 @@ def test_LogFormatter_sublabel(): _sub_labels(ax.xaxis, subs=[2, 3, 6]) -def _logfe_helper(formatter, base, locs, i, expected_result): +class FakeAxis(object): + """Allow Formatter to be called without having a "full" plot set up.""" + def __init__(self, vmin=1, vmax=10): + self.vmin = vmin + self.vmax = vmax + + def get_view_interval(self): + return self.vmin, self.vmax + + +@pytest.mark.parametrize( + 'labelOnlyBase, exponent, locs, positions, expected', + [ + (True, 4, np.arange(-3, 4.0), np.arange(-3, 4.0), + ['-3', '-2', '-1', '0', '1', '2', '3']), + # With labelOnlyBase=False, non-integer powers should be nicely + # formatted. + (False, 10, np.array([0.1, 0.00001, np.pi, 0.2, -0.2, -0.00001]), + range(6), ['0.1', '1e-05', '3.14', '0.2', '-0.2', '-1e-05']), + (False, 50, np.array([3, 5, 12, 42], dtype='float'), range(6), + ['3', '5', '12', '42']), + ]) +@pytest.mark.parametrize('base', [2.0, 5.0, 10.0, np.pi, np.e]) +def test_LogFormatterExponent(labelOnlyBase, base, exponent, + locs, positions, expected): + formatter = mticker.LogFormatterExponent(base=base, + labelOnlyBase=labelOnlyBase) + formatter.axis = FakeAxis(1, base**exponent) vals = base**locs - labels = [formatter(x, pos) for (x, pos) in zip(vals, i)] - assert labels == expected_result - - -def test_LogFormatterExponent(): - class FakeAxis(object): - """Allow Formatter to be called without having a "full" plot set up.""" - def __init__(self, vmin=1, vmax=10): - self.vmin = vmin - self.vmax = vmax + labels = [formatter(x, pos) for (x, pos) in zip(vals, positions)] + assert labels == expected - def get_view_interval(self): - return self.vmin, self.vmax - - i = np.arange(-3, 4, dtype=float) - expected_result = ['-3', '-2', '-1', '0', '1', '2', '3'] - for base in [2, 5.0, 10.0, np.pi, np.e]: - formatter = mticker.LogFormatterExponent(base=base) - formatter.axis = FakeAxis(1, base**4) - yield _logfe_helper, formatter, base, i, i, expected_result +def test_LogFormatterExponent_blank(): # Should be a blank string for non-integer powers if labelOnlyBase=True formatter = mticker.LogFormatterExponent(base=10, labelOnlyBase=True) formatter.axis = FakeAxis() 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]) - i = range(len(locs)) - expected_result = ['0.1', '1e-05', '3.14', '0.2', '-0.2', '-1e-05'] - for base in [2, 5, 10, np.pi, np.e]: - formatter = mticker.LogFormatterExponent(base, labelOnlyBase=False) - formatter.axis = FakeAxis(1, base**10) - yield _logfe_helper, formatter, base, locs, i, expected_result - - expected_result = ['3', '5', '12', '42'] - locs = np.array([3, 5, 12, 42], dtype='float') - for base in [2, 5.0, 10.0, np.pi, np.e]: - formatter = mticker.LogFormatterExponent(base, labelOnlyBase=False) - formatter.axis = FakeAxis(1, base**50) - yield _logfe_helper, formatter, base, locs, i, expected_result - def test_LogFormatterSciNotation(): test_cases = { @@ -335,14 +333,7 @@ def test_LogFormatterSciNotation(): assert formatter(value) == expected -def _pprint_helper(value, domain, expected): - fmt = mticker.LogFormatter() - label = fmt.pprint_val(value, domain) - assert label == expected - - -def test_logformatter_pprint(): - test_cases = ( +@pytest.mark.parametrize('value, domain, expected', [ (3.141592654e-05, 0.001, '3.142e-5'), (0.0003141592654, 0.001, '3.142e-4'), (0.003141592654, 0.001, '3.142e-3'), @@ -475,10 +466,11 @@ def test_logformatter_pprint(): (1000, 1000000.0, '1000'), (10000, 1000000.0, '1e4'), (100000, 1000000.0, '1e5') - ) - - for value, domain, expected in test_cases: - yield _pprint_helper, value, domain, expected +]) +def test_logformatter_pprint(value, domain, expected): + fmt = mticker.LogFormatter() + label = fmt.pprint_val(value, domain) + assert label == expected def test_use_offset(): @@ -498,7 +490,33 @@ def test_formatstrformatter(): assert '00002' == tmp_form(2) -def _percent_format_helper(xmax, decimals, symbol, x, display_range, expected): +percentformatter_test_cases = ( + # Check explicitly set decimals over different intervals and values + (100, 0, '%', 120, 100, '120%'), + (100, 0, '%', 100, 90, '100%'), + (100, 0, '%', 90, 50, '90%'), + (100, 0, '%', 1.7, 40, '2%'), + (100, 1, '%', 90.0, 100, '90.0%'), + (100, 1, '%', 80.1, 90, '80.1%'), + (100, 1, '%', 70.23, 50, '70.2%'), + # 60.554 instead of 60.55: see https://bugs.python.org/issue5118 + (100, 1, '%', 60.554, 40, '60.6%'), + # Check auto decimals over different intervals and values + (100, None, '%', 95, 1, '95.00%'), + (1.0, None, '%', 3, 6, '300%'), + (17.0, None, '%', 1, 8.5, '6%'), + (17.0, None, '%', 1, 8.4, '5.9%'), + (5, None, '%', -100, 0.000001, '-2000.00000%'), + # Check percent symbol + (1.0, 2, None, 1.2, 100, '120.00'), + (75, 3, '', 50, 100, '66.667'), + (42, None, '^^Foobar$$', 21, 12, '50.0^^Foobar$$'), +) + + +@pytest.mark.parametrize('xmax, decimals, symbol, x, display_range, expected', + percentformatter_test_cases) +def test_percentformatter(xmax, decimals, symbol, x, display_range, expected): formatter = mticker.PercentFormatter(xmax, decimals, symbol) assert formatter.format_pct(x, display_range) == expected @@ -507,33 +525,6 @@ def _percent_format_helper(xmax, decimals, symbol, x, display_range, expected): assert '002-01' == tmp_form(2, 1) -def test_percentformatter(): - test_cases = ( - # Check explicitly set decimals over different intervals and values - (100, 0, '%', 120, 100, '120%'), - (100, 0, '%', 100, 90, '100%'), - (100, 0, '%', 90, 50, '90%'), - (100, 0, '%', 1.7, 40, '2%'), - (100, 1, '%', 90.0, 100, '90.0%'), - (100, 1, '%', 80.1, 90, '80.1%'), - (100, 1, '%', 70.23, 50, '70.2%'), - # 60.554 instead of 60.55: see https://bugs.python.org/issue5118 - (100, 1, '%', 60.554, 40, '60.6%'), - # Check auto decimals over different intervals and values - (100, None, '%', 95, 1, '95.00%'), - (1.0, None, '%', 3, 6, '300%'), - (17.0, None, '%', 1, 8.5, '6%'), - (17.0, None, '%', 1, 8.4, '5.9%'), - (5, None, '%', -100, 0.000001, '-2000.00000%'), - # Check percent symbol - (1.0, 2, None, 1.2, 100, '120.00'), - (75, 3, '', 50, 100, '66.667'), - (42, None, '^^Foobar$$', 21, 12, '50.0^^Foobar$$'), - ) - for case in test_cases: - yield (_percent_format_helper,) + case - - def test_EngFormatter_formatting(): """ Create two instances of EngFormatter with default parameters, with and From 469e289a1abe37fa63475eb918138620f8803851 Mon Sep 17 00:00:00 2001 From: Elliott Sales de Andrade Date: Thu, 20 Oct 2016 21:24:30 -0400 Subject: [PATCH 3/4] TST: Remove nose functions in the last set of files. --- lib/matplotlib/tests/test_axes.py | 172 +++++++++++++++----------- lib/matplotlib/tests/test_cbook.py | 32 ++--- lib/matplotlib/tests/test_rcparams.py | 15 ++- lib/matplotlib/tests/test_ticker.py | 4 +- 4 files changed, 125 insertions(+), 98 deletions(-) diff --git a/lib/matplotlib/tests/test_axes.py b/lib/matplotlib/tests/test_axes.py index 7694828a01be..6841fcc5e824 100644 --- a/lib/matplotlib/tests/test_axes.py +++ b/lib/matplotlib/tests/test_axes.py @@ -7,9 +7,6 @@ from distutils.version import LooseVersion import io -from nose.tools import assert_raises -from nose.plugins.skip import SkipTest - import datetime import pytz @@ -375,7 +372,8 @@ def test_shaped_data(): plt.plot(y2) plt.subplot(413) - assert_raises(ValueError, plt.plot, (y1, y2)) + with pytest.raises(ValueError): + plt.plot((y1, y2)) plt.subplot(414) plt.plot(xdata[:, 1], xdata[1, :], 'o') @@ -863,12 +861,14 @@ def test_pcolorargs(): Z = np.sqrt(X**2 + Y**2)/5 _, ax = plt.subplots() - assert_raises(TypeError, ax.pcolormesh, y, x, Z) - assert_raises(TypeError, ax.pcolormesh, X, Y, Z.T) - assert_raises(TypeError, ax.pcolormesh, x, y, Z[:-1, :-1], - shading="gouraud") - assert_raises(TypeError, ax.pcolormesh, X, Y, Z[:-1, :-1], - shading="gouraud") + with pytest.raises(TypeError): + ax.pcolormesh(y, x, Z) + with pytest.raises(TypeError): + ax.pcolormesh(X, Y, Z.T) + with pytest.raises(TypeError): + ax.pcolormesh(x, y, Z[:-1, :-1], shading="gouraud") + with pytest.raises(TypeError): + ax.pcolormesh(X, Y, Z[:-1, :-1], shading="gouraud") @image_comparison(baseline_images=['canonical']) @@ -1316,13 +1316,15 @@ def test_scatter_2D(): fig, ax = plt.subplots() ax.scatter(x, y, c=z, s=200, edgecolors='face') + @cleanup def test_scatter_color(): # Try to catch cases where 'c' kwarg should have been used. - assert_raises(ValueError, plt.scatter, [1, 2], [1, 2], - color=[0.1, 0.2]) - assert_raises(ValueError, plt.scatter, [1, 2, 3], [1, 2, 3], - color=[1, 2, 3]) + with pytest.raises(ValueError): + plt.scatter([1, 2], [1, 2], color=[0.1, 0.2]) + with pytest.raises(ValueError): + plt.scatter([1, 2, 3], [1, 2, 3], color=[1, 2, 3]) + @cleanup def test_as_mpl_axes_api(): @@ -1813,7 +1815,8 @@ def test_bxp_bad_widths(): fig, ax = plt.subplots() ax.set_yscale('log') - assert_raises(ValueError, ax.bxp, logstats, widths=[1]) + with pytest.raises(ValueError): + ax.bxp(logstats, widths=[1]) @cleanup @@ -1825,7 +1828,8 @@ def test_bxp_bad_positions(): fig, ax = plt.subplots() ax.set_yscale('log') - assert_raises(ValueError, ax.bxp, logstats, positions=[2, 3]) + with pytest.raises(ValueError): + ax.bxp(logstats, positions=[2, 3]) @image_comparison(baseline_images=['boxplot', 'boxplot'], @@ -2010,7 +2014,8 @@ def test_boxplot_bad_medians_1(): x = np.linspace(-7, 7, 140) x = np.hstack([-25, x, 25]) fig, ax = plt.subplots() - assert_raises(ValueError, ax.boxplot, x, usermedians=[1, 2]) + with pytest.raises(ValueError): + ax.boxplot(x, usermedians=[1, 2]) @cleanup @@ -2018,7 +2023,8 @@ def test_boxplot_bad_medians_2(): x = np.linspace(-7, 7, 140) x = np.hstack([-25, x, 25]) fig, ax = plt.subplots() - assert_raises(ValueError, ax.boxplot, [x, x], usermedians=[[1, 2], [1, 2]]) + with pytest.raises(ValueError): + ax.boxplot([x, x], usermedians=[[1, 2], [1, 2]]) @cleanup @@ -2026,8 +2032,8 @@ def test_boxplot_bad_ci_1(): x = np.linspace(-7, 7, 140) x = np.hstack([-25, x, 25]) fig, ax = plt.subplots() - assert_raises(ValueError, ax.boxplot, [x, x], - conf_intervals=[[1, 2]]) + with pytest.raises(ValueError): + ax.boxplot([x, x], conf_intervals=[[1, 2]]) @cleanup @@ -2043,8 +2049,8 @@ def test_boxplot_bad_ci_2(): x = np.linspace(-7, 7, 140) x = np.hstack([-25, x, 25]) fig, ax = plt.subplots() - assert_raises(ValueError, ax.boxplot, [x, x], - conf_intervals=[[1, 2], [1]]) + with pytest.raises(ValueError): + ax.boxplot([x, x], conf_intervals=[[1, 2], [1]]) @image_comparison(baseline_images=['boxplot_mod_artists_after_plotting'], @@ -2227,7 +2233,8 @@ def test_violinplot_bad_positions(): # First 9 digits of frac(sqrt(47)) np.random.seed(855654600) data = [np.random.normal(size=100) for i in range(4)] - assert_raises(ValueError, ax.violinplot, data, positions=range(5)) + with pytest.raises(ValueError): + ax.violinplot(data, positions=range(5)) @cleanup @@ -2236,8 +2243,8 @@ def test_violinplot_bad_widths(): # First 9 digits of frac(sqrt(53)) np.random.seed(280109889) data = [np.random.normal(size=100) for i in range(4)] - assert_raises(ValueError, ax.violinplot, data, positions=range(4), - widths=[1, 2, 3]) + with pytest.raises(ValueError): + ax.violinplot(data, positions=range(4), widths=[1, 2, 3]) @cleanup @@ -2319,9 +2326,12 @@ def test_errorbar_shape(): yerr = np.vstack((yerr1, 2*yerr1)).T xerr = 0.1 + yerr - assert_raises(ValueError, ax.errorbar, x, y, yerr=yerr, fmt='o') - assert_raises(ValueError, ax.errorbar, x, y, xerr=xerr, fmt='o') - assert_raises(ValueError, ax.errorbar, x, y, yerr=yerr, xerr=xerr, fmt='o') + with pytest.raises(ValueError): + ax.errorbar(x, y, yerr=yerr, fmt='o') + with pytest.raises(ValueError): + ax.errorbar(x, y, xerr=xerr, fmt='o') + with pytest.raises(ValueError): + ax.errorbar(x, y, yerr=yerr, xerr=xerr, fmt='o') @image_comparison(baseline_images=['errorbar_limits']) @@ -3119,17 +3129,20 @@ 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, - noverlap=noverlap, pad_to=pad_to, sides='default', - mode='phase', scale='dB') + with pytest.raises(ValueError): + ax11.specgram(y, NFFT=NFFT, Fs=Fs, + noverlap=noverlap, pad_to=pad_to, sides='default', + mode='phase', scale='dB') - assert_raises(ValueError, ax12.specgram, y, NFFT=NFFT, Fs=Fs, - noverlap=noverlap, pad_to=pad_to, sides='onesided', - mode='phase', scale='dB') + with pytest.raises(ValueError): + ax12.specgram(y, NFFT=NFFT, Fs=Fs, + noverlap=noverlap, pad_to=pad_to, sides='onesided', + mode='phase', scale='dB') - assert_raises(ValueError, ax13.specgram, y, NFFT=NFFT, Fs=Fs, - noverlap=noverlap, pad_to=pad_to, sides='twosided', - mode='phase', scale='dB') + with pytest.raises(ValueError): + ax13.specgram(y, NFFT=NFFT, Fs=Fs, + noverlap=noverlap, pad_to=pad_to, sides='twosided', + mode='phase', scale='dB') @image_comparison(baseline_images=['specgram_angle_noise'], @@ -3166,17 +3179,20 @@ 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, - noverlap=noverlap, pad_to=pad_to, sides='default', - mode='phase', scale='dB') + with pytest.raises(ValueError): + ax11.specgram(y, NFFT=NFFT, Fs=Fs, + noverlap=noverlap, pad_to=pad_to, sides='default', + mode='phase', scale='dB') - assert_raises(ValueError, ax12.specgram, y, NFFT=NFFT, Fs=Fs, - noverlap=noverlap, pad_to=pad_to, sides='onesided', - mode='phase', scale='dB') + with pytest.raises(ValueError): + ax12.specgram(y, NFFT=NFFT, Fs=Fs, + noverlap=noverlap, pad_to=pad_to, sides='onesided', + mode='phase', scale='dB') - assert_raises(ValueError, ax13.specgram, y, NFFT=NFFT, Fs=Fs, - noverlap=noverlap, pad_to=pad_to, sides='twosided', - mode='phase', scale='dB') + with pytest.raises(ValueError): + ax13.specgram(y, NFFT=NFFT, Fs=Fs, + noverlap=noverlap, pad_to=pad_to, sides='twosided', + mode='phase', scale='dB') @image_comparison(baseline_images=['specgram_phase_freqs'], @@ -3221,17 +3237,20 @@ 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, - noverlap=noverlap, pad_to=pad_to, sides='default', - mode='phase', scale='dB') + with pytest.raises(ValueError): + ax11.specgram(y, NFFT=NFFT, Fs=Fs, + noverlap=noverlap, pad_to=pad_to, sides='default', + mode='phase', scale='dB') - assert_raises(ValueError, ax12.specgram, y, NFFT=NFFT, Fs=Fs, - noverlap=noverlap, pad_to=pad_to, sides='onesided', - mode='phase', scale='dB') + with pytest.raises(ValueError): + ax12.specgram(y, NFFT=NFFT, Fs=Fs, + noverlap=noverlap, pad_to=pad_to, sides='onesided', + mode='phase', scale='dB') - assert_raises(ValueError, ax13.specgram, y, NFFT=NFFT, Fs=Fs, - noverlap=noverlap, pad_to=pad_to, sides='twosided', - mode='phase', scale='dB') + with pytest.raises(ValueError): + ax13.specgram(y, NFFT=NFFT, Fs=Fs, + noverlap=noverlap, pad_to=pad_to, sides='twosided', + mode='phase', scale='dB') @image_comparison(baseline_images=['specgram_phase_noise'], @@ -3271,17 +3290,20 @@ def test_specgram_noise_phase(): pad_to=pad_to, sides='twosided', mode='phase', ) - assert_raises(ValueError, ax11.specgram, y, NFFT=NFFT, Fs=Fs, - noverlap=noverlap, pad_to=pad_to, sides='default', - mode='phase', scale='dB') + with pytest.raises(ValueError): + ax11.specgram(y, NFFT=NFFT, Fs=Fs, + noverlap=noverlap, pad_to=pad_to, sides='default', + mode='phase', scale='dB') - assert_raises(ValueError, ax12.specgram, y, NFFT=NFFT, Fs=Fs, - noverlap=noverlap, pad_to=pad_to, sides='onesided', - mode='phase', scale='dB') + with pytest.raises(ValueError): + ax12.specgram(y, NFFT=NFFT, Fs=Fs, + noverlap=noverlap, pad_to=pad_to, sides='onesided', + mode='phase', scale='dB') - assert_raises(ValueError, ax13.specgram, y, NFFT=NFFT, Fs=Fs, - noverlap=noverlap, pad_to=pad_to, sides='twosided', - mode='phase', scale='dB') + with pytest.raises(ValueError): + ax13.specgram(y, NFFT=NFFT, Fs=Fs, + noverlap=noverlap, pad_to=pad_to, sides='twosided', + mode='phase', scale='dB') @image_comparison(baseline_images=['psd_freqs'], remove_text=True, @@ -4230,8 +4252,10 @@ def test_square_plot(): @cleanup def test_no_None(): fig, ax = plt.subplots() - assert_raises(ValueError, plt.plot, None) - assert_raises(ValueError, plt.plot, None, None) + with pytest.raises(ValueError): + plt.plot(None) + with pytest.raises(ValueError): + plt.plot(None, None) @cleanup @@ -4335,8 +4359,10 @@ def test_title_location_roundtrip(): assert 'right' == ax.get_title(loc='right') assert 'aardvark' == ax.get_title() - assert_raises(ValueError, ax.get_title, loc='foo') - assert_raises(ValueError, ax.set_title, 'fail', loc='foo') + with pytest.raises(ValueError): + ax.get_title(loc='foo') + with pytest.raises(ValueError): + ax.set_title('fail', loc='foo') @image_comparison(baseline_images=["loglog"], remove_text=True, @@ -4484,7 +4510,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)))) @@ -4501,7 +4527,7 @@ def test_pandas_errorbar_indexing(): try: import pandas as pd except ImportError: - raise SkipTest("Pandas not installed") + pytest.skip("Pandas not installed") df = pd.DataFrame(np.random.uniform(size=(5, 4)), columns=['x', 'y', 'xe', 'ye'], @@ -4515,7 +4541,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:] @@ -4545,8 +4571,8 @@ def test_none_kwargs(): @cleanup def test_ls_ds_conflict(): - assert_raises(ValueError, plt.plot, range(32), - linestyle='steps-pre:', drawstyle='steps-post') + with pytest.raises(ValueError): + plt.plot(range(32), linestyle='steps-pre:', drawstyle='steps-post') @image_comparison(baseline_images=['date_timezone_x'], extensions=['png']) diff --git a/lib/matplotlib/tests/test_cbook.py b/lib/matplotlib/tests/test_cbook.py index 5960467b65eb..a8017a98f1dd 100644 --- a/lib/matplotlib/tests/test_cbook.py +++ b/lib/matplotlib/tests/test_cbook.py @@ -11,7 +11,6 @@ import numpy as np from numpy.testing.utils import (assert_array_equal, assert_approx_equal, assert_array_almost_equal) -from nose.tools import raises, assert_raises import pytest import matplotlib.cbook as cbook @@ -88,9 +87,9 @@ def setUp(self): self.arr_colors = ['r', 'g', 'b', 'c', 'm', 'y'] self.arr_rgba = mcolors.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) @@ -263,15 +262,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): + 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): + results = cbook.boxplot_stats(data) def test_boxplot_stats_autorange_false(self): x = np.zeros(shape=140) @@ -462,14 +461,17 @@ def test_to_midstep(): def test_step_fails(): - assert_raises(ValueError, cbook._step_validation, - np.arange(12).reshape(3, 4), 'a') - assert_raises(ValueError, cbook._step_validation, - np.arange(12), 'a') - assert_raises(ValueError, cbook._step_validation, - np.arange(12)) - assert_raises(ValueError, cbook._step_validation, - np.arange(12), np.arange(3)) + with pytest.raises(ValueError): + cbook._step_validation(np.arange(12).reshape(3, 4), 'a') + + with pytest.raises(ValueError): + cbook._step_validation(np.arange(12), 'a') + + with pytest.raises(ValueError): + cbook._step_validation(np.arange(12)) + + with pytest.raises(ValueError): + cbook._step_validation(np.arange(12), np.arange(3)) def test_grouper(): diff --git a/lib/matplotlib/tests/test_rcparams.py b/lib/matplotlib/tests/test_rcparams.py index 62d7d7928e89..f6ef82730624 100644 --- a/lib/matplotlib/tests/test_rcparams.py +++ b/lib/matplotlib/tests/test_rcparams.py @@ -16,7 +16,6 @@ from matplotlib.tests import assert_str_equal from matplotlib.testing.decorators import cleanup, knownfailureif import matplotlib.colors as mcolors -from nose.tools import assert_raises import nose from itertools import chain import numpy as np @@ -118,7 +117,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', @@ -128,7 +127,7 @@ def test_rcparams_update(): def test_rcparams_init(): - with assert_raises(ValueError): + with pytest.raises(ValueError): with warnings.catch_warnings(): warnings.filterwarnings('ignore', message='.*(validate)', @@ -166,11 +165,11 @@ def test_Bug_2543(): mpl.rcParams['svg.embed_char_paths'] = False assert mpl.rcParams['svg.fonttype'] == "none" - 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 @@ -367,7 +366,7 @@ def test_validator_valid(validator, arg, target): @pytest.mark.parametrize('validator, arg, exception_type', generate_validator_testcases(False)) def test_validator_invalid(validator, arg, exception_type): - with assert_raises(exception_type): + with pytest.raises(exception_type): validator(arg) @@ -387,7 +386,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 diff --git a/lib/matplotlib/tests/test_ticker.py b/lib/matplotlib/tests/test_ticker.py index bb012a6f4971..49d61a942039 100644 --- a/lib/matplotlib/tests/test_ticker.py +++ b/lib/matplotlib/tests/test_ticker.py @@ -3,7 +3,6 @@ import six -from nose.tools import assert_raises from numpy.testing import assert_almost_equal import numpy as np import pytest @@ -65,7 +64,8 @@ def test_AutoMinorLocator(): def test_LogLocator(): loc = mticker.LogLocator(numticks=5) - assert_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, From 8a1daab85abf6369ec6e94af641503342785b01a Mon Sep 17 00:00:00 2001 From: Elliott Sales de Andrade Date: Thu, 20 Oct 2016 21:29:41 -0400 Subject: [PATCH 4/4] TST: Remove converted files from default test modules. These no longer run with nose due to the parametrization, but they will still be run by the pytest job on CI. --- lib/matplotlib/__init__.py | 5 ----- lib/matplotlib/tests/test_animation.py | 5 ----- lib/matplotlib/tests/test_axes.py | 12 +----------- lib/matplotlib/tests/test_rcparams.py | 5 ----- lib/matplotlib/tests/test_ticker.py | 4 ---- 5 files changed, 1 insertion(+), 30 deletions(-) diff --git a/lib/matplotlib/__init__.py b/lib/matplotlib/__init__.py index 08e9c3948513..c2939ff18a04 100644 --- a/lib/matplotlib/__init__.py +++ b/lib/matplotlib/__init__.py @@ -1470,10 +1470,8 @@ def _jupyter_nbextension_paths(): default_test_modules = [ 'matplotlib.tests.test_agg', - 'matplotlib.tests.test_animation', 'matplotlib.tests.test_arrow_patches', 'matplotlib.tests.test_artist', - 'matplotlib.tests.test_axes', 'matplotlib.tests.test_backend_bases', 'matplotlib.tests.test_backend_pdf', 'matplotlib.tests.test_backend_pgf', @@ -1483,7 +1481,6 @@ def _jupyter_nbextension_paths(): 'matplotlib.tests.test_backend_svg', 'matplotlib.tests.test_basic', 'matplotlib.tests.test_bbox_tight', - 'matplotlib.tests.test_cbook', 'matplotlib.tests.test_coding_standards', 'matplotlib.tests.test_collections', 'matplotlib.tests.test_colorbar', @@ -1508,7 +1505,6 @@ def _jupyter_nbextension_paths(): 'matplotlib.tests.test_pickle', 'matplotlib.tests.test_png', 'matplotlib.tests.test_quiver', - 'matplotlib.tests.test_rcparams', 'matplotlib.tests.test_sankey', 'matplotlib.tests.test_scale', 'matplotlib.tests.test_simplification', @@ -1520,7 +1516,6 @@ def _jupyter_nbextension_paths(): 'matplotlib.tests.test_table', 'matplotlib.tests.test_text', 'matplotlib.tests.test_texmanager', - 'matplotlib.tests.test_ticker', 'matplotlib.tests.test_tightlayout', 'matplotlib.tests.test_transforms', 'matplotlib.tests.test_triangulation', diff --git a/lib/matplotlib/tests/test_animation.py b/lib/matplotlib/tests/test_animation.py index 492c252aa79e..d9c86e041b4b 100644 --- a/lib/matplotlib/tests/test_animation.py +++ b/lib/matplotlib/tests/test_animation.py @@ -195,8 +195,3 @@ def test_movie_writer_registry(): assert not animation.writers._dirty assert animation.writers.is_available("ffmpeg") mpl.rcParams['animation.ffmpeg_path'] = ffmpeg_path - - -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 6841fcc5e824..22b1289b7f02 100644 --- a/lib/matplotlib/tests/test_axes.py +++ b/lib/matplotlib/tests/test_axes.py @@ -32,7 +32,7 @@ # Note: Some test cases are run twice: once normally and once with labeled data # These two must be defined in the same test function or need to have -# different baseline images to prevent race conditions when nose runs +# different baseline images to prevent race conditions when pytest runs # the tests with multiple threads. @@ -4713,13 +4713,3 @@ def test_fillbetween_cycle(): face_target = mcolors.to_rgba('C{}'.format(j)) assert tuple(cc.get_facecolors().squeeze()) == tuple(face_target) assert tuple(cc.get_edgecolors().squeeze()) == tuple(edge_target) - - -if __name__ == '__main__': - import nose - import sys - - args = ['-s', '--with-doctest'] - argv = sys.argv - argv = argv[:1] + args + argv[1:] - nose.runmodule(argv=argv, exit=False) diff --git a/lib/matplotlib/tests/test_rcparams.py b/lib/matplotlib/tests/test_rcparams.py index f6ef82730624..8e7116f58cf8 100644 --- a/lib/matplotlib/tests/test_rcparams.py +++ b/lib/matplotlib/tests/test_rcparams.py @@ -16,7 +16,6 @@ from matplotlib.tests import assert_str_equal from matplotlib.testing.decorators import cleanup, knownfailureif import matplotlib.colors as mcolors -import nose from itertools import chain import numpy as np from matplotlib.rcsetup import (validate_bool_maybe_none, @@ -391,7 +390,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_ticker.py b/lib/matplotlib/tests/test_ticker.py index 49d61a942039..78d693adeaad 100644 --- a/lib/matplotlib/tests/test_ticker.py +++ b/lib/matplotlib/tests/test_ticker.py @@ -544,7 +544,3 @@ def test_EngFormatter_formatting(): assert with_unit(1) == u'1 s' assert with_unit(999.9) == u'999.9 s' assert with_unit(1001) == u'1.001 ks' - -if __name__ == '__main__': - import nose - nose.runmodule(argv=['-s', '--with-doctest'], exit=False) pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy