Skip to content

Commit

Permalink
Merge pull request #1 from joniemi/save_pickled_figures
Browse files Browse the repository at this point in the history
Save pickled figures
  • Loading branch information
joniemi authored Jun 3, 2020
2 parents 7df1b44 + 62a70ad commit ca4e751
Show file tree
Hide file tree
Showing 4 changed files with 69 additions and 6 deletions.
12 changes: 12 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,18 @@ if the PDF format is unsuitable.
plt.saveas = "%s.png" % (plt.saveas[:-4],)
Moreover, using the extension ``.pickle`` will tell pytest-plt to pickle the
current figure object. The figure can then be inspected using pyplot's
interactive GUI after unpickling the file. You can achieve this with the
following code snippet.

.. code-block:: python
import pickle
import matplotlib.pyplot as plt
pickle.load(open('path/to/my/plot/figure.pickle', 'rb'))
plt.show()
Configuration
=============

Expand Down
14 changes: 10 additions & 4 deletions pytest_plt/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import errno
import os
import pickle
import re

from matplotlib import use as mpl_use
Expand Down Expand Up @@ -147,10 +148,15 @@ def __exit__(self, type, value, traceback):

def save(self, path):
mkdir_p(os.path.dirname(path))
savefig_kw = {"bbox_inches": "tight"}
if hasattr(self.plt, "bbox_extra_artists"):
savefig_kw["bbox_extra_artists"] = self.plt.bbox_extra_artists
self.plt.savefig(path, **savefig_kw)

if path.endswith(".pickle"):
pickle.dump(self.plt.gcf(), open(path, "wb"))
else:
savefig_kw = {"bbox_inches": "tight"}
if hasattr(self.plt, "bbox_extra_artists"):
savefig_kw["bbox_extra_artists"] = self.plt.bbox_extra_artists
self.plt.savefig(path, **savefig_kw)

super(Plotter, self).save(path)


Expand Down
5 changes: 5 additions & 0 deletions pytest_plt/tests/test_plt.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,3 +42,8 @@ def test_bbox_extra_artists(plt):
def test_saveas(plt):
assert plt.saveas.endswith("saveas.pdf")
plt.saveas = None


def test_saveas_pickle(plt):
plt.subplots(2, 3) # The pickled figure will contain six axes.
plt.saveas = "%s.pickle" % (plt.saveas[:-4],)
44 changes: 42 additions & 2 deletions pytest_plt/tests/test_pytest.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
test files can be run manually by passing them to ``pytest``.
"""

import pickle
import matplotlib.pyplot as plt
from pathlib import Path

import pytest
Expand Down Expand Up @@ -49,7 +51,7 @@ def assert_all_passed(result):
"""
outcomes = result.parseoutcomes()
for outcome in outcomes:
if outcome not in ("passed", "seconds", "warnings"):
if outcome not in ("passed", "seconds", "warning"):
assert outcomes[outcome] == 0
return outcomes.get("passed", 0)

Expand Down Expand Up @@ -145,7 +147,7 @@ def test_filename_drop_prefix(testdir, prefix):
path = Path(plot)
assert path.parts[0] == "plots"
assert path.stem == plot_name
assert path.suffix in [".pdf", ".png"]
assert path.suffix in [".pdf", ".png", ".pickle"]
assert path.exists()


Expand Down Expand Up @@ -221,3 +223,41 @@ def test_default_dir(testdir):
assert path.parts[0] == "myoverridedir"
assert path.name.startswith("package.tests.")
assert path.exists()


def test_pickle_files_contain_a_figure(testdir):
""" Verify that pickle files can be loaded and contain the correct
figure. Th figure is tested by simply checking the number of axes.
For the expected number of axes, see test_plt.py::test_saveas_pickle
"""
copy_all_tests(testdir, "package/tests")

result = testdir.runpytest("-v", "--plots")

saved_files = [Path(plot) for _, plot in saved_plots(result)]
saved_pickle_files = [path for path in saved_files if path.suffix == ".pickle"]

for pickle_file in saved_pickle_files:
try:
pickle.load(open(pickle_file, "rb"))
assert 6 == len(plt.gcf().axes)
except pickle.UnpicklingError:
assert False, "Could not read a pickled file {}".format(str(pickle_file))


def test_image_files_are_not_pickled(testdir):
""" Verify that other output file formats are not mistakenly being
pickled.
"""
copy_all_tests(testdir, "package/tests")

result = testdir.runpytest("-v", "--plots")

saved_files = [Path(plot) for _, plot in saved_plots(result)]
saved_img_files = [path for path in saved_files if path.suffix != ".pickle"]

for img_file in saved_img_files:
with pytest.raises(pickle.UnpicklingError):
pickle.load(open(img_file, "rb"))

0 comments on commit ca4e751

Please sign in to comment.