Converted to pytest

This commit is contained in:
Andrew Murray 2020-02-25 20:57:27 +11:00
parent 80994bc0e5
commit 09b9198176
14 changed files with 1190 additions and 1144 deletions

View File

@ -3,23 +3,21 @@ import os
import pytest
from PIL import Image
from .helper import PillowTestCase, assert_image_similar
from .helper import assert_image_similar
base = os.path.join("Tests", "images", "bmp")
class TestBmpReference(PillowTestCase):
def get_files(self, d, ext=".bmp"):
def get_files(d, ext=".bmp"):
return [
os.path.join(base, d, f)
for f in os.listdir(os.path.join(base, d))
if ext in f
os.path.join(base, d, f) for f in os.listdir(os.path.join(base, d)) if ext in f
]
def test_bad(self):
def test_bad():
""" These shouldn't crash/dos, but they shouldn't return anything
either """
for f in self.get_files("b"):
for f in get_files("b"):
def open(f):
try:
@ -31,7 +29,8 @@ class TestBmpReference(PillowTestCase):
# Assert that there is no unclosed file warning
pytest.warns(None, open, f)
def test_questionable(self):
def test_questionable():
""" These shouldn't crash/dos, but it's not well defined that these
are in spec """
supported = [
@ -45,7 +44,7 @@ class TestBmpReference(PillowTestCase):
"pal8os2sp.bmp",
"rgb32bf-xbgr.bmp",
]
for f in self.get_files("q"):
for f in get_files("q"):
try:
with Image.open(f) as im:
im.load()
@ -55,7 +54,8 @@ class TestBmpReference(PillowTestCase):
if os.path.basename(f) in supported:
raise
def test_good(self):
def test_good():
""" These should all work. There's a set of target files in the
html directory that we can compare against. """
@ -86,7 +86,7 @@ class TestBmpReference(PillowTestCase):
name = os.path.splitext(name)[0]
return os.path.join(base, "html", "%s.png" % name)
for f in self.get_files("g"):
for f in get_files("g"):
try:
with Image.open(f) as im:
im.load()
@ -107,5 +107,4 @@ class TestBmpReference(PillowTestCase):
os.path.join(base, "g", "pal8rle.bmp"),
os.path.join(base, "g", "pal4rle.bmp"),
)
if f not in unsupported:
self.fail("Unsupported Image {}: {}".format(f, msg))
assert f in unsupported, "Unsupported Image {}: {}".format(f, msg)

View File

@ -1,20 +1,21 @@
from PIL import Image
from .helper import PillowTestCase, assert_image_equal
from .helper import assert_image_equal
class TestFileBlp(PillowTestCase):
def test_load_blp2_raw(self):
def test_load_blp2_raw():
with Image.open("Tests/images/blp/blp2_raw.blp") as im:
with Image.open("Tests/images/blp/blp2_raw.png") as target:
assert_image_equal(im, target)
def test_load_blp2_dxt1(self):
def test_load_blp2_dxt1():
with Image.open("Tests/images/blp/blp2_dxt1.blp") as im:
with Image.open("Tests/images/blp/blp2_dxt1.png") as target:
assert_image_equal(im, target)
def test_load_blp2_dxt1a(self):
def test_load_blp2_dxt1a():
with Image.open("Tests/images/blp/blp2_dxt1a.blp") as im:
with Image.open("Tests/images/blp/blp2_dxt1a.png") as target:
assert_image_equal(im, target)

View File

@ -1,15 +1,15 @@
from PIL import Image
from .helper import PillowTestCase, assert_image_equal, assert_image_similar
from .helper import assert_image_equal, assert_image_similar
class TestFileFtex(PillowTestCase):
def test_load_raw(self):
def test_load_raw():
with Image.open("Tests/images/ftex_uncompressed.ftu") as im:
with Image.open("Tests/images/ftex_uncompressed.png") as target:
assert_image_equal(im, target)
def test_load_dxt1(self):
def test_load_dxt1():
with Image.open("Tests/images/ftex_dxt1.ftc") as im:
with Image.open("Tests/images/ftex_dxt1.png") as target:
assert_image_similar(im, target.convert("RGBA"), 15)

View File

@ -1,10 +1,7 @@
from PIL import Image
from .helper import PillowTestCase
class TestFilePcd(PillowTestCase):
def test_load_raw(self):
def test_load_raw():
with Image.open("Tests/images/hopper.pcd") as im:
im.load() # should not segfault.

View File

