3030
3131from functools import wraps
3232
33+ import contextlib
3334import os
3435import sys
3536import shutil
@@ -92,6 +93,21 @@ def pytest_configure(config):
9293 generate_dir = generate_dir ))
9394
9495
96+ @contextlib .contextmanager
97+ def switch_backend (backend ):
98+ prev_backend = matplotlib .get_backend ().lower ()
99+ print ('Was: ' , prev_backend )
100+ if prev_backend != backend .lower ():
101+ print ('Switching to' , backend )
102+ plt .switch_backend (backend )
103+ yield
104+ print ('Switching back to' , prev_backend )
105+ plt .switch_backend (prev_backend )
106+ else :
107+ print ('No switch' )
108+ yield
109+
110+
95111class ImageComparison (object ):
96112
97113 def __init__ (self , config , baseline_dir = None , generate_dir = None ):
@@ -110,6 +126,7 @@ def pytest_runtest_setup(self, item):
110126 savefig_kwargs = compare .kwargs .get ('savefig_kwargs' , {})
111127 style = compare .kwargs .get ('style' , 'classic' )
112128 remove_text = compare .kwargs .get ('remove_text' , False )
129+ backend = compare .kwargs .get ('backend' , 'agg' )
113130
114131 if MPL_LT_15 and style == 'classic' :
115132 style = os .path .join (os .path .dirname (__file__ ), 'classic.mplstyle' )
@@ -131,7 +148,7 @@ def item_function_wrapper(*args, **kwargs):
131148
132149 baseline_remote = baseline_dir .startswith ('http' )
133150
134- with plt .style .context (style ):
151+ with plt .style .context (style ), switch_backend ( backend ) :
135152
136153 # Run test and get figure object
137154 import inspect
0 commit comments