diff --git a/lib/matplotlib/_pylab_helpers.py b/lib/matplotlib/_pylab_helpers.py index 748af4c572fb..1df053ef2585 100644 --- a/lib/matplotlib/_pylab_helpers.py +++ b/lib/matplotlib/_pylab_helpers.py @@ -78,8 +78,12 @@ def destroy_fig(fig): @staticmethod def destroy_all(): for manager in Gcf.figs.values(): - Gcf.destroy(manager.num) + manager.canvas.mpl_disconnect(manager._cidgcf) + manager.destroy() + Gcf._activeQue = [] + Gcf.figs.clear() + gc.collect() @staticmethod def has_fignum(num): diff --git a/lib/matplotlib/testing/compare.py b/lib/matplotlib/testing/compare.py index 0fff2a760092..ee386ae3bae6 100644 --- a/lib/matplotlib/testing/compare.py +++ b/lib/matplotlib/testing/compare.py @@ -83,6 +83,22 @@ def compare_float( expected, actual, relTol = None, absTol = None ): # convert files with that extension to png format. converter = { } +def make_external_conversion_command(cmd): + def convert(*args): + cmdline = cmd(*args) + oldname, newname = args + pipe = subprocess.Popen(cmdline, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + stdout, stderr = pipe.communicate() + errcode = pipe.wait() + if not os.path.exists(newname) or errcode: + msg = "Conversion command failed:\n%s\n" % ' '.join(cmd) + if stdout: + msg += "Standard output:\n%s\n" % stdout + if stderr: + msg += "Standard error:\n%s\n" % stderr + raise IOError, msg + return convert + if matplotlib.checkdep_ghostscript() is not None: # FIXME: make checkdep_ghostscript return the command if sys.platform == 'win32': @@ -92,13 +108,36 @@ def compare_float( expected, actual, relTol = None, absTol = None ): cmd = lambda old, new: \ [gs, '-q', '-sDEVICE=png16m', '-dNOPAUSE', '-dBATCH', '-sOutputFile=' + new, old] - converter['pdf'] = cmd - converter['eps'] = cmd + converter['pdf'] = make_external_conversion_command(cmd) + converter['eps'] = make_external_conversion_command(cmd) if matplotlib.checkdep_inkscape() is not None: - cmd = lambda old, new: \ - ['inkscape', old, '--export-png=' + new] - converter['svg'] = cmd + def make_svg_converter(): + def read_to_end(buf): + ret = '' + lastchar = '' + while True: + char = buf.readline(1) + if char == '>' and lastchar == '\n': + break + ret += char + lastchar = char + return ret + + p = subprocess.Popen(['inkscape', '--shell'], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT) + read_to_end(p.stdout) + + def convert_svg(old, new): + p.stdin.write('%s --export-png=%s\n' % (old, new)) + p.stdin.flush() + read_to_end(p.stdout) + + return convert_svg + + converter['svg'] = make_svg_converter() def comparable_formats(): '''Returns the list of file formats that compare_images can compare @@ -116,17 +155,7 @@ def convert(filename): newname = base + '_' + extension + '.png' if not os.path.exists(filename): raise IOError, "'%s' does not exist" % filename - cmd = converter[extension](filename, newname) - pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - stdout, stderr = pipe.communicate() - errcode = pipe.wait() - if not os.path.exists(newname) or errcode: - msg = "Conversion command failed:\n%s\n" % ' '.join(cmd) - if stdout: - msg += "Standard output:\n%s\n" % stdout - if stderr: - msg += "Standard error:\n%s\n" % stderr - raise IOError, msg + converter[extension](filename, newname) return newname verifiers = { } diff --git a/lib/matplotlib/testing/decorators.py b/lib/matplotlib/testing/decorators.py index 5c64bf510692..bb03f3ac4a39 100644 --- a/lib/matplotlib/testing/decorators.py +++ b/lib/matplotlib/testing/decorators.py @@ -1,9 +1,11 @@ from matplotlib.testing.noseclasses import KnownFailureTest, \ KnownFailureDidNotFailTest, ImageComparisonFailure -import os, sys, shutil +import os, sys, shutil, new import nose import matplotlib import matplotlib.tests +import matplotlib.units +from matplotlib import pyplot as plt import numpy as np from matplotlib.testing.compare import comparable_formats, compare_images @@ -46,7 +48,83 @@ def failer(*args, **kwargs): return nose.tools.make_decorator(f)(failer) return known_fail_decorator -def image_comparison(baseline_images=None,extensions=None,tol=1e-3): +class CleanupTest: + @classmethod + def setup_class(cls): + cls.original_rcParams = {} + cls.original_rcParams.update(matplotlib.rcParams) + + cls.original_units_registry = {} + cls.original_units_registry.update(matplotlib.units.registry) + + @classmethod + def teardown_class(cls): + plt.close('all') + + matplotlib.rcParams.clear() + matplotlib.rcParams.update(cls.original_rcParams) + + matplotlib.units.registry.clear() + matplotlib.units.registry.update(cls.original_units_registry) + + def test(self): + self.func() + +def cleanup(func): + new_class = new.classobj( + func.__name__, + (CleanupTest,), + {'func': staticmethod(func)}) + return new_class + +class ImageComparisonTest(CleanupTest): + @classmethod + def setup_class(cls): + CleanupTest.setup_class() + + cls.func() + + def test(self): + baseline_dir, result_dir = _image_directories(self.func) + + for fignum, baseline in zip(plt.get_fignums(), self.baseline_images): + figure = plt.figure(fignum) + + for extension in self.extensions: + will_fail = not extension in comparable_formats() + if will_fail: + fail_msg = 'Cannot compare %s files on this system' % extension + else: + fail_msg = 'No failure expected' + + orig_expected_fname = os.path.join(baseline_dir, baseline) + '.' + extension + expected_fname = os.path.join(result_dir, 'expected-' + baseline) + '.' + extension + actual_fname = os.path.join(result_dir, baseline) + '.' + extension + if os.path.exists(orig_expected_fname): + shutil.copyfile(orig_expected_fname, expected_fname) + else: + will_fail = True + fail_msg = 'Do not have baseline image %s' % expected_fname + + @knownfailureif( + will_fail, fail_msg, + known_exception_class=ImageComparisonFailure) + def do_test(): + figure.savefig(actual_fname) + + if not os.path.exists(expected_fname): + raise ImageComparisonFailure( + 'image does not exist: %s' % expected_fname) + + err = compare_images(expected_fname, actual_fname, self.tol, in_decorator=True) + if err: + raise ImageComparisonFailure( + 'images not close: %(actual)s vs. %(expected)s ' + '(RMS %(rms).3f)'%err) + + yield (do_test,) + +def image_comparison(baseline_images=None, extensions=None, tol=1e-3): """ call signature:: @@ -76,56 +154,22 @@ def image_comparison(baseline_images=None,extensions=None,tol=1e-3): # default extensions to test extensions = ['png', 'pdf', 'svg'] - # The multiple layers of defs are required because of how - # parameterized decorators work, and because we want to turn the - # single test_foo function to a generator that generates a - # separate test case for each file format. def compare_images_decorator(func): - baseline_dir, result_dir = _image_directories(func) - - def compare_images_generator(): - for extension in extensions: - orig_expected_fnames = [os.path.join(baseline_dir,fname) + '.' + extension for fname in baseline_images] - expected_fnames = [os.path.join(result_dir,'expected-'+fname) + '.' + extension for fname in baseline_images] - actual_fnames = [os.path.join(result_dir, fname) + '.' + extension for fname in baseline_images] - have_baseline_images = [os.path.exists(expected) for expected in orig_expected_fnames] - have_baseline_image = np.all(have_baseline_images) - is_comparable = extension in comparable_formats() - if not is_comparable: - fail_msg = 'Cannot compare %s files on this system' % extension - elif not have_baseline_image: - fail_msg = 'Do not have baseline images %s' % expected_fnames - else: - fail_msg = 'No failure expected' - will_fail = not (is_comparable and have_baseline_image) - @knownfailureif(will_fail, fail_msg, - known_exception_class=ImageComparisonFailure ) - def decorated_compare_images(): - # set the default format of savefig - matplotlib.rc('savefig', extension=extension) - # change to the result directory for the duration of the test - old_dir = os.getcwd() - os.chdir(result_dir) - try: - result = func() # actually call the test function - finally: - os.chdir(old_dir) - for original, expected in zip(orig_expected_fnames, expected_fnames): - if not os.path.exists(original): - raise ImageComparisonFailure( - 'image does not exist: %s'%original) - shutil.copyfile(original, expected) - for actual,expected in zip(actual_fnames,expected_fnames): - # compare the images - err = compare_images( expected, actual, tol, - in_decorator=True ) - if err: - raise ImageComparisonFailure( - 'images not close: %(actual)s vs. %(expected)s ' - '(RMS %(rms).3f)'%err) - return result - yield (decorated_compare_images,) - return nose.tools.make_decorator(func)(compare_images_generator) + # We want to run the setup function (the actual test function + # that generates the figure objects) only once for each type + # of output file. The only way to achieve this with nose + # appears to be to create a test class with "setup_class" and + # "teardown_class" methods. Creating a class instance doesn't + # work, so we use new.classobj to actually create a class and + # fill it with the appropriate methods. + new_class = new.classobj( + func.__name__, + (ImageComparisonTest,), + {'func': staticmethod(func), + 'baseline_images': baseline_images, + 'extensions': extensions, + 'tol': tol}) + return new_class return compare_images_decorator def _image_directories(func): @@ -134,7 +178,7 @@ def _image_directories(func): Create the result directory if it doesn't exist. """ module_name = func.__module__ - if module_name=='__main__': + if module_name == '__main__': # FIXME: this won't work for nested packages in matplotlib.tests import warnings warnings.warn('test module run as script. guessing baseline image locations') @@ -143,13 +187,13 @@ def _image_directories(func): subdir = os.path.splitext(os.path.split(script_name)[1])[0] else: mods = module_name.split('.') - assert mods.pop(0)=='matplotlib' - assert mods.pop(0)=='tests' + assert mods.pop(0) == 'matplotlib' + assert mods.pop(0) == 'tests' subdir = os.path.join(*mods) basedir = os.path.dirname(matplotlib.tests.__file__) - baseline_dir = os.path.join(basedir,'baseline_images',subdir) - result_dir = os.path.abspath(os.path.join('result_images',subdir)) + baseline_dir = os.path.join(basedir, 'baseline_images', subdir) + result_dir = os.path.abspath(os.path.join('result_images', subdir)) if not os.path.exists(result_dir): os.makedirs(result_dir) diff --git a/lib/matplotlib/tests/baseline_images/test_axes/polar_units_2.pdf b/lib/matplotlib/tests/baseline_images/test_axes/polar_units_2.pdf new file mode 100644 index 000000000000..109e59e19e17 Binary files /dev/null and b/lib/matplotlib/tests/baseline_images/test_axes/polar_units_2.pdf differ diff --git a/lib/matplotlib/tests/baseline_images/test_axes/polar_units_2.png b/lib/matplotlib/tests/baseline_images/test_axes/polar_units_2.png new file mode 100644 index 000000000000..3ad07042a8ce Binary files /dev/null and b/lib/matplotlib/tests/baseline_images/test_axes/polar_units_2.png differ diff --git a/lib/matplotlib/tests/baseline_images/test_axes/polar_units_2.svg b/lib/matplotlib/tests/baseline_images/test_axes/polar_units_2.svg new file mode 100644 index 000000000000..e854972fdae5 --- /dev/null +++ b/lib/matplotlib/tests/baseline_images/test_axes/polar_units_2.svg @@ -0,0 +1,715 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/lib/matplotlib/tests/test_axes.py b/lib/matplotlib/tests/test_axes.py index 5c67dc88de40..a5cb9c347ae9 100644 --- a/lib/matplotlib/tests/test_axes.py +++ b/lib/matplotlib/tests/test_axes.py @@ -24,23 +24,32 @@ def test_formatter_ticker(): fig = plt.figure() ax = plt.subplot( 111 ) ax.set_xlabel( "x-label 001" ) - fig.savefig( 'formatter_ticker_001' ) + fig = plt.figure() + ax = plt.subplot( 111 ) + ax.set_xlabel( "x-label 001" ) ax.plot( xdata, ydata1, color='blue', xunits="sec" ) - fig.savefig( 'formatter_ticker_002' ) + fig = plt.figure() + ax = plt.subplot( 111 ) + ax.set_xlabel( "x-label 001" ) + ax.plot( xdata, ydata1, color='blue', xunits="sec" ) ax.set_xlabel( "x-label 003" ) - fig.savefig( 'formatter_ticker_003' ) + fig = plt.figure() + ax = plt.subplot( 111 ) + ax.plot( xdata, ydata1, color='blue', xunits="sec" ) ax.plot( xdata, ydata2, color='green', xunits="hour" ) ax.set_xlabel( "x-label 004" ) - fig.savefig( 'formatter_ticker_004' ) # See SF bug 2846058 # https://sourceforge.net/tracker/?func=detail&aid=2846058&group_id=80706&atid=560720 + fig = plt.figure() + ax = plt.subplot( 111 ) + ax.plot( xdata, ydata1, color='blue', xunits="sec" ) + ax.plot( xdata, ydata2, color='green', xunits="hour" ) ax.set_xlabel( "x-label 005" ) ax.autoscale_view() - fig.savefig( 'formatter_ticker_005' ) @image_comparison(baseline_images=['offset_points']) def test_basic_annotate(): @@ -57,8 +66,6 @@ def test_basic_annotate(): ax.annotate( 'local max', xy=(3, 1), xycoords='data', xytext=(3, 3), textcoords='offset points' ) - fig.savefig( 'offset_points' ) - @image_comparison(baseline_images=['polar_axes']) def test_polar_annotations(): # you can specify the xypoint and the xytext in different @@ -91,8 +98,6 @@ def test_polar_annotations(): verticalalignment='baseline', ) - fig.savefig( 'polar_axes' ) - #-------------------------------------------------------------------- @image_comparison(baseline_images=['polar_coords']) def test_polar_coord_annotations(): @@ -122,7 +127,6 @@ def test_polar_coord_annotations(): ax.set_xlim( -20, 20 ) ax.set_ylim( -20, 20 ) - fig.savefig( 'polar_coords' ) @image_comparison(baseline_images=['fill_units']) def test_fill_units(): @@ -163,7 +167,6 @@ def test_fill_units(): facecolor="blue" ) fig.autofmt_xdate() - fig.savefig( 'fill_units' ) @image_comparison(baseline_images=['single_point']) def test_single_point(): @@ -174,8 +177,6 @@ def test_single_point(): plt.subplot( 212 ) plt.plot( [1], [1], 'o' ) - fig.savefig( 'single_point' ) - @image_comparison(baseline_images=['single_date']) def test_single_date(): time1=[ 721964.0 ] @@ -188,8 +189,6 @@ def test_single_date(): plt.subplot( 212 ) plt.plot( time1, data1, 'o', color='r' ) - fig.savefig( '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, @@ -232,8 +231,6 @@ def test_shaped_data(): plt.subplot( 414 ) plt.plot( xdata[:,1], xdata[1,:], 'o' ) - fig.savefig( 'shaped_data' ) - @image_comparison(baseline_images=['const_xy']) def test_const_xy(): fig = plt.figure() @@ -247,8 +244,6 @@ def test_const_xy(): plt.subplot( 313 ) plt.plot( np.ones( (10,) ), np.ones( (10,) ), 'o' ) - fig.savefig( 'const_xy' ) - @image_comparison(baseline_images=['polar_wrap_180', 'polar_wrap_360', ]) @@ -263,8 +258,6 @@ def test_polar_wrap(): plt.polar( [179*D2R, 181*D2R], [0.2, 0.1], "g.-" ) plt.rgrids( [0.05, 0.1, 0.15, 0.2, 0.25, 0.3] ) - fig.savefig( 'polar_wrap_180' ) - fig = plt.figure() #NOTE: resolution=1 really should be the default @@ -274,9 +267,7 @@ def test_polar_wrap(): plt.polar( [358*D2R, 2*D2R], [0.2, 0.1], "r.-" ) plt.rgrids( [0.05, 0.1, 0.15, 0.2, 0.25, 0.3] ) - fig.savefig( 'polar_wrap_360' ) - -@image_comparison(baseline_images=['polar_units']) +@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 @@ -299,7 +290,7 @@ def test_polar_units(): # polar( x2, y1, color = "red", xunits="rad" ) # polar( x2, y2, color = "green" ) - fig.savefig( 'polar_units' ) + fig = plt.figure() # make sure runits and theta units work y1 = [ y*km for y in y1 ] @@ -318,8 +309,6 @@ def test_polar_rmin(): ax.set_rmax(2.0) ax.set_rmin(0.5) - fig.savefig('polar_rmin') - @image_comparison(baseline_images=['axvspan_epoch']) def test_axvspan_epoch(): from datetime import datetime @@ -339,8 +328,6 @@ def test_axvspan_epoch(): ax = plt.gca() ax.set_xlim( t0 - 5.0*dt, tf + 5.0*dt ) - fig.savefig( 'axvspan_epoch' ) - @image_comparison(baseline_images=['axhspan_epoch']) def test_axhspan_epoch(): from datetime import datetime @@ -360,8 +347,6 @@ def test_axhspan_epoch(): ax = plt.gca() ax.set_ylim( t0 - 5.0*dt, tf + 5.0*dt ) - fig.savefig( 'axhspan_epoch' ) - @image_comparison(baseline_images=['hexbin_extent']) def test_hexbin_extent(): @@ -374,7 +359,6 @@ def test_hexbin_extent(): x, y = data ax.hexbin(x, y, extent=[.1, .3, .6, .7]) - fig.savefig('hexbin_extent') @image_comparison(baseline_images=['nonfinite_limits']) def test_nonfinite_limits(): @@ -384,7 +368,6 @@ def test_nonfinite_limits(): fig = plt.figure() ax = fig.add_subplot(111) ax.plot(x, y) - fig.savefig('nonfinite_limits') @image_comparison(baseline_images=['imshow']) def test_imshow(): @@ -400,7 +383,6 @@ def test_imshow(): ax = fig.add_subplot(111) ax.imshow(r) - fig.savefig('imshow') @image_comparison(baseline_images=['imshow_clip'], tol=1e-2) def test_imshow_clip(): @@ -427,7 +409,6 @@ def test_imshow_clip(): #Plot the image clipped by the contour ax.imshow(r, clip_path=clip_path) - fig.savefig('imshow_clip') @image_comparison(baseline_images=['polycollection_joinstyle']) def test_polycollection_joinstyle(): @@ -445,8 +426,6 @@ def test_polycollection_joinstyle(): ax.set_xticks([]) ax.set_yticks([]) - fig.savefig('polycollection_joinstyle') - @image_comparison(baseline_images=['fill_between_interpolate'], tol=1e-2) def test_fill_between_interpolate(): x = np.arange(0.0, 2, 0.02) @@ -466,8 +445,6 @@ def test_fill_between_interpolate(): 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) - fig.savefig('fill_between_interpolate') - @image_comparison(baseline_images=['symlog']) def test_symlog(): x = np.array([0,1,2,4,6,9,12,24]) @@ -480,8 +457,6 @@ def test_symlog(): ax.set_xscale=('linear') ax.set_ylim(-1,10000000) - fig.savefig('symlog') - @image_comparison(baseline_images=['pcolormesh'], tol=0.02) def test_pcolormesh(): n = 12 @@ -510,14 +485,11 @@ def test_pcolormesh(): ax.set_xticks([]) ax.set_yticks([]) - fig.savefig('pcolormesh') - @image_comparison(baseline_images=['canonical']) def test_canonical(): fig, ax = plt.subplots() ax.plot([1,2,3]) - fig.savefig('canonical') @image_comparison(baseline_images=['arc_ellipse']) @@ -557,8 +529,6 @@ def test_arc_ellipse(): ax.add_patch(e2) - fig.savefig('arc_ellipse') - @image_comparison(baseline_images=['units_strings']) def test_units_strings(): # Make sure passing in sequences of strings doesn't cause the unit @@ -568,7 +538,6 @@ def test_units_strings(): fig = plt.figure() ax = fig.add_subplot(111) ax.plot(Id, pout) - fig.savefig('units_strings') @image_comparison(baseline_images=['markevery']) def test_markevery(): @@ -583,7 +552,6 @@ def test_markevery(): ax.plot(x, y, 's', markevery=10, label='mark every 10') ax.plot(x, y, '+', markevery=(5, 20), label='mark every 5 starting at 10') ax.legend() - fig.savefig('markevery') @image_comparison(baseline_images=['markevery_line']) def test_markevery_line(): @@ -598,7 +566,6 @@ def test_markevery_line(): ax.plot(x, y, '-s', markevery=10, label='mark every 10') ax.plot(x, y, '-+', markevery=(5, 20), label='mark every 5 starting at 10') ax.legend() - fig.savefig('markevery_line') if __name__=='__main__': import nose diff --git a/lib/matplotlib/tests/test_backend_pdf.py b/lib/matplotlib/tests/test_backend_pdf.py index 1d9b7b0ed12f..63b2b7c2b397 100644 --- a/lib/matplotlib/tests/test_backend_pdf.py +++ b/lib/matplotlib/tests/test_backend_pdf.py @@ -6,9 +6,6 @@ @image_comparison(baseline_images=['pdf_use14corefonts'], extensions=['pdf']) def test_use14corefonts(): - original_rcParams = {} - original_rcParams.update(rcParams) - rcParams['backend'] = 'pdf' rcParams['pdf.use14corefonts'] = True rcParams['font.family'] = 'sans-serif' @@ -21,11 +18,7 @@ def test_use14corefonts(): and containing some French characters and the euro symbol: "Merci pépé pour les 10 €"''' - try: - plt.figure() - plt.title(title) - plt.text(0.5, 0.5, text, horizontalalignment='center', fontsize=24) - plt.axhline(0.5, linewidth=0.5) - plt.savefig('pdf_use14corefonts.pdf') - finally: - rcParams.update(original_rcParams) + plt.figure() + plt.title(title) + plt.text(0.5, 0.5, text, horizontalalignment='center', fontsize=24) + plt.axhline(0.5, linewidth=0.5) diff --git a/lib/matplotlib/tests/test_backend_svg.py b/lib/matplotlib/tests/test_backend_svg.py index c99c480981da..ba0a3ae76ec8 100644 --- a/lib/matplotlib/tests/test_backend_svg.py +++ b/lib/matplotlib/tests/test_backend_svg.py @@ -2,8 +2,9 @@ import numpy as np import cStringIO as StringIO import xml.parsers.expat -from matplotlib.testing.decorators import knownfailureif +from matplotlib.testing.decorators import knownfailureif, cleanup +@cleanup def test_visibility(): # This is SF 2856495. See # https://sourceforge.net/tracker/?func=detail&aid=2856495&group_id=80706&atid=560720 @@ -19,7 +20,7 @@ def test_visibility(): artist.set_visible(False) fd = StringIO.StringIO() - fig.savefig(fd,format='svg') + fig.savefig(fd, format='svg') fd.seek(0) buf = fd.read() diff --git a/lib/matplotlib/tests/test_dates.py b/lib/matplotlib/tests/test_dates.py index 04f491c597fa..43854ea4a6ab 100644 --- a/lib/matplotlib/tests/test_dates.py +++ b/lib/matplotlib/tests/test_dates.py @@ -1,6 +1,6 @@ import datetime import numpy as np -from matplotlib.testing.decorators import image_comparison, knownfailureif +from matplotlib.testing.decorators import image_comparison, knownfailureif, cleanup import matplotlib.pyplot as plt from nose.tools import assert_raises @@ -12,7 +12,6 @@ def test_date_empty(): fig = plt.figure() ax = fig.add_subplot(1,1,1) ax.xaxis_date() - fig.savefig('date_empty') @image_comparison(baseline_images=['date_axhspan']) def test_date_axhspan(): @@ -25,7 +24,6 @@ def test_date_axhspan(): ax.set_ylim(t0-datetime.timedelta(days=5), tf+datetime.timedelta(days=5)) fig.subplots_adjust(left=0.25) - fig.savefig('date_axhspan') @image_comparison(baseline_images=['date_axvspan']) def test_date_axvspan(): @@ -38,8 +36,6 @@ def test_date_axvspan(): ax.set_xlim(t0-datetime.timedelta(days=720), tf+datetime.timedelta(days=720)) fig.autofmt_xdate() - fig.savefig('date_axvspan') - @image_comparison(baseline_images=['date_axhline']) def test_date_axhline(): @@ -52,7 +48,6 @@ def test_date_axhline(): ax.set_ylim(t0-datetime.timedelta(days=5), tf+datetime.timedelta(days=5)) fig.subplots_adjust(left=0.25) - fig.savefig('date_axhline') @image_comparison(baseline_images=['date_axvline']) def test_date_axvline(): @@ -65,8 +60,8 @@ def test_date_axvline(): ax.set_xlim(t0-datetime.timedelta(days=5), tf+datetime.timedelta(days=5)) fig.autofmt_xdate() - fig.savefig('date_axvline') +@cleanup def test_too_many_date_ticks(): # Attempt to test SF 2715172, see # https://sourceforge.net/tracker/?func=detail&aid=2715172&group_id=80706&atid=560720 @@ -111,8 +106,6 @@ def test_RRuleLocator(): ax.autoscale_view() fig.autofmt_xdate() - fig.savefig( 'RRuleLocator_bounds' ) - @image_comparison(baseline_images=['DateFormatter_fractionalSeconds']) def test_DateFormatter(): import pylab @@ -139,9 +132,8 @@ def test_DateFormatter(): ax.autoscale_view() fig.autofmt_xdate() - fig.savefig( 'DateFormatter_fractionalSeconds' ) - #@image_comparison(baseline_images=['empty_date_bug']) +@cleanup @knownfailureif(True) def test_empty_date_with_year_formatter(): # exposes sf bug 2861426: https://sourceforge.net/tracker/?func=detail&aid=2861426&group_id=80706&atid=560720 diff --git a/lib/matplotlib/tests/test_image.py b/lib/matplotlib/tests/test_image.py index 23faf6c6b28f..65b377965463 100644 --- a/lib/matplotlib/tests/test_image.py +++ b/lib/matplotlib/tests/test_image.py @@ -1,6 +1,6 @@ import numpy as np -from matplotlib.testing.decorators import image_comparison, knownfailureif +from matplotlib.testing.decorators import image_comparison, knownfailureif, cleanup import matplotlib.pyplot as plt from nose.tools import assert_raises from numpy.testing import assert_array_equal @@ -28,8 +28,6 @@ def test_image_interps(): ax3.imshow(X, interpolation='bicubic') ax3.set_ylabel('bicubic') - fig.savefig('image_interps') - @image_comparison(baseline_images=['figimage-0', 'figimage-1'], extensions=['png'], tol=1.5e-3) def test_figimage(): 'test the figimage method' @@ -47,8 +45,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') - fig.savefig('figimage-%d' % int(suppressComposite), dpi=100) - +@cleanup def test_image_python_io(): fig = plt.figure() ax = fig.add_subplot(111) @@ -107,8 +104,6 @@ def test_image_clip(): im = ax.imshow(d, extent=(-pi,pi,-pi/2,pi/2)) - fig.savefig('image_clip') - @image_comparison(baseline_images=['imshow']) def test_imshow(): import numpy as np @@ -121,8 +116,6 @@ def test_imshow(): ax.set_xlim(0,3) ax.set_ylim(0,3) - fig.savefig('imshow') - 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 2cf7702244a2..17809bc6f1dc 100644 --- a/lib/matplotlib/tests/test_legend.py +++ b/lib/matplotlib/tests/test_legend.py @@ -14,7 +14,6 @@ def test_legend_auto1(): ax.plot(x, 50-x, 'o', label='y=1') ax.plot(x, x-50, 'o', label='y=-1') ax.legend(loc=0) - fig.savefig('legend_auto1') @image_comparison(baseline_images=['legend_auto2']) def test_legend_auto2(): @@ -25,5 +24,4 @@ def test_legend_auto2(): b1 = ax.bar(x, x, color='m') b2 = ax.bar(x, x[::-1], color='g') ax.legend([b1[0], b2[0]], ['up', 'down'], loc=0) - fig.savefig('legend_auto2') diff --git a/lib/matplotlib/tests/test_mathtext.py b/lib/matplotlib/tests/test_mathtext.py index 0c37f6b9d602..02d3bf9ab2a4 100644 --- a/lib/matplotlib/tests/test_mathtext.py +++ b/lib/matplotlib/tests/test_mathtext.py @@ -141,10 +141,9 @@ 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.savefig(filename) - fig.clf() - matplotlib.rcParams['mathtext.fontset'] = 'cm' - return single_test + func = single_test + func.__name__ = filename + "_test" + return func # We inject test functions into the global namespace, rather than # using a generator, so that individual tests can be run more diff --git a/lib/matplotlib/tests/test_png.py b/lib/matplotlib/tests/test_png.py index 58213c4aeb28..0e73a88aa77b 100644 --- a/lib/matplotlib/tests/test_png.py +++ b/lib/matplotlib/tests/test_png.py @@ -25,5 +25,3 @@ def test_pngsuite(): plt.gca().get_frame().set_facecolor("#ddffff") plt.gca().set_xlim(0, len(files)) - - fig.savefig('pngsuite') diff --git a/lib/matplotlib/tests/test_simplification.py b/lib/matplotlib/tests/test_simplification.py index b38ad48673db..4a02446a0196 100644 --- a/lib/matplotlib/tests/test_simplification.py +++ b/lib/matplotlib/tests/test_simplification.py @@ -1,6 +1,6 @@ import numpy as np import matplotlib -from matplotlib.testing.decorators import image_comparison, knownfailureif +from matplotlib.testing.decorators import image_comparison, knownfailureif, cleanup import matplotlib.pyplot as plt from pylab import * @@ -27,7 +27,6 @@ def test_clipping(): ax.set_ylim((-0.20, -0.28)) ax.set_xticks([]) ax.set_yticks([]) - fig.savefig('clipping') @image_comparison(baseline_images=['overflow'], tol=1e-2) def test_overflow(): @@ -41,8 +40,6 @@ def test_overflow(): ax.set_xticks([]) ax.set_yticks([]) - fig.savefig('overflow') - @image_comparison(baseline_images=['clipping_diamond']) def test_diamond(): x = np.array([0.0, 1.0, 0.0, -1.0, 0.0]) @@ -56,8 +53,7 @@ def test_diamond(): ax.set_xticks([]) ax.set_yticks([]) - fig.savefig('clipping_diamond') - +@cleanup def test_noise(): np.random.seed(0) x = np.random.uniform(size=(5000,)) * 50 @@ -77,6 +73,7 @@ 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 @@ -111,8 +108,6 @@ def test_simplify_curve(): ax.set_xlim((0, 2)) ax.set_ylim((0, 2)) - fig.savefig('simplify_curve') - @image_comparison(baseline_images=['hatch_simplify']) def test_hatch(): fig = plt.figure() @@ -121,8 +116,6 @@ def test_hatch(): ax.set_xlim((0.45, 0.55)) ax.set_ylim((0.45, 0.55)) - fig.savefig('hatch_simplify') - @image_comparison(baseline_images=['fft_peaks']) def test_fft_peaks(): fig = plt.figure() @@ -132,8 +125,6 @@ def test_fft_peaks(): ax.set_xticks([]) ax.set_yticks([]) - fig.savefig('fft_peaks') - path = p1[0].get_path() transform = p1[0].get_transform() path = transform.transform_path(path) @@ -143,6 +134,7 @@ def test_fft_peaks(): assert len(simplified) == 20 +@cleanup def test_start_with_moveto(): # Should be entirely clipped away to a single MOVETO data = """ @@ -175,6 +167,7 @@ def test_start_with_moveto(): assert len(segs) == 1 assert segs[0][1] == Path.MOVETO +@cleanup @raises(OverflowError) def test_throw_rendering_complexity_exceeded(): rcParams['path.simplify'] = False @@ -208,7 +201,6 @@ def test_clipper(): ax.yaxis.set_ticks_position('left') ax.set_xlim(5, 9) - fig.savefig('clipper_edge') @image_comparison(baseline_images=['para_equal_perp']) def test_para_equal_perp(): @@ -219,7 +211,6 @@ def test_para_equal_perp(): ax = fig.add_subplot(111) ax.plot(x + 1, y + 1) ax.plot(x + 1, y + 1, 'ro') - fig.savefig('para_equal_perp') if __name__=='__main__': import nose diff --git a/lib/matplotlib/tests/test_spines.py b/lib/matplotlib/tests/test_spines.py index adebc44a4b84..aa0722277c4a 100644 --- a/lib/matplotlib/tests/test_spines.py +++ b/lib/matplotlib/tests/test_spines.py @@ -18,4 +18,3 @@ def test_spines_axes_positions(): ax.xaxis.set_ticks_position('top') ax.spines['left'].set_color('none') ax.spines['bottom'].set_color('none') - fig.savefig('spines_axes_positions') diff --git a/lib/matplotlib/tests/test_text.py b/lib/matplotlib/tests/test_text.py index 9ef688e1015e..e01c23c897a0 100644 --- a/lib/matplotlib/tests/test_text.py +++ b/lib/matplotlib/tests/test_text.py @@ -62,8 +62,6 @@ def test_font_styles(): ax.set_xticks([]) ax.set_yticks([]) - fig.savefig('font_styles') - @image_comparison(baseline_images=['multiline']) def test_multiline(): fig = plt.figure() @@ -72,5 +70,3 @@ def test_multiline(): ax.set_xticks([]) ax.set_yticks([]) - - fig.savefig('multiline')