@@ -143,6 +143,20 @@ def switch_backend(backend):
143143 yield
144144
145145
146+ def close_mpl_figure (fig ):
147+ "Close a given matplotlib Figure. Any other type of figure is ignored"
148+
149+ import matplotlib .pyplot as plt
150+ from matplotlib .figure import Figure
151+
152+ # We only need to close actual Matplotlib figure objects. If
153+ # we are dealing with a figure-like object that provides
154+ # savefig but is not a real Matplotlib object, we shouldn't
155+ # try closing it here.
156+ if isinstance (fig , Figure ):
157+ plt .close (fig )
158+
159+
146160class ImageComparison (object ):
147161
148162 def __init__ (self , config , baseline_dir = None , generate_dir = None , results_dir = None ):
@@ -162,7 +176,6 @@ def pytest_runtest_setup(self, item):
162176
163177 import matplotlib
164178 import matplotlib .pyplot as plt
165- from matplotlib .figure import Figure
166179 from matplotlib .testing .compare import compare_images
167180 from matplotlib .testing .decorators import ImageComparisonTest as MplImageComparisonTest
168181 try :
@@ -231,13 +244,7 @@ def item_function_wrapper(*args, **kwargs):
231244 test_image = os .path .abspath (os .path .join (result_dir , filename ))
232245
233246 fig .savefig (test_image , ** savefig_kwargs )
234-
235- # We only need to close actual Matplotlib figure objects. If
236- # we are dealing with a figure-like object that provides
237- # savefig but is not a real Matplotlib object, we shouldn't
238- # try closing it here.
239- if isinstance (fig , Figure ):
240- plt .close (fig )
247+ close_mpl_figure (fig )
241248
242249 # Find path to baseline image
243250 if baseline_remote :
@@ -268,7 +275,7 @@ def item_function_wrapper(*args, **kwargs):
268275 os .makedirs (self .generate_dir )
269276
270277 fig .savefig (os .path .abspath (os .path .join (self .generate_dir , filename )), ** savefig_kwargs )
271- plt . close (fig )
278+ close_mpl_figure (fig )
272279 pytest .skip ("Skipping test, since generating data" )
273280
274281 if item .cls is not None :
@@ -294,7 +301,6 @@ def pytest_runtest_setup(self, item):
294301 return
295302
296303 import matplotlib .pyplot as plt
297- from matplotlib .figure import Figure
298304
299305 original = item .function
300306
@@ -306,12 +312,7 @@ def item_function_wrapper(*args, **kwargs):
306312 else : # function
307313 fig = original (* args , ** kwargs )
308314
309- # We only need to close actual Matplotlib figure objects. If
310- # we are dealing with a figure-like object that provides
311- # savefig but is not a real Matplotlib object, we shouldn't
312- # try closing it here.
313- if isinstance (fig , Figure ):
314- plt .close (fig )
315+ close_mpl_figure (fig )
315316
316317 if item .cls is not None :
317318 setattr (item .cls , item .function .__name__ , item_function_wrapper )
0 commit comments