@ -1,22 +1,22 @@
import pytest
from PIL import Image
from .helper import PillowTestCase, assert_image_equal, assert_image_similar, hopper
from .helper import assert_image_equal, assert_image_similar, hopper
# sample ppm stream
test_file = "Tests/images/hopper.ppm"
TEST_FILE = "Tests/images/hopper.ppm"
class TestFilePpm(PillowTestCase):
def test_sanity(self):
with Image.open(test_file) as im:
def test_sanity():
with Image.open(TEST_FILE) as im:
im.load()
assert im.mode == "RGB"
assert im.size == (128, 128)
assert im.format, "PPM"
assert im.get_format_mimetype() == "image/x-portable-pixmap"
def test_16bit_pgm(self):
def test_16bit_pgm():
with Image.open("Tests/images/16_bit_binary.pgm") as im:
im.load()
assert im.mode == "I"
@ -26,35 +26,39 @@ class TestFilePpm(PillowTestCase):
with Image.open("Tests/images/16_bit_binary_pgm.png") as tgt:
assert_image_equal(im, tgt)
def test_16bit_pgm_write(self):
def test_16bit_pgm_write(tmp_path):
with Image.open("Tests/images/16_bit_binary.pgm") as im:
im.load()
f = self.tempfile("temp.pgm")
f = str(tmp_path / "temp.pgm")
im.save(f, "PPM")
with Image.open(f) as reloaded:
assert_image_equal(im, reloaded)
def test_pnm(self):
def test_pnm(tmp_path):
with Image.open("Tests/images/hopper.pnm") as im:
assert_image_similar(im, hopper(), 0.0001)
f = self.tempfile("temp.pnm")
f = str(tmp_path / "temp.pnm")
im.save(f)
with Image.open(f) as reloaded:
assert_image_equal(im, reloaded)
def test_truncated_file(self):
path = self.tempfile("temp.pgm")
def test_truncated_file(tmp_path):
path = str(tmp_path / "temp.pgm")
with open(path, "w") as f:
f.write("P6")
with pytest.raises(ValueError):
Image.open(path)
def test_neg_ppm(self):
def test_neg_ppm():
# Storage.c accepted negative values for xsize, ysize. the
# internal open_ppm function didn't check for sanity but it
# has been removed. The default opener doesn't accept negative
@ -63,8 +67,9 @@ class TestFilePpm(PillowTestCase):
with pytest.raises(IOError):
Image.open("Tests/images/negative_size.ppm")
def test_mimetypes(self):
path = self.tempfile("temp.pgm")
def test_mimetypes(tmp_path):
path = str(tmp_path / "temp.pgm")
with open(path, "w") as f:
f.write("P4\n128 128\n255")

View File

@ -1,11 +1,10 @@
import pytest
from PIL import Image, SgiImagePlugin
from .helper import PillowTestCase, assert_image_equal, assert_image_similar, hopper
from .helper import assert_image_equal, assert_image_similar, hopper
class TestFileSgi(PillowTestCase):
def test_rgb(self):
def test_rgb():
# Created with ImageMagick then renamed:
# convert hopper.ppm -compress None sgi:hopper.rgb
test_file = "Tests/images/hopper.rgb"
@ -14,13 +13,15 @@ class TestFileSgi(PillowTestCase):
assert_image_equal(im, hopper())
assert im.get_format_mimetype() == "image/rgb"
def test_rgb16(self):
def test_rgb16():
test_file = "Tests/images/hopper16.rgb"
with Image.open(test_file) as im:
assert_image_equal(im, hopper())
def test_l(self):
def test_l():
# Created with ImageMagick
# convert hopper.ppm -monochrome -compress None sgi:hopper.bw
test_file = "Tests/images/hopper.bw"
@ -29,7 +30,8 @@ class TestFileSgi(PillowTestCase):
assert_image_similar(im, hopper("L"), 2)
assert im.get_format_mimetype() == "image/sgi"
def test_rgba(self):
def test_rgba():
# Created with ImageMagick:
# convert transparent.png -compress None transparent.sgi
test_file = "Tests/images/transparent.sgi"
@ -39,7 +41,8 @@ class TestFileSgi(PillowTestCase):
assert_image_equal(im, target)
assert im.get_format_mimetype() == "image/sgi"
def test_rle(self):
def test_rle():
# Created with ImageMagick:
# convert hopper.ppm hopper.sgi
test_file = "Tests/images/hopper.sgi"
@ -48,22 +51,25 @@ class TestFileSgi(PillowTestCase):
with Image.open("Tests/images/hopper.rgb") as target:
assert_image_equal(im, target)
def test_rle16(self):
def test_rle16():
test_file = "Tests/images/tv16.sgi"
with Image.open(test_file) as im:
with Image.open("Tests/images/tv.rgb") as target:
assert_image_equal(im, target)
def test_invalid_file(self):
def test_invalid_file():
invalid_file = "Tests/images/flower.jpg"
with pytest.raises(ValueError):
SgiImagePlugin.SgiImageFile(invalid_file)
def test_write(self):
def test_write(tmp_path):
def roundtrip(img):
out = self.tempfile("temp.sgi")
out = str(tmp_path / "temp.sgi")
img.save(out, format="sgi")
with Image.open(out) as reloaded:
assert_image_equal(img, reloaded)
@ -74,19 +80,21 @@ class TestFileSgi(PillowTestCase):
# Test 1 dimension for an L mode image
roundtrip(Image.new("L", (10, 1)))
def test_write16(self):
def test_write16(tmp_path):
test_file = "Tests/images/hopper16.rgb"
with Image.open(test_file) as im:
out = self.tempfile("temp.sgi")
out = str(tmp_path / "temp.sgi")
im.save(out, format="sgi", bpc=2)
with Image.open(out) as reloaded:
assert_image_equal(im, reloaded)
def test_unsupported_mode(self):
def test_unsupported_mode(tmp_path):
im = hopper("LA")
out = self.tempfile("temp.sgi")
out = str(tmp_path / "temp.sgi")
with pytest.raises(ValueError):
im.save(out, format="sgi")

