From b25ece364b5e7d9f97df38ca82b15c83c98daf6c Mon Sep 17 00:00:00 2001 From: Raphael Vieira Rossi Date: Thu, 16 Nov 2023 16:46:11 -0300 Subject: [PATCH] fix: check object Image has attribute 'fp' when closes --- Tests/test_image.py | 15 +++++++++++++++ src/PIL/Image.py | 13 +++++++------ 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/Tests/test_image.py b/Tests/test_image.py index 9efd4c467..0c6843346 100644 --- a/Tests/test_image.py +++ b/Tests/test_image.py @@ -1014,6 +1014,21 @@ class TestImage: except OSError as e: assert str(e) == "buffer overrun when reading image file" + @pytest.fixture(scope="function") + def inject_caplog(self, caplog): + self._caplog = caplog + + @pytest.mark.usefixtures("inject_caplog") + def test_close_graceful(self): + with Image.open("Tests/images/hopper.jpg") as im: + copy = im.copy() + im.close() + copy.close() + + assert len(self._caplog.records) == 0 + assert im.fp is None + assert copy.fp is None + class MockEncoder: pass diff --git a/src/PIL/Image.py b/src/PIL/Image.py index 546d90203..c873a93e7 100644 --- a/src/PIL/Image.py +++ b/src/PIL/Image.py @@ -550,12 +550,13 @@ class Image: more information. """ try: - if getattr(self, "_fp", False): - if self._fp != self.fp: - self._fp.close() - self._fp = DeferredError(ValueError("Operation on closed image")) - if self.fp: - self.fp.close() + if hasattr(self, "fp"): + if getattr(self, "_fp", False): + if self._fp != self.fp: + self._fp.close() + self._fp = DeferredError(ValueError("Operation on closed image")) + if self.fp: + self.fp.close() self.fp = None except Exception as msg: logger.debug("Error closing: %s", msg)