changes made to imagefile

This commit is contained in:
Deekshu Kare 2024-06-22 00:31:48 +02:00
parent 1bd1526ae6
commit 1881f22e89
3 changed files with 53 additions and 37 deletions

View File

@ -218,16 +218,60 @@ class MockPyEncoder(ImageFile.PyEncoder):
last: MockPyEncoder | None
def __init__(self, mode: str, *args: Any) -> None:
MockPyEncoder.last = self
super().__init__(mode, *args)
self._pushes_fd = False
self.cleanup_called = False
def encode(self, buffer):
# Simulate encoding
if buffer is None:
raise NotImplementedError
return 1, 1, b""
def cleanup(self) -> None:
self.cleanup_called = True
def test_encode_to_file() -> None:
encoder = MockPyEncoder("RGBA")
# Case: _pushes_fd is False
with pytest.raises(NotImplementedError):
encoder.encode_to_file(None, None)
# Case: _pushes_fd is True
encoder._pushes_fd = True
with pytest.raises(NotImplementedError):
encoder.encode_to_file(None, None)
# Case: encode method called with buffer (no exception)
buffer = BytesIO(b"\x00" * 10)
encoder._pushes_fd = False
encoder.encode = lambda buffer: (1, 1, b"")
try:
encoder.encode_to_file(buffer, None)
except NotImplementedError:
pass # NotImplementedError is expected
# Case: encode method raises NotImplementedError
encoder.encode = lambda buffer: (_ for _ in ()).throw(NotImplementedError)
with pytest.raises(NotImplementedError):
encoder.encode_to_file(buffer, None)
# Case: cleanup is called after exception
encoder.encode = lambda buffer: (_ for _ in ()).throw(ValueError)
with pytest.raises(ValueError):
encoder.encode_to_file(buffer, None)
assert encoder.cleanup_called
# Case: encode returns unexpected values
encoder.encode = lambda buffer: (None, None, None)
with pytest.raises(ValueError):
encoder.encode_to_file(buffer, None)
# Case: UnidentifiedImageError
with pytest.raises(UnidentifiedImageError):
encoder.encode_to_file(buffer, BytesIO(b"\x00" * 10))
xoff, yoff, xsize, ysize = 10, 20, 100, 100
@ -397,12 +441,3 @@ class TestPyEncoder(CodecsTest):
def test_zero_height(self) -> None:
with pytest.raises(UnidentifiedImageError):
Image.open("Tests/images/zero_height.j2k")
def test_encode_to_file_branches(self) -> None:
mock_file = BytesIO()
encoder = ImageFile.PyEncoder("RGB")
encoder.branches = {"1": False, "2": False}
errcode = encoder.encode_to_file(mock_file, 1024)
assert encoder.branches["1"] is True
assert encoder.branches["2"] is True
assert errcode == 0

View File

@ -15,7 +15,7 @@ def calculate_coverage(test_name):
all_branches = {
"branches1": Image.branches,
"branches2": PdfParser.XrefTable.branches,
"branches3": ImageCms.ImageCmsProfile.branches,
"branches3": ImageCms.PyCMSError.branches,
"branches4": McIdasImagePlugin.McIdasImageFile.branches,
"branches5": ImageFile.PyEncoder.branches,
# Add more

View File

@ -32,12 +32,6 @@ from ._typing import SupportsRead
branches = {
"1": False,
"2": False,
"3": False,
"4": False,
"5": False,
"6": False,
"7": False,
"8": False,
}
try:
@ -248,17 +242,6 @@ _FLAGS = {
class ImageCmsProfile:
branches = {
"1": False,
"2": False,
"3": False,
"4": False,
"5": False,
"6": False,
"7": False,
"8": False,
}
def __init__(self, profile: str | SupportsRead[bytes] | core.CmsProfile) -> None:
"""
:param profile: Either a string representing a filename,
@ -268,28 +251,20 @@ class ImageCmsProfile:
"""
if isinstance(profile, str):
ImageCmsProfile.branches["1"] = True
if sys.platform == "win32":
ImageCmsProfile.branches["2"] = True
profile_bytes_path = profile.encode()
try:
ImageCmsProfile.branches["3"] = True
profile_bytes_path.decode("ascii")
except UnicodeDecodeError:
ImageCmsProfile.branches["4"] = True
with open(profile, "rb") as f:
ImageCmsProfile.branches["5"] = True
self._set(core.profile_frombytes(f.read()))
return
self._set(core.profile_open(profile), profile)
elif hasattr(profile, "read"):
ImageCmsProfile.branches["6"] = True
self._set(core.profile_frombytes(profile.read()))
elif isinstance(profile, core.CmsProfile):
ImageCmsProfile.branches["7"] = True
self._set(profile)
else:
ImageCmsProfile.branches["8"] = True
msg = "Invalid type for Profile" # type: ignore[unreachable]
raise TypeError(msg)
@ -403,6 +378,10 @@ _CmsProfileCompatible = Union[
class PyCMSError(Exception):
branches = {
"1": False,
"2": False,
}
"""(pyCMS) Exception class.
This is used for all errors in the pyCMS API."""
@ -524,8 +503,10 @@ def getOpenProfile(
"""
try:
PyCMSError.branches["1"] = True
return ImageCmsProfile(profileFilename)
except (OSError, TypeError, ValueError) as v:
PyCMSError.branches["2"] = True
raise PyCMSError(v) from v