Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This line isn't strictly necessary to test the change. Are you closing im here just to be thorough and ensure that it also doesn't log any errors?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah! 👍

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