From 3b406112d0b59d525ddf81996918c035168d928c Mon Sep 17 00:00:00 2001 From: "James R. Barlow" Date: Tue, 25 Jan 2022 23:45:47 -0800 Subject: [PATCH] ghostscript: improve test coverage of error cases --- src/ocrmypdf/_exec/ghostscript.py | 9 ++++----- tests/test_ghostscript.py | 21 ++++++++++++++++++++- 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/src/ocrmypdf/_exec/ghostscript.py b/src/ocrmypdf/_exec/ghostscript.py index 9a1d596a..d791a4a3 100644 --- a/src/ocrmypdf/_exec/ghostscript.py +++ b/src/ocrmypdf/_exec/ghostscript.py @@ -71,7 +71,8 @@ def jpeg_passthrough_available() -> bool: def _gs_error_reported(stream) -> bool: - return True if re.search(r'error', stream, flags=re.IGNORECASE) else False + match = re.search(r'error', stream, flags=re.IGNORECASE) + return bool(match) def rasterize_pdf( @@ -160,16 +161,14 @@ class GhostscriptFollower: if not self.progressbar_class: return if not self.progressbar: - m = self.re_process.match(line.strip()) - if m: + if m := self.re_process.match(line.strip()): self.count = int(m.group(1)) self.progressbar = self.progressbar_class( total=self.count, desc="PDF/A conversion", unit='page' ) return else: - m = self.re_page.match(line.strip()) - if m: + if self.re_page.match(line.strip()): self.progressbar.update() diff --git a/tests/test_ghostscript.py b/tests/test_ghostscript.py index 45b1ca37..b612fc57 100644 --- a/tests/test_ghostscript.py +++ b/tests/test_ghostscript.py @@ -6,11 +6,13 @@ import logging +import subprocess from decimal import Decimal +from unittest.mock import patch import pikepdf import pytest -from PIL import Image +from PIL import Image, UnidentifiedImageError from ocrmypdf._exec.ghostscript import rasterize_pdf from ocrmypdf.exceptions import ExitCode @@ -124,3 +126,20 @@ def test_ghostscript_feature_elision(resources, outpdf): '--plugin', 'tests/plugins/gs_feature_elision.py', ) + + +def test_rasterize_pdf_errors(resources, no_outpdf, caplog): + with patch('ocrmypdf._exec.ghostscript.run') as mock: + # ghostscript can produce + mock.return_value = subprocess.CompletedProcess( + ['fakegs'], returncode=0, stdout=b'', stderr=b'error this is an error' + ) + with pytest.raises(UnidentifiedImageError): + rasterize_pdf( + resources / 'francais.pdf', + no_outpdf, + raster_device='pngmono', + raster_dpi=Resolution(100, 100), + ) + assert "this is an error" in caplog.text + assert "invalid page image file" in caplog.text