View File

@ -5,13 +5,12 @@ import pytest
from PIL import Image, TiffImagePlugin, TiffTags
from PIL.TiffImagePlugin import IFDRational
from .helper import PillowTestCase, assert_deep_equal, hopper
from .helper import assert_deep_equal, hopper
tag_ids = {info.name: info.value for info in TiffTags.TAGS_V2.values()}
TAG_IDS = {info.name: info.value for info in TiffTags.TAGS_V2.values()}
class TestFileTiffMetadata(PillowTestCase):
def test_rt_metadata(self):
def test_rt_metadata(tmp_path):
""" Test writing arbitrary metadata into the tiff image directory
Use case is ImageJ private tags, one numeric, one arbitrary
data. https://github.com/python-pillow/Pillow/issues/291
@ -36,20 +35,20 @@ class TestFileTiffMetadata(PillowTestCase):
doubledata = 67.89
info = TiffImagePlugin.ImageFileDirectory()
ImageJMetaData = tag_ids["ImageJMetaData"]
ImageJMetaDataByteCounts = tag_ids["ImageJMetaDataByteCounts"]
ImageDescription = tag_ids["ImageDescription"]
ImageJMetaData = TAG_IDS["ImageJMetaData"]
ImageJMetaDataByteCounts = TAG_IDS["ImageJMetaDataByteCounts"]
ImageDescription = TAG_IDS["ImageDescription"]
info[ImageJMetaDataByteCounts] = len(bindata)
info[ImageJMetaData] = bindata
info[tag_ids["RollAngle"]] = floatdata
info.tagtype[tag_ids["RollAngle"]] = 11
info[tag_ids["YawAngle"]] = doubledata
info.tagtype[tag_ids["YawAngle"]] = 12
info[TAG_IDS["RollAngle"]] = floatdata
info.tagtype[TAG_IDS["RollAngle"]] = 11
info[TAG_IDS["YawAngle"]] = doubledata
info.tagtype[TAG_IDS["YawAngle"]] = 12
info[ImageDescription] = textdata
f = self.tempfile("temp.tif")
f = str(tmp_path / "temp.tif")
img.save(f, tiffinfo=info)
@ -64,9 +63,9 @@ class TestFileTiffMetadata(PillowTestCase):
assert loaded.tag[ImageDescription] == (reloaded_textdata,)
assert loaded.tag_v2[ImageDescription] == reloaded_textdata
loaded_float = loaded.tag[tag_ids["RollAngle"]][0]
loaded_float = loaded.tag[TAG_IDS["RollAngle"]][0]
assert round(abs(loaded_float - floatdata), 5) == 0
loaded_double = loaded.tag[tag_ids["YawAngle"]][0]
loaded_double = loaded.tag[TAG_IDS["YawAngle"]][0]
assert round(abs(loaded_double - doubledata), 7) == 0
# check with 2 element ImageJMetaDataByteCounts, issue #2006
@ -78,7 +77,8 @@ class TestFileTiffMetadata(PillowTestCase):
assert loaded.tag[ImageJMetaDataByteCounts] == (8, len(bindata) - 8)
assert loaded.tag_v2[ImageJMetaDataByteCounts] == (8, len(bindata) - 8)
def test_read_metadata(self):
def test_read_metadata():
with Image.open("Tests/images/hopper_g4.tif") as img:
assert {
@ -119,10 +119,11 @@ class TestFileTiffMetadata(PillowTestCase):
"StripOffsets": (8,),
} == img.tag.named()
def test_write_metadata(self):
def test_write_metadata(tmp_path):
""" Test metadata writing through the python code """
with Image.open("Tests/images/hopper.tif") as img:
f = self.tempfile("temp.tiff")
f = str(tmp_path / "temp.tiff")
img.save(f, tiffinfo=img.tag)
original = img.tag_v2.named()
@ -154,20 +155,23 @@ class TestFileTiffMetadata(PillowTestCase):
if tag not in ignored:
assert value == reloaded[tag], "%s didn't roundtrip" % tag
def test_no_duplicate_50741_tag(self):
assert tag_ids["MakerNoteSafety"] == 50741
assert tag_ids["BestQualityScale"] == 50780
def test_empty_metadata(self):
def test_no_duplicate_50741_tag():
assert TAG_IDS["MakerNoteSafety"] == 50741
assert TAG_IDS["BestQualityScale"] == 50780
def test_empty_metadata():
f = io.BytesIO(b"II*\x00\x08\x00\x00\x00")
head = f.read(8)
info = TiffImagePlugin.ImageFileDirectory(head)
# Should not raise struct.error.
pytest.warns(UserWarning, info.load, f)
def test_iccprofile(self):
def test_iccprofile(tmp_path):
# https://github.com/python-pillow/Pillow/issues/1462
out = self.tempfile("temp.tiff")
out = str(tmp_path / "temp.tiff")
with Image.open("Tests/images/hopper.iccprofile.tif") as im:
im.save(out)
@ -175,7 +179,8 @@ class TestFileTiffMetadata(PillowTestCase):
assert not isinstance(im.info["icc_profile"], tuple)
assert im.info["icc_profile"] == reloaded.info["icc_profile"]
def test_iccprofile_binary(self):
def test_iccprofile_binary():
# https://github.com/python-pillow/Pillow/issues/1526
# We should be able to load this,
# but probably won't be able to save it.
@ -184,29 +189,33 @@ class TestFileTiffMetadata(PillowTestCase):
assert im.tag_v2.tagtype[34675] == 1
assert im.info["icc_profile"]
def test_iccprofile_save_png(self):
def test_iccprofile_save_png(tmp_path):
with Image.open("Tests/images/hopper.iccprofile.tif") as im:
outfile = self.tempfile("temp.png")
outfile = str(tmp_path / "temp.png")
im.save(outfile)
def test_iccprofile_binary_save_png(self):
def test_iccprofile_binary_save_png(tmp_path):
with Image.open("Tests/images/hopper.iccprofile_binary.tif") as im:
outfile = self.tempfile("temp.png")
outfile = str(tmp_path / "temp.png")
im.save(outfile)
def test_exif_div_zero(self):
def test_exif_div_zero(tmp_path):
im = hopper()
info = TiffImagePlugin.ImageFileDirectory_v2()
info[41988] = TiffImagePlugin.IFDRational(0, 0)
out = self.tempfile("temp.tiff")
out = str(tmp_path / "temp.tiff")
im.save(out, tiffinfo=info, compression="raw")
with Image.open(out) as reloaded:
assert 0 == reloaded.tag_v2[41988].numerator
assert 0 == reloaded.tag_v2[41988].denominator
def test_ifd_unsigned_rational(self):
def test_ifd_unsigned_rational(tmp_path):
im = hopper()
info = TiffImagePlugin.ImageFileDirectory_v2()
@ -217,7 +226,7 @@ class TestFileTiffMetadata(PillowTestCase):
info[41493] = TiffImagePlugin.IFDRational(numerator, 1)
out = self.tempfile("temp.tiff")
out = str(tmp_path / "temp.tiff")
im.save(out, tiffinfo=info, compression="raw")
with Image.open(out) as reloaded:
@ -229,14 +238,15 @@ class TestFileTiffMetadata(PillowTestCase):
info[41493] = TiffImagePlugin.IFDRational(numerator, 1)
out = self.tempfile("temp.tiff")
out = str(tmp_path / "temp.tiff")
im.save(out, tiffinfo=info, compression="raw")
with Image.open(out) as reloaded:
assert max_long == reloaded.tag_v2[41493].numerator
assert 1 == reloaded.tag_v2[41493].denominator
def test_ifd_signed_rational(self):
def test_ifd_signed_rational(tmp_path):
im = hopper()
info = TiffImagePlugin.ImageFileDirectory_v2()
@ -246,7 +256,7 @@ class TestFileTiffMetadata(PillowTestCase):
info[37380] = TiffImagePlugin.IFDRational(numerator, denominator)
out = self.tempfile("temp.tiff")
out = str(tmp_path / "temp.tiff")
im.save(out, tiffinfo=info, compression="raw")
with Image.open(out) as reloaded:
@ -258,7 +268,7 @@ class TestFileTiffMetadata(PillowTestCase):
info[37380] = TiffImagePlugin.IFDRational(numerator, denominator)
out = self.tempfile("temp.tiff")
out = str(tmp_path / "temp.tiff")
im.save(out, tiffinfo=info, compression="raw")
with Image.open(out) as reloaded:
@ -271,26 +281,28 @@ class TestFileTiffMetadata(PillowTestCase):
info[37380] = TiffImagePlugin.IFDRational(numerator, denominator)
out = self.tempfile("temp.tiff")
out = str(tmp_path / "temp.tiff")
im.save(out, tiffinfo=info, compression="raw")
with Image.open(out) as reloaded:
assert 2 ** 31 - 1 == reloaded.tag_v2[37380].numerator
assert -1 == reloaded.tag_v2[37380].denominator
def test_ifd_signed_long(self):
def test_ifd_signed_long(tmp_path):
im = hopper()
info = TiffImagePlugin.ImageFileDirectory_v2()
info[37000] = -60000
out = self.tempfile("temp.tiff")
out = str(tmp_path / "temp.tiff")
im.save(out, tiffinfo=info, compression="raw")
with Image.open(out) as reloaded:
assert reloaded.tag_v2[37000] == -60000
def test_empty_values(self):
def test_empty_values():
data = io.BytesIO(
b"II*\x00\x08\x00\x00\x00\x03\x00\x1a\x01\x05\x00\x00\x00\x00\x00"
b"\x00\x00\x00\x00\x1b\x01\x05\x00\x00\x00\x00\x00\x00\x00\x00\x00"
@ -304,17 +316,19 @@ class TestFileTiffMetadata(PillowTestCase):
info = dict(info)
assert 33432 in info
def test_PhotoshopInfo(self):
def test_PhotoshopInfo(tmp_path):
with Image.open("Tests/images/issue_2278.tif") as im:
assert len(im.tag_v2[34377]) == 1
assert isinstance(im.tag_v2[34377][0], bytes)
out = self.tempfile("temp.tiff")
out = str(tmp_path / "temp.tiff")
im.save(out)
with Image.open(out) as reloaded:
assert len(reloaded.tag_v2[34377]) == 1
assert isinstance(reloaded.tag_v2[34377][0], bytes)
def test_too_many_entries(self):
def test_too_many_entries():
ifd = TiffImagePlugin.ImageFileDirectory_v2()
# 277: ("SamplesPerPixel", SHORT, 1),

View File

@ -3,24 +3,27 @@ import itertools
from PIL import Image
from .helper import PillowTestCase, assert_image_similar, hopper
from .helper import assert_image_similar, hopper
class TestFormatHSV(PillowTestCase):
def int_to_float(self, i):
def int_to_float(i):
return i / 255
def str_to_float(self, i):
def str_to_float(i):
return ord(i) / 255
def tuple_to_ints(self, tp):
def tuple_to_ints(tp):
x, y, z = tp
return int(x * 255.0), int(y * 255.0), int(z * 255.0)
def test_sanity(self):
def test_sanity():
Image.new("HSV", (100, 100))
def wedge(self):
def wedge():
w = Image._wedge()
w90 = w.rotate(90)
@ -43,18 +46,17 @@ class TestFormatHSV(PillowTestCase):
return img
def to_xxx_colorsys(self, im, func, mode):
def to_xxx_colorsys(im, func, mode):
# convert the hard way using the library colorsys routines.
(r, g, b) = im.split()
conv_func = self.int_to_float
conv_func = int_to_float
converted = [
self.tuple_to_ints(func(conv_func(_r), conv_func(_g), conv_func(_b)))
for (_r, _g, _b) in itertools.zip_longest(
r.tobytes(), g.tobytes(), b.tobytes()
)
tuple_to_ints(func(conv_func(_r), conv_func(_g), conv_func(_b)))
for (_r, _g, _b) in itertools.zip_longest(r.tobytes(), g.tobytes(), b.tobytes())
]
new_bytes = b"".join(
@ -65,25 +67,25 @@ class TestFormatHSV(PillowTestCase):
return hsv
def to_hsv_colorsys(self, im):
return self.to_xxx_colorsys(im, colorsys.rgb_to_hsv, "HSV")
def to_rgb_colorsys(self, im):
return self.to_xxx_colorsys(im, colorsys.hsv_to_rgb, "RGB")
def to_hsv_colorsys(im):
return to_xxx_colorsys(im, colorsys.rgb_to_hsv, "HSV")
def test_wedge(self):
src = self.wedge().resize((3 * 32, 32), Image.BILINEAR)
def to_rgb_colorsys(im):
return to_xxx_colorsys(im, colorsys.hsv_to_rgb, "RGB")
def test_wedge():
src = wedge().resize((3 * 32, 32), Image.BILINEAR)
im = src.convert("HSV")
comparable = self.to_hsv_colorsys(src)
comparable = to_hsv_colorsys(src)
assert_image_similar(
im.getchannel(0), comparable.getchannel(0), 1, "Hue conversion is wrong"
)
assert_image_similar(
im.getchannel(1),
comparable.getchannel(1),
1,
"Saturation conversion is wrong",
im.getchannel(1), comparable.getchannel(1), 1, "Saturation conversion is wrong",
)
assert_image_similar(
im.getchannel(2), comparable.getchannel(2), 1, "Value conversion is wrong"
@ -102,43 +104,33 @@ class TestFormatHSV(PillowTestCase):
im.getchannel(2), comparable.getchannel(2), 3, "B conversion is wrong"
)
def test_convert(self):
def test_convert():
im = hopper("RGB").convert("HSV")
comparable = self.to_hsv_colorsys(hopper("RGB"))
comparable = to_hsv_colorsys(hopper("RGB"))
assert_image_similar(
im.getchannel(0), comparable.getchannel(0), 1, "Hue conversion is wrong"
)
assert_image_similar(
im.getchannel(1),
comparable.getchannel(1),
1,
"Saturation conversion is wrong",
im.getchannel(1), comparable.getchannel(1), 1, "Saturation conversion is wrong",
)
assert_image_similar(
im.getchannel(2), comparable.getchannel(2), 1, "Value conversion is wrong"
)
def test_hsv_to_rgb(self):
comparable = self.to_hsv_colorsys(hopper("RGB"))
def test_hsv_to_rgb():
comparable = to_hsv_colorsys(hopper("RGB"))
converted = comparable.convert("RGB")
comparable = self.to_rgb_colorsys(comparable)
comparable = to_rgb_colorsys(comparable)
assert_image_similar(
converted.getchannel(0),
comparable.getchannel(0),
3,
"R conversion is wrong",
converted.getchannel(0), comparable.getchannel(0), 3, "R conversion is wrong",
)
assert_image_similar(
converted.getchannel(1),
comparable.getchannel(1),
3,
"G conversion is wrong",
converted.getchannel(1), comparable.getchannel(1), 3, "G conversion is wrong",
)
assert_image_similar(
converted.getchannel(2),
comparable.getchannel(2),
3,
"B conversion is wrong",
converted.getchannel(2), comparable.getchannel(2), 3, "B conversion is wrong",
)

View File

@ -1,17 +1,10 @@
import pytest
from PIL import Image
from .helper import (
PillowTestCase,
assert_image,
assert_image_equal,
assert_image_similar,
hopper,
)
from .helper import assert_image, assert_image_equal, assert_image_similar, hopper
class TestImageConvert(PillowTestCase):
def test_sanity(self):
def test_sanity():
def convert(im, mode):
out = im.convert(mode)
assert out.mode == mode
@ -43,7 +36,8 @@ class TestImageConvert(PillowTestCase):
for mode in modes:
convert(im, mode)
def test_default(self):
def test_default():
im = hopper("P")
assert_image(im, "P", im.size)
@ -52,26 +46,32 @@ class TestImageConvert(PillowTestCase):
im = im.convert()
assert_image(im, "RGB", im.size)
# ref https://github.com/python-pillow/Pillow/issues/274
def _test_float_conversion(self, im):
# ref https://github.com/python-pillow/Pillow/issues/274
def _test_float_conversion(im):
orig = im.getpixel((5, 5))
converted = im.convert("F").getpixel((5, 5))
assert orig == converted
def test_8bit(self):
def test_8bit():
with Image.open("Tests/images/hopper.jpg") as im:
self._test_float_conversion(im.convert("L"))
_test_float_conversion(im.convert("L"))
def test_16bit(self):
def test_16bit():
with Image.open("Tests/images/16bit.cropped.tif") as im:
self._test_float_conversion(im)
_test_float_conversion(im)
def test_16bit_workaround(self):
def test_16bit_workaround():
with Image.open("Tests/images/16bit.cropped.tif") as im:
self._test_float_conversion(im.convert("I"))
_test_float_conversion(im.convert("I"))
def test_rgba_p(self):
def test_rgba_p():
im = hopper("RGBA")
im.putalpha(hopper("L"))
@ -80,11 +80,12 @@ class TestImageConvert(PillowTestCase):
assert_image_similar(im, comparable, 20)
def test_trns_p(self):
def test_trns_p(tmp_path):
im = hopper("P")
im.info["transparency"] = 0
f = self.tempfile("temp.png")
f = str(tmp_path / "temp.png")
im_l = im.convert("L")
assert im_l.info["transparency"] == 0 # undone
@ -94,9 +95,11 @@ class TestImageConvert(PillowTestCase):
assert im_rgb.info["transparency"] == (0, 0, 0) # undone
im_rgb.save(f)
# ref https://github.com/python-pillow/Pillow/issues/664
def test_trns_p_rgba(self):
# ref https://github.com/python-pillow/Pillow/issues/664
def test_trns_p_rgba():
# Arrange
im = hopper("P")
im.info["transparency"] = 128
@ -109,11 +112,12 @@ class TestImageConvert(PillowTestCase):
# https://github.com/python-pillow/Pillow/issues/2702
assert im_rgba.palette is None
def test_trns_l(self):
def test_trns_l(tmp_path):
im = hopper("L")
im.info["transparency"] = 128
f = self.tempfile("temp.png")
f = str(tmp_path / "temp.png")
im_rgb = im.convert("RGB")
assert im_rgb.info["transparency"] == (128, 128, 128) # undone
@ -127,11 +131,12 @@ class TestImageConvert(PillowTestCase):
assert "transparency" not in im_p.info
im_p.save(f)
def test_trns_RGB(self):
def test_trns_RGB(tmp_path):
im = hopper("RGB")
im.info["transparency"] = im.getpixel((0, 0))
f = self.tempfile("temp.png")
f = str(tmp_path / "temp.png")
im_l = im.convert("L")
assert im_l.info["transparency"] == im_l.getpixel((0, 0)) # undone
@ -149,7 +154,8 @@ class TestImageConvert(PillowTestCase):
assert "transparency" not in im_p.info
im_p.save(f)
def test_gif_with_rgba_palette_to_p(self):
def test_gif_with_rgba_palette_to_p():
# See https://github.com/python-pillow/Pillow/issues/2433
with Image.open("Tests/images/hopper.gif") as im:
im.info["transparency"] = 255
@ -160,7 +166,8 @@ class TestImageConvert(PillowTestCase):
# Should not raise ValueError: unrecognized raw mode
im_p.load()
def test_p_la(self):
def test_p_la():
im = hopper("RGBA")
alpha = hopper("L")
im.putalpha(alpha)
@ -169,7 +176,8 @@ class TestImageConvert(PillowTestCase):
assert_image_similar(alpha, comparable, 5)
def test_matrix_illegal_conversion(self):
def test_matrix_illegal_conversion():
# Arrange
im = hopper("CMYK")
# fmt: off
@ -184,7 +192,8 @@ class TestImageConvert(PillowTestCase):
with pytest.raises(ValueError):
im.convert(mode="CMYK", matrix=matrix)
def test_matrix_wrong_mode(self):
def test_matrix_wrong_mode():
# Arrange
im = hopper("L")
# fmt: off
@ -199,7 +208,8 @@ class TestImageConvert(PillowTestCase):
with pytest.raises(ValueError):
im.convert(mode="L", matrix=matrix)
def test_matrix_xyz(self):
def test_matrix_xyz():
def matrix_convert(mode):
# Arrange
im = hopper("RGB")
@ -230,7 +240,8 @@ class TestImageConvert(PillowTestCase):
matrix_convert("RGB")
matrix_convert("L")
def test_matrix_identity(self):
def test_matrix_identity():
# Arrange
im = hopper("RGB")
# fmt: off

View File

@ -1,10 +1,9 @@
from PIL import Image, features
from .helper import PillowTestCase, assert_image_equal, hopper
from .helper import assert_image_equal, hopper
class TestImageSplit(PillowTestCase):
def test_split(self):
def test_split():
def split(mode):
layers = hopper(mode).split()
return [(i.mode, i.size[0], i.size[1]) for i in layers]
@ -29,7 +28,8 @@ class TestImageSplit(PillowTestCase):
]
assert split("YCbCr") == [("L", 128, 128), ("L", 128, 128), ("L", 128, 128)]
def test_split_merge(self):
def test_split_merge():
def split_merge(mode):
return Image.merge(mode, hopper(mode).split())
@ -43,11 +43,12 @@ class TestImageSplit(PillowTestCase):
assert_image_equal(hopper("CMYK"), split_merge("CMYK"))
assert_image_equal(hopper("YCbCr"), split_merge("YCbCr"))
def test_split_open(self):
def test_split_open(tmp_path):
if features.check("zlib"):
test_file = self.tempfile("temp.png")
test_file = str(tmp_path / "temp.png")
else:
test_file = self.tempfile("temp.pcx")
test_file = str(tmp_path / "temp.pcx")
def split_open(mode):
hopper(mode).save(test_file)

View File

@ -1,17 +1,17 @@
import pytest
from PIL import Image, ImagePalette
from .helper import PillowTestCase, assert_image_equal
from .helper import assert_image_equal
class TestImagePalette(PillowTestCase):
def test_sanity(self):
def test_sanity():
ImagePalette.ImagePalette("RGB", list(range(256)) * 3)
with pytest.raises(ValueError):
ImagePalette.ImagePalette("RGB", list(range(256)) * 2)
def test_getcolor(self):
def test_getcolor():
palette = ImagePalette.ImagePalette()
@ -27,11 +27,12 @@ class TestImagePalette(PillowTestCase):
with pytest.raises(ValueError):
palette.getcolor("unknown")
def test_file(self):
def test_file(tmp_path):
palette = ImagePalette.ImagePalette("RGB", list(range(256)) * 3)
f = self.tempfile("temp.lut")
f = str(tmp_path / "temp.lut")
palette.save(f)
@ -45,7 +46,8 @@ class TestImagePalette(PillowTestCase):
assert isinstance(p, ImagePalette.ImagePalette)
assert p.palette == palette.tobytes()
def test_make_linear_lut(self):
def test_make_linear_lut():
# Arrange
black = 0
white = 255
@ -60,7 +62,8 @@ class TestImagePalette(PillowTestCase):
for i in range(0, len(lut)):
assert lut[i] == i
def test_make_linear_lut_not_yet_implemented(self):
def test_make_linear_lut_not_yet_implemented():
# Update after FIXME
# Arrange
black = 1
@ -70,7 +73,8 @@ class TestImagePalette(PillowTestCase):
with pytest.raises(NotImplementedError):
ImagePalette.make_linear_lut(black, white)
def test_make_gamma_lut(self):
def test_make_gamma_lut():
# Arrange
exp = 5
@ -87,7 +91,8 @@ class TestImagePalette(PillowTestCase):
assert lut[191] == 60
assert lut[255] == 255
def test_rawmode_valueerrors(self):
def test_rawmode_valueerrors(tmp_path):
# Arrange
palette = ImagePalette.raw("RGB", list(range(256)) * 3)
@ -96,11 +101,12 @@ class TestImagePalette(PillowTestCase):
palette.tobytes()
with pytest.raises(ValueError):
palette.getcolor((1, 2, 3))
f = self.tempfile("temp.lut")
f = str(tmp_path / "temp.lut")
with pytest.raises(ValueError):
palette.save(f)
def test_getdata(self):
def test_getdata():
# Arrange
data_in = list(range(256)) * 3
palette = ImagePalette.ImagePalette("RGB", data_in)
@ -111,7 +117,8 @@ class TestImagePalette(PillowTestCase):
# Assert
assert mode == "RGB;L"
def test_rawmode_getdata(self):
def test_rawmode_getdata():
# Arrange
data_in = list(range(256)) * 3
palette = ImagePalette.raw("RGB", data_in)
@ -123,9 +130,10 @@ class TestImagePalette(PillowTestCase):
assert rawmode == "RGB"
assert data_in == data_out
def test_2bit_palette(self):
def test_2bit_palette(tmp_path):
# issue #2258, 2 bit palettes are corrupted.
outfile = self.tempfile("temp.png")
outfile = str(tmp_path / "temp.png")
rgb = b"\x00" * 2 + b"\x01" * 2 + b"\x02" * 2
img = Image.frombytes("P", (6, 1), rgb)
@ -135,6 +143,7 @@ class TestImagePalette(PillowTestCase):
with Image.open(outfile) as reloaded:
assert_image_equal(img, reloaded)
def test_invalid_palette(self):
def test_invalid_palette():
with pytest.raises(IOError):
ImagePalette.load("Tests/images/hopper.jpg")

View File

@ -1,13 +1,12 @@
import pytest
from PIL import Image, ImageSequence, TiffImagePlugin
from .helper import PillowTestCase, assert_image_equal, hopper, skip_unless_feature
from .helper import assert_image_equal, hopper, skip_unless_feature
class TestImageSequence(PillowTestCase):
def test_sanity(self):
def test_sanity(tmp_path):
test_file = self.tempfile("temp.im")
test_file = str(tmp_path / "temp.im")
im = hopper("RGB")
im.save(test_file)
@ -25,7 +24,8 @@ class TestImageSequence(PillowTestCase):
with pytest.raises(AttributeError):
ImageSequence.Iterator(0)
def test_iterator(self):
def test_iterator():
with Image.open("Tests/images/multipage.tiff") as im:
i = ImageSequence.Iterator(im)
for index in range(0, im.n_frames):
@ -35,29 +35,34 @@ class TestImageSequence(PillowTestCase):
with pytest.raises(StopIteration):
next(i)
def test_iterator_min_frame(self):
def test_iterator_min_frame():
with Image.open("Tests/images/hopper.psd") as im:
i = ImageSequence.Iterator(im)
for index in range(1, im.n_frames):
assert i[index] == next(i)
def _test_multipage_tiff(self):
def _test_multipage_tiff():
with Image.open("Tests/images/multipage.tiff") as im:
for index, frame in enumerate(ImageSequence.Iterator(im)):
frame.load()
assert index == im.tell()
frame.convert("RGB")
def test_tiff(self):
self._test_multipage_tiff()
@skip_unless_feature("libtiff")
def test_libtiff(self):
def test_tiff():
_test_multipage_tiff()
@skip_unless_feature("libtiff")
def test_libtiff():
TiffImagePlugin.READ_LIBTIFF = True
self._test_multipage_tiff()
_test_multipage_tiff()
TiffImagePlugin.READ_LIBTIFF = False
def test_consecutive(self):
def test_consecutive():
with Image.open("Tests/images/multipage.tiff") as im:
firstFrame = None
for frame in ImageSequence.Iterator(im):
@ -67,7 +72,8 @@ class TestImageSequence(PillowTestCase):
assert_image_equal(frame, firstFrame)
break
def test_palette_mmap(self):
def test_palette_mmap():
# Using mmap in ImageFile can require to reload the palette.
with Image.open("Tests/images/multipage-mmap.tiff") as im:
color1 = im.getpalette()[0:3]
@ -75,7 +81,8 @@ class TestImageSequence(PillowTestCase):
color2 = im.getpalette()[0:3]
assert color1 == color2
def test_all_frames(self):
def test_all_frames():
# Test a single image
with Image.open("Tests/images/iss634.gif") as im:
ims = ImageSequence.all_frames(im)

View File

@ -3,32 +3,33 @@ from fractions import Fraction
from PIL import Image, TiffImagePlugin, features
from PIL.TiffImagePlugin import IFDRational
from .helper import PillowTestCase, hopper
from .helper import hopper
class Test_IFDRational(PillowTestCase):
def _test_equal(self, num, denom, target):
def _test_equal(num, denom, target):
t = IFDRational(num, denom)
assert target == t
assert t == target
def test_sanity(self):
self._test_equal(1, 1, 1)
self._test_equal(1, 1, Fraction(1, 1))
def test_sanity():
self._test_equal(2, 2, 1)
self._test_equal(1.0, 1, Fraction(1, 1))
_test_equal(1, 1, 1)
_test_equal(1, 1, Fraction(1, 1))
self._test_equal(Fraction(1, 1), 1, Fraction(1, 1))
self._test_equal(IFDRational(1, 1), 1, 1)
_test_equal(2, 2, 1)
_test_equal(1.0, 1, Fraction(1, 1))
self._test_equal(1, 2, Fraction(1, 2))
self._test_equal(1, 2, IFDRational(1, 2))
_test_equal(Fraction(1, 1), 1, Fraction(1, 1))
_test_equal(IFDRational(1, 1), 1, 1)
def test_nonetype(self):
_test_equal(1, 2, Fraction(1, 2))
_test_equal(1, 2, IFDRational(1, 2))
def test_nonetype():
# Fails if the _delegate function doesn't return a valid function
xres = IFDRational(72)
@ -41,7 +42,8 @@ class Test_IFDRational(PillowTestCase):
assert xres and 1
assert xres and yres
def test_ifd_rational_save(self):
def test_ifd_rational_save(tmp_path):
methods = (True, False)
if not features.check("libtiff"):
methods = (False,)
@ -50,7 +52,7 @@ class Test_IFDRational(PillowTestCase):
TiffImagePlugin.WRITE_LIBTIFF = libtiff
im = hopper()
out = self.tempfile("temp.tiff")
out = str(tmp_path / "temp.tiff")
res = IFDRational(301, 1)
im.save(out, dpi=(res, res), compression="raw")

View File

@ -1,13 +1,13 @@
from .helper import PillowTestCase, assert_image_equal, assert_image_similar, hopper
from .helper import assert_image_equal, assert_image_similar, hopper
class TestUploader(PillowTestCase):
def check_upload_equal(self):
def check_upload_equal():
result = hopper("P").convert("RGB")
target = hopper("RGB")
assert_image_equal(result, target)
def check_upload_similar(self):
def check_upload_similar():
result = hopper("P").convert("RGB")
target = hopper("RGB")
assert_image_similar(result, target, 0)