pytest-mpl
pytest-mpl is a pytest plugin designed to facilitate image comparison for Matplotlib figures. It enables users to test their Matplotlib outputs by comparing generated images against reference images using root mean square (RMS) difference or against SHA-256 hashes. The library is actively maintained, with its latest version being 0.19.0, and typically sees a few releases per year.
Warnings
- breaking When testing figures within classes, hash library test names generated prior to v0.16.0 will be incompatible. You must regenerate or update baseline image names to include the class name.
- gotcha Tests marked with `@pytest.mark.mpl_image_compare` will only perform image comparison if pytest is run with the `--mpl` command-line option. Without this flag, the tests will execute, but only basic assertions (e.g., that the code runs without error) will be checked, not the visual output.
- gotcha Baseline images or hash libraries must be explicitly generated before running image comparison tests. Tests will fail if no reference images/hashes exist or if they are not found in the expected location.
- gotcha When a test marked with `mpl_image_compare` returns a figure, `pytest` versions 7.2 and higher may emit a `PytestReturnNotNoneWarning` if `pytest-mpl` is not properly installed or configured, which could become an exception in future `pytest` releases. Ensure `pytest-mpl` is correctly installed and activated.
- gotcha Matplotlib's rendering can sometimes exhibit minor differences across different operating systems, Python versions, or specific backend configurations (e.g., font rendering). While `pytest-mpl` aims for robustness, ensure your baseline generation environment closely matches your testing environment for cross-platform consistency if this is a concern.
Install
-
pip install pytest-mpl
Imports
- mpl_image_compare
import pytest @pytest.mark.mpl_image_compare
Quickstart
import matplotlib.pyplot as plt
import pytest
@pytest.mark.mpl_image_compare
def test_simple_plot():
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [4, 5, 6])
ax.set_title("A simple line plot")
return fig
# To generate baseline images (run once or when figures change):
# pytest --mpl-generate-path=baseline_images
# To run tests and compare against baselines:
# pytest --mpl