Skip to content

Commit 54b9ab2

Browse files
committed
ENH: Support setting the backend per-test. (Fixes #35)
This works by using matplotlib's "experimental" support for switching backends, and should only be used to switch between image backends.
1 parent c213546 commit 54b9ab2

File tree

1 file changed

+18
-1
lines changed

1 file changed

+18
-1
lines changed

pytest_mpl/plugin.py

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030

3131
from functools import wraps
3232

33+
import contextlib
3334
import os
3435
import sys
3536
import 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+
95111
class 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

Comments
 (0)