Skip to content

Commit

Permalink
Merge pull request #1 from radarhere/check-image-has-fp-when-close
Browse files Browse the repository at this point in the history
Do not assign new fp attribute to image when closing
  • Loading branch information
RaphaelVRossi committed Nov 17, 2023
2 parents b25ece3 + 5f33175 commit 8186c63
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 16 deletions.
17 changes: 6 additions & 11 deletions Tests/test_image.py
@@ -1,4 +1,5 @@
import io
import logging
import os
import shutil
import sys
Expand Down Expand Up @@ -1014,20 +1015,14 @@ 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):
def test_close_graceful(self, caplog):
with Image.open("Tests/images/hopper.jpg") as im:
copy = im.copy()
im.close()
copy.close()

assert len(self._caplog.records) == 0
with caplog.at_level(logging.DEBUG):
im.close()
copy.close()
assert len(caplog.records) == 0
assert im.fp is None
assert copy.fp is None


class MockEncoder:
Expand Down
10 changes: 5 additions & 5 deletions src/PIL/Image.py
Expand Up @@ -549,17 +549,17 @@ def close(self):
:py:meth:`~PIL.Image.Image.load` method. See :ref:`file-handling` for
more information.
"""
try:
if hasattr(self, "fp"):
if hasattr(self, "fp"):
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()
self.fp = None
except Exception as msg:
logger.debug("Error closing: %s", msg)
self.fp = None
except Exception as msg:
logger.debug("Error closing: %s", msg)

if getattr(self, "map", None):
self.map = None
Expand Down

0 comments on commit 8186c63

Please sign in to comment.