Skip to main content

Fixtures for quickly making Matplotlib plots in tests

Project description

pytest-plt

pytest-plt provides fixtures for quickly creating Matplotlib plots in your tests.

Create PDF plots in one line with the plt fixture.

def test_rectification(plt):
    values = list(range(-10, 11))
    rectified = [v if v > 0 else 0 for v in values]
    assert all(v >= 0 for v in rectified)
    plt.plot(values, label="Original")
    plt.plot(rectified, label="Rectified")
    plt.legend()
https://i.imgur.com/2BFq2G2.png

To use these fixtures, install with

pip install pytest-plt

And pass the --plots option

pytest --plots

Usage

The plt fixture allows you to create PDF plots with as little as one line. It exposes the matplotlib.pyplot interface.

When running your tests, pass the --plots option (with optional directory name) to generate the plots (in this case, we save them to the “my_plots” directory):

pytest --plots my_plots

If no directory name is provided, plots will be saved to the “plots” directory:

pytest --plots

If you do not pass the --plots option, no Matplotlib commands will be executed, speeding up test execution.

Custom filenames and extensions

pytest-plt attempts to give each plot a readable name without being too long. Sometimes the default name is not good enough, so plt allows you to change it using plt.saveas:

def test_rectification(plt):
    values = list(range(-10, 11))
    rectified = [v if v > 0 else 0 for v in values]
    assert all(v >= 0 for v in rectified)
    plt.plot(values, label="Original")
    plt.plot(rectified, label="Rectified")
    plt.legend()
    plt.saveas = "test_rec.png"

The plt.saveas attribute contains the filename that will appear in the plots directory. You can modify this attribute within your test to change the filename that will be used to save the plot for a given test function. In the above example, running pytest with pytest --plots my_plots will result in a my_plots/test_rec.png file.

It should be noted that the file extension in plt.saveas will be used when saving the plot. That is, in the example above, the resulting plot will be a true PNG file, not a PDF with an incorrect .png extension. You can use the following snippet to change the file extension in a specific test if the PDF format is unsuitable.

plt.saveas = "%s.png" % (plt.saveas[:-4],)

Using plt.show

If you want to inspect a figure using the GUI that pops up with plt.show(), you can achieve this by saving a plot with the .pkl or .pickle extension. pytest-plt will pickle the current figure object for later inspection.

Building on the previous example, you can change the saveas attribute like so:

def test_rectification(plt):
    values = list(range(-10, 11))
    rectified = [v if v > 0 else 0 for v in values]
    assert all(v >= 0 for v in rectified)
    plt.plot(values, label="Original")
    plt.plot(rectified, label="Rectified")
    plt.legend()
    plt.saveas = "test_rec.pkl"

Then use the following snippet to inspect the figure.

>>> import pickle
>>> import matplotlib.pyplot as plt
>>> with open("path/to/test_rec.pkl", "rb") as fh:
...     fig = pickle.load(fh)
>>> plt.show()

Configuration

The following configuration options exist.

plt_filename_drop

plt_filename_drop accepts a list of regular expressions for parts of the filename to drop.

By default, plot filenames contain the full nodeid for the test in question, with directory separators (/) replaced with dots (.). If all tests reside in the same project directory, that name will appear at the start of all plot filenames, making them unnecessarily long.

In this case, we use the carat ^ to ensure that our regex matches the start of the filename only, and we remove the trailing dot as well (\.):

plt_filename_drop =
    ^project\.

If your tests always reside in a directory with a particular name (e.g. “tests”), you can safely remove this name wherever it occurs. In this case, we do not use the carat to allow the regex to match anywhere in the filename. Be careful, as this will match any directory that ends with “tests” (e.g. “other_tests”), and will remove the ends of these directory names.

plt_filename_drop =
    ^project\.
    tests\.

When using plt_filename_drop, take care to avoid collisions (situations where plots from two different tests will end up with the same name). In this case, the plots of later tests will override those of earlier tests with the same name.

plt_dirname

plt_dirname changes the default directory name for output plots.

The default plt_dirname is "plots". To change it to "test_plots", for example, add the following to your pytest.ini.

plt_dirname = test_plots

A directory provided at the command line with the --plots flag takes priority over plt_dirname.

See the full documentation for more details and configuration options.

Release History

1.1.1 (January 15, 2024)

Changed

  • Python 3.5, which is past its end of life, is no longer supported. (#26)

Fixed

  • Config options are now properly added to Pytest, eliminating a warning that was raised if a config option was set. (#26)

  • Handled multiple outputs when mocking out plt.subplots. (#29)

1.1.0 (August 17, 2020)

Added

  • Added the ability to save plots as pickle files using the .pkl or .pickle extensions with plt.saveas. (#23)

1.0.1 (October 28, 2019)

Fixed

  • We now use Windows-compatible plot filenames by default. Colons in plot filenames are replaced with hyphens. Filenames specified through plt.saveas are not modified. (#17, #21)

1.0.0 (August 9, 2019)

Initial release of pytest-plt! Thanks to all of the contributors for making this possible!

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pytest-plt-1.1.1.tar.gz (20.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pytest_plt-1.1.1-py3-none-any.whl (12.1 kB view details)

Uploaded Python 3

File details

Details for the file pytest-plt-1.1.1.tar.gz.

File metadata

  • Download URL: pytest-plt-1.1.1.tar.gz
  • Upload date:
  • Size: 20.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.9.18

File hashes

Hashes for pytest-plt-1.1.1.tar.gz
Algorithm Hash digest
SHA256 4cebb2547db028aaeecbb481356df3eb6cb3a66053ea5e9170a8683b55d41611
MD5 c391d6b8d5d0d50b9a82364e3ee7af50
BLAKE2b-256 0fbc2cbd5862edaddf9c06cbb90452e200dbae3106f58ac6b75737cc6e7c14f2

See more details on using hashes here.

File details

Details for the file pytest_plt-1.1.1-py3-none-any.whl.

File metadata

  • Download URL: pytest_plt-1.1.1-py3-none-any.whl
  • Upload date:
  • Size: 12.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.9.18

File hashes

Hashes for pytest_plt-1.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 f7b700f2a9add47666fc40e03ebd487f29ed20b558249cff48ff4aac62bd6be6
MD5 c29be995ca1801c940ff93d1f352318b
BLAKE2b-256 d9cde479c8ec8487cc2d9cb918a4c6a5391a1de0fc40a9828e1dc85c45cb933e

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page