fix: check object Image has attribute 'fp' when closes

This commit is contained in:
Raphael Vieira Rossi 2023-11-16 16:46:11 -03:00
parent da0b826e96
commit b25ece364b
No known key found for this signature in database
GPG Key ID: 898D70D024102716
2 changed files with 22 additions and 6 deletions

View File

@ -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

View File

@ -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)