Last active
June 25, 2022 16:55
-
-
Save rcomer/4ff103569b1154ae99742ab785e3ea90 to your computer and use it in GitHub Desktop.
Sketch of how Iris gallery tests might work with `pytest-mpl`. I guess we'd need multiple classes to handle examples with different numbers of figures (at time of writing all examples have one, two or four figures). See also https://stackoverflow.com/questions/72659961/generate-multiple-tests-based-on-a-functions-output.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import warnings | |
import matplotlib.pyplot as plt | |
import pytest | |
def my_plots(): | |
plt.figure() | |
plt.plot([0, 1]) | |
plt.show() | |
plt.figure() | |
plt.plot([0, 2]) | |
warnings.warn("bad things may happen") | |
plt.show() | |
def my_other_plots(): | |
plt.plot([1, 0]) | |
plt.show() | |
plt.figure() | |
plt.plot([-3, 5]) | |
plt.show() | |
@pytest.fixture(scope="class") | |
def image_setup_teardown(plot_func): | |
plt.close("all") | |
yield | |
plt.close("all") | |
@pytest.mark.mpl_image_compare | |
def check_fig(self, fig_index, get_figures): | |
return get_figures[fig_index] | |
@pytest.mark.parametrize("plot_func", [my_plots, my_other_plots], scope="class") | |
class TestPlots: | |
@pytest.fixture(scope="class") | |
def get_figures(self, plot_func, image_setup_teardown): | |
figs = [] | |
def append_fig(): | |
figs.append(plt.gcf()) | |
with pytest.MonkeyPatch.context() as mp: | |
mp.setattr(plt, "show", append_fig) | |
plot_func() | |
return figs | |
@pytest.mark.filterwarnings("error") | |
def test_num_figs(self, get_figures): | |
assert len(get_figures) == 2 | |
test_my_plots = pytest.mark.parametrize("fig_index", [0, 1])(check_fig) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment