Improve SgiImagePlugin test coverage by radarhere · Pull Request #8896 · python-pillow/Pillow

Looking at SgiImagePlugin, I see that an error for the incorrect number of bands will never be raised.

dim = 3
# X Dimension = width / Y Dimension = height
x, y = im.size
if im.mode == "L" and y == 1:
dim = 1
elif im.mode == "L":
dim = 2
# Z Dimension: Number of channels
z = len(im.mode)
if dim in {1, 2}:
z = 1
# assert we've got the right number of bands.
if len(im.getbands()) != z:
msg = f"incorrect number of bands in SGI write: {z} vs {len(im.getbands())}"
raise ValueError(msg)

Only L, RGB and RGBA modes are supported when saving.

def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
if im.mode not in {"RGB", "RGBA", "L"}:
msg = "Unsupported SGI image mode"

In the first code snippet, you can see that z = len(im.mode) would be set z to the correct values of 1 for L, 3 for RGB and 4 for RGBA. It is later set to 1 if dim is 1 or 2, but dim only has those values for L mode images, which should be 1 anyway.

So the error can be removed.

After some code simplification, this adds coverage for the lines missing at https://app.codecov.io/gh/python-pillow/Pillow/blob/main/src%2FPIL%2FSgiImagePlugin.py