diff --git a/docs/src/python/plot_utils.py b/docs/src/python/plot_utils.py index 2f18c794..89381617 100644 --- a/docs/src/python/plot_utils.py +++ b/docs/src/python/plot_utils.py @@ -106,7 +106,16 @@ def save_fig(fig, file_name, fmt=None, dpi=300, tight=True): subprocess.call('epstool --bbox --copy %s %s' % (tmp_name, file_name), shell=True) elif fmt == 'png': - subprocess.check_call(['convert', tmp_name, '-trim', file_name]) + try: + result = subprocess.call(['convert', tmp_name, '-trim', file_name]) + except OSError as exc: + logging.getLogger(__name__).warning( + "Could not run PNG trimmer: %s", exc + ) + result = 1 + # Do not let a partial conversion look like a successful result. + if result != 0 and os.path.isfile(file_name): + os.remove(file_name) elif fmt == 'pdf': subprocess.call('pdfcrop %s %s' % (tmp_name, file_name), shell=True) diff --git a/tests/test_plot_utils.py b/tests/test_plot_utils.py index c9439ff3..8fcf147d 100644 --- a/tests/test_plot_utils.py +++ b/tests/test_plot_utils.py @@ -1,7 +1,6 @@ """Regression tests for the figure-saving helper.""" import importlib.util -import subprocess import sys from pathlib import Path from tempfile import TemporaryDirectory @@ -33,22 +32,28 @@ class SaveFigTests(TestCase): def setUpClass(cls): cls.plot_utils = load_plot_utils() - def test_png_path_with_spaces_is_preserved_and_failures_are_raised(self): + def test_png_path_with_spaces_is_preserved_when_trimmer_fails(self): figure = Mock() + figure_data = b"saved figure" + + def write_temporary_figure(path, **kwargs): + Path(path).write_bytes(figure_data) + + figure.savefig.side_effect = write_temporary_figure + with TemporaryDirectory() as temporary: output = Path(temporary) / "target with space.png" - failure = subprocess.CalledProcessError(1, "convert") with patch.object( self.plot_utils.subprocess, - "check_call", - side_effect=failure, - ) as check_call: - with self.assertRaises(subprocess.CalledProcessError): - self.plot_utils.save_fig(figure, str(output)) + "call", + return_value=1, + ) as call: + self.plot_utils.save_fig(figure, str(output)) - check_call.assert_called_once_with([ + call.assert_called_once_with([ "convert", ANY, "-trim", str(output.resolve()) ]) + self.assertEqual(output.read_bytes(), figure_data) if __name__ == "__main__":