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.
pip install pytest-mplVerified import paths — ran on the pinned version, not inferred.
This example defines a basic pytest function that creates a Matplotlib figure and returns it. The `@pytest.mark.mpl_image_compare` decorator instructs pytest-mpl to compare the generated figure against a baseline. The commands below the code show how to generate initial baseline images and how to run the comparison tests. Ensure a directory named 'baseline_images' (or your chosen path) exists next to your test file.
Regenerate your hash library or update baseline image filenames to incorporate the class name for affected tests. Refer to the v0.16.0 release notes for details.
Always run pytest with `pytest --mpl` to enable image comparison for marked tests. Consider adding `--mpl` to your `pytest.ini` `addopts` for consistent behavior.
Generate baseline images using `pytest --mpl-generate-path=your_baseline_dir` or a hash library with `pytest --mpl-generate-hash-library=your_hash_library.json`. Store these baselines in a consistent, version-controlled location.
Verify `pytest-mpl` is installed (`pip install pytest-mpl`) and that pytest is loading it (check `pytest --trace-config`). `pytest-mpl` has added compatibility for `pytest 7` and `pytest 8.1` in recent versions.
Generate and test baselines in a consistent CI/CD environment or a Docker container to minimize environmental variations. Adjust the `tolerance` parameter in `@pytest.mark.mpl_image_compare` if minor, acceptable differences occur.