Skip to content

Commit

Permalink
fix: check object Image has attribute 'fp' when closes
Browse files Browse the repository at this point in the history
  • Loading branch information
RaphaelVRossi committed Nov 16, 2023
1 parent da0b826 commit b25ece3
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 6 deletions.
15 changes: 15 additions & 0 deletions Tests/test_image.py
Original file line number Diff line number Diff line change
Expand Up @@ -1014,6 +1014,21 @@ def test_fli_overrun2(self):
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
Expand Down
13 changes: 7 additions & 6 deletions src/PIL/Image.py
Original file line number Diff line number Diff line change
Expand Up @@ -550,12 +550,13 @@ def close(self):
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)
Expand Down

0 comments on commit b25ece3

Please sign in to comment.