Converted most assert statements to pytest

This commit is contained in:
Andrew Murray 2020-02-23 00:06:21 +11:00
parent 20d6b6271c
commit 8482919a37
53 changed files with 1716 additions and 1669 deletions

View File

@ -1,5 +1,6 @@
import unittest import unittest
import pytest
from PIL import Image from PIL import Image
from .helper import PillowTestCase from .helper import PillowTestCase
@ -13,7 +14,7 @@ class TestLibtiffSegfault(PillowTestCase):
libtiff >= 4.0.0 libtiff >= 4.0.0
""" """
with self.assertRaises(IOError): with pytest.raises(IOError):
with Image.open(TEST_FILE) as im: with Image.open(TEST_FILE) as im:
im.load() im.load()

View File

@ -20,10 +20,10 @@ class TestPngDos(PillowTestCase):
ImageFile.LOAD_TRUNCATED_IMAGES = False ImageFile.LOAD_TRUNCATED_IMAGES = False
for s in im.text.values(): for s in im.text.values():
self.assertLess(len(s), 1024 * 1024, "Text chunk larger than 1M") assert len(s) < 1024 * 1024, "Text chunk larger than 1M"
for s in im.info.values(): for s in im.info.values():
self.assertLess(len(s), 1024 * 1024, "Text chunk larger than 1M") assert len(s) < 1024 * 1024, "Text chunk larger than 1M"
def test_dos_text(self): def test_dos_text(self):
@ -31,11 +31,11 @@ class TestPngDos(PillowTestCase):
im = Image.open(TEST_FILE) im = Image.open(TEST_FILE)
im.load() im.load()
except ValueError as msg: except ValueError as msg:
self.assertTrue(msg, "Decompressed Data Too Large") assert msg, "Decompressed Data Too Large"
return return
for s in im.text.values(): for s in im.text.values():
self.assertLess(len(s), 1024 * 1024, "Text chunk larger than 1M") assert len(s) < 1024 * 1024, "Text chunk larger than 1M"
def test_dos_total_memory(self): def test_dos_total_memory(self):
im = Image.new("L", (1, 1)) im = Image.new("L", (1, 1))
@ -54,15 +54,13 @@ class TestPngDos(PillowTestCase):
try: try:
im2 = Image.open(b) im2 = Image.open(b)
except ValueError as msg: except ValueError as msg:
self.assertIn("Too much memory", msg) assert "Too much memory" in msg
return return
total_len = 0 total_len = 0
for txt in im2.text.values(): for txt in im2.text.values():
total_len += len(txt) total_len += len(txt)
self.assertLess( assert total_len < 64 * 1024 * 1024, "Total text chunks greater than 64M"
total_len, 64 * 1024 * 1024, "Total text chunks greater than 64M"
)
if __name__ == "__main__": if __name__ == "__main__":

View File

@ -240,7 +240,7 @@ class PillowLeakTestCase(PillowTestCase):
core() core()
mem = self._get_mem_usage() - start_mem mem = self._get_mem_usage() - start_mem
msg = "memory usage limit exceeded in iteration %d" % cycle msg = "memory usage limit exceeded in iteration %d" % cycle
self.assertLess(mem, self.mem_limit, msg) assert mem < self.mem_limit, msg
# helpers # helpers

View File

@ -1,6 +1,7 @@
import unittest import unittest
from array import array from array import array
import pytest
from PIL import Image, ImageFilter from PIL import Image, ImageFilter
from .helper import PillowTestCase, assert_image_equal from .helper import PillowTestCase, assert_image_equal
@ -74,10 +75,10 @@ class TestColorLut3DCoreAPI(PillowTestCase):
with self.assertRaisesRegex(ValueError, r"size1D \* size2D \* size3D"): with self.assertRaisesRegex(ValueError, r"size1D \* size2D \* size3D"):
im.im.color_lut_3d("RGB", Image.LINEAR, 3, 2, 2, 2, [0, 0, 0] * 9) im.im.color_lut_3d("RGB", Image.LINEAR, 3, 2, 2, 2, [0, 0, 0] * 9)
with self.assertRaises(TypeError): with pytest.raises(TypeError):
im.im.color_lut_3d("RGB", Image.LINEAR, 3, 2, 2, 2, [0, 0, "0"] * 8) im.im.color_lut_3d("RGB", Image.LINEAR, 3, 2, 2, 2, [0, 0, "0"] * 8)
with self.assertRaises(TypeError): with pytest.raises(TypeError):
im.im.color_lut_3d("RGB", Image.LINEAR, 3, 2, 2, 2, 16) im.im.color_lut_3d("RGB", Image.LINEAR, 3, 2, 2, 2, 16)
def test_correct_args(self): def test_correct_args(self):
@ -240,14 +241,14 @@ class TestColorLut3DCoreAPI(PillowTestCase):
-1, 2, 2, 2, 2, 2, -1, 2, 2, 2, 2, 2,
])).load() ])).load()
# fmt: on # fmt: on
self.assertEqual(transformed[0, 0], (0, 0, 255)) assert transformed[0, 0] == (0, 0, 255)
self.assertEqual(transformed[50, 50], (0, 0, 255)) assert transformed[50, 50] == (0, 0, 255)
self.assertEqual(transformed[255, 0], (0, 255, 255)) assert transformed[255, 0] == (0, 255, 255)
self.assertEqual(transformed[205, 50], (0, 255, 255)) assert transformed[205, 50] == (0, 255, 255)
self.assertEqual(transformed[0, 255], (255, 0, 0)) assert transformed[0, 255] == (255, 0, 0)
self.assertEqual(transformed[50, 205], (255, 0, 0)) assert transformed[50, 205] == (255, 0, 0)
self.assertEqual(transformed[255, 255], (255, 255, 0)) assert transformed[255, 255] == (255, 255, 0)
self.assertEqual(transformed[205, 205], (255, 255, 0)) assert transformed[205, 205] == (255, 255, 0)
# fmt: off # fmt: off
transformed = im._new(im.im.color_lut_3d('RGB', Image.LINEAR, transformed = im._new(im.im.color_lut_3d('RGB', Image.LINEAR,
@ -260,14 +261,14 @@ class TestColorLut3DCoreAPI(PillowTestCase):
-3, 5, 5, 5, 5, 5, -3, 5, 5, 5, 5, 5,
])).load() ])).load()
# fmt: on # fmt: on
self.assertEqual(transformed[0, 0], (0, 0, 255)) assert transformed[0, 0] == (0, 0, 255)
self.assertEqual(transformed[50, 50], (0, 0, 255)) assert transformed[50, 50] == (0, 0, 255)
self.assertEqual(transformed[255, 0], (0, 255, 255)) assert transformed[255, 0] == (0, 255, 255)
self.assertEqual(transformed[205, 50], (0, 255, 255)) assert transformed[205, 50] == (0, 255, 255)
self.assertEqual(transformed[0, 255], (255, 0, 0)) assert transformed[0, 255] == (255, 0, 0)
self.assertEqual(transformed[50, 205], (255, 0, 0)) assert transformed[50, 205] == (255, 0, 0)
self.assertEqual(transformed[255, 255], (255, 255, 0)) assert transformed[255, 255] == (255, 255, 0)
self.assertEqual(transformed[205, 205], (255, 255, 0)) assert transformed[205, 205] == (255, 255, 0)
class TestColorLut3DFilter(PillowTestCase): class TestColorLut3DFilter(PillowTestCase):
@ -301,20 +302,20 @@ class TestColorLut3DFilter(PillowTestCase):
def test_convert_table(self): def test_convert_table(self):
lut = ImageFilter.Color3DLUT(2, [0, 1, 2] * 8) lut = ImageFilter.Color3DLUT(2, [0, 1, 2] * 8)
self.assertEqual(tuple(lut.size), (2, 2, 2)) assert tuple(lut.size) == (2, 2, 2)
self.assertEqual(lut.name, "Color 3D LUT") assert lut.name == "Color 3D LUT"
# fmt: off # fmt: off
lut = ImageFilter.Color3DLUT((2, 2, 2), [ lut = ImageFilter.Color3DLUT((2, 2, 2), [
(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11), (0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11),
(12, 13, 14), (15, 16, 17), (18, 19, 20), (21, 22, 23)]) (12, 13, 14), (15, 16, 17), (18, 19, 20), (21, 22, 23)])
# fmt: on # fmt: on
self.assertEqual(tuple(lut.size), (2, 2, 2)) assert tuple(lut.size) == (2, 2, 2)
self.assertEqual(lut.table, list(range(24))) assert lut.table == list(range(24))
lut = ImageFilter.Color3DLUT((2, 2, 2), [(0, 1, 2, 3)] * 8, channels=4) lut = ImageFilter.Color3DLUT((2, 2, 2), [(0, 1, 2, 3)] * 8, channels=4)
self.assertEqual(tuple(lut.size), (2, 2, 2)) assert tuple(lut.size) == (2, 2, 2)
self.assertEqual(lut.table, list(range(4)) * 8) assert lut.table == list(range(4)) * 8
@unittest.skipIf(numpy is None, "Numpy is not installed") @unittest.skipIf(numpy is None, "Numpy is not installed")
def test_numpy_sources(self): def test_numpy_sources(self):
@ -324,30 +325,30 @@ class TestColorLut3DFilter(PillowTestCase):
table = numpy.ones((7, 6, 5, 3), dtype=numpy.float16) table = numpy.ones((7, 6, 5, 3), dtype=numpy.float16)
lut = ImageFilter.Color3DLUT((5, 6, 7), table) lut = ImageFilter.Color3DLUT((5, 6, 7), table)
self.assertIsInstance(lut.table, numpy.ndarray) assert isinstance(lut.table, numpy.ndarray)
self.assertEqual(lut.table.dtype, table.dtype) assert lut.table.dtype == table.dtype
self.assertEqual(lut.table.shape, (table.size,)) assert lut.table.shape == (table.size,)
table = numpy.ones((7 * 6 * 5, 3), dtype=numpy.float16) table = numpy.ones((7 * 6 * 5, 3), dtype=numpy.float16)
lut = ImageFilter.Color3DLUT((5, 6, 7), table) lut = ImageFilter.Color3DLUT((5, 6, 7), table)
self.assertEqual(lut.table.shape, (table.size,)) assert lut.table.shape == (table.size,)
table = numpy.ones((7 * 6 * 5 * 3), dtype=numpy.float16) table = numpy.ones((7 * 6 * 5 * 3), dtype=numpy.float16)
lut = ImageFilter.Color3DLUT((5, 6, 7), table) lut = ImageFilter.Color3DLUT((5, 6, 7), table)
self.assertEqual(lut.table.shape, (table.size,)) assert lut.table.shape == (table.size,)
# Check application # Check application
Image.new("RGB", (10, 10), 0).filter(lut) Image.new("RGB", (10, 10), 0).filter(lut)
# Check copy # Check copy
table[0] = 33 table[0] = 33
self.assertEqual(lut.table[0], 1) assert lut.table[0] == 1
# Check not copy # Check not copy
table = numpy.ones((7 * 6 * 5 * 3), dtype=numpy.float16) table = numpy.ones((7 * 6 * 5 * 3), dtype=numpy.float16)
lut = ImageFilter.Color3DLUT((5, 6, 7), table, _copy_table=False) lut = ImageFilter.Color3DLUT((5, 6, 7), table, _copy_table=False)
table[0] = 33 table[0] = 33
self.assertEqual(lut.table[0], 33) assert lut.table[0] == 33
@unittest.skipIf(numpy is None, "Numpy is not installed") @unittest.skipIf(numpy is None, "Numpy is not installed")
def test_numpy_formats(self): def test_numpy_formats(self):
@ -386,7 +387,7 @@ class TestColorLut3DFilter(PillowTestCase):
def test_repr(self): def test_repr(self):
lut = ImageFilter.Color3DLUT(2, [0, 1, 2] * 8) lut = ImageFilter.Color3DLUT(2, [0, 1, 2] * 8)
self.assertEqual(repr(lut), "<Color3DLUT from list size=2x2x2 channels=3>") assert repr(lut) == "<Color3DLUT from list size=2x2x2 channels=3>"
lut = ImageFilter.Color3DLUT( lut = ImageFilter.Color3DLUT(
(3, 4, 5), (3, 4, 5),
@ -395,8 +396,9 @@ class TestColorLut3DFilter(PillowTestCase):
target_mode="YCbCr", target_mode="YCbCr",
_copy_table=False, _copy_table=False,
) )
self.assertEqual( assert (
repr(lut), "<Color3DLUT from array size=3x4x5 channels=4 target_mode=YCbCr>" repr(lut)
== "<Color3DLUT from array size=3x4x5 channels=4 target_mode=YCbCr>"
) )
@ -417,25 +419,25 @@ class TestGenerateColorLut3D(PillowTestCase):
def test_3_channels(self): def test_3_channels(self):
lut = ImageFilter.Color3DLUT.generate(5, lambda r, g, b: (r, g, b)) lut = ImageFilter.Color3DLUT.generate(5, lambda r, g, b: (r, g, b))
self.assertEqual(tuple(lut.size), (5, 5, 5)) assert tuple(lut.size) == (5, 5, 5)
self.assertEqual(lut.name, "Color 3D LUT") assert lut.name == "Color 3D LUT"
# fmt: off # fmt: off
self.assertEqual(lut.table[:24], [ assert lut.table[:24] == [
0.0, 0.0, 0.0, 0.25, 0.0, 0.0, 0.5, 0.0, 0.0, 0.75, 0.0, 0.0, 0.0, 0.0, 0.0, 0.25, 0.0, 0.0, 0.5, 0.0, 0.0, 0.75, 0.0, 0.0,
1.0, 0.0, 0.0, 0.0, 0.25, 0.0, 0.25, 0.25, 0.0, 0.5, 0.25, 0.0]) 1.0, 0.0, 0.0, 0.0, 0.25, 0.0, 0.25, 0.25, 0.0, 0.5, 0.25, 0.0]
# fmt: on # fmt: on
def test_4_channels(self): def test_4_channels(self):
lut = ImageFilter.Color3DLUT.generate( lut = ImageFilter.Color3DLUT.generate(
5, channels=4, callback=lambda r, g, b: (b, r, g, (r + g + b) / 2) 5, channels=4, callback=lambda r, g, b: (b, r, g, (r + g + b) / 2)
) )
self.assertEqual(tuple(lut.size), (5, 5, 5)) assert tuple(lut.size) == (5, 5, 5)
self.assertEqual(lut.name, "Color 3D LUT") assert lut.name == "Color 3D LUT"
# fmt: off # fmt: off
self.assertEqual(lut.table[:24], [ assert lut.table[:24] == [
0.0, 0.0, 0.0, 0.0, 0.0, 0.25, 0.0, 0.125, 0.0, 0.5, 0.0, 0.25, 0.0, 0.0, 0.0, 0.0, 0.0, 0.25, 0.0, 0.125, 0.0, 0.5, 0.0, 0.25,
0.0, 0.75, 0.0, 0.375, 0.0, 1.0, 0.0, 0.5, 0.0, 0.0, 0.25, 0.125 0.0, 0.75, 0.0, 0.375, 0.0, 1.0, 0.0, 0.5, 0.0, 0.0, 0.25, 0.125
]) ]
# fmt: on # fmt: on
def test_apply(self): def test_apply(self):
@ -445,7 +447,7 @@ class TestGenerateColorLut3D(PillowTestCase):
im = Image.merge( im = Image.merge(
"RGB", [g, g.transpose(Image.ROTATE_90), g.transpose(Image.ROTATE_180)] "RGB", [g, g.transpose(Image.ROTATE_90), g.transpose(Image.ROTATE_180)]
) )
self.assertEqual(im, im.filter(lut)) assert im == im.filter(lut)
class TestTransformColorLut3D(PillowTestCase): class TestTransformColorLut3D(PillowTestCase):
@ -461,7 +463,7 @@ class TestTransformColorLut3D(PillowTestCase):
with self.assertRaisesRegex(ValueError, "should have either channels"): with self.assertRaisesRegex(ValueError, "should have either channels"):
source.transform(lambda r, g, b: (r, g, b, 1)) source.transform(lambda r, g, b: (r, g, b, 1))
with self.assertRaises(TypeError): with pytest.raises(TypeError):
source.transform(lambda r, g, b, a: (r, g, b)) source.transform(lambda r, g, b, a: (r, g, b))
def test_target_mode(self): def test_target_mode(self):
@ -470,31 +472,29 @@ class TestTransformColorLut3D(PillowTestCase):
) )
lut = source.transform(lambda r, g, b: (r, g, b)) lut = source.transform(lambda r, g, b: (r, g, b))
self.assertEqual(lut.mode, "HSV") assert lut.mode == "HSV"
lut = source.transform(lambda r, g, b: (r, g, b), target_mode="RGB") lut = source.transform(lambda r, g, b: (r, g, b), target_mode="RGB")
self.assertEqual(lut.mode, "RGB") assert lut.mode == "RGB"
def test_3_to_3_channels(self): def test_3_to_3_channels(self):
source = ImageFilter.Color3DLUT.generate((3, 4, 5), lambda r, g, b: (r, g, b)) source = ImageFilter.Color3DLUT.generate((3, 4, 5), lambda r, g, b: (r, g, b))
lut = source.transform(lambda r, g, b: (r * r, g * g, b * b)) lut = source.transform(lambda r, g, b: (r * r, g * g, b * b))
self.assertEqual(tuple(lut.size), tuple(source.size)) assert tuple(lut.size) == tuple(source.size)
self.assertEqual(len(lut.table), len(source.table)) assert len(lut.table) == len(source.table)
self.assertNotEqual(lut.table, source.table) assert lut.table != source.table
self.assertEqual( assert lut.table[0:10] == [0.0, 0.0, 0.0, 0.25, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0]
lut.table[0:10], [0.0, 0.0, 0.0, 0.25, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0]
)
def test_3_to_4_channels(self): def test_3_to_4_channels(self):
source = ImageFilter.Color3DLUT.generate((6, 5, 4), lambda r, g, b: (r, g, b)) source = ImageFilter.Color3DLUT.generate((6, 5, 4), lambda r, g, b: (r, g, b))
lut = source.transform(lambda r, g, b: (r * r, g * g, b * b, 1), channels=4) lut = source.transform(lambda r, g, b: (r * r, g * g, b * b, 1), channels=4)
self.assertEqual(tuple(lut.size), tuple(source.size)) assert tuple(lut.size) == tuple(source.size)
self.assertNotEqual(len(lut.table), len(source.table)) assert len(lut.table) != len(source.table)
self.assertNotEqual(lut.table, source.table) assert lut.table != source.table
# fmt: off # fmt: off
self.assertEqual(lut.table[0:16], [ assert lut.table[0:16] == [
0.0, 0.0, 0.0, 1, 0.2**2, 0.0, 0.0, 1, 0.0, 0.0, 0.0, 1, 0.2**2, 0.0, 0.0, 1,
0.4**2, 0.0, 0.0, 1, 0.6**2, 0.0, 0.0, 1]) 0.4**2, 0.0, 0.0, 1, 0.6**2, 0.0, 0.0, 1]
# fmt: on # fmt: on
def test_4_to_3_channels(self): def test_4_to_3_channels(self):
@ -504,13 +504,13 @@ class TestTransformColorLut3D(PillowTestCase):
lut = source.transform( lut = source.transform(
lambda r, g, b, a: (a - r * r, a - g * g, a - b * b), channels=3 lambda r, g, b, a: (a - r * r, a - g * g, a - b * b), channels=3
) )
self.assertEqual(tuple(lut.size), tuple(source.size)) assert tuple(lut.size) == tuple(source.size)
self.assertNotEqual(len(lut.table), len(source.table)) assert len(lut.table) != len(source.table)
self.assertNotEqual(lut.table, source.table) assert lut.table != source.table
# fmt: off # fmt: off
self.assertEqual(lut.table[0:18], [ assert lut.table[0:18] == [
1.0, 1.0, 1.0, 0.75, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.75, 1.0, 1.0, 0.0, 1.0, 1.0,
1.0, 0.96, 1.0, 0.75, 0.96, 1.0, 0.0, 0.96, 1.0]) 1.0, 0.96, 1.0, 0.75, 0.96, 1.0, 0.0, 0.96, 1.0]
# fmt: on # fmt: on
def test_4_to_4_channels(self): def test_4_to_4_channels(self):
@ -518,13 +518,13 @@ class TestTransformColorLut3D(PillowTestCase):
(6, 5, 4), lambda r, g, b: (r, g, b, 1), channels=4 (6, 5, 4), lambda r, g, b: (r, g, b, 1), channels=4
) )
lut = source.transform(lambda r, g, b, a: (r * r, g * g, b * b, a - 0.5)) lut = source.transform(lambda r, g, b, a: (r * r, g * g, b * b, a - 0.5))
self.assertEqual(tuple(lut.size), tuple(source.size)) assert tuple(lut.size) == tuple(source.size)
self.assertEqual(len(lut.table), len(source.table)) assert len(lut.table) == len(source.table)
self.assertNotEqual(lut.table, source.table) assert lut.table != source.table
# fmt: off # fmt: off
self.assertEqual(lut.table[0:16], [ assert lut.table[0:16] == [
0.0, 0.0, 0.0, 0.5, 0.2**2, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.5, 0.2**2, 0.0, 0.0, 0.5,
0.4**2, 0.0, 0.0, 0.5, 0.6**2, 0.0, 0.0, 0.5]) 0.4**2, 0.0, 0.0, 0.5, 0.6**2, 0.0, 0.0, 0.5]
# fmt: on # fmt: on
def test_with_normals_3_channels(self): def test_with_normals_3_channels(self):
@ -534,13 +534,13 @@ class TestTransformColorLut3D(PillowTestCase):
lut = source.transform( lut = source.transform(
lambda nr, ng, nb, r, g, b: (nr - r, ng - g, nb - b), with_normals=True lambda nr, ng, nb, r, g, b: (nr - r, ng - g, nb - b), with_normals=True
) )
self.assertEqual(tuple(lut.size), tuple(source.size)) assert tuple(lut.size) == tuple(source.size)
self.assertEqual(len(lut.table), len(source.table)) assert len(lut.table) == len(source.table)
self.assertNotEqual(lut.table, source.table) assert lut.table != source.table
# fmt: off # fmt: off
self.assertEqual(lut.table[0:18], [ assert lut.table[0:18] == [
0.0, 0.0, 0.0, 0.16, 0.0, 0.0, 0.24, 0.0, 0.0, 0.0, 0.0, 0.0, 0.16, 0.0, 0.0, 0.24, 0.0, 0.0,
0.24, 0.0, 0.0, 0.8 - (0.8**2), 0, 0, 0, 0, 0]) 0.24, 0.0, 0.0, 0.8 - (0.8**2), 0, 0, 0, 0, 0]
# fmt: on # fmt: on
def test_with_normals_4_channels(self): def test_with_normals_4_channels(self):
@ -551,11 +551,11 @@ class TestTransformColorLut3D(PillowTestCase):
lambda nr, ng, nb, r, g, b, a: (nr - r, ng - g, nb - b, a - 0.5), lambda nr, ng, nb, r, g, b, a: (nr - r, ng - g, nb - b, a - 0.5),
with_normals=True, with_normals=True,
) )
self.assertEqual(tuple(lut.size), tuple(source.size)) assert tuple(lut.size) == tuple(source.size)
self.assertEqual(len(lut.table), len(source.table)) assert len(lut.table) == len(source.table)
self.assertNotEqual(lut.table, source.table) assert lut.table != source.table
# fmt: off # fmt: off
self.assertEqual(lut.table[0:16], [ assert lut.table[0:16] == [
0.0, 0.0, 0.0, 0.5, 0.25, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.5, 0.25, 0.0, 0.0, 0.5,
0.0, 0.0, 0.0, 0.5, 0.0, 0.16, 0.0, 0.5]) 0.0, 0.0, 0.0, 0.5, 0.0, 0.16, 0.0, 0.5]
# fmt: on # fmt: on

View File

@ -43,38 +43,44 @@ class TestCoreMemory(PillowTestCase):
def test_get_alignment(self): def test_get_alignment(self):
alignment = Image.core.get_alignment() alignment = Image.core.get_alignment()
self.assertGreater(alignment, 0) assert alignment > 0
def test_set_alignment(self): def test_set_alignment(self):
for i in [1, 2, 4, 8, 16, 32]: for i in [1, 2, 4, 8, 16, 32]:
Image.core.set_alignment(i) Image.core.set_alignment(i)
alignment = Image.core.get_alignment() alignment = Image.core.get_alignment()
self.assertEqual(alignment, i) assert alignment == i
# Try to construct new image # Try to construct new image
Image.new("RGB", (10, 10)) Image.new("RGB", (10, 10))
self.assertRaises(ValueError, Image.core.set_alignment, 0) with pytest.raises(ValueError):
self.assertRaises(ValueError, Image.core.set_alignment, -1) Image.core.set_alignment(0)
self.assertRaises(ValueError, Image.core.set_alignment, 3) with pytest.raises(ValueError):
Image.core.set_alignment(-1)
with pytest.raises(ValueError):
Image.core.set_alignment(3)
def test_get_block_size(self): def test_get_block_size(self):
block_size = Image.core.get_block_size() block_size = Image.core.get_block_size()
self.assertGreaterEqual(block_size, 4096) assert block_size >= 4096
def test_set_block_size(self): def test_set_block_size(self):
for i in [4096, 2 * 4096, 3 * 4096]: for i in [4096, 2 * 4096, 3 * 4096]:
Image.core.set_block_size(i) Image.core.set_block_size(i)
block_size = Image.core.get_block_size() block_size = Image.core.get_block_size()
self.assertEqual(block_size, i) assert block_size == i
# Try to construct new image # Try to construct new image
Image.new("RGB", (10, 10)) Image.new("RGB", (10, 10))
self.assertRaises(ValueError, Image.core.set_block_size, 0) with pytest.raises(ValueError):
self.assertRaises(ValueError, Image.core.set_block_size, -1) Image.core.set_block_size(0)
self.assertRaises(ValueError, Image.core.set_block_size, 4000) with pytest.raises(ValueError):
Image.core.set_block_size(-1)
with pytest.raises(ValueError):
Image.core.set_block_size(4000)
def test_set_block_size_stats(self): def test_set_block_size_stats(self):
Image.core.reset_stats() Image.core.reset_stats()
@ -83,28 +89,30 @@ class TestCoreMemory(PillowTestCase):
Image.new("RGB", (256, 256)) Image.new("RGB", (256, 256))
stats = Image.core.get_stats() stats = Image.core.get_stats()
self.assertGreaterEqual(stats["new_count"], 1) assert stats["new_count"] >= 1
self.assertGreaterEqual(stats["allocated_blocks"], 64) assert stats["allocated_blocks"] >= 64
if not is_pypy(): if not is_pypy():
self.assertGreaterEqual(stats["freed_blocks"], 64) assert stats["freed_blocks"] >= 64
def test_get_blocks_max(self): def test_get_blocks_max(self):
blocks_max = Image.core.get_blocks_max() blocks_max = Image.core.get_blocks_max()
self.assertGreaterEqual(blocks_max, 0) assert blocks_max >= 0
def test_set_blocks_max(self): def test_set_blocks_max(self):
for i in [0, 1, 10]: for i in [0, 1, 10]:
Image.core.set_blocks_max(i) Image.core.set_blocks_max(i)
blocks_max = Image.core.get_blocks_max() blocks_max = Image.core.get_blocks_max()
self.assertEqual(blocks_max, i) assert blocks_max == i
# Try to construct new image # Try to construct new image
Image.new("RGB", (10, 10)) Image.new("RGB", (10, 10))
self.assertRaises(ValueError, Image.core.set_blocks_max, -1) with pytest.raises(ValueError):
Image.core.set_blocks_max(-1)
if sys.maxsize < 2 ** 32: if sys.maxsize < 2 ** 32:
self.assertRaises(ValueError, Image.core.set_blocks_max, 2 ** 29) with pytest.raises(ValueError):
Image.core.set_blocks_max(2 ** 29)
@unittest.skipIf(is_pypy(), "images are not collected") @unittest.skipIf(is_pypy(), "images are not collected")
def test_set_blocks_max_stats(self): def test_set_blocks_max_stats(self):
@ -115,11 +123,11 @@ class TestCoreMemory(PillowTestCase):
Image.new("RGB", (256, 256)) Image.new("RGB", (256, 256))
stats = Image.core.get_stats() stats = Image.core.get_stats()
self.assertGreaterEqual(stats["new_count"], 2) assert stats["new_count"] >= 2
self.assertGreaterEqual(stats["allocated_blocks"], 64) assert stats["allocated_blocks"] >= 64
self.assertGreaterEqual(stats["reused_blocks"], 64) assert stats["reused_blocks"] >= 64
self.assertEqual(stats["freed_blocks"], 0) assert stats["freed_blocks"] == 0
self.assertEqual(stats["blocks_cached"], 64) assert stats["blocks_cached"] == 64
@unittest.skipIf(is_pypy(), "images are not collected") @unittest.skipIf(is_pypy(), "images are not collected")
def test_clear_cache_stats(self): def test_clear_cache_stats(self):
@ -133,11 +141,11 @@ class TestCoreMemory(PillowTestCase):
Image.core.clear_cache(16) Image.core.clear_cache(16)
stats = Image.core.get_stats() stats = Image.core.get_stats()
self.assertGreaterEqual(stats["new_count"], 2) assert stats["new_count"] >= 2
self.assertGreaterEqual(stats["allocated_blocks"], 64) assert stats["allocated_blocks"] >= 64
self.assertGreaterEqual(stats["reused_blocks"], 64) assert stats["reused_blocks"] >= 64
self.assertGreaterEqual(stats["freed_blocks"], 48) assert stats["freed_blocks"] >= 48
self.assertEqual(stats["blocks_cached"], 16) assert stats["blocks_cached"] == 16
def test_large_images(self): def test_large_images(self):
Image.core.reset_stats() Image.core.reset_stats()
@ -147,12 +155,12 @@ class TestCoreMemory(PillowTestCase):
Image.core.clear_cache() Image.core.clear_cache()
stats = Image.core.get_stats() stats = Image.core.get_stats()
self.assertGreaterEqual(stats["new_count"], 1) assert stats["new_count"] >= 1
self.assertGreaterEqual(stats["allocated_blocks"], 16) assert stats["allocated_blocks"] >= 16
self.assertGreaterEqual(stats["reused_blocks"], 0) assert stats["reused_blocks"] >= 0
self.assertEqual(stats["blocks_cached"], 0) assert stats["blocks_cached"] == 0
if not is_pypy(): if not is_pypy():
self.assertGreaterEqual(stats["freed_blocks"], 16) assert stats["freed_blocks"] >= 16
class TestEnvVars(PillowTestCase): class TestEnvVars(PillowTestCase):
@ -165,9 +173,9 @@ class TestEnvVars(PillowTestCase):
def test_units(self): def test_units(self):
Image._apply_env_variables({"PILLOW_BLOCKS_MAX": "2K"}) Image._apply_env_variables({"PILLOW_BLOCKS_MAX": "2K"})
self.assertEqual(Image.core.get_blocks_max(), 2 * 1024) assert Image.core.get_blocks_max() == 2 * 1024
Image._apply_env_variables({"PILLOW_BLOCK_SIZE": "2m"}) Image._apply_env_variables({"PILLOW_BLOCK_SIZE": "2m"})
self.assertEqual(Image.core.get_block_size(), 2 * 1024 * 1024) assert Image.core.get_block_size() == 2 * 1024 * 1024
def test_warnings(self): def test_warnings(self):
pytest.warns( pytest.warns(

View File

@ -1,6 +1,7 @@
import io import io
import unittest import unittest
import pytest
from PIL import EpsImagePlugin, Image, features from PIL import EpsImagePlugin, Image, features
from .helper import PillowTestCase, assert_image_similar, hopper, skip_unless_feature from .helper import PillowTestCase, assert_image_similar, hopper, skip_unless_feature
@ -28,44 +29,45 @@ class TestFileEps(PillowTestCase):
# Regular scale # Regular scale
with Image.open(file1) as image1: with Image.open(file1) as image1:
image1.load() image1.load()
self.assertEqual(image1.mode, "RGB") assert image1.mode == "RGB"
self.assertEqual(image1.size, (460, 352)) assert image1.size == (460, 352)
self.assertEqual(image1.format, "EPS") assert image1.format == "EPS"
with Image.open(file2) as image2: with Image.open(file2) as image2:
image2.load() image2.load()
self.assertEqual(image2.mode, "RGB") assert image2.mode == "RGB"
self.assertEqual(image2.size, (360, 252)) assert image2.size == (360, 252)
self.assertEqual(image2.format, "EPS") assert image2.format == "EPS"
# Double scale # Double scale
with Image.open(file1) as image1_scale2: with Image.open(file1) as image1_scale2:
image1_scale2.load(scale=2) image1_scale2.load(scale=2)
self.assertEqual(image1_scale2.mode, "RGB") assert image1_scale2.mode == "RGB"
self.assertEqual(image1_scale2.size, (920, 704)) assert image1_scale2.size == (920, 704)
self.assertEqual(image1_scale2.format, "EPS") assert image1_scale2.format == "EPS"
with Image.open(file2) as image2_scale2: with Image.open(file2) as image2_scale2:
image2_scale2.load(scale=2) image2_scale2.load(scale=2)
self.assertEqual(image2_scale2.mode, "RGB") assert image2_scale2.mode == "RGB"
self.assertEqual(image2_scale2.size, (720, 504)) assert image2_scale2.size == (720, 504)
self.assertEqual(image2_scale2.format, "EPS") assert image2_scale2.format == "EPS"
def test_invalid_file(self): def test_invalid_file(self):
invalid_file = "Tests/images/flower.jpg" invalid_file = "Tests/images/flower.jpg"
self.assertRaises(SyntaxError, EpsImagePlugin.EpsImageFile, invalid_file) with pytest.raises(SyntaxError):
EpsImagePlugin.EpsImageFile(invalid_file)
@unittest.skipUnless(HAS_GHOSTSCRIPT, "Ghostscript not available") @unittest.skipUnless(HAS_GHOSTSCRIPT, "Ghostscript not available")
def test_cmyk(self): def test_cmyk(self):
with Image.open("Tests/images/pil_sample_cmyk.eps") as cmyk_image: with Image.open("Tests/images/pil_sample_cmyk.eps") as cmyk_image:
self.assertEqual(cmyk_image.mode, "CMYK") assert cmyk_image.mode == "CMYK"
self.assertEqual(cmyk_image.size, (100, 100)) assert cmyk_image.size == (100, 100)
self.assertEqual(cmyk_image.format, "EPS") assert cmyk_image.format == "EPS"
cmyk_image.load() cmyk_image.load()
self.assertEqual(cmyk_image.mode, "RGB") assert cmyk_image.mode == "RGB"
if features.check("jpg"): if features.check("jpg"):
with Image.open("Tests/images/pil_sample_rgb.jpg") as target: with Image.open("Tests/images/pil_sample_rgb.jpg") as target:
@ -111,7 +113,8 @@ class TestFileEps(PillowTestCase):
def test_image_mode_not_supported(self): def test_image_mode_not_supported(self):
im = hopper("RGBA") im = hopper("RGBA")
tmpfile = self.tempfile("temp.eps") tmpfile = self.tempfile("temp.eps")
self.assertRaises(ValueError, im.save, tmpfile) with pytest.raises(ValueError):
im.save(tmpfile)
@unittest.skipUnless(HAS_GHOSTSCRIPT, "Ghostscript not available") @unittest.skipUnless(HAS_GHOSTSCRIPT, "Ghostscript not available")
@skip_unless_feature("zlib") @skip_unless_feature("zlib")
@ -162,7 +165,7 @@ class TestFileEps(PillowTestCase):
with Image.open(fn) as im: with Image.open(fn) as im:
new_size = (100, 100) new_size = (100, 100)
im = im.resize(new_size) im = im.resize(new_size)
self.assertEqual(im.size, new_size) assert im.size == new_size
@unittest.skipUnless(HAS_GHOSTSCRIPT, "Ghostscript not available") @unittest.skipUnless(HAS_GHOSTSCRIPT, "Ghostscript not available")
def test_thumbnail(self): def test_thumbnail(self):
@ -173,7 +176,7 @@ class TestFileEps(PillowTestCase):
with Image.open(file1) as im: with Image.open(file1) as im:
new_size = (100, 100) new_size = (100, 100)
im.thumbnail(new_size) im.thumbnail(new_size)
self.assertEqual(max(im.size), max(new_size)) assert max(im.size) == max(new_size)
def test_read_binary_preview(self): def test_read_binary_preview(self):
# Issue 302 # Issue 302
@ -185,10 +188,10 @@ class TestFileEps(PillowTestCase):
ending = "Failure with line ending: %s" % ( ending = "Failure with line ending: %s" % (
"".join("%s" % ord(s) for s in ending) "".join("%s" % ord(s) for s in ending)
) )
self.assertEqual(t.readline().strip("\r\n"), "something", ending) assert t.readline().strip("\r\n") == "something", ending
self.assertEqual(t.readline().strip("\r\n"), "else", ending) assert t.readline().strip("\r\n") == "else", ending
self.assertEqual(t.readline().strip("\r\n"), "baz", ending) assert t.readline().strip("\r\n") == "baz", ending
self.assertEqual(t.readline().strip("\r\n"), "bif", ending) assert t.readline().strip("\r\n") == "bif", ending
def _test_readline_io_psfile(self, test_string, ending): def _test_readline_io_psfile(self, test_string, ending):
f = io.BytesIO(test_string.encode("latin-1")) f = io.BytesIO(test_string.encode("latin-1"))
@ -228,7 +231,7 @@ class TestFileEps(PillowTestCase):
# Act / Assert # Act / Assert
for filename in FILES: for filename in FILES:
with Image.open(filename) as img: with Image.open(filename) as img:
self.assertEqual(img.mode, "RGB") assert img.mode == "RGB"
@unittest.skipUnless(HAS_GHOSTSCRIPT, "Ghostscript not available") @unittest.skipUnless(HAS_GHOSTSCRIPT, "Ghostscript not available")
def test_emptyline(self): def test_emptyline(self):
@ -237,6 +240,6 @@ class TestFileEps(PillowTestCase):
with Image.open(emptyline_file) as image: with Image.open(emptyline_file) as image:
image.load() image.load()
self.assertEqual(image.mode, "RGB") assert image.mode == "RGB"
self.assertEqual(image.size, (460, 352)) assert image.size == (460, 352)
self.assertEqual(image.format, "EPS") assert image.format == "EPS"

View File

@ -24,10 +24,10 @@ class TestFileGif(PillowTestCase):
def test_sanity(self): def test_sanity(self):
with Image.open(TEST_GIF) as im: with Image.open(TEST_GIF) as im:
im.load() im.load()
self.assertEqual(im.mode, "P") assert im.mode == "P"
self.assertEqual(im.size, (128, 128)) assert im.size == (128, 128)
self.assertEqual(im.format, "GIF") assert im.format == "GIF"
self.assertEqual(im.info["version"], b"GIF89a") assert im.info["version"] == b"GIF89a"
@unittest.skipIf(is_pypy(), "Requires CPython") @unittest.skipIf(is_pypy(), "Requires CPython")
def test_unclosed_file(self): def test_unclosed_file(self):
@ -55,7 +55,8 @@ class TestFileGif(PillowTestCase):
def test_invalid_file(self): def test_invalid_file(self):
invalid_file = "Tests/images/flower.jpg" invalid_file = "Tests/images/flower.jpg"
self.assertRaises(SyntaxError, GifImagePlugin.GifImageFile, invalid_file) with pytest.raises(SyntaxError):
GifImagePlugin.GifImageFile(invalid_file)
def test_optimize(self): def test_optimize(self):
def test_grayscale(optimize): def test_grayscale(optimize):
@ -70,10 +71,10 @@ class TestFileGif(PillowTestCase):
im.save(test_file, "GIF", optimize=optimize) im.save(test_file, "GIF", optimize=optimize)
return len(test_file.getvalue()) return len(test_file.getvalue())
self.assertEqual(test_grayscale(0), 800) assert test_grayscale(0) == 800
self.assertEqual(test_grayscale(1), 44) assert test_grayscale(1) == 44
self.assertEqual(test_bilevel(0), 800) assert test_bilevel(0) == 800
self.assertEqual(test_bilevel(1), 800) assert test_bilevel(1) == 800
def test_optimize_correctness(self): def test_optimize_correctness(self):
# 256 color Palette image, posterize to > 128 and < 128 levels # 256 color Palette image, posterize to > 128 and < 128 levels
@ -94,7 +95,7 @@ class TestFileGif(PillowTestCase):
palette_length = max( palette_length = max(
i + 1 for i, v in enumerate(reloaded.histogram()) if v i + 1 for i, v in enumerate(reloaded.histogram()) if v
) )
self.assertEqual(expected_palette_length, palette_length) assert expected_palette_length == palette_length
assert_image_equal(im.convert("RGB"), reloaded.convert("RGB")) assert_image_equal(im.convert("RGB"), reloaded.convert("RGB"))
@ -117,7 +118,7 @@ class TestFileGif(PillowTestCase):
im = Image.frombytes("L", (16, 16), bytes(range(256))) im = Image.frombytes("L", (16, 16), bytes(range(256)))
test_file = BytesIO() test_file = BytesIO()
im.save(test_file, "GIF", optimize=True) im.save(test_file, "GIF", optimize=True)
self.assertEqual(im.mode, "L") assert im.mode == "L"
def test_roundtrip(self): def test_roundtrip(self):
out = self.tempfile("temp.gif") out = self.tempfile("temp.gif")
@ -153,7 +154,7 @@ class TestFileGif(PillowTestCase):
im.save(out, save_all=True) im.save(out, save_all=True)
with Image.open(out) as reread: with Image.open(out) as reread:
self.assertEqual(reread.n_frames, 5) assert reread.n_frames == 5
def test_headers_saving_for_animated_gifs(self): def test_headers_saving_for_animated_gifs(self):
important_headers = ["background", "version", "duration", "loop"] important_headers = ["background", "version", "duration", "loop"]
@ -167,7 +168,7 @@ class TestFileGif(PillowTestCase):
with Image.open(out) as reread: with Image.open(out) as reread:
for header in important_headers: for header in important_headers:
self.assertEqual(info[header], reread.info[header]) assert info[header] == reread.info[header]
def test_palette_handling(self): def test_palette_handling(self):
# see https://github.com/python-pillow/Pillow/issues/513 # see https://github.com/python-pillow/Pillow/issues/513
@ -237,7 +238,7 @@ class TestFileGif(PillowTestCase):
framecount += 1 framecount += 1
img.seek(img.tell() + 1) img.seek(img.tell() + 1)
except EOFError: except EOFError:
self.assertEqual(framecount, 5) assert framecount == 5
def test_seek_info(self): def test_seek_info(self):
with Image.open("Tests/images/iss634.gif") as im: with Image.open("Tests/images/iss634.gif") as im:
@ -246,7 +247,7 @@ class TestFileGif(PillowTestCase):
im.seek(1) im.seek(1)
im.seek(0) im.seek(0)
self.assertEqual(im.info, info) assert im.info == info
def test_seek_rewind(self): def test_seek_rewind(self):
with Image.open("Tests/images/iss634.gif") as im: with Image.open("Tests/images/iss634.gif") as im:
@ -261,20 +262,21 @@ class TestFileGif(PillowTestCase):
for path, n_frames in [[TEST_GIF, 1], ["Tests/images/iss634.gif", 42]]: for path, n_frames in [[TEST_GIF, 1], ["Tests/images/iss634.gif", 42]]:
# Test is_animated before n_frames # Test is_animated before n_frames
with Image.open(path) as im: with Image.open(path) as im:
self.assertEqual(im.is_animated, n_frames != 1) assert im.is_animated == (n_frames != 1)
# Test is_animated after n_frames # Test is_animated after n_frames
with Image.open(path) as im: with Image.open(path) as im:
self.assertEqual(im.n_frames, n_frames) assert im.n_frames == n_frames
self.assertEqual(im.is_animated, n_frames != 1) assert im.is_animated == (n_frames != 1)
def test_eoferror(self): def test_eoferror(self):
with Image.open(TEST_GIF) as im: with Image.open(TEST_GIF) as im:
n_frames = im.n_frames n_frames = im.n_frames
# Test seeking past the last frame # Test seeking past the last frame
self.assertRaises(EOFError, im.seek, n_frames) with pytest.raises(EOFError):
self.assertLess(im.tell(), n_frames) im.seek(n_frames)
assert im.tell() < n_frames
# Test that seeking to the last frame does not raise an error # Test that seeking to the last frame does not raise an error
im.seek(n_frames - 1) im.seek(n_frames - 1)
@ -284,7 +286,7 @@ class TestFileGif(PillowTestCase):
try: try:
while True: while True:
img.seek(img.tell() + 1) img.seek(img.tell() + 1)
self.assertEqual(img.disposal_method, 1) assert img.disposal_method == 1
except EOFError: except EOFError:
pass pass
@ -293,7 +295,7 @@ class TestFileGif(PillowTestCase):
try: try:
while True: while True:
img.seek(img.tell() + 1) img.seek(img.tell() + 1)
self.assertEqual(img.disposal_method, 2) assert img.disposal_method == 2
except EOFError: except EOFError:
pass pass
@ -302,7 +304,7 @@ class TestFileGif(PillowTestCase):
try: try:
while True: while True:
img.seek(img.tell() + 1) img.seek(img.tell() + 1)
self.assertEqual(img.disposal_method, 3) assert img.disposal_method == 3
except EOFError: except EOFError:
pass pass
@ -320,7 +322,7 @@ class TestFileGif(PillowTestCase):
with Image.open(out) as img: with Image.open(out) as img:
for _ in range(2): for _ in range(2):
img.seek(img.tell() + 1) img.seek(img.tell() + 1)
self.assertEqual(img.disposal_method, method) assert img.disposal_method == method
# check per frame disposal # check per frame disposal
im_list[0].save( im_list[0].save(
@ -334,7 +336,7 @@ class TestFileGif(PillowTestCase):
for i in range(2): for i in range(2):
img.seek(img.tell() + 1) img.seek(img.tell() + 1)
self.assertEqual(img.disposal_method, i + 1) assert img.disposal_method == i + 1
def test_dispose2_palette(self): def test_dispose2_palette(self):
out = self.tempfile("temp.gif") out = self.tempfile("temp.gif")
@ -360,10 +362,10 @@ class TestFileGif(PillowTestCase):
rgb_img = img.convert("RGB") rgb_img = img.convert("RGB")
# Check top left pixel matches background # Check top left pixel matches background
self.assertEqual(rgb_img.getpixel((0, 0)), (255, 0, 0)) assert rgb_img.getpixel((0, 0)) == (255, 0, 0)
# Center remains red every frame # Center remains red every frame
self.assertEqual(rgb_img.getpixel((50, 50)), circle) assert rgb_img.getpixel((50, 50)) == circle
def test_dispose2_diff(self): def test_dispose2_diff(self):
out = self.tempfile("temp.gif") out = self.tempfile("temp.gif")
@ -398,13 +400,13 @@ class TestFileGif(PillowTestCase):
rgb_img = img.convert("RGBA") rgb_img = img.convert("RGBA")
# Check left circle is correct colour # Check left circle is correct colour
self.assertEqual(rgb_img.getpixel((20, 50)), colours[0]) assert rgb_img.getpixel((20, 50)) == colours[0]
# Check right circle is correct colour # Check right circle is correct colour
self.assertEqual(rgb_img.getpixel((80, 50)), colours[1]) assert rgb_img.getpixel((80, 50)) == colours[1]
# Check BG is correct colour # Check BG is correct colour
self.assertEqual(rgb_img.getpixel((1, 1)), (255, 255, 255, 0)) assert rgb_img.getpixel((1, 1)) == (255, 255, 255, 0)
def test_dispose2_background(self): def test_dispose2_background(self):
out = self.tempfile("temp.gif") out = self.tempfile("temp.gif")
@ -429,7 +431,7 @@ class TestFileGif(PillowTestCase):
with Image.open(out) as im: with Image.open(out) as im:
im.seek(1) im.seek(1)
self.assertEqual(im.getpixel((0, 0)), 0) assert im.getpixel((0, 0)) == 0
def test_iss634(self): def test_iss634(self):
with Image.open("Tests/images/iss634.gif") as img: with Image.open("Tests/images/iss634.gif") as img:
@ -437,7 +439,7 @@ class TestFileGif(PillowTestCase):
img.seek(img.tell() + 1) img.seek(img.tell() + 1)
# all transparent pixels should be replaced with the color from the # all transparent pixels should be replaced with the color from the
# first frame # first frame
self.assertEqual(img.histogram()[img.info["transparency"]], 0) assert img.histogram()[img.info["transparency"]] == 0
def test_duration(self): def test_duration(self):
duration = 1000 duration = 1000
@ -450,7 +452,7 @@ class TestFileGif(PillowTestCase):
im.save(out, duration=duration) im.save(out, duration=duration)
with Image.open(out) as reread: with Image.open(out) as reread:
self.assertEqual(reread.info["duration"], duration) assert reread.info["duration"] == duration
def test_multiple_duration(self): def test_multiple_duration(self):
duration_list = [1000, 2000, 3000] duration_list = [1000, 2000, 3000]
@ -469,7 +471,7 @@ class TestFileGif(PillowTestCase):
with Image.open(out) as reread: with Image.open(out) as reread:
for duration in duration_list: for duration in duration_list:
self.assertEqual(reread.info["duration"], duration) assert reread.info["duration"] == duration
try: try:
reread.seek(reread.tell() + 1) reread.seek(reread.tell() + 1)
except EOFError: except EOFError:
@ -482,7 +484,7 @@ class TestFileGif(PillowTestCase):
with Image.open(out) as reread: with Image.open(out) as reread:
for duration in duration_list: for duration in duration_list:
self.assertEqual(reread.info["duration"], duration) assert reread.info["duration"] == duration
try: try:
reread.seek(reread.tell() + 1) reread.seek(reread.tell() + 1)
except EOFError: except EOFError:
@ -506,10 +508,10 @@ class TestFileGif(PillowTestCase):
with Image.open(out) as reread: with Image.open(out) as reread:
# Assert that the first three frames were combined # Assert that the first three frames were combined
self.assertEqual(reread.n_frames, 2) assert reread.n_frames == 2
# Assert that the new duration is the total of the identical frames # Assert that the new duration is the total of the identical frames
self.assertEqual(reread.info["duration"], 4500) assert reread.info["duration"] == 4500
def test_identical_frames_to_single_frame(self): def test_identical_frames_to_single_frame(self):
for duration in ([1000, 1500, 2000, 4000], (1000, 1500, 2000, 4000), 8500): for duration in ([1000, 1500, 2000, 4000], (1000, 1500, 2000, 4000), 8500):
@ -525,10 +527,10 @@ class TestFileGif(PillowTestCase):
) )
with Image.open(out) as reread: with Image.open(out) as reread:
# Assert that all frames were combined # Assert that all frames were combined
self.assertEqual(reread.n_frames, 1) assert reread.n_frames == 1
# Assert that the new duration is the total of the identical frames # Assert that the new duration is the total of the identical frames
self.assertEqual(reread.info["duration"], 8500) assert reread.info["duration"] == 8500
def test_number_of_loops(self): def test_number_of_loops(self):
number_of_loops = 2 number_of_loops = 2
@ -538,7 +540,7 @@ class TestFileGif(PillowTestCase):
im.save(out, loop=number_of_loops) im.save(out, loop=number_of_loops)
with Image.open(out) as reread: with Image.open(out) as reread:
self.assertEqual(reread.info["loop"], number_of_loops) assert reread.info["loop"] == number_of_loops
def test_background(self): def test_background(self):
out = self.tempfile("temp.gif") out = self.tempfile("temp.gif")
@ -547,30 +549,28 @@ class TestFileGif(PillowTestCase):
im.save(out) im.save(out)
with Image.open(out) as reread: with Image.open(out) as reread:
self.assertEqual(reread.info["background"], im.info["background"]) assert reread.info["background"] == im.info["background"]
if features.check("webp") and features.check("webp_anim"): if features.check("webp") and features.check("webp_anim"):
with Image.open("Tests/images/hopper.webp") as im: with Image.open("Tests/images/hopper.webp") as im:
self.assertIsInstance(im.info["background"], tuple) assert isinstance(im.info["background"], tuple)
im.save(out) im.save(out)
def test_comment(self): def test_comment(self):
with Image.open(TEST_GIF) as im: with Image.open(TEST_GIF) as im:
self.assertEqual( assert im.info["comment"] == b"File written by Adobe Photoshop\xa8 4.0"
im.info["comment"], b"File written by Adobe Photoshop\xa8 4.0"
)
out = self.tempfile("temp.gif") out = self.tempfile("temp.gif")
im = Image.new("L", (100, 100), "#000") im = Image.new("L", (100, 100), "#000")
im.info["comment"] = b"Test comment text" im.info["comment"] = b"Test comment text"
im.save(out) im.save(out)
with Image.open(out) as reread: with Image.open(out) as reread:
self.assertEqual(reread.info["comment"], im.info["comment"]) assert reread.info["comment"] == im.info["comment"]
im.info["comment"] = "Test comment text" im.info["comment"] = "Test comment text"
im.save(out) im.save(out)
with Image.open(out) as reread: with Image.open(out) as reread:
self.assertEqual(reread.info["comment"], im.info["comment"].encode()) assert reread.info["comment"] == im.info["comment"].encode()
def test_comment_over_255(self): def test_comment_over_255(self):
out = self.tempfile("temp.gif") out = self.tempfile("temp.gif")
@ -582,7 +582,7 @@ class TestFileGif(PillowTestCase):
im.save(out) im.save(out)
with Image.open(out) as reread: with Image.open(out) as reread:
self.assertEqual(reread.info["comment"], comment) assert reread.info["comment"] == comment
def test_zero_comment_subblocks(self): def test_zero_comment_subblocks(self):
with Image.open("Tests/images/hopper_zero_comment_subblocks.gif") as im: with Image.open("Tests/images/hopper_zero_comment_subblocks.gif") as im:
@ -595,7 +595,7 @@ class TestFileGif(PillowTestCase):
def assertVersionAfterSave(im, version): def assertVersionAfterSave(im, version):
im.save(out) im.save(out)
with Image.open(out) as reread: with Image.open(out) as reread:
self.assertEqual(reread.info["version"], version) assert reread.info["version"] == version
# Test that GIF87a is used by default # Test that GIF87a is used by default
im = Image.new("L", (100, 100), "#000") im = Image.new("L", (100, 100), "#000")
@ -627,7 +627,7 @@ class TestFileGif(PillowTestCase):
im.copy().save(out, save_all=True, append_images=ims) im.copy().save(out, save_all=True, append_images=ims)
with Image.open(out) as reread: with Image.open(out) as reread:
self.assertEqual(reread.n_frames, 3) assert reread.n_frames == 3
# Tests appending using a generator # Tests appending using a generator
def imGenerator(ims): def imGenerator(ims):
@ -636,7 +636,7 @@ class TestFileGif(PillowTestCase):
im.save(out, save_all=True, append_images=imGenerator(ims)) im.save(out, save_all=True, append_images=imGenerator(ims))
with Image.open(out) as reread: with Image.open(out) as reread:
self.assertEqual(reread.n_frames, 3) assert reread.n_frames == 3
# Tests appending single and multiple frame images # Tests appending single and multiple frame images
with Image.open("Tests/images/dispose_none.gif") as im: with Image.open("Tests/images/dispose_none.gif") as im:
@ -644,7 +644,7 @@ class TestFileGif(PillowTestCase):
im.save(out, save_all=True, append_images=[im2]) im.save(out, save_all=True, append_images=[im2])
with Image.open(out) as reread: with Image.open(out) as reread:
self.assertEqual(reread.n_frames, 10) assert reread.n_frames == 10
def test_transparent_optimize(self): def test_transparent_optimize(self):
# from issue #2195, if the transparent color is incorrectly # from issue #2195, if the transparent color is incorrectly
@ -664,7 +664,7 @@ class TestFileGif(PillowTestCase):
im.save(out, transparency=253) im.save(out, transparency=253)
with Image.open(out) as reloaded: with Image.open(out) as reloaded:
self.assertEqual(reloaded.info["transparency"], 253) assert reloaded.info["transparency"] == 253
def test_rgb_transparency(self): def test_rgb_transparency(self):
out = self.tempfile("temp.gif") out = self.tempfile("temp.gif")
@ -675,7 +675,7 @@ class TestFileGif(PillowTestCase):
pytest.warns(UserWarning, im.save, out) pytest.warns(UserWarning, im.save, out)
with Image.open(out) as reloaded: with Image.open(out) as reloaded:
self.assertNotIn("transparency", reloaded.info) assert "transparency" not in reloaded.info
# Multiple frames # Multiple frames
im = Image.new("RGB", (1, 1)) im = Image.new("RGB", (1, 1))
@ -684,7 +684,7 @@ class TestFileGif(PillowTestCase):
pytest.warns(UserWarning, im.save, out, save_all=True, append_images=ims) pytest.warns(UserWarning, im.save, out, save_all=True, append_images=ims)
with Image.open(out) as reloaded: with Image.open(out) as reloaded:
self.assertNotIn("transparency", reloaded.info) assert "transparency" not in reloaded.info
def test_bbox(self): def test_bbox(self):
out = self.tempfile("temp.gif") out = self.tempfile("temp.gif")
@ -694,7 +694,7 @@ class TestFileGif(PillowTestCase):
im.save(out, save_all=True, append_images=ims) im.save(out, save_all=True, append_images=ims)
with Image.open(out) as reread: with Image.open(out) as reread:
self.assertEqual(reread.n_frames, 2) assert reread.n_frames == 2
def test_palette_save_L(self): def test_palette_save_L(self):
# generate an L mode image with a separate palette # generate an L mode image with a separate palette
@ -772,20 +772,20 @@ class TestFileGif(PillowTestCase):
with open("Tests/images/gif_header_data.pkl", "rb") as f: with open("Tests/images/gif_header_data.pkl", "rb") as f:
(h_target, d_target) = pickle.load(f) (h_target, d_target) = pickle.load(f)
self.assertEqual(h, h_target) assert h == h_target
self.assertEqual(d, d_target) assert d == d_target
finally: finally:
GifImagePlugin._FORCE_OPTIMIZE = False GifImagePlugin._FORCE_OPTIMIZE = False
def test_lzw_bits(self): def test_lzw_bits(self):
# see https://github.com/python-pillow/Pillow/issues/2811 # see https://github.com/python-pillow/Pillow/issues/2811
with Image.open("Tests/images/issue_2811.gif") as im: with Image.open("Tests/images/issue_2811.gif") as im:
self.assertEqual(im.tile[0][3][0], 11) # LZW bits assert im.tile[0][3][0] == 11 # LZW bits
# codec error prepatch # codec error prepatch
im.load() im.load()
def test_extents(self): def test_extents(self):
with Image.open("Tests/images/test_extents.gif") as im: with Image.open("Tests/images/test_extents.gif") as im:
self.assertEqual(im.size, (100, 100)) assert im.size == (100, 100)
im.seek(1) im.seek(1)
self.assertEqual(im.size, (150, 150)) assert im.size == (150, 150)

View File

@ -22,9 +22,9 @@ class TestFileIcns(PillowTestCase):
# Assert that there is no unclosed file warning # Assert that there is no unclosed file warning
pytest.warns(None, im.load) pytest.warns(None, im.load)
self.assertEqual(im.mode, "RGBA") assert im.mode == "RGBA"
self.assertEqual(im.size, (1024, 1024)) assert im.size == (1024, 1024)
self.assertEqual(im.format, "ICNS") assert im.format == "ICNS"
@unittest.skipIf(sys.platform != "darwin", "requires macOS") @unittest.skipIf(sys.platform != "darwin", "requires macOS")
def test_save(self): def test_save(self):
@ -34,9 +34,9 @@ class TestFileIcns(PillowTestCase):
im.save(temp_file) im.save(temp_file)
with Image.open(temp_file) as reread: with Image.open(temp_file) as reread:
self.assertEqual(reread.mode, "RGBA") assert reread.mode == "RGBA"
self.assertEqual(reread.size, (1024, 1024)) assert reread.size == (1024, 1024)
self.assertEqual(reread.format, "ICNS") assert reread.format == "ICNS"
@unittest.skipIf(sys.platform != "darwin", "requires macOS") @unittest.skipIf(sys.platform != "darwin", "requires macOS")
def test_save_append_images(self): def test_save_append_images(self):
@ -63,11 +63,11 @@ class TestFileIcns(PillowTestCase):
hr = h * r hr = h * r
im.size = (w, h, r) im.size = (w, h, r)
im.load() im.load()
self.assertEqual(im.mode, "RGBA") assert im.mode == "RGBA"
self.assertEqual(im.size, (wr, hr)) assert im.size == (wr, hr)
# Check that we cannot load an incorrect size # Check that we cannot load an incorrect size
with self.assertRaises(ValueError): with pytest.raises(ValueError):
im.size = (1, 1) im.size = (1, 1)
def test_older_icon(self): def test_older_icon(self):
@ -80,8 +80,8 @@ class TestFileIcns(PillowTestCase):
with Image.open("Tests/images/pillow2.icns") as im2: with Image.open("Tests/images/pillow2.icns") as im2:
im2.size = (w, h, r) im2.size = (w, h, r)
im2.load() im2.load()
self.assertEqual(im2.mode, "RGBA") assert im2.mode == "RGBA"
self.assertEqual(im2.size, (wr, hr)) assert im2.size == (wr, hr)
def test_jp2_icon(self): def test_jp2_icon(self):
# This icon was made by using Uli Kusterer's oldiconutil to replace # This icon was made by using Uli Kusterer's oldiconutil to replace
@ -101,21 +101,22 @@ class TestFileIcns(PillowTestCase):
with Image.open("Tests/images/pillow3.icns") as im2: with Image.open("Tests/images/pillow3.icns") as im2:
im2.size = (w, h, r) im2.size = (w, h, r)
im2.load() im2.load()
self.assertEqual(im2.mode, "RGBA") assert im2.mode == "RGBA"
self.assertEqual(im2.size, (wr, hr)) assert im2.size == (wr, hr)
def test_getimage(self): def test_getimage(self):
with open(TEST_FILE, "rb") as fp: with open(TEST_FILE, "rb") as fp:
icns_file = IcnsImagePlugin.IcnsFile(fp) icns_file = IcnsImagePlugin.IcnsFile(fp)
im = icns_file.getimage() im = icns_file.getimage()
self.assertEqual(im.mode, "RGBA") assert im.mode == "RGBA"
self.assertEqual(im.size, (1024, 1024)) assert im.size == (1024, 1024)
im = icns_file.getimage((512, 512)) im = icns_file.getimage((512, 512))
self.assertEqual(im.mode, "RGBA") assert im.mode == "RGBA"
self.assertEqual(im.size, (512, 512)) assert im.size == (512, 512)
def test_not_an_icns_file(self): def test_not_an_icns_file(self):
with io.BytesIO(b"invalid\n") as fp: with io.BytesIO(b"invalid\n") as fp:
self.assertRaises(SyntaxError, IcnsImagePlugin.IcnsFile, fp) with pytest.raises(SyntaxError):
IcnsImagePlugin.IcnsFile(fp)

View File

@ -12,14 +12,15 @@ class TestFileIco(PillowTestCase):
def test_sanity(self): def test_sanity(self):
with Image.open(TEST_ICO_FILE) as im: with Image.open(TEST_ICO_FILE) as im:
im.load() im.load()
self.assertEqual(im.mode, "RGBA") assert im.mode == "RGBA"
self.assertEqual(im.size, (16, 16)) assert im.size == (16, 16)
self.assertEqual(im.format, "ICO") assert im.format == "ICO"
self.assertEqual(im.get_format_mimetype(), "image/x-icon") assert im.get_format_mimetype() == "image/x-icon"
def test_invalid_file(self): def test_invalid_file(self):
with open("Tests/images/flower.jpg", "rb") as fp: with open("Tests/images/flower.jpg", "rb") as fp:
self.assertRaises(SyntaxError, IcoImagePlugin.IcoImageFile, fp) with pytest.raises(SyntaxError):
IcoImagePlugin.IcoImageFile(fp)
def test_save_to_bytes(self): def test_save_to_bytes(self):
output = io.BytesIO() output = io.BytesIO()
@ -29,11 +30,11 @@ class TestFileIco(PillowTestCase):
# the default image # the default image
output.seek(0) output.seek(0)
with Image.open(output) as reloaded: with Image.open(output) as reloaded:
self.assertEqual(reloaded.info["sizes"], {(32, 32), (64, 64)}) assert reloaded.info["sizes"] == {(32, 32), (64, 64)}
self.assertEqual(im.mode, reloaded.mode) assert im.mode == reloaded.mode
self.assertEqual((64, 64), reloaded.size) assert (64, 64) == reloaded.size
self.assertEqual(reloaded.format, "ICO") assert reloaded.format == "ICO"
assert_image_equal(reloaded, hopper().resize((64, 64), Image.LANCZOS)) assert_image_equal(reloaded, hopper().resize((64, 64), Image.LANCZOS))
# the other one # the other one
@ -41,14 +42,14 @@ class TestFileIco(PillowTestCase):
with Image.open(output) as reloaded: with Image.open(output) as reloaded:
reloaded.size = (32, 32) reloaded.size = (32, 32)
self.assertEqual(im.mode, reloaded.mode) assert im.mode == reloaded.mode
self.assertEqual((32, 32), reloaded.size) assert (32, 32) == reloaded.size
self.assertEqual(reloaded.format, "ICO") assert reloaded.format == "ICO"
assert_image_equal(reloaded, hopper().resize((32, 32), Image.LANCZOS)) assert_image_equal(reloaded, hopper().resize((32, 32), Image.LANCZOS))
def test_incorrect_size(self): def test_incorrect_size(self):
with Image.open(TEST_ICO_FILE) as im: with Image.open(TEST_ICO_FILE) as im:
with self.assertRaises(ValueError): with pytest.raises(ValueError):
im.size = (1, 1) im.size = (1, 1)
def test_save_256x256(self): def test_save_256x256(self):
@ -62,7 +63,7 @@ class TestFileIco(PillowTestCase):
with Image.open(outfile) as im_saved: with Image.open(outfile) as im_saved:
# Assert # Assert
self.assertEqual(im_saved.size, (256, 256)) assert im_saved.size == (256, 256)
def test_only_save_relevant_sizes(self): def test_only_save_relevant_sizes(self):
"""Issue #2266 https://github.com/python-pillow/Pillow/issues/2266 """Issue #2266 https://github.com/python-pillow/Pillow/issues/2266
@ -77,16 +78,14 @@ class TestFileIco(PillowTestCase):
with Image.open(outfile) as im_saved: with Image.open(outfile) as im_saved:
# Assert # Assert
self.assertEqual( assert im_saved.info["sizes"] == {(16, 16), (24, 24), (32, 32), (48, 48)}
im_saved.info["sizes"], {(16, 16), (24, 24), (32, 32), (48, 48)}
)
def test_unexpected_size(self): def test_unexpected_size(self):
# This image has been manually hexedited to state that it is 16x32 # This image has been manually hexedited to state that it is 16x32
# while the image within is still 16x16 # while the image within is still 16x16
def open(): def open():
with Image.open("Tests/images/hopper_unexpected.ico") as im: with Image.open("Tests/images/hopper_unexpected.ico") as im:
self.assertEqual(im.size, (16, 16)) assert im.size == (16, 16)
pytest.warns(UserWarning, open) pytest.warns(UserWarning, open)

View File

@ -46,21 +46,20 @@ class TestFileJpeg(PillowTestCase):
with Image.open(TEST_FILE) as im: with Image.open(TEST_FILE) as im:
im.load() im.load()
self.assertEqual(im.mode, "RGB") assert im.mode == "RGB"
self.assertEqual(im.size, (128, 128)) assert im.size == (128, 128)
self.assertEqual(im.format, "JPEG") assert im.format == "JPEG"
self.assertEqual(im.get_format_mimetype(), "image/jpeg") assert im.get_format_mimetype() == "image/jpeg"
def test_app(self): def test_app(self):
# Test APP/COM reader (@PIL135) # Test APP/COM reader (@PIL135)
with Image.open(TEST_FILE) as im: with Image.open(TEST_FILE) as im:
self.assertEqual( assert im.applist[0] == ("APP0", b"JFIF\x00\x01\x01\x01\x00`\x00`\x00\x00")
im.applist[0], ("APP0", b"JFIF\x00\x01\x01\x01\x00`\x00`\x00\x00") assert im.applist[1] == (
"COM",
b"File written by Adobe Photoshop\xa8 4.0\x00",
) )
self.assertEqual( assert len(im.applist) == 2
im.applist[1], ("COM", b"File written by Adobe Photoshop\xa8 4.0\x00")
)
self.assertEqual(len(im.applist), 2)
def test_cmyk(self): def test_cmyk(self):
# Test CMYK handling. Thanks to Tim and Charlie for test data, # Test CMYK handling. Thanks to Tim and Charlie for test data,
@ -69,26 +68,26 @@ class TestFileJpeg(PillowTestCase):
with Image.open(f) as im: with Image.open(f) as im:
# the source image has red pixels in the upper left corner. # the source image has red pixels in the upper left corner.
c, m, y, k = [x / 255.0 for x in im.getpixel((0, 0))] c, m, y, k = [x / 255.0 for x in im.getpixel((0, 0))]
self.assertEqual(c, 0.0) assert c == 0.0
self.assertGreater(m, 0.8) assert m > 0.8
self.assertGreater(y, 0.8) assert y > 0.8
self.assertEqual(k, 0.0) assert k == 0.0
# the opposite corner is black # the opposite corner is black
c, m, y, k = [ c, m, y, k = [
x / 255.0 for x in im.getpixel((im.size[0] - 1, im.size[1] - 1)) x / 255.0 for x in im.getpixel((im.size[0] - 1, im.size[1] - 1))
] ]
self.assertGreater(k, 0.9) assert k > 0.9
# roundtrip, and check again # roundtrip, and check again
im = self.roundtrip(im) im = self.roundtrip(im)
c, m, y, k = [x / 255.0 for x in im.getpixel((0, 0))] c, m, y, k = [x / 255.0 for x in im.getpixel((0, 0))]
self.assertEqual(c, 0.0) assert c == 0.0
self.assertGreater(m, 0.8) assert m > 0.8
self.assertGreater(y, 0.8) assert y > 0.8
self.assertEqual(k, 0.0) assert k == 0.0
c, m, y, k = [ c, m, y, k = [
x / 255.0 for x in im.getpixel((im.size[0] - 1, im.size[1] - 1)) x / 255.0 for x in im.getpixel((im.size[0] - 1, im.size[1] - 1))
] ]
self.assertGreater(k, 0.9) assert k > 0.9
def test_dpi(self): def test_dpi(self):
def test(xdpi, ydpi=None): def test(xdpi, ydpi=None):
@ -96,27 +95,27 @@ class TestFileJpeg(PillowTestCase):
im = self.roundtrip(im, dpi=(xdpi, ydpi or xdpi)) im = self.roundtrip(im, dpi=(xdpi, ydpi or xdpi))
return im.info.get("dpi") return im.info.get("dpi")
self.assertEqual(test(72), (72, 72)) assert test(72) == (72, 72)
self.assertEqual(test(300), (300, 300)) assert test(300) == (300, 300)
self.assertEqual(test(100, 200), (100, 200)) assert test(100, 200) == (100, 200)
self.assertIsNone(test(0)) # square pixels assert test(0) is None # square pixels
def test_icc(self): def test_icc(self):
# Test ICC support # Test ICC support
with Image.open("Tests/images/rgb.jpg") as im1: with Image.open("Tests/images/rgb.jpg") as im1:
icc_profile = im1.info["icc_profile"] icc_profile = im1.info["icc_profile"]
self.assertEqual(len(icc_profile), 3144) assert len(icc_profile) == 3144
# Roundtrip via physical file. # Roundtrip via physical file.
f = self.tempfile("temp.jpg") f = self.tempfile("temp.jpg")
im1.save(f, icc_profile=icc_profile) im1.save(f, icc_profile=icc_profile)
with Image.open(f) as im2: with Image.open(f) as im2:
self.assertEqual(im2.info.get("icc_profile"), icc_profile) assert im2.info.get("icc_profile") == icc_profile
# Roundtrip via memory buffer. # Roundtrip via memory buffer.
im1 = self.roundtrip(hopper()) im1 = self.roundtrip(hopper())
im2 = self.roundtrip(hopper(), icc_profile=icc_profile) im2 = self.roundtrip(hopper(), icc_profile=icc_profile)
assert_image_equal(im1, im2) assert_image_equal(im1, im2)
self.assertFalse(im1.info.get("icc_profile")) assert not im1.info.get("icc_profile")
self.assertTrue(im2.info.get("icc_profile")) assert im2.info.get("icc_profile")
def test_icc_big(self): def test_icc_big(self):
# Make sure that the "extra" support handles large blocks # Make sure that the "extra" support handles large blocks
@ -125,9 +124,9 @@ class TestFileJpeg(PillowTestCase):
# using a 4-byte test code should allow us to detect out of # using a 4-byte test code should allow us to detect out of
# order issues. # order issues.
icc_profile = (b"Test" * int(n / 4 + 1))[:n] icc_profile = (b"Test" * int(n / 4 + 1))[:n]
self.assertEqual(len(icc_profile), n) # sanity assert len(icc_profile) == n # sanity
im1 = self.roundtrip(hopper(), icc_profile=icc_profile) im1 = self.roundtrip(hopper(), icc_profile=icc_profile)
self.assertEqual(im1.info.get("icc_profile"), icc_profile or None) assert im1.info.get("icc_profile") == (icc_profile or None)
test(0) test(0)
test(1) test(1)
@ -163,8 +162,8 @@ class TestFileJpeg(PillowTestCase):
im3 = self.roundtrip(hopper(), optimize=1) im3 = self.roundtrip(hopper(), optimize=1)
assert_image_equal(im1, im2) assert_image_equal(im1, im2)
assert_image_equal(im1, im3) assert_image_equal(im1, im3)
self.assertGreaterEqual(im1.bytes, im2.bytes) assert im1.bytes >= im2.bytes
self.assertGreaterEqual(im1.bytes, im3.bytes) assert im1.bytes >= im3.bytes
def test_optimize_large_buffer(self): def test_optimize_large_buffer(self):
# https://github.com/python-pillow/Pillow/issues/148 # https://github.com/python-pillow/Pillow/issues/148
@ -177,12 +176,12 @@ class TestFileJpeg(PillowTestCase):
im1 = self.roundtrip(hopper()) im1 = self.roundtrip(hopper())
im2 = self.roundtrip(hopper(), progressive=False) im2 = self.roundtrip(hopper(), progressive=False)
im3 = self.roundtrip(hopper(), progressive=True) im3 = self.roundtrip(hopper(), progressive=True)
self.assertFalse(im1.info.get("progressive")) assert not im1.info.get("progressive")
self.assertFalse(im2.info.get("progressive")) assert not im2.info.get("progressive")
self.assertTrue(im3.info.get("progressive")) assert im3.info.get("progressive")
assert_image_equal(im1, im3) assert_image_equal(im1, im3)
self.assertGreaterEqual(im1.bytes, im3.bytes) assert im1.bytes >= im3.bytes
def test_progressive_large_buffer(self): def test_progressive_large_buffer(self):
f = self.tempfile("temp.jpg") f = self.tempfile("temp.jpg")
@ -229,7 +228,7 @@ class TestFileJpeg(PillowTestCase):
exif = im._getexif() exif = im._getexif()
# Assert # Assert
self.assertEqual(exif[gps_index], expected_exif_gps) assert exif[gps_index] == expected_exif_gps
def test_exif_rollback(self): def test_exif_rollback(self):
# rolling back exif support in 3.1 to pre-3.0 formatting. # rolling back exif support in 3.1 to pre-3.0 formatting.
@ -264,7 +263,7 @@ class TestFileJpeg(PillowTestCase):
exif = im._getexif() exif = im._getexif()
for tag, value in expected_exif.items(): for tag, value in expected_exif.items():
self.assertEqual(value, exif[tag]) assert value == exif[tag]
def test_exif_gps_typeerror(self): def test_exif_gps_typeerror(self):
with Image.open("Tests/images/exif_gps_typeerror.jpg") as im: with Image.open("Tests/images/exif_gps_typeerror.jpg") as im:
@ -274,30 +273,30 @@ class TestFileJpeg(PillowTestCase):
def test_progressive_compat(self): def test_progressive_compat(self):
im1 = self.roundtrip(hopper()) im1 = self.roundtrip(hopper())
self.assertFalse(im1.info.get("progressive")) assert not im1.info.get("progressive")
self.assertFalse(im1.info.get("progression")) assert not im1.info.get("progression")
im2 = self.roundtrip(hopper(), progressive=0) im2 = self.roundtrip(hopper(), progressive=0)
im3 = self.roundtrip(hopper(), progression=0) # compatibility im3 = self.roundtrip(hopper(), progression=0) # compatibility
self.assertFalse(im2.info.get("progressive")) assert not im2.info.get("progressive")
self.assertFalse(im2.info.get("progression")) assert not im2.info.get("progression")
self.assertFalse(im3.info.get("progressive")) assert not im3.info.get("progressive")
self.assertFalse(im3.info.get("progression")) assert not im3.info.get("progression")
im2 = self.roundtrip(hopper(), progressive=1) im2 = self.roundtrip(hopper(), progressive=1)
im3 = self.roundtrip(hopper(), progression=1) # compatibility im3 = self.roundtrip(hopper(), progression=1) # compatibility
assert_image_equal(im1, im2) assert_image_equal(im1, im2)
assert_image_equal(im1, im3) assert_image_equal(im1, im3)
self.assertTrue(im2.info.get("progressive")) assert im2.info.get("progressive")
self.assertTrue(im2.info.get("progression")) assert im2.info.get("progression")
self.assertTrue(im3.info.get("progressive")) assert im3.info.get("progressive")
self.assertTrue(im3.info.get("progression")) assert im3.info.get("progression")
def test_quality(self): def test_quality(self):
im1 = self.roundtrip(hopper()) im1 = self.roundtrip(hopper())
im2 = self.roundtrip(hopper(), quality=50) im2 = self.roundtrip(hopper(), quality=50)
assert_image(im1, im2.mode, im2.size) assert_image(im1, im2.mode, im2.size)
self.assertGreaterEqual(im1.bytes, im2.bytes) assert im1.bytes >= im2.bytes
def test_smooth(self): def test_smooth(self):
im1 = self.roundtrip(hopper()) im1 = self.roundtrip(hopper())
@ -311,35 +310,36 @@ class TestFileJpeg(PillowTestCase):
# experimental API # experimental API
im = self.roundtrip(hopper(), subsampling=-1) # default im = self.roundtrip(hopper(), subsampling=-1) # default
self.assertEqual(getsampling(im), (2, 2, 1, 1, 1, 1)) assert getsampling(im) == (2, 2, 1, 1, 1, 1)
im = self.roundtrip(hopper(), subsampling=0) # 4:4:4 im = self.roundtrip(hopper(), subsampling=0) # 4:4:4
self.assertEqual(getsampling(im), (1, 1, 1, 1, 1, 1)) assert getsampling(im) == (1, 1, 1, 1, 1, 1)
im = self.roundtrip(hopper(), subsampling=1) # 4:2:2 im = self.roundtrip(hopper(), subsampling=1) # 4:2:2
self.assertEqual(getsampling(im), (2, 1, 1, 1, 1, 1)) assert getsampling(im) == (2, 1, 1, 1, 1, 1)
im = self.roundtrip(hopper(), subsampling=2) # 4:2:0 im = self.roundtrip(hopper(), subsampling=2) # 4:2:0
self.assertEqual(getsampling(im), (2, 2, 1, 1, 1, 1)) assert getsampling(im) == (2, 2, 1, 1, 1, 1)
im = self.roundtrip(hopper(), subsampling=3) # default (undefined) im = self.roundtrip(hopper(), subsampling=3) # default (undefined)
self.assertEqual(getsampling(im), (2, 2, 1, 1, 1, 1)) assert getsampling(im) == (2, 2, 1, 1, 1, 1)
im = self.roundtrip(hopper(), subsampling="4:4:4") im = self.roundtrip(hopper(), subsampling="4:4:4")
self.assertEqual(getsampling(im), (1, 1, 1, 1, 1, 1)) assert getsampling(im) == (1, 1, 1, 1, 1, 1)
im = self.roundtrip(hopper(), subsampling="4:2:2") im = self.roundtrip(hopper(), subsampling="4:2:2")
self.assertEqual(getsampling(im), (2, 1, 1, 1, 1, 1)) assert getsampling(im) == (2, 1, 1, 1, 1, 1)
im = self.roundtrip(hopper(), subsampling="4:2:0") im = self.roundtrip(hopper(), subsampling="4:2:0")
self.assertEqual(getsampling(im), (2, 2, 1, 1, 1, 1)) assert getsampling(im) == (2, 2, 1, 1, 1, 1)
im = self.roundtrip(hopper(), subsampling="4:1:1") im = self.roundtrip(hopper(), subsampling="4:1:1")
self.assertEqual(getsampling(im), (2, 2, 1, 1, 1, 1)) assert getsampling(im) == (2, 2, 1, 1, 1, 1)
self.assertRaises(TypeError, self.roundtrip, hopper(), subsampling="1:1:1") with pytest.raises(TypeError):
self.roundtrip(hopper(), subsampling="1:1:1")
def test_exif(self): def test_exif(self):
with Image.open("Tests/images/pil_sample_rgb.jpg") as im: with Image.open("Tests/images/pil_sample_rgb.jpg") as im:
info = im._getexif() info = im._getexif()
self.assertEqual(info[305], "Adobe Photoshop CS Macintosh") assert info[305] == "Adobe Photoshop CS Macintosh"
def test_mp(self): def test_mp(self):
with Image.open("Tests/images/pil_sample_rgb.jpg") as im: with Image.open("Tests/images/pil_sample_rgb.jpg") as im:
self.assertIsNone(im._getmp()) assert im._getmp() is None
def test_quality_keep(self): def test_quality_keep(self):
# RGB # RGB
@ -372,16 +372,16 @@ class TestFileJpeg(PillowTestCase):
with Image.open(filename) as im: with Image.open(filename) as im:
im.load() im.load()
ImageFile.LOAD_TRUNCATED_IMAGES = False ImageFile.LOAD_TRUNCATED_IMAGES = False
self.assertIsNotNone(im.getbbox()) assert im.getbbox() is not None
def test_truncated_jpeg_throws_IOError(self): def test_truncated_jpeg_throws_IOError(self):
filename = "Tests/images/truncated_jpeg.jpg" filename = "Tests/images/truncated_jpeg.jpg"
with Image.open(filename) as im: with Image.open(filename) as im:
with self.assertRaises(IOError): with pytest.raises(IOError):
im.load() im.load()
# Test that the error is raised if loaded a second time # Test that the error is raised if loaded a second time
with self.assertRaises(IOError): with pytest.raises(IOError):
im.load() im.load()
def _n_qtables_helper(self, n, test_file): def _n_qtables_helper(self, n, test_file):
@ -389,15 +389,15 @@ class TestFileJpeg(PillowTestCase):
f = self.tempfile("temp.jpg") f = self.tempfile("temp.jpg")
im.save(f, qtables=[[n] * 64] * n) im.save(f, qtables=[[n] * 64] * n)
with Image.open(f) as im: with Image.open(f) as im:
self.assertEqual(len(im.quantization), n) assert len(im.quantization) == n
reloaded = self.roundtrip(im, qtables="keep") reloaded = self.roundtrip(im, qtables="keep")
self.assertEqual(im.quantization, reloaded.quantization) assert im.quantization == reloaded.quantization
def test_qtables(self): def test_qtables(self):
with Image.open("Tests/images/hopper.jpg") as im: with Image.open("Tests/images/hopper.jpg") as im:
qtables = im.quantization qtables = im.quantization
reloaded = self.roundtrip(im, qtables=qtables, subsampling=0) reloaded = self.roundtrip(im, qtables=qtables, subsampling=0)
self.assertEqual(im.quantization, reloaded.quantization) assert im.quantization == reloaded.quantization
assert_image_similar(im, self.roundtrip(im, qtables="web_low"), 30) assert_image_similar(im, self.roundtrip(im, qtables="web_low"), 30)
assert_image_similar(im, self.roundtrip(im, qtables="web_high"), 30) assert_image_similar(im, self.roundtrip(im, qtables="web_high"), 30)
assert_image_similar(im, self.roundtrip(im, qtables="keep"), 30) assert_image_similar(im, self.roundtrip(im, qtables="keep"), 30)
@ -475,16 +475,21 @@ class TestFileJpeg(PillowTestCase):
self._n_qtables_helper(4, "Tests/images/pil_sample_cmyk.jpg") self._n_qtables_helper(4, "Tests/images/pil_sample_cmyk.jpg")
# not a sequence # not a sequence
self.assertRaises(ValueError, self.roundtrip, im, qtables="a") with pytest.raises(ValueError):
self.roundtrip(im, qtables="a")
# sequence wrong length # sequence wrong length
self.assertRaises(ValueError, self.roundtrip, im, qtables=[]) with pytest.raises(ValueError):
self.roundtrip(im, qtables=[])
# sequence wrong length # sequence wrong length
self.assertRaises(ValueError, self.roundtrip, im, qtables=[1, 2, 3, 4, 5]) with pytest.raises(ValueError):
self.roundtrip(im, qtables=[1, 2, 3, 4, 5])
# qtable entry not a sequence # qtable entry not a sequence
self.assertRaises(ValueError, self.roundtrip, im, qtables=[1]) with pytest.raises(ValueError):
self.roundtrip(im, qtables=[1])
# qtable entry has wrong number of items # qtable entry has wrong number of items
self.assertRaises(ValueError, self.roundtrip, im, qtables=[[1, 2, 3, 4]]) with pytest.raises(ValueError):
self.roundtrip(im, qtables=[[1, 2, 3, 4]])
@unittest.skipUnless(djpeg_available(), "djpeg not available") @unittest.skipUnless(djpeg_available(), "djpeg not available")
def test_load_djpeg(self): def test_load_djpeg(self):
@ -505,8 +510,8 @@ class TestFileJpeg(PillowTestCase):
tag_ids = {v: k for k, v in ExifTags.TAGS.items()} tag_ids = {v: k for k, v in ExifTags.TAGS.items()}
# Assert # Assert
self.assertEqual(tag_ids["RelatedImageWidth"], 0x1001) assert tag_ids["RelatedImageWidth"] == 0x1001
self.assertEqual(tag_ids["RelatedImageLength"], 0x1002) assert tag_ids["RelatedImageLength"] == 0x1002
def test_MAXBLOCK_scaling(self): def test_MAXBLOCK_scaling(self):
im = self.gen_random_image((512, 512)) im = self.gen_random_image((512, 512))
@ -529,7 +534,7 @@ class TestFileJpeg(PillowTestCase):
with pytest.warns(UserWarning, Image.open, fn) as im: with pytest.warns(UserWarning, Image.open, fn) as im:
# Assert # Assert
self.assertEqual(im.format, "JPEG") assert im.format == "JPEG"
def test_save_correct_modes(self): def test_save_correct_modes(self):
out = BytesIO() out = BytesIO()
@ -542,7 +547,8 @@ class TestFileJpeg(PillowTestCase):
out = BytesIO() out = BytesIO()
for mode in ["LA", "La", "RGBA", "RGBa", "P"]: for mode in ["LA", "La", "RGBA", "RGBa", "P"]:
img = Image.new(mode, (20, 20)) img = Image.new(mode, (20, 20))
self.assertRaises(IOError, img.save, out, "JPEG") with pytest.raises(IOError):
img.save(out, "JPEG")
def test_save_tiff_with_dpi(self): def test_save_tiff_with_dpi(self):
# Arrange # Arrange
@ -555,16 +561,16 @@ class TestFileJpeg(PillowTestCase):
# Assert # Assert
with Image.open(outfile) as reloaded: with Image.open(outfile) as reloaded:
reloaded.load() reloaded.load()
self.assertEqual(im.info["dpi"], reloaded.info["dpi"]) assert im.info["dpi"] == reloaded.info["dpi"]
def test_load_dpi_rounding(self): def test_load_dpi_rounding(self):
# Round up # Round up
with Image.open("Tests/images/iptc_roundUp.jpg") as im: with Image.open("Tests/images/iptc_roundUp.jpg") as im:
self.assertEqual(im.info["dpi"], (44, 44)) assert im.info["dpi"] == (44, 44)
# Round down # Round down
with Image.open("Tests/images/iptc_roundDown.jpg") as im: with Image.open("Tests/images/iptc_roundDown.jpg") as im:
self.assertEqual(im.info["dpi"], (2, 2)) assert im.info["dpi"] == (2, 2)
def test_save_dpi_rounding(self): def test_save_dpi_rounding(self):
outfile = self.tempfile("temp.jpg") outfile = self.tempfile("temp.jpg")
@ -572,12 +578,12 @@ class TestFileJpeg(PillowTestCase):
im.save(outfile, dpi=(72.2, 72.2)) im.save(outfile, dpi=(72.2, 72.2))
with Image.open(outfile) as reloaded: with Image.open(outfile) as reloaded:
self.assertEqual(reloaded.info["dpi"], (72, 72)) assert reloaded.info["dpi"] == (72, 72)
im.save(outfile, dpi=(72.8, 72.8)) im.save(outfile, dpi=(72.8, 72.8))
with Image.open(outfile) as reloaded: with Image.open(outfile) as reloaded:
self.assertEqual(reloaded.info["dpi"], (73, 73)) assert reloaded.info["dpi"] == (73, 73)
def test_dpi_tuple_from_exif(self): def test_dpi_tuple_from_exif(self):
# Arrange # Arrange
@ -586,7 +592,7 @@ class TestFileJpeg(PillowTestCase):
with Image.open("Tests/images/photoshop-200dpi.jpg") as im: with Image.open("Tests/images/photoshop-200dpi.jpg") as im:
# Act / Assert # Act / Assert
self.assertEqual(im.info.get("dpi"), (200, 200)) assert im.info.get("dpi") == (200, 200)
def test_dpi_int_from_exif(self): def test_dpi_int_from_exif(self):
# Arrange # Arrange
@ -595,7 +601,7 @@ class TestFileJpeg(PillowTestCase):
with Image.open("Tests/images/exif-72dpi-int.jpg") as im: with Image.open("Tests/images/exif-72dpi-int.jpg") as im:
# Act / Assert # Act / Assert
self.assertEqual(im.info.get("dpi"), (72, 72)) assert im.info.get("dpi") == (72, 72)
def test_dpi_from_dpcm_exif(self): def test_dpi_from_dpcm_exif(self):
# Arrange # Arrange
@ -604,7 +610,7 @@ class TestFileJpeg(PillowTestCase):
with Image.open("Tests/images/exif-200dpcm.jpg") as im: with Image.open("Tests/images/exif-200dpcm.jpg") as im:
# Act / Assert # Act / Assert
self.assertEqual(im.info.get("dpi"), (508, 508)) assert im.info.get("dpi") == (508, 508)
def test_dpi_exif_zero_division(self): def test_dpi_exif_zero_division(self):
# Arrange # Arrange
@ -614,7 +620,7 @@ class TestFileJpeg(PillowTestCase):
# Act / Assert # Act / Assert
# This should return the default, and not raise a ZeroDivisionError # This should return the default, and not raise a ZeroDivisionError
self.assertEqual(im.info.get("dpi"), (72, 72)) assert im.info.get("dpi") == (72, 72)
def test_no_dpi_in_exif(self): def test_no_dpi_in_exif(self):
# Arrange # Arrange
@ -625,7 +631,7 @@ class TestFileJpeg(PillowTestCase):
# Act / Assert # Act / Assert
# "When the image resolution is unknown, 72 [dpi] is designated." # "When the image resolution is unknown, 72 [dpi] is designated."
# http://www.exiv2.org/tags.html # http://www.exiv2.org/tags.html
self.assertEqual(im.info.get("dpi"), (72, 72)) assert im.info.get("dpi") == (72, 72)
def test_invalid_exif(self): def test_invalid_exif(self):
# This is no-dpi-in-exif with the tiff header of the exif block # This is no-dpi-in-exif with the tiff header of the exif block
@ -634,7 +640,7 @@ class TestFileJpeg(PillowTestCase):
# This should return the default, and not a SyntaxError or # This should return the default, and not a SyntaxError or
# OSError for unidentified image. # OSError for unidentified image.
self.assertEqual(im.info.get("dpi"), (72, 72)) assert im.info.get("dpi") == (72, 72)
def test_invalid_exif_x_resolution(self): def test_invalid_exif_x_resolution(self):
# When no x or y resolution is defined in EXIF # When no x or y resolution is defined in EXIF
@ -642,7 +648,7 @@ class TestFileJpeg(PillowTestCase):
# This should return the default, and not a ValueError or # This should return the default, and not a ValueError or
# OSError for an unidentified image. # OSError for an unidentified image.
self.assertEqual(im.info.get("dpi"), (72, 72)) assert im.info.get("dpi") == (72, 72)
def test_ifd_offset_exif(self): def test_ifd_offset_exif(self):
# Arrange # Arrange
@ -651,19 +657,16 @@ class TestFileJpeg(PillowTestCase):
with Image.open("Tests/images/exif-ifd-offset.jpg") as im: with Image.open("Tests/images/exif-ifd-offset.jpg") as im:
# Act / Assert # Act / Assert
self.assertEqual(im._getexif()[306], "2017:03:13 23:03:09") assert im._getexif()[306] == "2017:03:13 23:03:09"
def test_photoshop(self): def test_photoshop(self):
with Image.open("Tests/images/photoshop-200dpi.jpg") as im: with Image.open("Tests/images/photoshop-200dpi.jpg") as im:
self.assertEqual( assert im.info["photoshop"][0x03ED] == {
im.info["photoshop"][0x03ED], "XResolution": 200.0,
{ "DisplayedUnitsX": 1,
"XResolution": 200.0, "YResolution": 200.0,
"DisplayedUnitsX": 1, "DisplayedUnitsY": 1,
"YResolution": 200.0, }
"DisplayedUnitsY": 1,
},
)
# Test that the image can still load, even with broken Photoshop data # Test that the image can still load, even with broken Photoshop data
# This image had the APP13 length hexedited to be smaller # This image had the APP13 length hexedited to be smaller
@ -672,14 +675,14 @@ class TestFileJpeg(PillowTestCase):
# This image does not contain a Photoshop header string # This image does not contain a Photoshop header string
with Image.open("Tests/images/app13.jpg") as im: with Image.open("Tests/images/app13.jpg") as im:
self.assertNotIn("photoshop", im.info) assert "photoshop" not in im.info
def test_photoshop_malformed_and_multiple(self): def test_photoshop_malformed_and_multiple(self):
with Image.open("Tests/images/app13-multiple.jpg") as im: with Image.open("Tests/images/app13-multiple.jpg") as im:
self.assertIn("photoshop", im.info) assert "photoshop" in im.info
self.assertEqual(24, len(im.info["photoshop"])) assert 24 == len(im.info["photoshop"])
apps_13_lengths = [len(v) for k, v in im.applist if k == "APP13"] apps_13_lengths = [len(v) for k, v in im.applist if k == "APP13"]
self.assertEqual([65504, 24], apps_13_lengths) assert [65504, 24] == apps_13_lengths
@unittest.skipUnless(is_win32(), "Windows only") @unittest.skipUnless(is_win32(), "Windows only")
@ -693,9 +696,10 @@ class TestFileCloseW32(PillowTestCase):
im = Image.open(tmpfile) im = Image.open(tmpfile)
fp = im.fp fp = im.fp
self.assertFalse(fp.closed) assert not fp.closed
self.assertRaises(WindowsError, os.remove, tmpfile) with pytest.raises(WindowsError):
os.remove(tmpfile)
im.load() im.load()
self.assertTrue(fp.closed) assert fp.closed
# this should not fail, as load should have closed the file. # this should not fail, as load should have closed the file.
os.remove(tmpfile) os.remove(tmpfile)

View File

@ -38,21 +38,22 @@ class TestFileJpeg2k(PillowTestCase):
with Image.open("Tests/images/test-card-lossless.jp2") as im: with Image.open("Tests/images/test-card-lossless.jp2") as im:
px = im.load() px = im.load()
self.assertEqual(px[0, 0], (0, 0, 0)) assert px[0, 0] == (0, 0, 0)
self.assertEqual(im.mode, "RGB") assert im.mode == "RGB"
self.assertEqual(im.size, (640, 480)) assert im.size == (640, 480)
self.assertEqual(im.format, "JPEG2000") assert im.format == "JPEG2000"
self.assertEqual(im.get_format_mimetype(), "image/jp2") assert im.get_format_mimetype() == "image/jp2"
def test_jpf(self): def test_jpf(self):
with Image.open("Tests/images/balloon.jpf") as im: with Image.open("Tests/images/balloon.jpf") as im:
self.assertEqual(im.format, "JPEG2000") assert im.format == "JPEG2000"
self.assertEqual(im.get_format_mimetype(), "image/jpx") assert im.get_format_mimetype() == "image/jpx"
def test_invalid_file(self): def test_invalid_file(self):
invalid_file = "Tests/images/flower.jpg" invalid_file = "Tests/images/flower.jpg"
self.assertRaises(SyntaxError, Jpeg2KImagePlugin.Jpeg2KImageFile, invalid_file) with pytest.raises(SyntaxError):
Jpeg2KImagePlugin.Jpeg2KImageFile(invalid_file)
def test_bytesio(self): def test_bytesio(self):
with open("Tests/images/test-card-lossless.jp2", "rb") as f: with open("Tests/images/test-card-lossless.jp2", "rb") as f:
@ -95,7 +96,7 @@ class TestFileJpeg2k(PillowTestCase):
assert_image_equal(im, test_card) assert_image_equal(im, test_card)
def test_tiled_offset_too_small(self): def test_tiled_offset_too_small(self):
with self.assertRaises(ValueError): with pytest.raises(ValueError):
self.roundtrip( self.roundtrip(
test_card, tile_size=(128, 128), tile_offset=(0, 0), offset=(128, 32) test_card, tile_size=(128, 128), tile_offset=(0, 0), offset=(128, 32)
) )
@ -116,7 +117,7 @@ class TestFileJpeg2k(PillowTestCase):
with Image.open("Tests/images/test-card-lossless.jp2") as im: with Image.open("Tests/images/test-card-lossless.jp2") as im:
im.reduce = 2 im.reduce = 2
im.load() im.load()
self.assertEqual(im.size, (160, 120)) assert im.size == (160, 120)
def test_layers_type(self): def test_layers_type(self):
outfile = self.tempfile("temp_layers.jp2") outfile = self.tempfile("temp_layers.jp2")
@ -124,9 +125,8 @@ class TestFileJpeg2k(PillowTestCase):
test_card.save(outfile, quality_layers=quality_layers) test_card.save(outfile, quality_layers=quality_layers)
for quality_layers in ["quality_layers", ("100", "50", "10")]: for quality_layers in ["quality_layers", ("100", "50", "10")]:
self.assertRaises( with pytest.raises(ValueError):
ValueError, test_card.save, outfile, quality_layers=quality_layers test_card.save(outfile, quality_layers=quality_layers)
)
def test_layers(self): def test_layers(self):
out = BytesIO() out = BytesIO()
@ -156,17 +156,17 @@ class TestFileJpeg2k(PillowTestCase):
jp2.load() jp2.load()
# Assert # Assert
self.assertEqual(j2k.mode, "RGBA") assert j2k.mode == "RGBA"
self.assertEqual(jp2.mode, "RGBA") assert jp2.mode == "RGBA"
def test_16bit_monochrome_has_correct_mode(self): def test_16bit_monochrome_has_correct_mode(self):
with Image.open("Tests/images/16bit.cropped.j2k") as j2k: with Image.open("Tests/images/16bit.cropped.j2k") as j2k:
j2k.load() j2k.load()
self.assertEqual(j2k.mode, "I;16") assert j2k.mode == "I;16"
with Image.open("Tests/images/16bit.cropped.jp2") as jp2: with Image.open("Tests/images/16bit.cropped.jp2") as jp2:
jp2.load() jp2.load()
self.assertEqual(jp2.mode, "I;16") assert jp2.mode == "I;16"
@pytest.mark.xfail(is_big_endian() and on_ci(), reason="Fails on big-endian") @pytest.mark.xfail(is_big_endian() and on_ci(), reason="Fails on big-endian")
def test_16bit_monochrome_jp2_like_tiff(self): def test_16bit_monochrome_jp2_like_tiff(self):
@ -193,7 +193,7 @@ class TestFileJpeg2k(PillowTestCase):
def test_unbound_local(self): def test_unbound_local(self):
# prepatch, a malformed jp2 file could cause an UnboundLocalError # prepatch, a malformed jp2 file could cause an UnboundLocalError
# exception. # exception.
with self.assertRaises(IOError): with pytest.raises(IOError):
Image.open("Tests/images/unbound_variable.jp2") Image.open("Tests/images/unbound_variable.jp2")
def test_parser_feed(self): def test_parser_feed(self):
@ -206,4 +206,4 @@ class TestFileJpeg2k(PillowTestCase):
p.feed(data) p.feed(data)
# Assert # Assert
self.assertEqual(p.image.size, (640, 480)) assert p.image.size == (640, 480)

View File

@ -6,6 +6,7 @@ import os
from collections import namedtuple from collections import namedtuple
from ctypes import c_float from ctypes import c_float
import pytest
from PIL import Image, ImageFilter, TiffImagePlugin, TiffTags from PIL import Image, ImageFilter, TiffImagePlugin, TiffTags
from .helper import ( from .helper import (
@ -26,14 +27,14 @@ class LibTiffTestCase(PillowTestCase):
def _assert_noerr(self, im): def _assert_noerr(self, im):
"""Helper tests that assert basic sanity about the g4 tiff reading""" """Helper tests that assert basic sanity about the g4 tiff reading"""
# 1 bit # 1 bit
self.assertEqual(im.mode, "1") assert im.mode == "1"
# Does the data actually load # Does the data actually load
im.load() im.load()
im.getdata() im.getdata()
try: try:
self.assertEqual(im._compression, "group4") assert im._compression == "group4"
except AttributeError: except AttributeError:
print("No _compression") print("No _compression")
print(dir(im)) print(dir(im))
@ -52,7 +53,7 @@ class TestFileLibTiff(LibTiffTestCase):
test_file = "Tests/images/hopper_g4_500.tif" test_file = "Tests/images/hopper_g4_500.tif"
with Image.open(test_file) as im: with Image.open(test_file) as im:
self.assertEqual(im.size, (500, 500)) assert im.size == (500, 500)
self._assert_noerr(im) self._assert_noerr(im)
def test_g4_large(self): def test_g4_large(self):
@ -66,7 +67,7 @@ class TestFileLibTiff(LibTiffTestCase):
test_file = "Tests/images/hopper_g4_500.tif" test_file = "Tests/images/hopper_g4_500.tif"
with open(test_file, "rb") as f: with open(test_file, "rb") as f:
with Image.open(f) as im: with Image.open(f) as im:
self.assertEqual(im.size, (500, 500)) assert im.size == (500, 500)
self._assert_noerr(im) self._assert_noerr(im)
def test_g4_tiff_bytesio(self): def test_g4_tiff_bytesio(self):
@ -77,7 +78,7 @@ class TestFileLibTiff(LibTiffTestCase):
s.write(f.read()) s.write(f.read())
s.seek(0) s.seek(0)
with Image.open(s) as im: with Image.open(s) as im:
self.assertEqual(im.size, (500, 500)) assert im.size == (500, 500)
self._assert_noerr(im) self._assert_noerr(im)
def test_g4_non_disk_file_object(self): def test_g4_non_disk_file_object(self):
@ -89,7 +90,7 @@ class TestFileLibTiff(LibTiffTestCase):
s.seek(0) s.seek(0)
r = io.BufferedReader(s) r = io.BufferedReader(s)
with Image.open(r) as im: with Image.open(r) as im:
self.assertEqual(im.size, (500, 500)) assert im.size == (500, 500)
self._assert_noerr(im) self._assert_noerr(im)
def test_g4_eq_png(self): def test_g4_eq_png(self):
@ -111,25 +112,25 @@ class TestFileLibTiff(LibTiffTestCase):
with Image.open(test_file) as orig: with Image.open(test_file) as orig:
out = self.tempfile("temp.tif") out = self.tempfile("temp.tif")
rot = orig.transpose(Image.ROTATE_90) rot = orig.transpose(Image.ROTATE_90)
self.assertEqual(rot.size, (500, 500)) assert rot.size == (500, 500)
rot.save(out) rot.save(out)
with Image.open(out) as reread: with Image.open(out) as reread:
self.assertEqual(reread.size, (500, 500)) assert reread.size == (500, 500)
self._assert_noerr(reread) self._assert_noerr(reread)
assert_image_equal(reread, rot) assert_image_equal(reread, rot)
self.assertEqual(reread.info["compression"], "group4") assert reread.info["compression"] == "group4"
self.assertEqual(reread.info["compression"], orig.info["compression"]) assert reread.info["compression"] == orig.info["compression"]
self.assertNotEqual(orig.tobytes(), reread.tobytes()) assert orig.tobytes() != reread.tobytes()
def test_adobe_deflate_tiff(self): def test_adobe_deflate_tiff(self):
test_file = "Tests/images/tiff_adobe_deflate.tif" test_file = "Tests/images/tiff_adobe_deflate.tif"
with Image.open(test_file) as im: with Image.open(test_file) as im:
self.assertEqual(im.mode, "RGB") assert im.mode == "RGB"
self.assertEqual(im.size, (278, 374)) assert im.size == (278, 374)
self.assertEqual(im.tile[0][:3], ("libtiff", (0, 0, 278, 374), 0)) assert im.tile[0][:3] == ("libtiff", (0, 0, 278, 374), 0)
im.load() im.load()
assert_image_equal_tofile(im, "Tests/images/tiff_adobe_deflate.png") assert_image_equal_tofile(im, "Tests/images/tiff_adobe_deflate.png")
@ -166,24 +167,21 @@ class TestFileLibTiff(LibTiffTestCase):
val = original[tag] val = original[tag]
if tag.endswith("Resolution"): if tag.endswith("Resolution"):
if legacy_api: if legacy_api:
self.assertEqual( assert (
c_float(val[0][0] / val[0][1]).value, c_float(val[0][0] / val[0][1]).value
c_float(value[0][0] / value[0][1]).value, == c_float(value[0][0] / value[0][1]).value
msg="%s didn't roundtrip" % tag, ), ("%s didn't roundtrip" % tag)
)
else: else:
self.assertEqual( assert c_float(val).value == c_float(value).value, (
c_float(val).value, "%s didn't roundtrip" % tag
c_float(value).value,
msg="%s didn't roundtrip" % tag,
) )
else: else:
self.assertEqual(val, value, msg="%s didn't roundtrip" % tag) assert val == value, "%s didn't roundtrip" % tag
# https://github.com/python-pillow/Pillow/issues/1561 # https://github.com/python-pillow/Pillow/issues/1561
requested_fields = ["StripByteCounts", "RowsPerStrip", "StripOffsets"] requested_fields = ["StripByteCounts", "RowsPerStrip", "StripOffsets"]
for field in requested_fields: for field in requested_fields:
self.assertIn(field, reloaded, "%s not in metadata" % field) assert field in reloaded, "%s not in metadata" % field
def test_additional_metadata(self): def test_additional_metadata(self):
# these should not crash. Seriously dummy data, most of it doesn't make # these should not crash. Seriously dummy data, most of it doesn't make
@ -303,7 +301,7 @@ class TestFileLibTiff(LibTiffTestCase):
if libtiff and isinstance(value, bytes): if libtiff and isinstance(value, bytes):
value = value.decode() value = value.decode()
self.assertEqual(reloaded_value, value) assert reloaded_value == value
# Test with types # Test with types
ifd = TiffImagePlugin.ImageFileDirectory_v2() ifd = TiffImagePlugin.ImageFileDirectory_v2()
@ -331,7 +329,7 @@ class TestFileLibTiff(LibTiffTestCase):
im.save(out, dpi=(72, 72)) im.save(out, dpi=(72, 72))
TiffImagePlugin.WRITE_LIBTIFF = False TiffImagePlugin.WRITE_LIBTIFF = False
with Image.open(out) as reloaded: with Image.open(out) as reloaded:
self.assertEqual(reloaded.info["dpi"], (72.0, 72.0)) assert reloaded.info["dpi"] == (72.0, 72.0)
def test_g3_compression(self): def test_g3_compression(self):
with Image.open("Tests/images/hopper_g4_500.tif") as i: with Image.open("Tests/images/hopper_g4_500.tif") as i:
@ -339,44 +337,44 @@ class TestFileLibTiff(LibTiffTestCase):
i.save(out, compression="group3") i.save(out, compression="group3")
with Image.open(out) as reread: with Image.open(out) as reread:
self.assertEqual(reread.info["compression"], "group3") assert reread.info["compression"] == "group3"
assert_image_equal(reread, i) assert_image_equal(reread, i)
def test_little_endian(self): def test_little_endian(self):
with Image.open("Tests/images/16bit.deflate.tif") as im: with Image.open("Tests/images/16bit.deflate.tif") as im:
self.assertEqual(im.getpixel((0, 0)), 480) assert im.getpixel((0, 0)) == 480
self.assertEqual(im.mode, "I;16") assert im.mode == "I;16"
b = im.tobytes() b = im.tobytes()
# Bytes are in image native order (little endian) # Bytes are in image native order (little endian)
self.assertEqual(b[0], ord(b"\xe0")) assert b[0] == ord(b"\xe0")
self.assertEqual(b[1], ord(b"\x01")) assert b[1] == ord(b"\x01")
out = self.tempfile("temp.tif") out = self.tempfile("temp.tif")
# out = "temp.le.tif" # out = "temp.le.tif"
im.save(out) im.save(out)
with Image.open(out) as reread: with Image.open(out) as reread:
self.assertEqual(reread.info["compression"], im.info["compression"]) assert reread.info["compression"] == im.info["compression"]
self.assertEqual(reread.getpixel((0, 0)), 480) assert reread.getpixel((0, 0)) == 480
# UNDONE - libtiff defaults to writing in native endian, so # UNDONE - libtiff defaults to writing in native endian, so
# on big endian, we'll get back mode = 'I;16B' here. # on big endian, we'll get back mode = 'I;16B' here.
def test_big_endian(self): def test_big_endian(self):
with Image.open("Tests/images/16bit.MM.deflate.tif") as im: with Image.open("Tests/images/16bit.MM.deflate.tif") as im:
self.assertEqual(im.getpixel((0, 0)), 480) assert im.getpixel((0, 0)) == 480
self.assertEqual(im.mode, "I;16B") assert im.mode == "I;16B"
b = im.tobytes() b = im.tobytes()
# Bytes are in image native order (big endian) # Bytes are in image native order (big endian)
self.assertEqual(b[0], ord(b"\x01")) assert b[0] == ord(b"\x01")
self.assertEqual(b[1], ord(b"\xe0")) assert b[1] == ord(b"\xe0")
out = self.tempfile("temp.tif") out = self.tempfile("temp.tif")
im.save(out) im.save(out)
with Image.open(out) as reread: with Image.open(out) as reread:
self.assertEqual(reread.info["compression"], im.info["compression"]) assert reread.info["compression"] == im.info["compression"]
self.assertEqual(reread.getpixel((0, 0)), 480) assert reread.getpixel((0, 0)) == 480
def test_g4_string_info(self): def test_g4_string_info(self):
"""Tests String data in info directory""" """Tests String data in info directory"""
@ -388,8 +386,8 @@ class TestFileLibTiff(LibTiffTestCase):
orig.save(out) orig.save(out)
with Image.open(out) as reread: with Image.open(out) as reread:
self.assertEqual("temp.tif", reread.tag_v2[269]) assert "temp.tif" == reread.tag_v2[269]
self.assertEqual("temp.tif", reread.tag[269][0]) assert "temp.tif" == reread.tag[269][0]
def test_12bit_rawmode(self): def test_12bit_rawmode(self):
""" Are we generating the same interpretation """ Are we generating the same interpretation
@ -445,18 +443,22 @@ class TestFileLibTiff(LibTiffTestCase):
with Image.open(out) as im3: with Image.open(out) as im3:
assert_image_similar(im2, im3, 30) assert_image_similar(im2, im3, 30)
self.assertGreater(size_raw, size_compressed) assert size_raw > size_compressed
self.assertGreater(size_compressed, size_jpeg) assert size_compressed > size_jpeg
self.assertGreater(size_jpeg, size_jpeg_30) assert size_jpeg > size_jpeg_30
def test_quality(self): def test_quality(self):
im = hopper("RGB") im = hopper("RGB")
out = self.tempfile("temp.tif") out = self.tempfile("temp.tif")
self.assertRaises(ValueError, im.save, out, compression="tiff_lzw", quality=50) with pytest.raises(ValueError):
self.assertRaises(ValueError, im.save, out, compression="jpeg", quality=-1) im.save(out, compression="tiff_lzw", quality=50)
self.assertRaises(ValueError, im.save, out, compression="jpeg", quality=101) with pytest.raises(ValueError):
self.assertRaises(ValueError, im.save, out, compression="jpeg", quality="good") im.save(out, compression="jpeg", quality=-1)
with pytest.raises(ValueError):
im.save(out, compression="jpeg", quality=101)
with pytest.raises(ValueError):
im.save(out, compression="jpeg", quality="good")
im.save(out, compression="jpeg", quality=0) im.save(out, compression="jpeg", quality=0)
im.save(out, compression="jpeg", quality=100) im.save(out, compression="jpeg", quality=100)
@ -476,9 +478,12 @@ class TestFileLibTiff(LibTiffTestCase):
im = hopper("RGB") im = hopper("RGB")
out = self.tempfile("temp.tif") out = self.tempfile("temp.tif")
self.assertRaises(IOError, im.save, out, compression="tiff_ccitt") with pytest.raises(IOError):
self.assertRaises(IOError, im.save, out, compression="group3") im.save(out, compression="tiff_ccitt")
self.assertRaises(IOError, im.save, out, compression="group4") with pytest.raises(IOError):
im.save(out, compression="group3")
with pytest.raises(IOError):
im.save(out, compression="group4")
def test_fp_leak(self): def test_fp_leak(self):
im = Image.open("Tests/images/hopper_g4_500.tif") im = Image.open("Tests/images/hopper_g4_500.tif")
@ -486,10 +491,13 @@ class TestFileLibTiff(LibTiffTestCase):
os.fstat(fn) os.fstat(fn)
im.load() # this should close it. im.load() # this should close it.
self.assertRaises(OSError, os.fstat, fn) with pytest.raises(OSError):
os.fstat(fn)
im = None # this should force even more closed. im = None # this should force even more closed.
self.assertRaises(OSError, os.fstat, fn) with pytest.raises(OSError):
self.assertRaises(OSError, os.close, fn) os.fstat(fn)
with pytest.raises(OSError):
os.close(fn)
def test_multipage(self): def test_multipage(self):
# issue #862 # issue #862
@ -498,19 +506,19 @@ class TestFileLibTiff(LibTiffTestCase):
# file is a multipage tiff, 10x10 green, 10x10 red, 20x20 blue # file is a multipage tiff, 10x10 green, 10x10 red, 20x20 blue
im.seek(0) im.seek(0)
self.assertEqual(im.size, (10, 10)) assert im.size == (10, 10)
self.assertEqual(im.convert("RGB").getpixel((0, 0)), (0, 128, 0)) assert im.convert("RGB").getpixel((0, 0)) == (0, 128, 0)
self.assertTrue(im.tag.next) assert im.tag.next
im.seek(1) im.seek(1)
self.assertEqual(im.size, (10, 10)) assert im.size == (10, 10)
self.assertEqual(im.convert("RGB").getpixel((0, 0)), (255, 0, 0)) assert im.convert("RGB").getpixel((0, 0)) == (255, 0, 0)
self.assertTrue(im.tag.next) assert im.tag.next
im.seek(2) im.seek(2)
self.assertFalse(im.tag.next) assert not im.tag.next
self.assertEqual(im.size, (20, 20)) assert im.size == (20, 20)
self.assertEqual(im.convert("RGB").getpixel((0, 0)), (0, 0, 255)) assert im.convert("RGB").getpixel((0, 0)) == (0, 0, 255)
TiffImagePlugin.READ_LIBTIFF = False TiffImagePlugin.READ_LIBTIFF = False
@ -519,7 +527,7 @@ class TestFileLibTiff(LibTiffTestCase):
TiffImagePlugin.READ_LIBTIFF = True TiffImagePlugin.READ_LIBTIFF = True
with Image.open("Tests/images/multipage.tiff") as im: with Image.open("Tests/images/multipage.tiff") as im:
frames = im.n_frames frames = im.n_frames
self.assertEqual(frames, 3) assert frames == 3
for _ in range(frames): for _ in range(frames):
im.seek(0) im.seek(0)
# Should not raise ValueError: I/O operation on closed file # Should not raise ValueError: I/O operation on closed file
@ -530,9 +538,9 @@ class TestFileLibTiff(LibTiffTestCase):
def test__next(self): def test__next(self):
TiffImagePlugin.READ_LIBTIFF = True TiffImagePlugin.READ_LIBTIFF = True
with Image.open("Tests/images/hopper.tif") as im: with Image.open("Tests/images/hopper.tif") as im:
self.assertFalse(im.tag.next) assert not im.tag.next
im.load() im.load()
self.assertFalse(im.tag.next) assert not im.tag.next
def test_4bit(self): def test_4bit(self):
# Arrange # Arrange
@ -545,8 +553,8 @@ class TestFileLibTiff(LibTiffTestCase):
TiffImagePlugin.READ_LIBTIFF = False TiffImagePlugin.READ_LIBTIFF = False
# Assert # Assert
self.assertEqual(im.size, (128, 128)) assert im.size == (128, 128)
self.assertEqual(im.mode, "L") assert im.mode == "L"
assert_image_similar(im, original, 7.3) assert_image_similar(im, original, 7.3)
def test_gray_semibyte_per_pixel(self): def test_gray_semibyte_per_pixel(self):
@ -573,13 +581,13 @@ class TestFileLibTiff(LibTiffTestCase):
original = hopper("L") original = hopper("L")
for epsilon, group in test_files: for epsilon, group in test_files:
with Image.open(group[0]) as im: with Image.open(group[0]) as im:
self.assertEqual(im.size, (128, 128)) assert im.size == (128, 128)
self.assertEqual(im.mode, "L") assert im.mode == "L"
assert_image_similar(im, original, epsilon) assert_image_similar(im, original, epsilon)
for file in group[1:]: for file in group[1:]:
with Image.open(file) as im2: with Image.open(file) as im2:
self.assertEqual(im2.size, (128, 128)) assert im2.size == (128, 128)
self.assertEqual(im2.mode, "L") assert im2.mode == "L"
assert_image_equal(im, im2) assert_image_equal(im, im2)
def test_save_bytesio(self): def test_save_bytesio(self):
@ -650,29 +658,29 @@ class TestFileLibTiff(LibTiffTestCase):
def test_read_icc(self): def test_read_icc(self):
with Image.open("Tests/images/hopper.iccprofile.tif") as img: with Image.open("Tests/images/hopper.iccprofile.tif") as img:
icc = img.info.get("icc_profile") icc = img.info.get("icc_profile")
self.assertIsNotNone(icc) assert icc is not None
TiffImagePlugin.READ_LIBTIFF = True TiffImagePlugin.READ_LIBTIFF = True
with Image.open("Tests/images/hopper.iccprofile.tif") as img: with Image.open("Tests/images/hopper.iccprofile.tif") as img:
icc_libtiff = img.info.get("icc_profile") icc_libtiff = img.info.get("icc_profile")
self.assertIsNotNone(icc_libtiff) assert icc_libtiff is not None
TiffImagePlugin.READ_LIBTIFF = False TiffImagePlugin.READ_LIBTIFF = False
self.assertEqual(icc, icc_libtiff) assert icc == icc_libtiff
def test_multipage_compression(self): def test_multipage_compression(self):
with Image.open("Tests/images/compression.tif") as im: with Image.open("Tests/images/compression.tif") as im:
im.seek(0) im.seek(0)
self.assertEqual(im._compression, "tiff_ccitt") assert im._compression == "tiff_ccitt"
self.assertEqual(im.size, (10, 10)) assert im.size == (10, 10)
im.seek(1) im.seek(1)
self.assertEqual(im._compression, "packbits") assert im._compression == "packbits"
self.assertEqual(im.size, (10, 10)) assert im.size == (10, 10)
im.load() im.load()
im.seek(0) im.seek(0)
self.assertEqual(im._compression, "tiff_ccitt") assert im._compression == "tiff_ccitt"
self.assertEqual(im.size, (10, 10)) assert im.size == (10, 10)
im.load() im.load()
def test_save_tiff_with_jpegtables(self): def test_save_tiff_with_jpegtables(self):
@ -689,38 +697,27 @@ class TestFileLibTiff(LibTiffTestCase):
def test_16bit_RGB_tiff(self): def test_16bit_RGB_tiff(self):
with Image.open("Tests/images/tiff_16bit_RGB.tiff") as im: with Image.open("Tests/images/tiff_16bit_RGB.tiff") as im:
self.assertEqual(im.mode, "RGB") assert im.mode == "RGB"
self.assertEqual(im.size, (100, 40)) assert im.size == (100, 40)
self.assertEqual( assert im.tile, [
im.tile, (
[ "libtiff",
( (0, 0, 100, 40),
"libtiff", 0,
(0, 0, 100, 40), ("RGB;16N", "tiff_adobe_deflate", False, 8),
0, )
("RGB;16N", "tiff_adobe_deflate", False, 8), ]
)
],
)
im.load() im.load()
assert_image_equal_tofile(im, "Tests/images/tiff_16bit_RGB_target.png") assert_image_equal_tofile(im, "Tests/images/tiff_16bit_RGB_target.png")
def test_16bit_RGBa_tiff(self): def test_16bit_RGBa_tiff(self):
with Image.open("Tests/images/tiff_16bit_RGBa.tiff") as im: with Image.open("Tests/images/tiff_16bit_RGBa.tiff") as im:
self.assertEqual(im.mode, "RGBA") assert im.mode == "RGBA"
self.assertEqual(im.size, (100, 40)) assert im.size == (100, 40)
self.assertEqual( assert im.tile, [
im.tile, ("libtiff", (0, 0, 100, 40), 0, ("RGBa;16N", "tiff_lzw", False, 38236),)
[ ]
(
"libtiff",
(0, 0, 100, 40),
0,
("RGBa;16N", "tiff_lzw", False, 38236),
)
],
)
im.load() im.load()
assert_image_equal_tofile(im, "Tests/images/tiff_16bit_RGBa_target.png") assert_image_equal_tofile(im, "Tests/images/tiff_16bit_RGBa_target.png")
@ -730,12 +727,11 @@ class TestFileLibTiff(LibTiffTestCase):
# Read TIFF JPEG images from GIMP [@PIL168] # Read TIFF JPEG images from GIMP [@PIL168]
filename = "Tests/images/pil168.tif" filename = "Tests/images/pil168.tif"
with Image.open(filename) as im: with Image.open(filename) as im:
self.assertEqual(im.mode, "RGB") assert im.mode == "RGB"
self.assertEqual(im.size, (256, 256)) assert im.size == (256, 256)
self.assertEqual( assert im.tile == [
im.tile, ("libtiff", (0, 0, 256, 256), 0, ("RGB", "jpeg", False, 5122))
[("libtiff", (0, 0, 256, 256), 0, ("RGB", "jpeg", False, 5122))], ]
)
im.load() im.load()
assert_image_equal_tofile(im, "Tests/images/pil168.png") assert_image_equal_tofile(im, "Tests/images/pil168.png")
@ -743,15 +739,15 @@ class TestFileLibTiff(LibTiffTestCase):
def test_sampleformat(self): def test_sampleformat(self):
# https://github.com/python-pillow/Pillow/issues/1466 # https://github.com/python-pillow/Pillow/issues/1466
with Image.open("Tests/images/copyleft.tiff") as im: with Image.open("Tests/images/copyleft.tiff") as im:
self.assertEqual(im.mode, "RGB") assert im.mode == "RGB"
assert_image_equal_tofile(im, "Tests/images/copyleft.png", mode="RGB") assert_image_equal_tofile(im, "Tests/images/copyleft.png", mode="RGB")
def test_lzw(self): def test_lzw(self):
with Image.open("Tests/images/hopper_lzw.tif") as im: with Image.open("Tests/images/hopper_lzw.tif") as im:
self.assertEqual(im.mode, "RGB") assert im.mode == "RGB"
self.assertEqual(im.size, (128, 128)) assert im.size == (128, 128)
self.assertEqual(im.format, "TIFF") assert im.format == "TIFF"
im2 = hopper() im2 = hopper()
assert_image_similar(im, im2, 5) assert_image_similar(im, im2, 5)
@ -800,7 +796,7 @@ class TestFileLibTiff(LibTiffTestCase):
infile = "Tests/images/no_rows_per_strip.tif" infile = "Tests/images/no_rows_per_strip.tif"
with Image.open(infile) as im: with Image.open(infile) as im:
im.load() im.load()
self.assertEqual(im.size, (950, 975)) assert im.size == (950, 975)
def test_orientation(self): def test_orientation(self):
with Image.open("Tests/images/g4_orientation_1.tif") as base_im: with Image.open("Tests/images/g4_orientation_1.tif") as base_im:
@ -834,9 +830,9 @@ class TestFileLibTiff(LibTiffTestCase):
def test_realloc_overflow(self): def test_realloc_overflow(self):
TiffImagePlugin.READ_LIBTIFF = True TiffImagePlugin.READ_LIBTIFF = True
with Image.open("Tests/images/tiff_overflow_rows_per_strip.tif") as im: with Image.open("Tests/images/tiff_overflow_rows_per_strip.tif") as im:
with self.assertRaises(IOError) as e: with pytest.raises(IOError) as e:
im.load() im.load()
# Assert that the error code is IMAGING_CODEC_MEMORY # Assert that the error code is IMAGING_CODEC_MEMORY
self.assertEqual(str(e.exception), "-9") assert str(e.value) == "-9"
TiffImagePlugin.READ_LIBTIFF = False TiffImagePlugin.READ_LIBTIFF = False

View File

@ -21,7 +21,7 @@ class TestFileLibTiffSmall(LibTiffTestCase):
test_file = "Tests/images/hopper_g4.tif" test_file = "Tests/images/hopper_g4.tif"
with open(test_file, "rb") as f: with open(test_file, "rb") as f:
with Image.open(f) as im: with Image.open(f) as im:
self.assertEqual(im.size, (128, 128)) assert im.size == (128, 128)
self._assert_noerr(im) self._assert_noerr(im)
def test_g4_hopper_bytesio(self): def test_g4_hopper_bytesio(self):
@ -32,7 +32,7 @@ class TestFileLibTiffSmall(LibTiffTestCase):
s.write(f.read()) s.write(f.read())
s.seek(0) s.seek(0)
with Image.open(s) as im: with Image.open(s) as im:
self.assertEqual(im.size, (128, 128)) assert im.size == (128, 128)
self._assert_noerr(im) self._assert_noerr(im)
def test_g4_hopper(self): def test_g4_hopper(self):
@ -40,5 +40,5 @@ class TestFileLibTiffSmall(LibTiffTestCase):
test_file = "Tests/images/hopper_g4.tif" test_file = "Tests/images/hopper_g4.tif"
with Image.open(test_file) as im: with Image.open(test_file) as im:
self.assertEqual(im.size, (128, 128)) assert im.size == (128, 128)
self._assert_noerr(im) self._assert_noerr(im)

View File

@ -1,6 +1,7 @@
import os import os
import unittest import unittest
import pytest
from PIL import Image, MspImagePlugin from PIL import Image, MspImagePlugin
from .helper import PillowTestCase, assert_image_equal, hopper from .helper import PillowTestCase, assert_image_equal, hopper
@ -18,14 +19,15 @@ class TestFileMsp(PillowTestCase):
with Image.open(test_file) as im: with Image.open(test_file) as im:
im.load() im.load()
self.assertEqual(im.mode, "1") assert im.mode == "1"
self.assertEqual(im.size, (128, 128)) assert im.size == (128, 128)
self.assertEqual(im.format, "MSP") assert im.format == "MSP"
def test_invalid_file(self): def test_invalid_file(self):
invalid_file = "Tests/images/flower.jpg" invalid_file = "Tests/images/flower.jpg"
self.assertRaises(SyntaxError, MspImagePlugin.MspImageFile, invalid_file) with pytest.raises(SyntaxError):
MspImagePlugin.MspImageFile(invalid_file)
def test_bad_checksum(self): def test_bad_checksum(self):
# Arrange # Arrange
@ -33,7 +35,8 @@ class TestFileMsp(PillowTestCase):
bad_checksum = "Tests/images/hopper_bad_checksum.msp" bad_checksum = "Tests/images/hopper_bad_checksum.msp"
# Act / Assert # Act / Assert
self.assertRaises(SyntaxError, MspImagePlugin.MspImageFile, bad_checksum) with pytest.raises(SyntaxError):
MspImagePlugin.MspImageFile(bad_checksum)
def test_open_windows_v1(self): def test_open_windows_v1(self):
# Arrange # Arrange
@ -42,7 +45,7 @@ class TestFileMsp(PillowTestCase):
# Assert # Assert
assert_image_equal(im, hopper("1")) assert_image_equal(im, hopper("1"))
self.assertIsInstance(im, MspImagePlugin.MspImageFile) assert isinstance(im, MspImagePlugin.MspImageFile)
def _assert_file_image_equal(self, source_path, target_path): def _assert_file_image_equal(self, source_path, target_path):
with Image.open(source_path) as im: with Image.open(source_path) as im:
@ -76,4 +79,5 @@ class TestFileMsp(PillowTestCase):
filename = self.tempfile("temp.msp") filename = self.tempfile("temp.msp")
# Act/Assert # Act/Assert
self.assertRaises(IOError, im.save, filename) with pytest.raises(IOError):
im.save(filename)

View File

@ -1,5 +1,7 @@
import os.path import os.path
import pytest
from .helper import ( from .helper import (
PillowTestCase, PillowTestCase,
assert_image_equal, assert_image_equal,
@ -21,8 +23,8 @@ class TestFilePalm(PillowTestCase):
im.save(outfile) im.save(outfile)
# Assert # Assert
self.assertTrue(os.path.isfile(outfile)) assert os.path.isfile(outfile)
self.assertGreater(os.path.getsize(outfile), 0) assert os.path.getsize(outfile) > 0
def roundtrip(self, mode): def roundtrip(self, mode):
if not self._roundtrip: if not self._roundtrip:
@ -57,11 +59,13 @@ class TestFilePalm(PillowTestCase):
mode = "L" mode = "L"
# Act / Assert # Act / Assert
self.assertRaises(IOError, self.helper_save_as_palm, mode) with pytest.raises(IOError):
self.helper_save_as_palm(mode)
def test_rgb_ioerror(self): def test_rgb_ioerror(self):
# Arrange # Arrange
mode = "RGB" mode = "RGB"
# Act / Assert # Act / Assert
self.assertRaises(IOError, self.helper_save_as_palm, mode) with pytest.raises(IOError):
self.helper_save_as_palm(mode)

View File

@ -1,3 +1,4 @@
import pytest
from PIL import Image, ImageFile, PcxImagePlugin from PIL import Image, ImageFile, PcxImagePlugin
from .helper import PillowTestCase, assert_image_equal, hopper from .helper import PillowTestCase, assert_image_equal, hopper
@ -8,10 +9,10 @@ class TestFilePcx(PillowTestCase):
f = self.tempfile("temp.pcx") f = self.tempfile("temp.pcx")
im.save(f) im.save(f)
with Image.open(f) as im2: with Image.open(f) as im2:
self.assertEqual(im2.mode, im.mode) assert im2.mode == im.mode
self.assertEqual(im2.size, im.size) assert im2.size == im.size
self.assertEqual(im2.format, "PCX") assert im2.format == "PCX"
self.assertEqual(im2.get_format_mimetype(), "image/x-pcx") assert im2.get_format_mimetype() == "image/x-pcx"
assert_image_equal(im2, im) assert_image_equal(im2, im)
def test_sanity(self): def test_sanity(self):
@ -21,12 +22,14 @@ class TestFilePcx(PillowTestCase):
# Test an unsupported mode # Test an unsupported mode
f = self.tempfile("temp.pcx") f = self.tempfile("temp.pcx")
im = hopper("RGBA") im = hopper("RGBA")
self.assertRaises(ValueError, im.save, f) with pytest.raises(ValueError):
im.save(f)
def test_invalid_file(self): def test_invalid_file(self):
invalid_file = "Tests/images/flower.jpg" invalid_file = "Tests/images/flower.jpg"
self.assertRaises(SyntaxError, PcxImagePlugin.PcxImageFile, invalid_file) with pytest.raises(SyntaxError):
PcxImagePlugin.PcxImageFile(invalid_file)
def test_odd(self): def test_odd(self):
# see issue #523, odd sized images should have a stride that's even. # see issue #523, odd sized images should have a stride that's even.
@ -42,11 +45,11 @@ class TestFilePcx(PillowTestCase):
test_file = "Tests/images/pil184.pcx" test_file = "Tests/images/pil184.pcx"
with Image.open(test_file) as im: with Image.open(test_file) as im:
self.assertEqual(im.size, (447, 144)) assert im.size == (447, 144)
self.assertEqual(im.tile[0][1], (0, 0, 447, 144)) assert im.tile[0][1] == (0, 0, 447, 144)
# Make sure all pixels are either 0 or 255. # Make sure all pixels are either 0 or 255.
self.assertEqual(im.histogram()[0] + im.histogram()[255], 447 * 144) assert im.histogram()[0] + im.histogram()[255] == 447 * 144
def test_1px_width(self): def test_1px_width(self):
im = Image.new("L", (1, 256)) im = Image.new("L", (1, 256))

View File

@ -4,6 +4,7 @@ import os.path
import tempfile import tempfile
import time import time
import pytest
from PIL import Image, PdfParser from PIL import Image, PdfParser
from .helper import PillowTestCase, hopper from .helper import PillowTestCase, hopper
@ -19,20 +20,20 @@ class TestFilePdf(PillowTestCase):
im.save(outfile, **kwargs) im.save(outfile, **kwargs)
# Assert # Assert
self.assertTrue(os.path.isfile(outfile)) assert os.path.isfile(outfile)
self.assertGreater(os.path.getsize(outfile), 0) assert os.path.getsize(outfile) > 0
with PdfParser.PdfParser(outfile) as pdf: with PdfParser.PdfParser(outfile) as pdf:
if kwargs.get("append_images", False) or kwargs.get("append", False): if kwargs.get("append_images", False) or kwargs.get("append", False):
self.assertGreater(len(pdf.pages), 1) assert len(pdf.pages) > 1
else: else:
self.assertGreater(len(pdf.pages), 0) assert len(pdf.pages) > 0
with open(outfile, "rb") as fp: with open(outfile, "rb") as fp:
contents = fp.read() contents = fp.read()
size = tuple( size = tuple(
int(d) int(d)
for d in contents.split(b"/MediaBox [ 0 0 ")[1].split(b"]")[0].split() for d in contents.split(b"/MediaBox [ 0 0 ")[1].split(b"]")[0].split()
) )
self.assertEqual(im.size, size) assert im.size == size
return outfile return outfile
@ -75,7 +76,8 @@ class TestFilePdf(PillowTestCase):
im = hopper("LA") im = hopper("LA")
outfile = self.tempfile("temp_LA.pdf") outfile = self.tempfile("temp_LA.pdf")
self.assertRaises(ValueError, im.save, outfile) with pytest.raises(ValueError):
im.save(outfile)
def test_save_all(self): def test_save_all(self):
# Single frame image # Single frame image
@ -87,15 +89,15 @@ class TestFilePdf(PillowTestCase):
outfile = self.tempfile("temp.pdf") outfile = self.tempfile("temp.pdf")
im.save(outfile, save_all=True) im.save(outfile, save_all=True)
self.assertTrue(os.path.isfile(outfile)) assert os.path.isfile(outfile)
self.assertGreater(os.path.getsize(outfile), 0) assert os.path.getsize(outfile) > 0
# Append images # Append images
ims = [hopper()] ims = [hopper()]
im.copy().save(outfile, save_all=True, append_images=ims) im.copy().save(outfile, save_all=True, append_images=ims)
self.assertTrue(os.path.isfile(outfile)) assert os.path.isfile(outfile)
self.assertGreater(os.path.getsize(outfile), 0) assert os.path.getsize(outfile) > 0
# Test appending using a generator # Test appending using a generator
def imGenerator(ims): def imGenerator(ims):
@ -103,15 +105,15 @@ class TestFilePdf(PillowTestCase):
im.save(outfile, save_all=True, append_images=imGenerator(ims)) im.save(outfile, save_all=True, append_images=imGenerator(ims))
self.assertTrue(os.path.isfile(outfile)) assert os.path.isfile(outfile)
self.assertGreater(os.path.getsize(outfile), 0) assert os.path.getsize(outfile) > 0
# Append JPEG images # Append JPEG images
with Image.open("Tests/images/flower.jpg") as jpeg: with Image.open("Tests/images/flower.jpg") as jpeg:
jpeg.save(outfile, save_all=True, append_images=[jpeg.copy()]) jpeg.save(outfile, save_all=True, append_images=[jpeg.copy()])
self.assertTrue(os.path.isfile(outfile)) assert os.path.isfile(outfile)
self.assertGreater(os.path.getsize(outfile), 0) assert os.path.getsize(outfile) > 0
def test_multiframe_normal_save(self): def test_multiframe_normal_save(self):
# Test saving a multiframe image without save_all # Test saving a multiframe image without save_all
@ -120,69 +122,67 @@ class TestFilePdf(PillowTestCase):
outfile = self.tempfile("temp.pdf") outfile = self.tempfile("temp.pdf")
im.save(outfile) im.save(outfile)
self.assertTrue(os.path.isfile(outfile)) assert os.path.isfile(outfile)
self.assertGreater(os.path.getsize(outfile), 0) assert os.path.getsize(outfile) > 0
def test_pdf_open(self): def test_pdf_open(self):
# fail on a buffer full of null bytes # fail on a buffer full of null bytes
self.assertRaises( with pytest.raises(PdfParser.PdfFormatError):
PdfParser.PdfFormatError, PdfParser.PdfParser, buf=bytearray(65536) PdfParser.PdfParser(buf=bytearray(65536))
)
# make an empty PDF object # make an empty PDF object
with PdfParser.PdfParser() as empty_pdf: with PdfParser.PdfParser() as empty_pdf:
self.assertEqual(len(empty_pdf.pages), 0) assert len(empty_pdf.pages) == 0
self.assertEqual(len(empty_pdf.info), 0) assert len(empty_pdf.info) == 0
self.assertFalse(empty_pdf.should_close_buf) assert not empty_pdf.should_close_buf
self.assertFalse(empty_pdf.should_close_file) assert not empty_pdf.should_close_file
# make a PDF file # make a PDF file
pdf_filename = self.helper_save_as_pdf("RGB") pdf_filename = self.helper_save_as_pdf("RGB")
# open the PDF file # open the PDF file
with PdfParser.PdfParser(filename=pdf_filename) as hopper_pdf: with PdfParser.PdfParser(filename=pdf_filename) as hopper_pdf:
self.assertEqual(len(hopper_pdf.pages), 1) assert len(hopper_pdf.pages) == 1
self.assertTrue(hopper_pdf.should_close_buf) assert hopper_pdf.should_close_buf
self.assertTrue(hopper_pdf.should_close_file) assert hopper_pdf.should_close_file
# read a PDF file from a buffer with a non-zero offset # read a PDF file from a buffer with a non-zero offset
with open(pdf_filename, "rb") as f: with open(pdf_filename, "rb") as f:
content = b"xyzzy" + f.read() content = b"xyzzy" + f.read()
with PdfParser.PdfParser(buf=content, start_offset=5) as hopper_pdf: with PdfParser.PdfParser(buf=content, start_offset=5) as hopper_pdf:
self.assertEqual(len(hopper_pdf.pages), 1) assert len(hopper_pdf.pages) == 1
self.assertFalse(hopper_pdf.should_close_buf) assert not hopper_pdf.should_close_buf
self.assertFalse(hopper_pdf.should_close_file) assert not hopper_pdf.should_close_file
# read a PDF file from an already open file # read a PDF file from an already open file
with open(pdf_filename, "rb") as f: with open(pdf_filename, "rb") as f:
with PdfParser.PdfParser(f=f) as hopper_pdf: with PdfParser.PdfParser(f=f) as hopper_pdf:
self.assertEqual(len(hopper_pdf.pages), 1) assert len(hopper_pdf.pages) == 1
self.assertTrue(hopper_pdf.should_close_buf) assert hopper_pdf.should_close_buf
self.assertFalse(hopper_pdf.should_close_file) assert not hopper_pdf.should_close_file
def test_pdf_append_fails_on_nonexistent_file(self): def test_pdf_append_fails_on_nonexistent_file(self):
im = hopper("RGB") im = hopper("RGB")
with tempfile.TemporaryDirectory() as temp_dir: with tempfile.TemporaryDirectory() as temp_dir:
self.assertRaises( with pytest.raises(IOError):
IOError, im.save, os.path.join(temp_dir, "nonexistent.pdf"), append=True im.save(os.path.join(temp_dir, "nonexistent.pdf"), append=True)
)
def check_pdf_pages_consistency(self, pdf): def check_pdf_pages_consistency(self, pdf):
pages_info = pdf.read_indirect(pdf.pages_ref) pages_info = pdf.read_indirect(pdf.pages_ref)
self.assertNotIn(b"Parent", pages_info) assert b"Parent" not in pages_info
self.assertIn(b"Kids", pages_info) assert b"Kids" in pages_info
kids_not_used = pages_info[b"Kids"] kids_not_used = pages_info[b"Kids"]
for page_ref in pdf.pages: for page_ref in pdf.pages:
while True: while True:
if page_ref in kids_not_used: if page_ref in kids_not_used:
kids_not_used.remove(page_ref) kids_not_used.remove(page_ref)
page_info = pdf.read_indirect(page_ref) page_info = pdf.read_indirect(page_ref)
self.assertIn(b"Parent", page_info) assert b"Parent" in page_info
page_ref = page_info[b"Parent"] page_ref = page_info[b"Parent"]
if page_ref == pdf.pages_ref: if page_ref == pdf.pages_ref:
break break
self.assertEqual(pdf.pages_ref, page_info[b"Parent"]) assert pdf.pages_ref == page_info[b"Parent"]
self.assertEqual(kids_not_used, []) assert kids_not_used == []
def test_pdf_append(self): def test_pdf_append(self):
# make a PDF file # make a PDF file
@ -190,14 +190,12 @@ class TestFilePdf(PillowTestCase):
# open it, check pages and info # open it, check pages and info
with PdfParser.PdfParser(pdf_filename, mode="r+b") as pdf: with PdfParser.PdfParser(pdf_filename, mode="r+b") as pdf:
self.assertEqual(len(pdf.pages), 1) assert len(pdf.pages) == 1
self.assertEqual(len(pdf.info), 4) assert len(pdf.info) == 4
self.assertEqual( assert pdf.info.Title == os.path.splitext(os.path.basename(pdf_filename))[0]
pdf.info.Title, os.path.splitext(os.path.basename(pdf_filename))[0] assert pdf.info.Producer == "PdfParser"
) assert b"CreationDate" in pdf.info
self.assertEqual(pdf.info.Producer, "PdfParser") assert b"ModDate" in pdf.info
self.assertIn(b"CreationDate", pdf.info)
self.assertIn(b"ModDate", pdf.info)
self.check_pdf_pages_consistency(pdf) self.check_pdf_pages_consistency(pdf)
# append some info # append some info
@ -211,11 +209,11 @@ class TestFilePdf(PillowTestCase):
# open it again, check pages and info again # open it again, check pages and info again
with PdfParser.PdfParser(pdf_filename) as pdf: with PdfParser.PdfParser(pdf_filename) as pdf:
self.assertEqual(len(pdf.pages), 1) assert len(pdf.pages) == 1
self.assertEqual(len(pdf.info), 8) assert len(pdf.info) == 8
self.assertEqual(pdf.info.Title, "abc") assert pdf.info.Title == "abc"
self.assertIn(b"CreationDate", pdf.info) assert b"CreationDate" in pdf.info
self.assertIn(b"ModDate", pdf.info) assert b"ModDate" in pdf.info
self.check_pdf_pages_consistency(pdf) self.check_pdf_pages_consistency(pdf)
# append two images # append two images
@ -225,15 +223,15 @@ class TestFilePdf(PillowTestCase):
# open the PDF again, check pages and info again # open the PDF again, check pages and info again
with PdfParser.PdfParser(pdf_filename) as pdf: with PdfParser.PdfParser(pdf_filename) as pdf:
self.assertEqual(len(pdf.pages), 3) assert len(pdf.pages) == 3
self.assertEqual(len(pdf.info), 8) assert len(pdf.info) == 8
self.assertEqual(PdfParser.decode_text(pdf.info[b"Title"]), "abc") assert PdfParser.decode_text(pdf.info[b"Title"]) == "abc"
self.assertEqual(pdf.info.Title, "abc") assert pdf.info.Title == "abc"
self.assertEqual(pdf.info.Producer, "PdfParser") assert pdf.info.Producer == "PdfParser"
self.assertEqual(pdf.info.Keywords, "qw)e\\r(ty") assert pdf.info.Keywords == "qw)e\\r(ty"
self.assertEqual(pdf.info.Subject, "ghi\uABCD") assert pdf.info.Subject == "ghi\uABCD"
self.assertIn(b"CreationDate", pdf.info) assert b"CreationDate" in pdf.info
self.assertIn(b"ModDate", pdf.info) assert b"ModDate" in pdf.info
self.check_pdf_pages_consistency(pdf) self.check_pdf_pages_consistency(pdf)
def test_pdf_info(self): def test_pdf_info(self):
@ -252,15 +250,15 @@ class TestFilePdf(PillowTestCase):
# open it, check pages and info # open it, check pages and info
with PdfParser.PdfParser(pdf_filename) as pdf: with PdfParser.PdfParser(pdf_filename) as pdf:
self.assertEqual(len(pdf.info), 8) assert len(pdf.info) == 8
self.assertEqual(pdf.info.Title, "title") assert pdf.info.Title == "title"
self.assertEqual(pdf.info.Author, "author") assert pdf.info.Author == "author"
self.assertEqual(pdf.info.Subject, "subject") assert pdf.info.Subject == "subject"
self.assertEqual(pdf.info.Keywords, "keywords") assert pdf.info.Keywords == "keywords"
self.assertEqual(pdf.info.Creator, "creator") assert pdf.info.Creator == "creator"
self.assertEqual(pdf.info.Producer, "producer") assert pdf.info.Producer == "producer"
self.assertEqual(pdf.info.CreationDate, time.strptime("2000", "%Y")) assert pdf.info.CreationDate == time.strptime("2000", "%Y")
self.assertEqual(pdf.info.ModDate, time.strptime("2001", "%Y")) assert pdf.info.ModDate == time.strptime("2001", "%Y")
self.check_pdf_pages_consistency(pdf) self.check_pdf_pages_consistency(pdf)
def test_pdf_append_to_bytesio(self): def test_pdf_append_to_bytesio(self):
@ -268,8 +266,8 @@ class TestFilePdf(PillowTestCase):
f = io.BytesIO() f = io.BytesIO()
im.save(f, format="PDF") im.save(f, format="PDF")
initial_size = len(f.getvalue()) initial_size = len(f.getvalue())
self.assertGreater(initial_size, 0) assert initial_size > 0
im = hopper("P") im = hopper("P")
f = io.BytesIO(f.getvalue()) f = io.BytesIO(f.getvalue())
im.save(f, format="PDF", append=True) im.save(f, format="PDF", append=True)
self.assertGreater(len(f.getvalue()), initial_size) assert len(f.getvalue()) > initial_size

View File

@ -83,10 +83,10 @@ class TestFilePng(PillowTestCase):
with Image.open(test_file) as im: with Image.open(test_file) as im:
im.load() im.load()
self.assertEqual(im.mode, "RGB") assert im.mode == "RGB"
self.assertEqual(im.size, (128, 128)) assert im.size == (128, 128)
self.assertEqual(im.format, "PNG") assert im.format == "PNG"
self.assertEqual(im.get_format_mimetype(), "image/png") assert im.get_format_mimetype() == "image/png"
for mode in ["1", "L", "P", "RGB", "I", "I;16"]: for mode in ["1", "L", "P", "RGB", "I", "I;16"]:
im = hopper(mode) im = hopper(mode)
@ -99,112 +99,114 @@ class TestFilePng(PillowTestCase):
def test_invalid_file(self): def test_invalid_file(self):
invalid_file = "Tests/images/flower.jpg" invalid_file = "Tests/images/flower.jpg"
self.assertRaises(SyntaxError, PngImagePlugin.PngImageFile, invalid_file) with pytest.raises(SyntaxError):
PngImagePlugin.PngImageFile(invalid_file)
def test_broken(self): def test_broken(self):
# Check reading of totally broken files. In this case, the test # Check reading of totally broken files. In this case, the test
# file was checked into Subversion as a text file. # file was checked into Subversion as a text file.
test_file = "Tests/images/broken.png" test_file = "Tests/images/broken.png"
self.assertRaises(IOError, Image.open, test_file) with pytest.raises(IOError):
Image.open(test_file)
def test_bad_text(self): def test_bad_text(self):
# Make sure PIL can read malformed tEXt chunks (@PIL152) # Make sure PIL can read malformed tEXt chunks (@PIL152)
im = load(HEAD + chunk(b"tEXt") + TAIL) im = load(HEAD + chunk(b"tEXt") + TAIL)
self.assertEqual(im.info, {}) assert im.info == {}
im = load(HEAD + chunk(b"tEXt", b"spam") + TAIL) im = load(HEAD + chunk(b"tEXt", b"spam") + TAIL)
self.assertEqual(im.info, {"spam": ""}) assert im.info == {"spam": ""}
im = load(HEAD + chunk(b"tEXt", b"spam\0") + TAIL) im = load(HEAD + chunk(b"tEXt", b"spam\0") + TAIL)
self.assertEqual(im.info, {"spam": ""}) assert im.info == {"spam": ""}
im = load(HEAD + chunk(b"tEXt", b"spam\0egg") + TAIL) im = load(HEAD + chunk(b"tEXt", b"spam\0egg") + TAIL)
self.assertEqual(im.info, {"spam": "egg"}) assert im.info == {"spam": "egg"}
im = load(HEAD + chunk(b"tEXt", b"spam\0egg\0") + TAIL) im = load(HEAD + chunk(b"tEXt", b"spam\0egg\0") + TAIL)
self.assertEqual(im.info, {"spam": "egg\x00"}) assert im.info == {"spam": "egg\x00"}
def test_bad_ztxt(self): def test_bad_ztxt(self):
# Test reading malformed zTXt chunks (python-pillow/Pillow#318) # Test reading malformed zTXt chunks (python-pillow/Pillow#318)
im = load(HEAD + chunk(b"zTXt") + TAIL) im = load(HEAD + chunk(b"zTXt") + TAIL)
self.assertEqual(im.info, {}) assert im.info == {}
im = load(HEAD + chunk(b"zTXt", b"spam") + TAIL) im = load(HEAD + chunk(b"zTXt", b"spam") + TAIL)
self.assertEqual(im.info, {"spam": ""}) assert im.info == {"spam": ""}
im = load(HEAD + chunk(b"zTXt", b"spam\0") + TAIL) im = load(HEAD + chunk(b"zTXt", b"spam\0") + TAIL)
self.assertEqual(im.info, {"spam": ""}) assert im.info == {"spam": ""}
im = load(HEAD + chunk(b"zTXt", b"spam\0\0") + TAIL) im = load(HEAD + chunk(b"zTXt", b"spam\0\0") + TAIL)
self.assertEqual(im.info, {"spam": ""}) assert im.info == {"spam": ""}
im = load(HEAD + chunk(b"zTXt", b"spam\0\0" + zlib.compress(b"egg")[:1]) + TAIL) im = load(HEAD + chunk(b"zTXt", b"spam\0\0" + zlib.compress(b"egg")[:1]) + TAIL)
self.assertEqual(im.info, {"spam": ""}) assert im.info == {"spam": ""}
im = load(HEAD + chunk(b"zTXt", b"spam\0\0" + zlib.compress(b"egg")) + TAIL) im = load(HEAD + chunk(b"zTXt", b"spam\0\0" + zlib.compress(b"egg")) + TAIL)
self.assertEqual(im.info, {"spam": "egg"}) assert im.info == {"spam": "egg"}
def test_bad_itxt(self): def test_bad_itxt(self):
im = load(HEAD + chunk(b"iTXt") + TAIL) im = load(HEAD + chunk(b"iTXt") + TAIL)
self.assertEqual(im.info, {}) assert im.info == {}
im = load(HEAD + chunk(b"iTXt", b"spam") + TAIL) im = load(HEAD + chunk(b"iTXt", b"spam") + TAIL)
self.assertEqual(im.info, {}) assert im.info == {}
im = load(HEAD + chunk(b"iTXt", b"spam\0") + TAIL) im = load(HEAD + chunk(b"iTXt", b"spam\0") + TAIL)
self.assertEqual(im.info, {}) assert im.info == {}
im = load(HEAD + chunk(b"iTXt", b"spam\0\x02") + TAIL) im = load(HEAD + chunk(b"iTXt", b"spam\0\x02") + TAIL)
self.assertEqual(im.info, {}) assert im.info == {}
im = load(HEAD + chunk(b"iTXt", b"spam\0\0\0foo\0") + TAIL) im = load(HEAD + chunk(b"iTXt", b"spam\0\0\0foo\0") + TAIL)
self.assertEqual(im.info, {}) assert im.info == {}
im = load(HEAD + chunk(b"iTXt", b"spam\0\0\0en\0Spam\0egg") + TAIL) im = load(HEAD + chunk(b"iTXt", b"spam\0\0\0en\0Spam\0egg") + TAIL)
self.assertEqual(im.info, {"spam": "egg"}) assert im.info == {"spam": "egg"}
self.assertEqual(im.info["spam"].lang, "en") assert im.info["spam"].lang == "en"
self.assertEqual(im.info["spam"].tkey, "Spam") assert im.info["spam"].tkey == "Spam"
im = load( im = load(
HEAD HEAD
+ chunk(b"iTXt", b"spam\0\1\0en\0Spam\0" + zlib.compress(b"egg")[:1]) + chunk(b"iTXt", b"spam\0\1\0en\0Spam\0" + zlib.compress(b"egg")[:1])
+ TAIL + TAIL
) )
self.assertEqual(im.info, {"spam": ""}) assert im.info == {"spam": ""}
im = load( im = load(
HEAD HEAD
+ chunk(b"iTXt", b"spam\0\1\1en\0Spam\0" + zlib.compress(b"egg")) + chunk(b"iTXt", b"spam\0\1\1en\0Spam\0" + zlib.compress(b"egg"))
+ TAIL + TAIL
) )
self.assertEqual(im.info, {}) assert im.info == {}
im = load( im = load(
HEAD HEAD
+ chunk(b"iTXt", b"spam\0\1\0en\0Spam\0" + zlib.compress(b"egg")) + chunk(b"iTXt", b"spam\0\1\0en\0Spam\0" + zlib.compress(b"egg"))
+ TAIL + TAIL
) )
self.assertEqual(im.info, {"spam": "egg"}) assert im.info == {"spam": "egg"}
self.assertEqual(im.info["spam"].lang, "en") assert im.info["spam"].lang == "en"
self.assertEqual(im.info["spam"].tkey, "Spam") assert im.info["spam"].tkey == "Spam"
def test_interlace(self): def test_interlace(self):
test_file = "Tests/images/pil123p.png" test_file = "Tests/images/pil123p.png"
with Image.open(test_file) as im: with Image.open(test_file) as im:
assert_image(im, "P", (162, 150)) assert_image(im, "P", (162, 150))
self.assertTrue(im.info.get("interlace")) assert im.info.get("interlace")
im.load() im.load()
test_file = "Tests/images/pil123rgba.png" test_file = "Tests/images/pil123rgba.png"
with Image.open(test_file) as im: with Image.open(test_file) as im:
assert_image(im, "RGBA", (162, 150)) assert_image(im, "RGBA", (162, 150))
self.assertTrue(im.info.get("interlace")) assert im.info.get("interlace")
im.load() im.load()
@ -216,69 +218,69 @@ class TestFilePng(PillowTestCase):
assert_image(im, "RGBA", (162, 150)) assert_image(im, "RGBA", (162, 150))
# image has 124 unique alpha values # image has 124 unique alpha values
self.assertEqual(len(im.getchannel("A").getcolors()), 124) assert len(im.getchannel("A").getcolors()) == 124
def test_load_transparent_rgb(self): def test_load_transparent_rgb(self):
test_file = "Tests/images/rgb_trns.png" test_file = "Tests/images/rgb_trns.png"
with Image.open(test_file) as im: with Image.open(test_file) as im:
self.assertEqual(im.info["transparency"], (0, 255, 52)) assert im.info["transparency"] == (0, 255, 52)
assert_image(im, "RGB", (64, 64)) assert_image(im, "RGB", (64, 64))
im = im.convert("RGBA") im = im.convert("RGBA")
assert_image(im, "RGBA", (64, 64)) assert_image(im, "RGBA", (64, 64))
# image has 876 transparent pixels # image has 876 transparent pixels
self.assertEqual(im.getchannel("A").getcolors()[0][0], 876) assert im.getchannel("A").getcolors()[0][0] == 876
def test_save_p_transparent_palette(self): def test_save_p_transparent_palette(self):
in_file = "Tests/images/pil123p.png" in_file = "Tests/images/pil123p.png"
with Image.open(in_file) as im: with Image.open(in_file) as im:
# 'transparency' contains a byte string with the opacity for # 'transparency' contains a byte string with the opacity for
# each palette entry # each palette entry
self.assertEqual(len(im.info["transparency"]), 256) assert len(im.info["transparency"]) == 256
test_file = self.tempfile("temp.png") test_file = self.tempfile("temp.png")
im.save(test_file) im.save(test_file)
# check if saved image contains same transparency # check if saved image contains same transparency
with Image.open(test_file) as im: with Image.open(test_file) as im:
self.assertEqual(len(im.info["transparency"]), 256) assert len(im.info["transparency"]) == 256
assert_image(im, "P", (162, 150)) assert_image(im, "P", (162, 150))
im = im.convert("RGBA") im = im.convert("RGBA")
assert_image(im, "RGBA", (162, 150)) assert_image(im, "RGBA", (162, 150))
# image has 124 unique alpha values # image has 124 unique alpha values
self.assertEqual(len(im.getchannel("A").getcolors()), 124) assert len(im.getchannel("A").getcolors()) == 124
def test_save_p_single_transparency(self): def test_save_p_single_transparency(self):
in_file = "Tests/images/p_trns_single.png" in_file = "Tests/images/p_trns_single.png"
with Image.open(in_file) as im: with Image.open(in_file) as im:
# pixel value 164 is full transparent # pixel value 164 is full transparent
self.assertEqual(im.info["transparency"], 164) assert im.info["transparency"] == 164
self.assertEqual(im.getpixel((31, 31)), 164) assert im.getpixel((31, 31)) == 164
test_file = self.tempfile("temp.png") test_file = self.tempfile("temp.png")
im.save(test_file) im.save(test_file)
# check if saved image contains same transparency # check if saved image contains same transparency
with Image.open(test_file) as im: with Image.open(test_file) as im:
self.assertEqual(im.info["transparency"], 164) assert im.info["transparency"] == 164
self.assertEqual(im.getpixel((31, 31)), 164) assert im.getpixel((31, 31)) == 164
assert_image(im, "P", (64, 64)) assert_image(im, "P", (64, 64))
im = im.convert("RGBA") im = im.convert("RGBA")
assert_image(im, "RGBA", (64, 64)) assert_image(im, "RGBA", (64, 64))
self.assertEqual(im.getpixel((31, 31)), (0, 255, 52, 0)) assert im.getpixel((31, 31)) == (0, 255, 52, 0)
# image has 876 transparent pixels # image has 876 transparent pixels
self.assertEqual(im.getchannel("A").getcolors()[0][0], 876) assert im.getchannel("A").getcolors()[0][0] == 876
def test_save_p_transparent_black(self): def test_save_p_transparent_black(self):
# check if solid black image with full transparency # check if solid black image with full transparency
# is supported (check for #1838) # is supported (check for #1838)
im = Image.new("RGBA", (10, 10), (0, 0, 0, 0)) im = Image.new("RGBA", (10, 10), (0, 0, 0, 0))
self.assertEqual(im.getcolors(), [(100, (0, 0, 0, 0))]) assert im.getcolors() == [(100, (0, 0, 0, 0))]
im = im.convert("P") im = im.convert("P")
test_file = self.tempfile("temp.png") test_file = self.tempfile("temp.png")
@ -286,34 +288,32 @@ class TestFilePng(PillowTestCase):
# check if saved image contains same transparency # check if saved image contains same transparency
with Image.open(test_file) as im: with Image.open(test_file) as im:
self.assertEqual(len(im.info["transparency"]), 256) assert len(im.info["transparency"]) == 256
assert_image(im, "P", (10, 10)) assert_image(im, "P", (10, 10))
im = im.convert("RGBA") im = im.convert("RGBA")
assert_image(im, "RGBA", (10, 10)) assert_image(im, "RGBA", (10, 10))
self.assertEqual(im.getcolors(), [(100, (0, 0, 0, 0))]) assert im.getcolors() == [(100, (0, 0, 0, 0))]
def test_save_greyscale_transparency(self): def test_save_greyscale_transparency(self):
for mode, num_transparent in {"1": 1994, "L": 559, "I": 559}.items(): for mode, num_transparent in {"1": 1994, "L": 559, "I": 559}.items():
in_file = "Tests/images/" + mode.lower() + "_trns.png" in_file = "Tests/images/" + mode.lower() + "_trns.png"
with Image.open(in_file) as im: with Image.open(in_file) as im:
self.assertEqual(im.mode, mode) assert im.mode == mode
self.assertEqual(im.info["transparency"], 255) assert im.info["transparency"] == 255
im_rgba = im.convert("RGBA") im_rgba = im.convert("RGBA")
self.assertEqual(im_rgba.getchannel("A").getcolors()[0][0], num_transparent) assert im_rgba.getchannel("A").getcolors()[0][0] == num_transparent
test_file = self.tempfile("temp.png") test_file = self.tempfile("temp.png")
im.save(test_file) im.save(test_file)
with Image.open(test_file) as test_im: with Image.open(test_file) as test_im:
self.assertEqual(test_im.mode, mode) assert test_im.mode == mode
self.assertEqual(test_im.info["transparency"], 255) assert test_im.info["transparency"] == 255
assert_image_equal(im, test_im) assert_image_equal(im, test_im)
test_im_rgba = test_im.convert("RGBA") test_im_rgba = test_im.convert("RGBA")
self.assertEqual( assert test_im_rgba.getchannel("A").getcolors()[0][0] == num_transparent
test_im_rgba.getchannel("A").getcolors()[0][0], num_transparent
)
def test_save_rgb_single_transparency(self): def test_save_rgb_single_transparency(self):
in_file = "Tests/images/caption_6_33_22.png" in_file = "Tests/images/caption_6_33_22.png"
@ -330,7 +330,8 @@ class TestFilePng(PillowTestCase):
with Image.open(TEST_PNG_FILE) as im: with Image.open(TEST_PNG_FILE) as im:
im.load() im.load()
self.assertRaises(RuntimeError, im.verify) with pytest.raises(RuntimeError):
im.verify()
def test_verify_struct_error(self): def test_verify_struct_error(self):
# Check open/load/verify exception (#1755) # Check open/load/verify exception (#1755)
@ -344,8 +345,9 @@ class TestFilePng(PillowTestCase):
test_file = f.read()[:offset] test_file = f.read()[:offset]
with Image.open(BytesIO(test_file)) as im: with Image.open(BytesIO(test_file)) as im:
self.assertIsNotNone(im.fp) assert im.fp is not None
self.assertRaises((IOError, SyntaxError), im.verify) with pytest.raises((IOError, SyntaxError)):
im.verify()
def test_verify_ignores_crc_error(self): def test_verify_ignores_crc_error(self):
# check ignores crc errors in ancillary chunks # check ignores crc errors in ancillary chunks
@ -354,12 +356,13 @@ class TestFilePng(PillowTestCase):
broken_crc_chunk_data = chunk_data[:-1] + b"q" # break CRC broken_crc_chunk_data = chunk_data[:-1] + b"q" # break CRC
image_data = HEAD + broken_crc_chunk_data + TAIL image_data = HEAD + broken_crc_chunk_data + TAIL
self.assertRaises(SyntaxError, PngImagePlugin.PngImageFile, BytesIO(image_data)) with pytest.raises(SyntaxError):
PngImagePlugin.PngImageFile(BytesIO(image_data))
ImageFile.LOAD_TRUNCATED_IMAGES = True ImageFile.LOAD_TRUNCATED_IMAGES = True
try: try:
im = load(image_data) im = load(image_data)
self.assertIsNotNone(im) assert im is not None
finally: finally:
ImageFile.LOAD_TRUNCATED_IMAGES = False ImageFile.LOAD_TRUNCATED_IMAGES = False
@ -370,9 +373,8 @@ class TestFilePng(PillowTestCase):
ImageFile.LOAD_TRUNCATED_IMAGES = True ImageFile.LOAD_TRUNCATED_IMAGES = True
try: try:
self.assertRaises( with pytest.raises(SyntaxError):
SyntaxError, PngImagePlugin.PngImageFile, BytesIO(image_data) PngImagePlugin.PngImageFile(BytesIO(image_data))
)
finally: finally:
ImageFile.LOAD_TRUNCATED_IMAGES = False ImageFile.LOAD_TRUNCATED_IMAGES = False
@ -381,24 +383,24 @@ class TestFilePng(PillowTestCase):
with Image.open(TEST_PNG_FILE) as im: with Image.open(TEST_PNG_FILE) as im:
im = roundtrip(im, dpi=(100, 100)) im = roundtrip(im, dpi=(100, 100))
self.assertEqual(im.info["dpi"], (100, 100)) assert im.info["dpi"] == (100, 100)
def test_load_dpi_rounding(self): def test_load_dpi_rounding(self):
# Round up # Round up
with Image.open(TEST_PNG_FILE) as im: with Image.open(TEST_PNG_FILE) as im:
self.assertEqual(im.info["dpi"], (96, 96)) assert im.info["dpi"] == (96, 96)
# Round down # Round down
with Image.open("Tests/images/icc_profile_none.png") as im: with Image.open("Tests/images/icc_profile_none.png") as im:
self.assertEqual(im.info["dpi"], (72, 72)) assert im.info["dpi"] == (72, 72)
def test_save_dpi_rounding(self): def test_save_dpi_rounding(self):
with Image.open(TEST_PNG_FILE) as im: with Image.open(TEST_PNG_FILE) as im:
im = roundtrip(im, dpi=(72.2, 72.2)) im = roundtrip(im, dpi=(72.2, 72.2))
self.assertEqual(im.info["dpi"], (72, 72)) assert im.info["dpi"] == (72, 72)
im = roundtrip(im, dpi=(72.8, 72.8)) im = roundtrip(im, dpi=(72.8, 72.8))
self.assertEqual(im.info["dpi"], (73, 73)) assert im.info["dpi"] == (73, 73)
def test_roundtrip_text(self): def test_roundtrip_text(self):
# Check text roundtripping # Check text roundtripping
@ -409,8 +411,8 @@ class TestFilePng(PillowTestCase):
info.add_text("ZIP", "VALUE", zip=True) info.add_text("ZIP", "VALUE", zip=True)
im = roundtrip(im, pnginfo=info) im = roundtrip(im, pnginfo=info)
self.assertEqual(im.info, {"TXT": "VALUE", "ZIP": "VALUE"}) assert im.info == {"TXT": "VALUE", "ZIP": "VALUE"}
self.assertEqual(im.text, {"TXT": "VALUE", "ZIP": "VALUE"}) assert im.text == {"TXT": "VALUE", "ZIP": "VALUE"}
def test_roundtrip_itxt(self): def test_roundtrip_itxt(self):
# Check iTXt roundtripping # Check iTXt roundtripping
@ -421,12 +423,12 @@ class TestFilePng(PillowTestCase):
info.add_text("eggs", PngImagePlugin.iTXt("Spam", "en", "Eggs"), zip=True) info.add_text("eggs", PngImagePlugin.iTXt("Spam", "en", "Eggs"), zip=True)
im = roundtrip(im, pnginfo=info) im = roundtrip(im, pnginfo=info)
self.assertEqual(im.info, {"spam": "Eggs", "eggs": "Spam"}) assert im.info == {"spam": "Eggs", "eggs": "Spam"}
self.assertEqual(im.text, {"spam": "Eggs", "eggs": "Spam"}) assert im.text == {"spam": "Eggs", "eggs": "Spam"}
self.assertEqual(im.text["spam"].lang, "en") assert im.text["spam"].lang == "en"
self.assertEqual(im.text["spam"].tkey, "Spam") assert im.text["spam"].tkey == "Spam"
self.assertEqual(im.text["eggs"].lang, "en") assert im.text["eggs"].lang == "en"
self.assertEqual(im.text["eggs"].tkey, "Eggs") assert im.text["eggs"].tkey == "Eggs"
def test_nonunicode_text(self): def test_nonunicode_text(self):
# Check so that non-Unicode text is saved as a tEXt rather than iTXt # Check so that non-Unicode text is saved as a tEXt rather than iTXt
@ -435,7 +437,7 @@ class TestFilePng(PillowTestCase):
info = PngImagePlugin.PngInfo() info = PngImagePlugin.PngInfo()
info.add_text("Text", "Ascii") info.add_text("Text", "Ascii")
im = roundtrip(im, pnginfo=info) im = roundtrip(im, pnginfo=info)
self.assertIsInstance(im.info["Text"], str) assert isinstance(im.info["Text"], str)
def test_unicode_text(self): def test_unicode_text(self):
# Check preservation of non-ASCII characters # Check preservation of non-ASCII characters
@ -445,7 +447,7 @@ class TestFilePng(PillowTestCase):
info = PngImagePlugin.PngInfo() info = PngImagePlugin.PngInfo()
info.add_text("Text", value) info.add_text("Text", value)
im = roundtrip(im, pnginfo=info) im = roundtrip(im, pnginfo=info)
self.assertEqual(im.info, {"Text": value}) assert im.info == {"Text": value}
rt_text(" Aa" + chr(0xA0) + chr(0xC4) + chr(0xFF)) # Latin1 rt_text(" Aa" + chr(0xA0) + chr(0xC4) + chr(0xFF)) # Latin1
rt_text(chr(0x400) + chr(0x472) + chr(0x4FF)) # Cyrillic rt_text(chr(0x400) + chr(0x472) + chr(0x4FF)) # Cyrillic
@ -463,7 +465,8 @@ class TestFilePng(PillowTestCase):
data = b"\x89" + fd.read() data = b"\x89" + fd.read()
pngfile = BytesIO(data) pngfile = BytesIO(data)
self.assertRaises(IOError, Image.open, pngfile) with pytest.raises(IOError):
Image.open(pngfile)
def test_trns_rgb(self): def test_trns_rgb(self):
# Check writing and reading of tRNS chunks for RGB images. # Check writing and reading of tRNS chunks for RGB images.
@ -471,14 +474,14 @@ class TestFilePng(PillowTestCase):
test_file = "Tests/images/caption_6_33_22.png" test_file = "Tests/images/caption_6_33_22.png"
with Image.open(test_file) as im: with Image.open(test_file) as im:
self.assertEqual(im.info["transparency"], (248, 248, 248)) assert im.info["transparency"] == (248, 248, 248)
# check saving transparency by default # check saving transparency by default
im = roundtrip(im) im = roundtrip(im)
self.assertEqual(im.info["transparency"], (248, 248, 248)) assert im.info["transparency"] == (248, 248, 248)
im = roundtrip(im, transparency=(0, 1, 2)) im = roundtrip(im, transparency=(0, 1, 2))
self.assertEqual(im.info["transparency"], (0, 1, 2)) assert im.info["transparency"] == (0, 1, 2)
def test_trns_p(self): def test_trns_p(self):
# Check writing a transparency of 0, issue #528 # Check writing a transparency of 0, issue #528
@ -489,7 +492,7 @@ class TestFilePng(PillowTestCase):
im.save(f) im.save(f)
with Image.open(f) as im2: with Image.open(f) as im2:
self.assertIn("transparency", im2.info) assert "transparency" in im2.info
assert_image_equal(im2.convert("RGBA"), im.convert("RGBA")) assert_image_equal(im2.convert("RGBA"), im.convert("RGBA"))
@ -498,42 +501,42 @@ class TestFilePng(PillowTestCase):
test_file = "Tests/images/tRNS_null_1x1.png" test_file = "Tests/images/tRNS_null_1x1.png"
with Image.open(test_file) as im: with Image.open(test_file) as im:
self.assertEqual(im.info["transparency"], 0) assert im.info["transparency"] == 0
def test_save_icc_profile(self): def test_save_icc_profile(self):
with Image.open("Tests/images/icc_profile_none.png") as im: with Image.open("Tests/images/icc_profile_none.png") as im:
self.assertIsNone(im.info["icc_profile"]) assert im.info["icc_profile"] is None
with Image.open("Tests/images/icc_profile.png") as with_icc: with Image.open("Tests/images/icc_profile.png") as with_icc:
expected_icc = with_icc.info["icc_profile"] expected_icc = with_icc.info["icc_profile"]
im = roundtrip(im, icc_profile=expected_icc) im = roundtrip(im, icc_profile=expected_icc)
self.assertEqual(im.info["icc_profile"], expected_icc) assert im.info["icc_profile"] == expected_icc
def test_discard_icc_profile(self): def test_discard_icc_profile(self):
with Image.open("Tests/images/icc_profile.png") as im: with Image.open("Tests/images/icc_profile.png") as im:
im = roundtrip(im, icc_profile=None) im = roundtrip(im, icc_profile=None)
self.assertNotIn("icc_profile", im.info) assert "icc_profile" not in im.info
def test_roundtrip_icc_profile(self): def test_roundtrip_icc_profile(self):
with Image.open("Tests/images/icc_profile.png") as im: with Image.open("Tests/images/icc_profile.png") as im:
expected_icc = im.info["icc_profile"] expected_icc = im.info["icc_profile"]
im = roundtrip(im) im = roundtrip(im)
self.assertEqual(im.info["icc_profile"], expected_icc) assert im.info["icc_profile"] == expected_icc
def test_roundtrip_no_icc_profile(self): def test_roundtrip_no_icc_profile(self):
with Image.open("Tests/images/icc_profile_none.png") as im: with Image.open("Tests/images/icc_profile_none.png") as im:
self.assertIsNone(im.info["icc_profile"]) assert im.info["icc_profile"] is None
im = roundtrip(im) im = roundtrip(im)
self.assertNotIn("icc_profile", im.info) assert "icc_profile" not in im.info
def test_repr_png(self): def test_repr_png(self):
im = hopper() im = hopper()
with Image.open(BytesIO(im._repr_png_())) as repr_png: with Image.open(BytesIO(im._repr_png_())) as repr_png:
self.assertEqual(repr_png.format, "PNG") assert repr_png.format == "PNG"
assert_image_equal(im, repr_png) assert_image_equal(im, repr_png)
def test_chunk_order(self): def test_chunk_order(self):
@ -545,54 +548,55 @@ class TestFilePng(PillowTestCase):
# https://www.w3.org/TR/PNG/#5ChunkOrdering # https://www.w3.org/TR/PNG/#5ChunkOrdering
# IHDR - shall be first # IHDR - shall be first
self.assertEqual(chunks.index(b"IHDR"), 0) assert chunks.index(b"IHDR") == 0
# PLTE - before first IDAT # PLTE - before first IDAT
self.assertLess(chunks.index(b"PLTE"), chunks.index(b"IDAT")) assert chunks.index(b"PLTE") < chunks.index(b"IDAT")
# iCCP - before PLTE and IDAT # iCCP - before PLTE and IDAT
self.assertLess(chunks.index(b"iCCP"), chunks.index(b"PLTE")) assert chunks.index(b"iCCP") < chunks.index(b"PLTE")
self.assertLess(chunks.index(b"iCCP"), chunks.index(b"IDAT")) assert chunks.index(b"iCCP") < chunks.index(b"IDAT")
# tRNS - after PLTE, before IDAT # tRNS - after PLTE, before IDAT
self.assertGreater(chunks.index(b"tRNS"), chunks.index(b"PLTE")) assert chunks.index(b"tRNS") > chunks.index(b"PLTE")
self.assertLess(chunks.index(b"tRNS"), chunks.index(b"IDAT")) assert chunks.index(b"tRNS") < chunks.index(b"IDAT")
# pHYs - before IDAT # pHYs - before IDAT
self.assertLess(chunks.index(b"pHYs"), chunks.index(b"IDAT")) assert chunks.index(b"pHYs") < chunks.index(b"IDAT")
def test_getchunks(self): def test_getchunks(self):
im = hopper() im = hopper()
chunks = PngImagePlugin.getchunks(im) chunks = PngImagePlugin.getchunks(im)
self.assertEqual(len(chunks), 3) assert len(chunks) == 3
def test_textual_chunks_after_idat(self): def test_textual_chunks_after_idat(self):
with Image.open("Tests/images/hopper.png") as im: with Image.open("Tests/images/hopper.png") as im:
self.assertIn("comment", im.text.keys()) assert "comment" in im.text.keys()
for k, v in { for k, v in {
"date:create": "2014-09-04T09:37:08+03:00", "date:create": "2014-09-04T09:37:08+03:00",
"date:modify": "2014-09-04T09:37:08+03:00", "date:modify": "2014-09-04T09:37:08+03:00",
}.items(): }.items():
self.assertEqual(im.text[k], v) assert im.text[k] == v
# Raises a SyntaxError in load_end # Raises a SyntaxError in load_end
with Image.open("Tests/images/broken_data_stream.png") as im: with Image.open("Tests/images/broken_data_stream.png") as im:
with self.assertRaises(IOError): with pytest.raises(IOError):
self.assertIsInstance(im.text, dict) assert isinstance(im.text, dict)
# Raises a UnicodeDecodeError in load_end # Raises a UnicodeDecodeError in load_end
with Image.open("Tests/images/truncated_image.png") as im: with Image.open("Tests/images/truncated_image.png") as im:
# The file is truncated # The file is truncated
self.assertRaises(IOError, lambda: im.text) with pytest.raises(IOError):
im.text()
ImageFile.LOAD_TRUNCATED_IMAGES = True ImageFile.LOAD_TRUNCATED_IMAGES = True
self.assertIsInstance(im.text, dict) assert isinstance(im.text, dict)
ImageFile.LOAD_TRUNCATED_IMAGES = False ImageFile.LOAD_TRUNCATED_IMAGES = False
# Raises an EOFError in load_end # Raises an EOFError in load_end
with Image.open("Tests/images/hopper_idat_after_image_end.png") as im: with Image.open("Tests/images/hopper_idat_after_image_end.png") as im:
self.assertEqual(im.text, {"TXT": "VALUE", "ZIP": "VALUE"}) assert im.text == {"TXT": "VALUE", "ZIP": "VALUE"}
def test_exif(self): def test_exif(self):
with Image.open("Tests/images/exif.png") as im: with Image.open("Tests/images/exif.png") as im:
exif = im._getexif() exif = im._getexif()
self.assertEqual(exif[274], 1) assert exif[274] == 1
def test_exif_save(self): def test_exif_save(self):
with Image.open("Tests/images/exif.png") as im: with Image.open("Tests/images/exif.png") as im:
@ -601,7 +605,7 @@ class TestFilePng(PillowTestCase):
with Image.open(test_file) as reloaded: with Image.open(test_file) as reloaded:
exif = reloaded._getexif() exif = reloaded._getexif()
self.assertEqual(exif[274], 1) assert exif[274] == 1
def test_exif_from_jpg(self): def test_exif_from_jpg(self):
with Image.open("Tests/images/pil_sample_rgb.jpg") as im: with Image.open("Tests/images/pil_sample_rgb.jpg") as im:
@ -610,7 +614,7 @@ class TestFilePng(PillowTestCase):
with Image.open(test_file) as reloaded: with Image.open(test_file) as reloaded:
exif = reloaded._getexif() exif = reloaded._getexif()
self.assertEqual(exif[305], "Adobe Photoshop CS Macintosh") assert exif[305] == "Adobe Photoshop CS Macintosh"
def test_exif_argument(self): def test_exif_argument(self):
with Image.open(TEST_PNG_FILE) as im: with Image.open(TEST_PNG_FILE) as im:
@ -618,13 +622,13 @@ class TestFilePng(PillowTestCase):
im.save(test_file, exif=b"exifstring") im.save(test_file, exif=b"exifstring")
with Image.open(test_file) as reloaded: with Image.open(test_file) as reloaded:
self.assertEqual(reloaded.info["exif"], b"Exif\x00\x00exifstring") assert reloaded.info["exif"] == b"Exif\x00\x00exifstring"
@skip_unless_feature("webp") @skip_unless_feature("webp")
@skip_unless_feature("webp_anim") @skip_unless_feature("webp_anim")
def test_apng(self): def test_apng(self):
with Image.open("Tests/images/iss634.apng") as im: with Image.open("Tests/images/iss634.apng") as im:
self.assertEqual(im.get_format_mimetype(), "image/apng") assert im.get_format_mimetype() == "image/apng"
# This also tests reading unknown PNG chunks (fcTL and fdAT) in load_end # This also tests reading unknown PNG chunks (fcTL and fdAT) in load_end
with Image.open("Tests/images/iss634.webp") as expected: with Image.open("Tests/images/iss634.webp") as expected:

View File

@ -1,3 +1,4 @@
import pytest
from PIL import Image from PIL import Image
from .helper import PillowTestCase, assert_image_equal, assert_image_similar, hopper from .helper import PillowTestCase, assert_image_equal, assert_image_similar, hopper
@ -10,17 +11,17 @@ class TestFilePpm(PillowTestCase):
def test_sanity(self): def test_sanity(self):
with Image.open(test_file) as im: with Image.open(test_file) as im:
im.load() im.load()
self.assertEqual(im.mode, "RGB") assert im.mode == "RGB"
self.assertEqual(im.size, (128, 128)) assert im.size == (128, 128)
self.assertEqual(im.format, "PPM") assert im.format, "PPM"
self.assertEqual(im.get_format_mimetype(), "image/x-portable-pixmap") assert im.get_format_mimetype() == "image/x-portable-pixmap"
def test_16bit_pgm(self): def test_16bit_pgm(self):
with Image.open("Tests/images/16_bit_binary.pgm") as im: with Image.open("Tests/images/16_bit_binary.pgm") as im:
im.load() im.load()
self.assertEqual(im.mode, "I") assert im.mode == "I"
self.assertEqual(im.size, (20, 100)) assert im.size == (20, 100)
self.assertEqual(im.get_format_mimetype(), "image/x-portable-graymap") assert im.get_format_mimetype() == "image/x-portable-graymap"
with Image.open("Tests/images/16_bit_binary_pgm.png") as tgt: with Image.open("Tests/images/16_bit_binary_pgm.png") as tgt:
assert_image_equal(im, tgt) assert_image_equal(im, tgt)
@ -50,7 +51,8 @@ class TestFilePpm(PillowTestCase):
with open(path, "w") as f: with open(path, "w") as f:
f.write("P6") f.write("P6")
self.assertRaises(ValueError, Image.open, path) with pytest.raises(ValueError):
Image.open(path)
def test_neg_ppm(self): def test_neg_ppm(self):
# Storage.c accepted negative values for xsize, ysize. the # Storage.c accepted negative values for xsize, ysize. the
@ -58,7 +60,7 @@ class TestFilePpm(PillowTestCase):
# has been removed. The default opener doesn't accept negative # has been removed. The default opener doesn't accept negative
# sizes. # sizes.
with self.assertRaises(IOError): with pytest.raises(IOError):
Image.open("Tests/images/negative_size.ppm") Image.open("Tests/images/negative_size.ppm")
def test_mimetypes(self): def test_mimetypes(self):
@ -67,9 +69,9 @@ class TestFilePpm(PillowTestCase):
with open(path, "w") as f: with open(path, "w") as f:
f.write("P4\n128 128\n255") f.write("P4\n128 128\n255")
with Image.open(path) as im: with Image.open(path) as im:
self.assertEqual(im.get_format_mimetype(), "image/x-portable-bitmap") assert im.get_format_mimetype() == "image/x-portable-bitmap"
with open(path, "w") as f: with open(path, "w") as f:
f.write("PyCMYK\n128 128\n255") f.write("PyCMYK\n128 128\n255")
with Image.open(path) as im: with Image.open(path) as im:
self.assertEqual(im.get_format_mimetype(), "image/x-portable-anymap") assert im.get_format_mimetype() == "image/x-portable-anymap"

View File

@ -1,3 +1,4 @@
import pytest
from PIL import Image, SgiImagePlugin from PIL import Image, SgiImagePlugin
from .helper import PillowTestCase, assert_image_equal, assert_image_similar, hopper from .helper import PillowTestCase, assert_image_equal, assert_image_similar, hopper
@ -11,7 +12,7 @@ class TestFileSgi(PillowTestCase):
with Image.open(test_file) as im: with Image.open(test_file) as im:
assert_image_equal(im, hopper()) assert_image_equal(im, hopper())
self.assertEqual(im.get_format_mimetype(), "image/rgb") assert im.get_format_mimetype() == "image/rgb"
def test_rgb16(self): def test_rgb16(self):
test_file = "Tests/images/hopper16.rgb" test_file = "Tests/images/hopper16.rgb"
@ -26,7 +27,7 @@ class TestFileSgi(PillowTestCase):
with Image.open(test_file) as im: with Image.open(test_file) as im:
assert_image_similar(im, hopper("L"), 2) assert_image_similar(im, hopper("L"), 2)
self.assertEqual(im.get_format_mimetype(), "image/sgi") assert im.get_format_mimetype() == "image/sgi"
def test_rgba(self): def test_rgba(self):
# Created with ImageMagick: # Created with ImageMagick:
@ -36,7 +37,7 @@ class TestFileSgi(PillowTestCase):
with Image.open(test_file) as im: with Image.open(test_file) as im:
with Image.open("Tests/images/transparent.png") as target: with Image.open("Tests/images/transparent.png") as target:
assert_image_equal(im, target) assert_image_equal(im, target)
self.assertEqual(im.get_format_mimetype(), "image/sgi") assert im.get_format_mimetype() == "image/sgi"
def test_rle(self): def test_rle(self):
# Created with ImageMagick: # Created with ImageMagick:
@ -57,7 +58,8 @@ class TestFileSgi(PillowTestCase):
def test_invalid_file(self): def test_invalid_file(self):
invalid_file = "Tests/images/flower.jpg" invalid_file = "Tests/images/flower.jpg"
self.assertRaises(ValueError, SgiImagePlugin.SgiImageFile, invalid_file) with pytest.raises(ValueError):
SgiImagePlugin.SgiImageFile(invalid_file)
def test_write(self): def test_write(self):
def roundtrip(img): def roundtrip(img):
@ -86,4 +88,5 @@ class TestFileSgi(PillowTestCase):
im = hopper("LA") im = hopper("LA")
out = self.tempfile("temp.sgi") out = self.tempfile("temp.sgi")
self.assertRaises(ValueError, im.save, out, format="sgi") with pytest.raises(ValueError):
im.save(out, format="sgi")

View File

@ -14,9 +14,9 @@ class TestImageSpider(PillowTestCase):
def test_sanity(self): def test_sanity(self):
with Image.open(TEST_FILE) as im: with Image.open(TEST_FILE) as im:
im.load() im.load()
self.assertEqual(im.mode, "F") assert im.mode == "F"
self.assertEqual(im.size, (128, 128)) assert im.size == (128, 128)
self.assertEqual(im.format, "SPIDER") assert im.format == "SPIDER"
@unittest.skipIf(is_pypy(), "Requires CPython") @unittest.skipIf(is_pypy(), "Requires CPython")
def test_unclosed_file(self): def test_unclosed_file(self):
@ -51,9 +51,9 @@ class TestImageSpider(PillowTestCase):
# Assert # Assert
with Image.open(temp) as im2: with Image.open(temp) as im2:
self.assertEqual(im2.mode, "F") assert im2.mode == "F"
self.assertEqual(im2.size, (128, 128)) assert im2.size == (128, 128)
self.assertEqual(im2.format, "SPIDER") assert im2.format == "SPIDER"
def test_tempfile(self): def test_tempfile(self):
# Arrange # Arrange
@ -66,12 +66,12 @@ class TestImageSpider(PillowTestCase):
# Assert # Assert
fp.seek(0) fp.seek(0)
with Image.open(fp) as reloaded: with Image.open(fp) as reloaded:
self.assertEqual(reloaded.mode, "F") assert reloaded.mode == "F"
self.assertEqual(reloaded.size, (128, 128)) assert reloaded.size == (128, 128)
self.assertEqual(reloaded.format, "SPIDER") assert reloaded.format == "SPIDER"
def test_isSpiderImage(self): def test_isSpiderImage(self):
self.assertTrue(SpiderImagePlugin.isSpiderImage(TEST_FILE)) assert SpiderImagePlugin.isSpiderImage(TEST_FILE)
def test_tell(self): def test_tell(self):
# Arrange # Arrange
@ -81,12 +81,12 @@ class TestImageSpider(PillowTestCase):
index = im.tell() index = im.tell()
# Assert # Assert
self.assertEqual(index, 0) assert index == 0
def test_n_frames(self): def test_n_frames(self):
with Image.open(TEST_FILE) as im: with Image.open(TEST_FILE) as im:
self.assertEqual(im.n_frames, 1) assert im.n_frames == 1
self.assertFalse(im.is_animated) assert not im.is_animated
def test_loadImageSeries(self): def test_loadImageSeries(self):
# Arrange # Arrange
@ -97,9 +97,9 @@ class TestImageSpider(PillowTestCase):
img_list = SpiderImagePlugin.loadImageSeries(file_list) img_list = SpiderImagePlugin.loadImageSeries(file_list)
# Assert # Assert
self.assertEqual(len(img_list), 1) assert len(img_list) == 1
self.assertIsInstance(img_list[0], Image.Image) assert isinstance(img_list[0], Image.Image)
self.assertEqual(img_list[0].size, (128, 128)) assert img_list[0].size == (128, 128)
def test_loadImageSeries_no_input(self): def test_loadImageSeries_no_input(self):
# Arrange # Arrange
@ -109,7 +109,7 @@ class TestImageSpider(PillowTestCase):
img_list = SpiderImagePlugin.loadImageSeries(file_list) img_list = SpiderImagePlugin.loadImageSeries(file_list)
# Assert # Assert
self.assertIsNone(img_list) assert img_list is None
def test_isInt_not_a_number(self): def test_isInt_not_a_number(self):
# Arrange # Arrange
@ -119,21 +119,23 @@ class TestImageSpider(PillowTestCase):
ret = SpiderImagePlugin.isInt(not_a_number) ret = SpiderImagePlugin.isInt(not_a_number)
# Assert # Assert
self.assertEqual(ret, 0) assert ret == 0
def test_invalid_file(self): def test_invalid_file(self):
invalid_file = "Tests/images/invalid.spider" invalid_file = "Tests/images/invalid.spider"
self.assertRaises(IOError, Image.open, invalid_file) with pytest.raises(IOError):
Image.open(invalid_file)
def test_nonstack_file(self): def test_nonstack_file(self):
with Image.open(TEST_FILE) as im: with Image.open(TEST_FILE) as im:
self.assertRaises(EOFError, im.seek, 0) with pytest.raises(EOFError):
im.seek(0)
def test_nonstack_dos(self): def test_nonstack_dos(self):
with Image.open(TEST_FILE) as im: with Image.open(TEST_FILE) as im:
for i, frame in enumerate(ImageSequence.Iterator(im)): for i, frame in enumerate(ImageSequence.Iterator(im)):
self.assertLessEqual(i, 1, "Non-stack DOS file test failed") assert i <= 1, "Non-stack DOS file test failed"
# for issue #4093 # for issue #4093
def test_odd_size(self): def test_odd_size(self):

View File

@ -26,7 +26,7 @@ class TestFileTga(PillowTestCase):
for png_path in png_paths: for png_path in png_paths:
with Image.open(png_path) as reference_im: with Image.open(png_path) as reference_im:
self.assertEqual(reference_im.mode, mode) assert reference_im.mode == mode
path_no_ext = os.path.splitext(png_path)[0] path_no_ext = os.path.splitext(png_path)[0]
for origin, rle in product(self._ORIGINS, (True, False)): for origin, rle in product(self._ORIGINS, (True, False)):
@ -35,21 +35,18 @@ class TestFileTga(PillowTestCase):
) )
with Image.open(tga_path) as original_im: with Image.open(tga_path) as original_im:
self.assertEqual(original_im.format, "TGA") assert original_im.format == "TGA"
self.assertEqual( assert original_im.get_format_mimetype() == "image/x-tga"
original_im.get_format_mimetype(), "image/x-tga"
)
if rle: if rle:
self.assertEqual( assert original_im.info["compression"] == "tga_rle"
original_im.info["compression"], "tga_rle" assert (
) original_im.info["orientation"]
self.assertEqual( == self._ORIGIN_TO_ORIENTATION[origin]
original_im.info["orientation"],
self._ORIGIN_TO_ORIENTATION[origin],
) )
if mode == "P": if mode == "P":
self.assertEqual( assert (
original_im.getpalette(), reference_im.getpalette() original_im.getpalette()
== reference_im.getpalette()
) )
assert_image_equal(original_im, reference_im) assert_image_equal(original_im, reference_im)
@ -62,17 +59,18 @@ class TestFileTga(PillowTestCase):
original_im.save(out, rle=rle) original_im.save(out, rle=rle)
with Image.open(out) as saved_im: with Image.open(out) as saved_im:
if rle: if rle:
self.assertEqual( assert (
saved_im.info["compression"], saved_im.info["compression"]
original_im.info["compression"], == original_im.info["compression"]
) )
self.assertEqual( assert (
saved_im.info["orientation"], saved_im.info["orientation"]
original_im.info["orientation"], == original_im.info["orientation"]
) )
if mode == "P": if mode == "P":
self.assertEqual( assert (
saved_im.getpalette(), original_im.getpalette() saved_im.getpalette()
== original_im.getpalette()
) )
assert_image_equal(saved_im, original_im) assert_image_equal(saved_im, original_im)
@ -85,7 +83,7 @@ class TestFileTga(PillowTestCase):
with Image.open(test_file) as im: with Image.open(test_file) as im:
# Assert # Assert
self.assertEqual(im.size, (100, 100)) assert im.size == (100, 100)
def test_id_field_rle(self): def test_id_field_rle(self):
# tga file with id field # tga file with id field
@ -95,7 +93,7 @@ class TestFileTga(PillowTestCase):
with Image.open(test_file) as im: with Image.open(test_file) as im:
# Assert # Assert
self.assertEqual(im.size, (199, 199)) assert im.size == (199, 199)
def test_save(self): def test_save(self):
test_file = "Tests/images/tga_id_field.tga" test_file = "Tests/images/tga_id_field.tga"
@ -105,19 +103,19 @@ class TestFileTga(PillowTestCase):
# Save # Save
im.save(out) im.save(out)
with Image.open(out) as test_im: with Image.open(out) as test_im:
self.assertEqual(test_im.size, (100, 100)) assert test_im.size == (100, 100)
self.assertEqual(test_im.info["id_section"], im.info["id_section"]) assert test_im.info["id_section"] == im.info["id_section"]
# RGBA save # RGBA save
im.convert("RGBA").save(out) im.convert("RGBA").save(out)
with Image.open(out) as test_im: with Image.open(out) as test_im:
self.assertEqual(test_im.size, (100, 100)) assert test_im.size == (100, 100)
def test_save_wrong_mode(self): def test_save_wrong_mode(self):
im = hopper("PA") im = hopper("PA")
out = self.tempfile("temp.tga") out = self.tempfile("temp.tga")
with self.assertRaises(OSError): with pytest.raises(OSError):
im.save(out) im.save(out)
def test_save_id_section(self): def test_save_id_section(self):
@ -128,18 +126,18 @@ class TestFileTga(PillowTestCase):
# Check there is no id section # Check there is no id section
im.save(out) im.save(out)
with Image.open(out) as test_im: with Image.open(out) as test_im:
self.assertNotIn("id_section", test_im.info) assert "id_section" not in test_im.info
# Save with custom id section # Save with custom id section
im.save(out, id_section=b"Test content") im.save(out, id_section=b"Test content")
with Image.open(out) as test_im: with Image.open(out) as test_im:
self.assertEqual(test_im.info["id_section"], b"Test content") assert test_im.info["id_section"] == b"Test content"
# Save with custom id section greater than 255 characters # Save with custom id section greater than 255 characters
id_section = b"Test content" * 25 id_section = b"Test content" * 25
pytest.warns(UserWarning, lambda: im.save(out, id_section=id_section)) pytest.warns(UserWarning, lambda: im.save(out, id_section=id_section))
with Image.open(out) as test_im: with Image.open(out) as test_im:
self.assertEqual(test_im.info["id_section"], id_section[:255]) assert test_im.info["id_section"] == id_section[:255]
test_file = "Tests/images/tga_id_field.tga" test_file = "Tests/images/tga_id_field.tga"
with Image.open(test_file) as im: with Image.open(test_file) as im:
@ -147,49 +145,49 @@ class TestFileTga(PillowTestCase):
# Save with no id section # Save with no id section
im.save(out, id_section="") im.save(out, id_section="")
with Image.open(out) as test_im: with Image.open(out) as test_im:
self.assertNotIn("id_section", test_im.info) assert "id_section" not in test_im.info
def test_save_orientation(self): def test_save_orientation(self):
test_file = "Tests/images/rgb32rle.tga" test_file = "Tests/images/rgb32rle.tga"
out = self.tempfile("temp.tga") out = self.tempfile("temp.tga")
with Image.open(test_file) as im: with Image.open(test_file) as im:
self.assertEqual(im.info["orientation"], -1) assert im.info["orientation"] == -1
im.save(out, orientation=1) im.save(out, orientation=1)
with Image.open(out) as test_im: with Image.open(out) as test_im:
self.assertEqual(test_im.info["orientation"], 1) assert test_im.info["orientation"] == 1
def test_save_rle(self): def test_save_rle(self):
test_file = "Tests/images/rgb32rle.tga" test_file = "Tests/images/rgb32rle.tga"
with Image.open(test_file) as im: with Image.open(test_file) as im:
self.assertEqual(im.info["compression"], "tga_rle") assert im.info["compression"] == "tga_rle"
out = self.tempfile("temp.tga") out = self.tempfile("temp.tga")
# Save # Save
im.save(out) im.save(out)
with Image.open(out) as test_im: with Image.open(out) as test_im:
self.assertEqual(test_im.size, (199, 199)) assert test_im.size == (199, 199)
self.assertEqual(test_im.info["compression"], "tga_rle") assert test_im.info["compression"] == "tga_rle"
# Save without compression # Save without compression
im.save(out, compression=None) im.save(out, compression=None)
with Image.open(out) as test_im: with Image.open(out) as test_im:
self.assertNotIn("compression", test_im.info) assert "compression" not in test_im.info
# RGBA save # RGBA save
im.convert("RGBA").save(out) im.convert("RGBA").save(out)
with Image.open(out) as test_im: with Image.open(out) as test_im:
self.assertEqual(test_im.size, (199, 199)) assert test_im.size == (199, 199)
test_file = "Tests/images/tga_id_field.tga" test_file = "Tests/images/tga_id_field.tga"
with Image.open(test_file) as im: with Image.open(test_file) as im:
self.assertNotIn("compression", im.info) assert "compression" not in im.info
# Save with compression # Save with compression
im.save(out, compression="tga_rle") im.save(out, compression="tga_rle")
with Image.open(out) as test_im: with Image.open(out) as test_im:
self.assertEqual(test_im.info["compression"], "tga_rle") assert test_im.info["compression"] == "tga_rle"
def test_save_l_transparency(self): def test_save_l_transparency(self):
# There are 559 transparent pixels in la.tga. # There are 559 transparent pixels in la.tga.
@ -197,14 +195,14 @@ class TestFileTga(PillowTestCase):
in_file = "Tests/images/la.tga" in_file = "Tests/images/la.tga"
with Image.open(in_file) as im: with Image.open(in_file) as im:
self.assertEqual(im.mode, "LA") assert im.mode == "LA"
self.assertEqual(im.getchannel("A").getcolors()[0][0], num_transparent) assert im.getchannel("A").getcolors()[0][0] == num_transparent
out = self.tempfile("temp.tga") out = self.tempfile("temp.tga")
im.save(out) im.save(out)
with Image.open(out) as test_im: with Image.open(out) as test_im:
self.assertEqual(test_im.mode, "LA") assert test_im.mode == "LA"
self.assertEqual(test_im.getchannel("A").getcolors()[0][0], num_transparent) assert test_im.getchannel("A").getcolors()[0][0] == num_transparent
assert_image_equal(im, test_im) assert_image_equal(im, test_im)

View File

@ -30,9 +30,9 @@ class TestFileTiff(PillowTestCase):
with Image.open(filename) as im: with Image.open(filename) as im:
im.load() im.load()
self.assertEqual(im.mode, "RGB") assert im.mode == "RGB"
self.assertEqual(im.size, (128, 128)) assert im.size == (128, 128)
self.assertEqual(im.format, "TIFF") assert im.format == "TIFF"
hopper("1").save(filename) hopper("1").save(filename)
with Image.open(filename): with Image.open(filename):
@ -82,53 +82,54 @@ class TestFileTiff(PillowTestCase):
filename = "Tests/images/pil136.tiff" filename = "Tests/images/pil136.tiff"
with Image.open(filename) as im: with Image.open(filename) as im:
self.assertEqual(im.mode, "RGBA") assert im.mode == "RGBA"
self.assertEqual(im.size, (55, 43)) assert im.size == (55, 43)
self.assertEqual(im.tile, [("raw", (0, 0, 55, 43), 8, ("RGBa", 0, 1))]) assert im.tile == [("raw", (0, 0, 55, 43), 8, ("RGBa", 0, 1))]
im.load() im.load()
assert_image_similar_tofile(im, "Tests/images/pil136.png", 1) assert_image_similar_tofile(im, "Tests/images/pil136.png", 1)
def test_wrong_bits_per_sample(self): def test_wrong_bits_per_sample(self):
with Image.open("Tests/images/tiff_wrong_bits_per_sample.tiff") as im: with Image.open("Tests/images/tiff_wrong_bits_per_sample.tiff") as im:
self.assertEqual(im.mode, "RGBA") assert im.mode == "RGBA"
self.assertEqual(im.size, (52, 53)) assert im.size == (52, 53)
self.assertEqual(im.tile, [("raw", (0, 0, 52, 53), 160, ("RGBA", 0, 1))]) assert im.tile == [("raw", (0, 0, 52, 53), 160, ("RGBA", 0, 1))]
im.load() im.load()
def test_set_legacy_api(self): def test_set_legacy_api(self):
ifd = TiffImagePlugin.ImageFileDirectory_v2() ifd = TiffImagePlugin.ImageFileDirectory_v2()
with self.assertRaises(Exception) as e: with pytest.raises(Exception) as e:
ifd.legacy_api = None ifd.legacy_api = None
self.assertEqual(str(e.exception), "Not allowing setting of legacy api") assert str(e.value) == "Not allowing setting of legacy api"
def test_xyres_tiff(self): def test_xyres_tiff(self):
filename = "Tests/images/pil168.tif" filename = "Tests/images/pil168.tif"
with Image.open(filename) as im: with Image.open(filename) as im:
# legacy api # legacy api
self.assertIsInstance(im.tag[X_RESOLUTION][0], tuple) assert isinstance(im.tag[X_RESOLUTION][0], tuple)
self.assertIsInstance(im.tag[Y_RESOLUTION][0], tuple) assert isinstance(im.tag[Y_RESOLUTION][0], tuple)
# v2 api # v2 api
self.assertIsInstance(im.tag_v2[X_RESOLUTION], TiffImagePlugin.IFDRational) assert isinstance(im.tag_v2[X_RESOLUTION], TiffImagePlugin.IFDRational)
self.assertIsInstance(im.tag_v2[Y_RESOLUTION], TiffImagePlugin.IFDRational) assert isinstance(im.tag_v2[Y_RESOLUTION], TiffImagePlugin.IFDRational)
self.assertEqual(im.info["dpi"], (72.0, 72.0)) assert im.info["dpi"] == (72.0, 72.0)
def test_xyres_fallback_tiff(self): def test_xyres_fallback_tiff(self):
filename = "Tests/images/compression.tif" filename = "Tests/images/compression.tif"
with Image.open(filename) as im: with Image.open(filename) as im:
# v2 api # v2 api
self.assertIsInstance(im.tag_v2[X_RESOLUTION], TiffImagePlugin.IFDRational) assert isinstance(im.tag_v2[X_RESOLUTION], TiffImagePlugin.IFDRational)
self.assertIsInstance(im.tag_v2[Y_RESOLUTION], TiffImagePlugin.IFDRational) assert isinstance(im.tag_v2[Y_RESOLUTION], TiffImagePlugin.IFDRational)
self.assertRaises(KeyError, lambda: im.tag_v2[RESOLUTION_UNIT]) with pytest.raises(KeyError):
im.tag_v2[RESOLUTION_UNIT]
# Legacy. # Legacy.
self.assertEqual(im.info["resolution"], (100.0, 100.0)) assert im.info["resolution"] == (100.0, 100.0)
# Fallback "inch". # Fallback "inch".
self.assertEqual(im.info["dpi"], (100.0, 100.0)) assert im.info["dpi"] == (100.0, 100.0)
def test_int_resolution(self): def test_int_resolution(self):
filename = "Tests/images/pil168.tif" filename = "Tests/images/pil168.tif"
@ -138,21 +139,21 @@ class TestFileTiff(PillowTestCase):
im.tag_v2[X_RESOLUTION] = 71 im.tag_v2[X_RESOLUTION] = 71
im.tag_v2[Y_RESOLUTION] = 71 im.tag_v2[Y_RESOLUTION] = 71
im._setup() im._setup()
self.assertEqual(im.info["dpi"], (71.0, 71.0)) assert im.info["dpi"] == (71.0, 71.0)
def test_load_dpi_rounding(self): def test_load_dpi_rounding(self):
for resolutionUnit, dpi in ((None, (72, 73)), (2, (72, 73)), (3, (183, 185))): for resolutionUnit, dpi in ((None, (72, 73)), (2, (72, 73)), (3, (183, 185))):
with Image.open( with Image.open(
"Tests/images/hopper_roundDown_" + str(resolutionUnit) + ".tif" "Tests/images/hopper_roundDown_" + str(resolutionUnit) + ".tif"
) as im: ) as im:
self.assertEqual(im.tag_v2.get(RESOLUTION_UNIT), resolutionUnit) assert im.tag_v2.get(RESOLUTION_UNIT) == resolutionUnit
self.assertEqual(im.info["dpi"], (dpi[0], dpi[0])) assert im.info["dpi"] == (dpi[0], dpi[0])
with Image.open( with Image.open(
"Tests/images/hopper_roundUp_" + str(resolutionUnit) + ".tif" "Tests/images/hopper_roundUp_" + str(resolutionUnit) + ".tif"
) as im: ) as im:
self.assertEqual(im.tag_v2.get(RESOLUTION_UNIT), resolutionUnit) assert im.tag_v2.get(RESOLUTION_UNIT) == resolutionUnit
self.assertEqual(im.info["dpi"], (dpi[1], dpi[1])) assert im.info["dpi"] == (dpi[1], dpi[1])
def test_save_dpi_rounding(self): def test_save_dpi_rounding(self):
outfile = self.tempfile("temp.tif") outfile = self.tempfile("temp.tif")
@ -162,7 +163,7 @@ class TestFileTiff(PillowTestCase):
with Image.open(outfile) as reloaded: with Image.open(outfile) as reloaded:
reloaded.load() reloaded.load()
self.assertEqual((round(dpi), round(dpi)), reloaded.info["dpi"]) assert (round(dpi), round(dpi)) == reloaded.info["dpi"]
def test_save_setting_missing_resolution(self): def test_save_setting_missing_resolution(self):
b = BytesIO() b = BytesIO()
@ -170,16 +171,18 @@ class TestFileTiff(PillowTestCase):
b, format="tiff", resolution=123.45 b, format="tiff", resolution=123.45
) )
with Image.open(b) as im: with Image.open(b) as im:
self.assertEqual(float(im.tag_v2[X_RESOLUTION]), 123.45) assert float(im.tag_v2[X_RESOLUTION]) == 123.45
self.assertEqual(float(im.tag_v2[Y_RESOLUTION]), 123.45) assert float(im.tag_v2[Y_RESOLUTION]) == 123.45
def test_invalid_file(self): def test_invalid_file(self):
invalid_file = "Tests/images/flower.jpg" invalid_file = "Tests/images/flower.jpg"
self.assertRaises(SyntaxError, TiffImagePlugin.TiffImageFile, invalid_file) with pytest.raises(SyntaxError):
TiffImagePlugin.TiffImageFile(invalid_file)
TiffImagePlugin.PREFIXES.append(b"\xff\xd8\xff\xe0") TiffImagePlugin.PREFIXES.append(b"\xff\xd8\xff\xe0")
self.assertRaises(SyntaxError, TiffImagePlugin.TiffImageFile, invalid_file) with pytest.raises(SyntaxError):
TiffImagePlugin.TiffImageFile(invalid_file)
TiffImagePlugin.PREFIXES.pop() TiffImagePlugin.PREFIXES.pop()
def test_bad_exif(self): def test_bad_exif(self):
@ -195,34 +198,35 @@ class TestFileTiff(PillowTestCase):
def test_save_unsupported_mode(self): def test_save_unsupported_mode(self):
im = hopper("HSV") im = hopper("HSV")
outfile = self.tempfile("temp.tif") outfile = self.tempfile("temp.tif")
self.assertRaises(IOError, im.save, outfile) with pytest.raises(IOError):
im.save(outfile)
def test_little_endian(self): def test_little_endian(self):
with Image.open("Tests/images/16bit.cropped.tif") as im: with Image.open("Tests/images/16bit.cropped.tif") as im:
self.assertEqual(im.getpixel((0, 0)), 480) assert im.getpixel((0, 0)) == 480
self.assertEqual(im.mode, "I;16") assert im.mode == "I;16"
b = im.tobytes() b = im.tobytes()
# Bytes are in image native order (little endian) # Bytes are in image native order (little endian)
self.assertEqual(b[0], ord(b"\xe0")) assert b[0] == ord(b"\xe0")
self.assertEqual(b[1], ord(b"\x01")) assert b[1] == ord(b"\x01")
def test_big_endian(self): def test_big_endian(self):
with Image.open("Tests/images/16bit.MM.cropped.tif") as im: with Image.open("Tests/images/16bit.MM.cropped.tif") as im:
self.assertEqual(im.getpixel((0, 0)), 480) assert im.getpixel((0, 0)) == 480
self.assertEqual(im.mode, "I;16B") assert im.mode == "I;16B"
b = im.tobytes() b = im.tobytes()
# Bytes are in image native order (big endian) # Bytes are in image native order (big endian)
self.assertEqual(b[0], ord(b"\x01")) assert b[0] == ord(b"\x01")
self.assertEqual(b[1], ord(b"\xe0")) assert b[1] == ord(b"\xe0")
def test_16bit_s(self): def test_16bit_s(self):
with Image.open("Tests/images/16bit.s.tif") as im: with Image.open("Tests/images/16bit.s.tif") as im:
im.load() im.load()
self.assertEqual(im.mode, "I") assert im.mode == "I"
self.assertEqual(im.getpixel((0, 0)), 32767) assert im.getpixel((0, 0)) == 32767
self.assertEqual(im.getpixel((0, 1)), 0) assert im.getpixel((0, 1)) == 0
def test_12bit_rawmode(self): def test_12bit_rawmode(self):
""" Are we generating the same interpretation """ Are we generating the same interpretation
@ -243,13 +247,12 @@ class TestFileTiff(PillowTestCase):
with Image.open(path) as im: with Image.open(path) as im:
im.load() im.load()
self.assertEqual(im.getpixel((0, 0)), -0.4526388943195343) assert im.getpixel((0, 0)) == -0.4526388943195343
self.assertEqual(im.getextrema(), (-3.140936851501465, 3.140684127807617)) assert im.getextrema() == (-3.140936851501465, 3.140684127807617)
def test_unknown_pixel_mode(self): def test_unknown_pixel_mode(self):
self.assertRaises( with pytest.raises(IOError):
IOError, Image.open, "Tests/images/hopper_unknown_pixel_mode.tif" Image.open("Tests/images/hopper_unknown_pixel_mode.tif")
)
def test_n_frames(self): def test_n_frames(self):
for path, n_frames in [ for path, n_frames in [
@ -257,16 +260,17 @@ class TestFileTiff(PillowTestCase):
["Tests/images/multipage.tiff", 3], ["Tests/images/multipage.tiff", 3],
]: ]:
with Image.open(path) as im: with Image.open(path) as im:
self.assertEqual(im.n_frames, n_frames) assert im.n_frames == n_frames
self.assertEqual(im.is_animated, n_frames != 1) assert im.is_animated == (n_frames != 1)
def test_eoferror(self): def test_eoferror(self):
with Image.open("Tests/images/multipage-lastframe.tif") as im: with Image.open("Tests/images/multipage-lastframe.tif") as im:
n_frames = im.n_frames n_frames = im.n_frames
# Test seeking past the last frame # Test seeking past the last frame
self.assertRaises(EOFError, im.seek, n_frames) with pytest.raises(EOFError):
self.assertLess(im.tell(), n_frames) im.seek(n_frames)
assert im.tell() < n_frames
# Test that seeking to the last frame does not raise an error # Test that seeking to the last frame does not raise an error
im.seek(n_frames - 1) im.seek(n_frames - 1)
@ -277,29 +281,29 @@ class TestFileTiff(PillowTestCase):
# file is a multipage tiff: 10x10 green, 10x10 red, 20x20 blue # file is a multipage tiff: 10x10 green, 10x10 red, 20x20 blue
im.seek(0) im.seek(0)
self.assertEqual(im.size, (10, 10)) assert im.size == (10, 10)
self.assertEqual(im.convert("RGB").getpixel((0, 0)), (0, 128, 0)) assert im.convert("RGB").getpixel((0, 0)) == (0, 128, 0)
im.seek(1) im.seek(1)
im.load() im.load()
self.assertEqual(im.size, (10, 10)) assert im.size == (10, 10)
self.assertEqual(im.convert("RGB").getpixel((0, 0)), (255, 0, 0)) assert im.convert("RGB").getpixel((0, 0)) == (255, 0, 0)
im.seek(0) im.seek(0)
im.load() im.load()
self.assertEqual(im.size, (10, 10)) assert im.size == (10, 10)
self.assertEqual(im.convert("RGB").getpixel((0, 0)), (0, 128, 0)) assert im.convert("RGB").getpixel((0, 0)) == (0, 128, 0)
im.seek(2) im.seek(2)
im.load() im.load()
self.assertEqual(im.size, (20, 20)) assert im.size == (20, 20)
self.assertEqual(im.convert("RGB").getpixel((0, 0)), (0, 0, 255)) assert im.convert("RGB").getpixel((0, 0)) == (0, 0, 255)
def test_multipage_last_frame(self): def test_multipage_last_frame(self):
with Image.open("Tests/images/multipage-lastframe.tif") as im: with Image.open("Tests/images/multipage-lastframe.tif") as im:
im.load() im.load()
self.assertEqual(im.size, (20, 20)) assert im.size == (20, 20)
self.assertEqual(im.convert("RGB").getpixel((0, 0)), (0, 0, 255)) assert im.convert("RGB").getpixel((0, 0)) == (0, 0, 255)
def test___str__(self): def test___str__(self):
filename = "Tests/images/pil136.tiff" filename = "Tests/images/pil136.tiff"
@ -309,7 +313,7 @@ class TestFileTiff(PillowTestCase):
ret = str(im.ifd) ret = str(im.ifd)
# Assert # Assert
self.assertIsInstance(ret, str) assert isinstance(ret, str)
def test_dict(self): def test_dict(self):
# Arrange # Arrange
@ -332,7 +336,7 @@ class TestFileTiff(PillowTestCase):
283: 72.0, 283: 72.0,
284: 1, 284: 1,
} }
self.assertEqual(dict(im.tag_v2), v2_tags) assert dict(im.tag_v2) == v2_tags
# legacy interface # legacy interface
legacy_tags = { legacy_tags = {
@ -350,7 +354,7 @@ class TestFileTiff(PillowTestCase):
283: ((720000, 10000),), 283: ((720000, 10000),),
284: (1,), 284: (1,),
} }
self.assertEqual(dict(im.tag), legacy_tags) assert dict(im.tag) == legacy_tags
def test__delitem__(self): def test__delitem__(self):
filename = "Tests/images/pil136.tiff" filename = "Tests/images/pil136.tiff"
@ -358,66 +362,68 @@ class TestFileTiff(PillowTestCase):
len_before = len(dict(im.ifd)) len_before = len(dict(im.ifd))
del im.ifd[256] del im.ifd[256]
len_after = len(dict(im.ifd)) len_after = len(dict(im.ifd))
self.assertEqual(len_before, len_after + 1) assert len_before == len_after + 1
def test_load_byte(self): def test_load_byte(self):
for legacy_api in [False, True]: for legacy_api in [False, True]:
ifd = TiffImagePlugin.ImageFileDirectory_v2() ifd = TiffImagePlugin.ImageFileDirectory_v2()
data = b"abc" data = b"abc"
ret = ifd.load_byte(data, legacy_api) ret = ifd.load_byte(data, legacy_api)
self.assertEqual(ret, b"abc") assert ret == b"abc"
def test_load_string(self): def test_load_string(self):
ifd = TiffImagePlugin.ImageFileDirectory_v2() ifd = TiffImagePlugin.ImageFileDirectory_v2()
data = b"abc\0" data = b"abc\0"
ret = ifd.load_string(data, False) ret = ifd.load_string(data, False)
self.assertEqual(ret, "abc") assert ret == "abc"
def test_load_float(self): def test_load_float(self):
ifd = TiffImagePlugin.ImageFileDirectory_v2() ifd = TiffImagePlugin.ImageFileDirectory_v2()
data = b"abcdabcd" data = b"abcdabcd"
ret = ifd.load_float(data, False) ret = ifd.load_float(data, False)
self.assertEqual(ret, (1.6777999408082104e22, 1.6777999408082104e22)) assert ret == (1.6777999408082104e22, 1.6777999408082104e22)
def test_load_double(self): def test_load_double(self):
ifd = TiffImagePlugin.ImageFileDirectory_v2() ifd = TiffImagePlugin.ImageFileDirectory_v2()
data = b"abcdefghabcdefgh" data = b"abcdefghabcdefgh"
ret = ifd.load_double(data, False) ret = ifd.load_double(data, False)
self.assertEqual(ret, (8.540883223036124e194, 8.540883223036124e194)) assert ret == (8.540883223036124e194, 8.540883223036124e194)
def test_seek(self): def test_seek(self):
filename = "Tests/images/pil136.tiff" filename = "Tests/images/pil136.tiff"
with Image.open(filename) as im: with Image.open(filename) as im:
im.seek(0) im.seek(0)
self.assertEqual(im.tell(), 0) assert im.tell() == 0
def test_seek_eof(self): def test_seek_eof(self):
filename = "Tests/images/pil136.tiff" filename = "Tests/images/pil136.tiff"
with Image.open(filename) as im: with Image.open(filename) as im:
self.assertEqual(im.tell(), 0) assert im.tell() == 0
self.assertRaises(EOFError, im.seek, -1) with pytest.raises(EOFError):
self.assertRaises(EOFError, im.seek, 1) im.seek(-1)
with pytest.raises(EOFError):
im.seek(1)
def test__limit_rational_int(self): def test__limit_rational_int(self):
from PIL.TiffImagePlugin import _limit_rational from PIL.TiffImagePlugin import _limit_rational
value = 34 value = 34
ret = _limit_rational(value, 65536) ret = _limit_rational(value, 65536)
self.assertEqual(ret, (34, 1)) assert ret == (34, 1)
def test__limit_rational_float(self): def test__limit_rational_float(self):
from PIL.TiffImagePlugin import _limit_rational from PIL.TiffImagePlugin import _limit_rational
value = 22.3 value = 22.3
ret = _limit_rational(value, 65536) ret = _limit_rational(value, 65536)
self.assertEqual(ret, (223, 10)) assert ret == (223, 10)
def test_4bit(self): def test_4bit(self):
test_file = "Tests/images/hopper_gray_4bpp.tif" test_file = "Tests/images/hopper_gray_4bpp.tif"
original = hopper("L") original = hopper("L")
with Image.open(test_file) as im: with Image.open(test_file) as im:
self.assertEqual(im.size, (128, 128)) assert im.size == (128, 128)
self.assertEqual(im.mode, "L") assert im.mode == "L"
assert_image_similar(im, original, 7.3) assert_image_similar(im, original, 7.3)
def test_gray_semibyte_per_pixel(self): def test_gray_semibyte_per_pixel(self):
@ -444,13 +450,13 @@ class TestFileTiff(PillowTestCase):
original = hopper("L") original = hopper("L")
for epsilon, group in test_files: for epsilon, group in test_files:
with Image.open(group[0]) as im: with Image.open(group[0]) as im:
self.assertEqual(im.size, (128, 128)) assert im.size == (128, 128)
self.assertEqual(im.mode, "L") assert im.mode == "L"
assert_image_similar(im, original, epsilon) assert_image_similar(im, original, epsilon)
for file in group[1:]: for file in group[1:]:
with Image.open(file) as im2: with Image.open(file) as im2:
self.assertEqual(im2.size, (128, 128)) assert im2.size == (128, 128)
self.assertEqual(im2.mode, "L") assert im2.mode == "L"
assert_image_equal(im, im2) assert_image_equal(im, im2)
def test_with_underscores(self): def test_with_underscores(self):
@ -460,19 +466,19 @@ class TestFileTiff(PillowTestCase):
with Image.open(filename) as im: with Image.open(filename) as im:
# legacy interface # legacy interface
self.assertEqual(im.tag[X_RESOLUTION][0][0], 72) assert im.tag[X_RESOLUTION][0][0] == 72
self.assertEqual(im.tag[Y_RESOLUTION][0][0], 36) assert im.tag[Y_RESOLUTION][0][0] == 36
# v2 interface # v2 interface
self.assertEqual(im.tag_v2[X_RESOLUTION], 72) assert im.tag_v2[X_RESOLUTION] == 72
self.assertEqual(im.tag_v2[Y_RESOLUTION], 36) assert im.tag_v2[Y_RESOLUTION] == 36
def test_roundtrip_tiff_uint16(self): def test_roundtrip_tiff_uint16(self):
# Test an image of all '0' values # Test an image of all '0' values
pixel_value = 0x1234 pixel_value = 0x1234
infile = "Tests/images/uint16_1_4660.tif" infile = "Tests/images/uint16_1_4660.tif"
with Image.open(infile) as im: with Image.open(infile) as im:
self.assertEqual(im.getpixel((0, 0)), pixel_value) assert im.getpixel((0, 0)) == pixel_value
tmpfile = self.tempfile("temp.tif") tmpfile = self.tempfile("temp.tif")
im.save(tmpfile) im.save(tmpfile)
@ -523,7 +529,7 @@ class TestFileTiff(PillowTestCase):
mp.seek(0, os.SEEK_SET) mp.seek(0, os.SEEK_SET)
with Image.open(mp) as im: with Image.open(mp) as im:
self.assertEqual(im.n_frames, 3) assert im.n_frames == 3
# Test appending images # Test appending images
mp = BytesIO() mp = BytesIO()
@ -533,7 +539,7 @@ class TestFileTiff(PillowTestCase):
mp.seek(0, os.SEEK_SET) mp.seek(0, os.SEEK_SET)
with Image.open(mp) as reread: with Image.open(mp) as reread:
self.assertEqual(reread.n_frames, 3) assert reread.n_frames == 3
# Test appending using a generator # Test appending using a generator
def imGenerator(ims): def imGenerator(ims):
@ -544,7 +550,7 @@ class TestFileTiff(PillowTestCase):
mp.seek(0, os.SEEK_SET) mp.seek(0, os.SEEK_SET)
with Image.open(mp) as reread: with Image.open(mp) as reread:
self.assertEqual(reread.n_frames, 3) assert reread.n_frames == 3
def test_saving_icc_profile(self): def test_saving_icc_profile(self):
# Tests saving TIFF with icc_profile set. # Tests saving TIFF with icc_profile set.
@ -558,7 +564,7 @@ class TestFileTiff(PillowTestCase):
tmpfile = self.tempfile("temp.tif") tmpfile = self.tempfile("temp.tif")
im.save(tmpfile, "TIFF", compression="raw") im.save(tmpfile, "TIFF", compression="raw")
with Image.open(tmpfile) as reloaded: with Image.open(tmpfile) as reloaded:
self.assertEqual(b"Dummy value", reloaded.info["icc_profile"]) assert b"Dummy value" == reloaded.info["icc_profile"]
def test_close_on_load_exclusive(self): def test_close_on_load_exclusive(self):
# similar to test_fd_leak, but runs on unixlike os # similar to test_fd_leak, but runs on unixlike os
@ -569,9 +575,9 @@ class TestFileTiff(PillowTestCase):
im = Image.open(tmpfile) im = Image.open(tmpfile)
fp = im.fp fp = im.fp
self.assertFalse(fp.closed) assert not fp.closed
im.load() im.load()
self.assertTrue(fp.closed) assert fp.closed
def test_close_on_load_nonexclusive(self): def test_close_on_load_nonexclusive(self):
tmpfile = self.tempfile("temp.tif") tmpfile = self.tempfile("temp.tif")
@ -582,16 +588,16 @@ class TestFileTiff(PillowTestCase):
with open(tmpfile, "rb") as f: with open(tmpfile, "rb") as f:
im = Image.open(f) im = Image.open(f)
fp = im.fp fp = im.fp
self.assertFalse(fp.closed) assert not fp.closed
im.load() im.load()
self.assertFalse(fp.closed) assert not fp.closed
# Ignore this UserWarning which triggers for four tags: # Ignore this UserWarning which triggers for four tags:
# "Possibly corrupt EXIF data. Expecting to read 50404352 bytes but..." # "Possibly corrupt EXIF data. Expecting to read 50404352 bytes but..."
@pytest.mark.filterwarnings("ignore:Possibly corrupt EXIF data") @pytest.mark.filterwarnings("ignore:Possibly corrupt EXIF data")
def test_string_dimension(self): def test_string_dimension(self):
# Assert that an error is raised if one of the dimensions is a string # Assert that an error is raised if one of the dimensions is a string
with self.assertRaises(ValueError): with pytest.raises(ValueError):
Image.open("Tests/images/string_dimension.tiff") Image.open("Tests/images/string_dimension.tiff")
@ -606,10 +612,11 @@ class TestFileTiffW32(PillowTestCase):
im = Image.open(tmpfile) im = Image.open(tmpfile)
fp = im.fp fp = im.fp
self.assertFalse(fp.closed) assert not fp.closed
self.assertRaises(WindowsError, os.remove, tmpfile) with pytest.raises(WindowsError):
os.remove(tmpfile)
im.load() im.load()
self.assertTrue(fp.closed) assert fp.closed
# this closes the mmap # this closes the mmap
im.close() im.close()

View File

@ -55,14 +55,14 @@ class TestFileTiffMetadata(PillowTestCase):
with Image.open(f) as loaded: with Image.open(f) as loaded:
self.assertEqual(loaded.tag[ImageJMetaDataByteCounts], (len(bindata),)) assert loaded.tag[ImageJMetaDataByteCounts] == (len(bindata),)
self.assertEqual(loaded.tag_v2[ImageJMetaDataByteCounts], (len(bindata),)) assert loaded.tag_v2[ImageJMetaDataByteCounts] == (len(bindata),)
self.assertEqual(loaded.tag[ImageJMetaData], bindata) assert loaded.tag[ImageJMetaData] == bindata
self.assertEqual(loaded.tag_v2[ImageJMetaData], bindata) assert loaded.tag_v2[ImageJMetaData] == bindata
self.assertEqual(loaded.tag[ImageDescription], (reloaded_textdata,)) assert loaded.tag[ImageDescription] == (reloaded_textdata,)
self.assertEqual(loaded.tag_v2[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]
self.assertAlmostEqual(loaded_float, floatdata, places=5) self.assertAlmostEqual(loaded_float, floatdata, places=5)
@ -75,59 +75,49 @@ class TestFileTiffMetadata(PillowTestCase):
img.save(f, tiffinfo=info) img.save(f, tiffinfo=info)
with Image.open(f) as loaded: with Image.open(f) as loaded:
self.assertEqual( assert loaded.tag[ImageJMetaDataByteCounts] == (8, len(bindata) - 8)
loaded.tag[ImageJMetaDataByteCounts], (8, len(bindata) - 8) assert loaded.tag_v2[ImageJMetaDataByteCounts] == (8, len(bindata) - 8)
)
self.assertEqual(
loaded.tag_v2[ImageJMetaDataByteCounts], (8, len(bindata) - 8)
)
def test_read_metadata(self): def test_read_metadata(self):
with Image.open("Tests/images/hopper_g4.tif") as img: with Image.open("Tests/images/hopper_g4.tif") as img:
self.assertEqual( assert {
{ "YResolution": IFDRational(4294967295, 113653537),
"YResolution": IFDRational(4294967295, 113653537), "PlanarConfiguration": 1,
"PlanarConfiguration": 1, "BitsPerSample": (1,),
"BitsPerSample": (1,), "ImageLength": 128,
"ImageLength": 128, "Compression": 4,
"Compression": 4, "FillOrder": 1,
"FillOrder": 1, "RowsPerStrip": 128,
"RowsPerStrip": 128, "ResolutionUnit": 3,
"ResolutionUnit": 3, "PhotometricInterpretation": 0,
"PhotometricInterpretation": 0, "PageNumber": (0, 1),
"PageNumber": (0, 1), "XResolution": IFDRational(4294967295, 113653537),
"XResolution": IFDRational(4294967295, 113653537), "ImageWidth": 128,
"ImageWidth": 128, "Orientation": 1,
"Orientation": 1, "StripByteCounts": (1968,),
"StripByteCounts": (1968,), "SamplesPerPixel": 1,
"SamplesPerPixel": 1, "StripOffsets": (8,),
"StripOffsets": (8,), } == img.tag_v2.named()
},
img.tag_v2.named(),
)
self.assertEqual( assert {
{ "YResolution": ((4294967295, 113653537),),
"YResolution": ((4294967295, 113653537),), "PlanarConfiguration": (1,),
"PlanarConfiguration": (1,), "BitsPerSample": (1,),
"BitsPerSample": (1,), "ImageLength": (128,),
"ImageLength": (128,), "Compression": (4,),
"Compression": (4,), "FillOrder": (1,),
"FillOrder": (1,), "RowsPerStrip": (128,),
"RowsPerStrip": (128,), "ResolutionUnit": (3,),
"ResolutionUnit": (3,), "PhotometricInterpretation": (0,),
"PhotometricInterpretation": (0,), "PageNumber": (0, 1),
"PageNumber": (0, 1), "XResolution": ((4294967295, 113653537),),
"XResolution": ((4294967295, 113653537),), "ImageWidth": (128,),
"ImageWidth": (128,), "Orientation": (1,),
"Orientation": (1,), "StripByteCounts": (1968,),
"StripByteCounts": (1968,), "SamplesPerPixel": (1,),
"SamplesPerPixel": (1,), "StripOffsets": (8,),
"StripOffsets": (8,), } == img.tag.named()
},
img.tag.named(),
)
def test_write_metadata(self): def test_write_metadata(self):
""" Test metadata writing through the python code """ """ Test metadata writing through the python code """
@ -156,19 +146,17 @@ class TestFileTiffMetadata(PillowTestCase):
"{} didn't roundtrip, {}, {}".format(tag, original[tag], value), "{} didn't roundtrip, {}, {}".format(tag, original[tag], value),
) )
else: else:
self.assertEqual( assert original[tag] == value, "{} didn't roundtrip, {}, {}".format(
original[tag], tag, original[tag], value
value,
"{} didn't roundtrip, {}, {}".format(tag, original[tag], value),
) )
for tag, value in original.items(): for tag, value in original.items():
if tag not in ignored: if tag not in ignored:
self.assertEqual(value, reloaded[tag], "%s didn't roundtrip" % tag) assert value == reloaded[tag], "%s didn't roundtrip" % tag
def test_no_duplicate_50741_tag(self): def test_no_duplicate_50741_tag(self):
self.assertEqual(tag_ids["MakerNoteSafety"], 50741) assert tag_ids["MakerNoteSafety"] == 50741
self.assertEqual(tag_ids["BestQualityScale"], 50780) assert tag_ids["BestQualityScale"] == 50780
def test_empty_metadata(self): def test_empty_metadata(self):
f = io.BytesIO(b"II*\x00\x08\x00\x00\x00") f = io.BytesIO(b"II*\x00\x08\x00\x00\x00")
@ -184,8 +172,8 @@ class TestFileTiffMetadata(PillowTestCase):
im.save(out) im.save(out)
with Image.open(out) as reloaded: with Image.open(out) as reloaded:
self.assertNotIsInstance(im.info["icc_profile"], tuple) assert not isinstance(im.info["icc_profile"], tuple)
self.assertEqual(im.info["icc_profile"], reloaded.info["icc_profile"]) assert im.info["icc_profile"] == reloaded.info["icc_profile"]
def test_iccprofile_binary(self): def test_iccprofile_binary(self):
# https://github.com/python-pillow/Pillow/issues/1526 # https://github.com/python-pillow/Pillow/issues/1526
@ -193,8 +181,8 @@ class TestFileTiffMetadata(PillowTestCase):
# but probably won't be able to save it. # but probably won't be able to save it.
with Image.open("Tests/images/hopper.iccprofile_binary.tif") as im: with Image.open("Tests/images/hopper.iccprofile_binary.tif") as im:
self.assertEqual(im.tag_v2.tagtype[34675], 1) assert im.tag_v2.tagtype[34675] == 1
self.assertTrue(im.info["icc_profile"]) assert im.info["icc_profile"]
def test_iccprofile_save_png(self): def test_iccprofile_save_png(self):
with Image.open("Tests/images/hopper.iccprofile.tif") as im: with Image.open("Tests/images/hopper.iccprofile.tif") as im:
@ -215,8 +203,8 @@ class TestFileTiffMetadata(PillowTestCase):
im.save(out, tiffinfo=info, compression="raw") im.save(out, tiffinfo=info, compression="raw")
with Image.open(out) as reloaded: with Image.open(out) as reloaded:
self.assertEqual(0, reloaded.tag_v2[41988].numerator) assert 0 == reloaded.tag_v2[41988].numerator
self.assertEqual(0, reloaded.tag_v2[41988].denominator) assert 0 == reloaded.tag_v2[41988].denominator
def test_ifd_unsigned_rational(self): def test_ifd_unsigned_rational(self):
im = hopper() im = hopper()
@ -233,8 +221,8 @@ class TestFileTiffMetadata(PillowTestCase):
im.save(out, tiffinfo=info, compression="raw") im.save(out, tiffinfo=info, compression="raw")
with Image.open(out) as reloaded: with Image.open(out) as reloaded:
self.assertEqual(max_long, reloaded.tag_v2[41493].numerator) assert max_long == reloaded.tag_v2[41493].numerator
self.assertEqual(1, reloaded.tag_v2[41493].denominator) assert 1 == reloaded.tag_v2[41493].denominator
# out of bounds of 4 byte unsigned long # out of bounds of 4 byte unsigned long
numerator = max_long + 1 numerator = max_long + 1
@ -245,8 +233,8 @@ class TestFileTiffMetadata(PillowTestCase):
im.save(out, tiffinfo=info, compression="raw") im.save(out, tiffinfo=info, compression="raw")
with Image.open(out) as reloaded: with Image.open(out) as reloaded:
self.assertEqual(max_long, reloaded.tag_v2[41493].numerator) assert max_long == reloaded.tag_v2[41493].numerator
self.assertEqual(1, reloaded.tag_v2[41493].denominator) assert 1 == reloaded.tag_v2[41493].denominator
def test_ifd_signed_rational(self): def test_ifd_signed_rational(self):
im = hopper() im = hopper()
@ -262,8 +250,8 @@ class TestFileTiffMetadata(PillowTestCase):
im.save(out, tiffinfo=info, compression="raw") im.save(out, tiffinfo=info, compression="raw")
with Image.open(out) as reloaded: with Image.open(out) as reloaded:
self.assertEqual(numerator, reloaded.tag_v2[37380].numerator) assert numerator == reloaded.tag_v2[37380].numerator
self.assertEqual(denominator, reloaded.tag_v2[37380].denominator) assert denominator == reloaded.tag_v2[37380].denominator
numerator = -(2 ** 31) numerator = -(2 ** 31)
denominator = 2 ** 31 - 1 denominator = 2 ** 31 - 1
@ -274,8 +262,8 @@ class TestFileTiffMetadata(PillowTestCase):
im.save(out, tiffinfo=info, compression="raw") im.save(out, tiffinfo=info, compression="raw")
with Image.open(out) as reloaded: with Image.open(out) as reloaded:
self.assertEqual(numerator, reloaded.tag_v2[37380].numerator) assert numerator == reloaded.tag_v2[37380].numerator
self.assertEqual(denominator, reloaded.tag_v2[37380].denominator) assert denominator == reloaded.tag_v2[37380].denominator
# out of bounds of 4 byte signed long # out of bounds of 4 byte signed long
numerator = -(2 ** 31) - 1 numerator = -(2 ** 31) - 1
@ -287,8 +275,8 @@ class TestFileTiffMetadata(PillowTestCase):
im.save(out, tiffinfo=info, compression="raw") im.save(out, tiffinfo=info, compression="raw")
with Image.open(out) as reloaded: with Image.open(out) as reloaded:
self.assertEqual(2 ** 31 - 1, reloaded.tag_v2[37380].numerator) assert 2 ** 31 - 1 == reloaded.tag_v2[37380].numerator
self.assertEqual(-1, reloaded.tag_v2[37380].denominator) assert -1 == reloaded.tag_v2[37380].denominator
def test_ifd_signed_long(self): def test_ifd_signed_long(self):
im = hopper() im = hopper()
@ -300,7 +288,7 @@ class TestFileTiffMetadata(PillowTestCase):
im.save(out, tiffinfo=info, compression="raw") im.save(out, tiffinfo=info, compression="raw")
with Image.open(out) as reloaded: with Image.open(out) as reloaded:
self.assertEqual(reloaded.tag_v2[37000], -60000) assert reloaded.tag_v2[37000] == -60000
def test_empty_values(self): def test_empty_values(self):
data = io.BytesIO( data = io.BytesIO(
@ -314,17 +302,17 @@ class TestFileTiffMetadata(PillowTestCase):
info.load(data) info.load(data)
# Should not raise ValueError. # Should not raise ValueError.
info = dict(info) info = dict(info)
self.assertIn(33432, info) assert 33432 in info
def test_PhotoshopInfo(self): def test_PhotoshopInfo(self):
with Image.open("Tests/images/issue_2278.tif") as im: with Image.open("Tests/images/issue_2278.tif") as im:
self.assertEqual(len(im.tag_v2[34377]), 1) assert len(im.tag_v2[34377]) == 1
self.assertIsInstance(im.tag_v2[34377][0], bytes) assert isinstance(im.tag_v2[34377][0], bytes)
out = self.tempfile("temp.tiff") out = self.tempfile("temp.tiff")
im.save(out) im.save(out)
with Image.open(out) as reloaded: with Image.open(out) as reloaded:
self.assertEqual(len(reloaded.tag_v2[34377]), 1) assert len(reloaded.tag_v2[34377]) == 1
self.assertIsInstance(reloaded.tag_v2[34377][0], bytes) assert isinstance(reloaded.tag_v2[34377][0], bytes)
def test_too_many_entries(self): def test_too_many_entries(self):
ifd = TiffImagePlugin.ImageFileDirectory_v2() ifd = TiffImagePlugin.ImageFileDirectory_v2()

View File

@ -47,9 +47,9 @@ class TestFileWebp(PillowTestCase):
""" """
with Image.open("Tests/images/hopper.webp") as image: with Image.open("Tests/images/hopper.webp") as image:
self.assertEqual(image.mode, self.rgb_mode) assert image.mode == self.rgb_mode
self.assertEqual(image.size, (128, 128)) assert image.size == (128, 128)
self.assertEqual(image.format, "WEBP") assert image.format == "WEBP"
image.load() image.load()
image.getdata() image.getdata()
@ -67,9 +67,9 @@ class TestFileWebp(PillowTestCase):
hopper(self.rgb_mode).save(temp_file) hopper(self.rgb_mode).save(temp_file)
with Image.open(temp_file) as image: with Image.open(temp_file) as image:
self.assertEqual(image.mode, self.rgb_mode) assert image.mode == self.rgb_mode
self.assertEqual(image.size, (128, 128)) assert image.size == (128, 128)
self.assertEqual(image.format, "WEBP") assert image.format == "WEBP"
image.load() image.load()
image.getdata() image.getdata()
@ -95,9 +95,9 @@ class TestFileWebp(PillowTestCase):
temp_file = self.tempfile("temp.webp") temp_file = self.tempfile("temp.webp")
hopper("L").save(temp_file) hopper("L").save(temp_file)
with Image.open(temp_file) as image: with Image.open(temp_file) as image:
self.assertEqual(image.mode, self.rgb_mode) assert image.mode == self.rgb_mode
self.assertEqual(image.size, (128, 128)) assert image.size == (128, 128)
self.assertEqual(image.format, "WEBP") assert image.format == "WEBP"
image.load() image.load()
image.getdata() image.getdata()
@ -114,9 +114,9 @@ class TestFileWebp(PillowTestCase):
temp_file = self.tempfile("temp.webp") temp_file = self.tempfile("temp.webp")
hopper("P").save(temp_file) hopper("P").save(temp_file)
with Image.open(temp_file) as image: with Image.open(temp_file) as image:
self.assertEqual(image.mode, self.rgb_mode) assert image.mode == self.rgb_mode
self.assertEqual(image.size, (128, 128)) assert image.size == (128, 128)
self.assertEqual(image.format, "WEBP") assert image.format == "WEBP"
image.load() image.load()
image.getdata() image.getdata()
@ -130,8 +130,10 @@ class TestFileWebp(PillowTestCase):
""" """
if _webp.HAVE_WEBPANIM: if _webp.HAVE_WEBPANIM:
self.assertRaises(TypeError, _webp.WebPAnimEncoder) with pytest.raises(TypeError):
self.assertRaises(TypeError, _webp.WebPEncode) _webp.WebPAnimEncoder()
with pytest.raises(TypeError):
_webp.WebPEncode()
def test_WebPDecode_with_invalid_args(self): def test_WebPDecode_with_invalid_args(self):
""" """
@ -139,8 +141,10 @@ class TestFileWebp(PillowTestCase):
""" """
if _webp.HAVE_WEBPANIM: if _webp.HAVE_WEBPANIM:
self.assertRaises(TypeError, _webp.WebPAnimDecoder) with pytest.raises(TypeError):
self.assertRaises(TypeError, _webp.WebPDecode) _webp.WebPAnimDecoder()
with pytest.raises(TypeError):
_webp.WebPDecode()
def test_no_resource_warning(self): def test_no_resource_warning(self):
file_path = "Tests/images/hopper.webp" file_path = "Tests/images/hopper.webp"
@ -173,4 +177,4 @@ class TestFileWebp(PillowTestCase):
difference = sum( difference = sum(
[abs(original_value[i] - reread_value[i]) for i in range(0, 3)] [abs(original_value[i] - reread_value[i]) for i in range(0, 3)]
) )
self.assertLess(difference, 5) assert difference < 5

View File

@ -1,3 +1,4 @@
import pytest
from PIL import Image, WmfImagePlugin from PIL import Image, WmfImagePlugin
from .helper import PillowTestCase, assert_image_similar, hopper from .helper import PillowTestCase, assert_image_similar, hopper
@ -39,7 +40,7 @@ class TestFileWmf(PillowTestCase):
im = hopper() im = hopper()
tmpfile = self.tempfile("temp.wmf") tmpfile = self.tempfile("temp.wmf")
im.save(tmpfile) im.save(tmpfile)
self.assertTrue(handler.methodCalled) assert handler.methodCalled
# Restore the state before this test # Restore the state before this test
WmfImagePlugin.register_handler(None) WmfImagePlugin.register_handler(None)
@ -47,19 +48,19 @@ class TestFileWmf(PillowTestCase):
def test_load_dpi_rounding(self): def test_load_dpi_rounding(self):
# Round up # Round up
with Image.open("Tests/images/drawing.emf") as im: with Image.open("Tests/images/drawing.emf") as im:
self.assertEqual(im.info["dpi"], 1424) assert im.info["dpi"] == 1424
# Round down # Round down
with Image.open("Tests/images/drawing_roundDown.emf") as im: with Image.open("Tests/images/drawing_roundDown.emf") as im:
self.assertEqual(im.info["dpi"], 1426) assert im.info["dpi"] == 1426
def test_load_set_dpi(self): def test_load_set_dpi(self):
with Image.open("Tests/images/drawing.wmf") as im: with Image.open("Tests/images/drawing.wmf") as im:
self.assertEqual(im.size, (82, 82)) assert im.size == (82, 82)
if hasattr(Image.core, "drawwmf"): if hasattr(Image.core, "drawwmf"):
im.load(144) im.load(144)
self.assertEqual(im.size, (164, 164)) assert im.size == (164, 164)
with Image.open("Tests/images/drawing_wmf_ref_144.png") as expected: with Image.open("Tests/images/drawing_wmf_ref_144.png") as expected:
assert_image_similar(im, expected, 2.0) assert_image_similar(im, expected, 2.0)
@ -69,4 +70,5 @@ class TestFileWmf(PillowTestCase):
for ext in [".wmf", ".emf"]: for ext in [".wmf", ".emf"]:
tmpfile = self.tempfile("temp" + ext) tmpfile = self.tempfile("temp" + ext)
self.assertRaises(IOError, im.save, tmpfile) with pytest.raises(IOError):
im.save(tmpfile)

View File

@ -1,3 +1,4 @@
import pytest
from PIL import FontFile, Image, ImageDraw, ImageFont, PcfFontFile from PIL import FontFile, Image, ImageDraw, ImageFont, PcfFontFile
from .helper import ( from .helper import (
@ -17,9 +18,9 @@ class TestFontPcf(PillowTestCase):
def save_font(self): def save_font(self):
with open(fontname, "rb") as test_file: with open(fontname, "rb") as test_file:
font = PcfFontFile.PcfFontFile(test_file) font = PcfFontFile.PcfFontFile(test_file)
self.assertIsInstance(font, FontFile.FontFile) assert isinstance(font, FontFile.FontFile)
# check the number of characters in the font # check the number of characters in the font
self.assertEqual(len([_f for _f in font.glyph if _f]), 223) assert len([_f for _f in font.glyph if _f]) == 223
tempname = self.tempfile("temp.pil") tempname = self.tempfile("temp.pil")
self.addCleanup(self.delete_tempfile, tempname[:-4] + ".pbm") self.addCleanup(self.delete_tempfile, tempname[:-4] + ".pbm")
@ -31,7 +32,7 @@ class TestFontPcf(PillowTestCase):
with open(tempname, "rb") as f_loaded: with open(tempname, "rb") as f_loaded:
with open("Tests/fonts/10x20.pil", "rb") as f_target: with open("Tests/fonts/10x20.pil", "rb") as f_target:
self.assertEqual(f_loaded.read(), f_target.read()) assert f_loaded.read() == f_target.read()
return tempname return tempname
def test_sanity(self): def test_sanity(self):
@ -39,7 +40,8 @@ class TestFontPcf(PillowTestCase):
def test_invalid_file(self): def test_invalid_file(self):
with open("Tests/images/flower.jpg", "rb") as fp: with open("Tests/images/flower.jpg", "rb") as fp:
self.assertRaises(SyntaxError, PcfFontFile.PcfFontFile, fp) with pytest.raises(SyntaxError):
PcfFontFile.PcfFontFile(fp)
def test_draw(self): def test_draw(self):
tempname = self.save_font() tempname = self.save_font()
@ -55,11 +57,11 @@ class TestFontPcf(PillowTestCase):
font = ImageFont.load(tempname) font = ImageFont.load(tempname)
for i in range(255): for i in range(255):
(dx, dy) = font.getsize(chr(i)) (dx, dy) = font.getsize(chr(i))
self.assertEqual(dy, 20) assert dy == 20
self.assertIn(dx, (0, 10)) assert dx in (0, 10)
for l in range(len(message)): for l in range(len(message)):
msg = message[: l + 1] msg = message[: l + 1]
self.assertEqual(font.getsize(msg), (len(msg) * 10, 20)) assert font.getsize(msg) == (len(msg) * 10, 20)
def _test_high_characters(self, message): def _test_high_characters(self, message):
tempname = self.save_font() tempname = self.save_font()

View File

@ -53,66 +53,72 @@ class TestImage(PillowTestCase):
"BGR;24", "BGR;24",
"BGR;32", "BGR;32",
]: ]:
with self.assertRaises(ValueError) as e: with pytest.raises(ValueError) as e:
Image.new(mode, (1, 1)) Image.new(mode, (1, 1))
self.assertEqual(str(e.exception), "unrecognized image mode") assert str(e.value) == "unrecognized image mode"
def test_exception_inheritance(self): def test_exception_inheritance(self):
self.assertTrue(issubclass(UnidentifiedImageError, IOError)) assert issubclass(UnidentifiedImageError, IOError)
def test_sanity(self): def test_sanity(self):
im = Image.new("L", (100, 100)) im = Image.new("L", (100, 100))
self.assertEqual(repr(im)[:45], "<PIL.Image.Image image mode=L size=100x100 at") assert repr(im)[:45] == "<PIL.Image.Image image mode=L size=100x100 at"
self.assertEqual(im.mode, "L") assert im.mode == "L"
self.assertEqual(im.size, (100, 100)) assert im.size == (100, 100)
im = Image.new("RGB", (100, 100)) im = Image.new("RGB", (100, 100))
self.assertEqual(repr(im)[:45], "<PIL.Image.Image image mode=RGB size=100x100 ") assert repr(im)[:45] == "<PIL.Image.Image image mode=RGB size=100x100 "
self.assertEqual(im.mode, "RGB") assert im.mode == "RGB"
self.assertEqual(im.size, (100, 100)) assert im.size == (100, 100)
Image.new("L", (100, 100), None) Image.new("L", (100, 100), None)
im2 = Image.new("L", (100, 100), 0) im2 = Image.new("L", (100, 100), 0)
im3 = Image.new("L", (100, 100), "black") im3 = Image.new("L", (100, 100), "black")
self.assertEqual(im2.getcolors(), [(10000, 0)]) assert im2.getcolors() == [(10000, 0)]
self.assertEqual(im3.getcolors(), [(10000, 0)]) assert im3.getcolors() == [(10000, 0)]
self.assertRaises(ValueError, Image.new, "X", (100, 100)) with pytest.raises(ValueError):
self.assertRaises(ValueError, Image.new, "", (100, 100)) Image.new("X", (100, 100))
# self.assertRaises(MemoryError, Image.new, "L", (1000000, 1000000)) with pytest.raises(ValueError):
Image.new("", (100, 100))
# with pytest.raises(MemoryError):
# Image.new("L", (1000000, 1000000))
def test_width_height(self): def test_width_height(self):
im = Image.new("RGB", (1, 2)) im = Image.new("RGB", (1, 2))
self.assertEqual(im.width, 1) assert im.width == 1
self.assertEqual(im.height, 2) assert im.height == 2
with self.assertRaises(AttributeError): with pytest.raises(AttributeError):
im.size = (3, 4) im.size = (3, 4)
def test_invalid_image(self): def test_invalid_image(self):
import io import io
im = io.BytesIO(b"") im = io.BytesIO(b"")
self.assertRaises(UnidentifiedImageError, Image.open, im) with pytest.raises(UnidentifiedImageError):
Image.open(im)
def test_bad_mode(self): def test_bad_mode(self):
self.assertRaises(ValueError, Image.open, "filename", "bad mode") with pytest.raises(ValueError):
Image.open("filename", "bad mode")
def test_stringio(self): def test_stringio(self):
self.assertRaises(ValueError, Image.open, io.StringIO()) with pytest.raises(ValueError):
Image.open(io.StringIO())
def test_pathlib(self): def test_pathlib(self):
from PIL.Image import Path from PIL.Image import Path
with Image.open(Path("Tests/images/multipage-mmap.tiff")) as im: with Image.open(Path("Tests/images/multipage-mmap.tiff")) as im:
self.assertEqual(im.mode, "P") assert im.mode == "P"
self.assertEqual(im.size, (10, 10)) assert im.size == (10, 10)
with Image.open(Path("Tests/images/hopper.jpg")) as im: with Image.open(Path("Tests/images/hopper.jpg")) as im:
self.assertEqual(im.mode, "RGB") assert im.mode == "RGB"
self.assertEqual(im.size, (128, 128)) assert im.size == (128, 128)
temp_file = self.tempfile("temp.jpg") temp_file = self.tempfile("temp.jpg")
if os.path.exists(temp_file): if os.path.exists(temp_file):
@ -145,17 +151,18 @@ class TestImage(PillowTestCase):
def test_unknown_extension(self): def test_unknown_extension(self):
im = hopper() im = hopper()
temp_file = self.tempfile("temp.unknown") temp_file = self.tempfile("temp.unknown")
self.assertRaises(ValueError, im.save, temp_file) with pytest.raises(ValueError):
im.save(temp_file)
def test_internals(self): def test_internals(self):
im = Image.new("L", (100, 100)) im = Image.new("L", (100, 100))
im.readonly = 1 im.readonly = 1
im._copy() im._copy()
self.assertFalse(im.readonly) assert not im.readonly
im.readonly = 1 im.readonly = 1
im.paste(0, (0, 0, 100, 100)) im.paste(0, (0, 0, 100, 100))
self.assertFalse(im.readonly) assert not im.readonly
@unittest.skipIf(is_win32(), "Test requires opening tempfile twice") @unittest.skipIf(is_win32(), "Test requires opening tempfile twice")
def test_readonly_save(self): def test_readonly_save(self):
@ -163,7 +170,7 @@ class TestImage(PillowTestCase):
shutil.copy("Tests/images/rgb32bf-rgba.bmp", temp_file) shutil.copy("Tests/images/rgb32bf-rgba.bmp", temp_file)
with Image.open(temp_file) as im: with Image.open(temp_file) as im:
self.assertTrue(im.readonly) assert im.readonly
im.save(temp_file) im.save(temp_file)
def test_dump(self): def test_dump(self):
@ -174,7 +181,8 @@ class TestImage(PillowTestCase):
im._dump(self.tempfile("temp_RGB.ppm")) im._dump(self.tempfile("temp_RGB.ppm"))
im = Image.new("HSV", (10, 10)) im = Image.new("HSV", (10, 10))
self.assertRaises(ValueError, im._dump, self.tempfile("temp_HSV.ppm")) with pytest.raises(ValueError):
im._dump(self.tempfile("temp_HSV.ppm"))
def test_comparison_with_other_type(self): def test_comparison_with_other_type(self):
# Arrange # Arrange
@ -183,8 +191,8 @@ class TestImage(PillowTestCase):
# Act/Assert # Act/Assert
# Shouldn't cause AttributeError (#774) # Shouldn't cause AttributeError (#774)
self.assertFalse(item is None) assert item is not None
self.assertFalse(item == num) assert item != num
def test_expand_x(self): def test_expand_x(self):
# Arrange # Arrange
@ -196,8 +204,8 @@ class TestImage(PillowTestCase):
im = im._expand(xmargin) im = im._expand(xmargin)
# Assert # Assert
self.assertEqual(im.size[0], orig_size[0] + 2 * xmargin) assert im.size[0] == orig_size[0] + 2 * xmargin
self.assertEqual(im.size[1], orig_size[1] + 2 * xmargin) assert im.size[1] == orig_size[1] + 2 * xmargin
def test_expand_xy(self): def test_expand_xy(self):
# Arrange # Arrange
@ -210,21 +218,25 @@ class TestImage(PillowTestCase):
im = im._expand(xmargin, ymargin) im = im._expand(xmargin, ymargin)
# Assert # Assert
self.assertEqual(im.size[0], orig_size[0] + 2 * xmargin) assert im.size[0] == orig_size[0] + 2 * xmargin
self.assertEqual(im.size[1], orig_size[1] + 2 * ymargin) assert im.size[1] == orig_size[1] + 2 * ymargin
def test_getbands(self): def test_getbands(self):
# Assert # Assert
self.assertEqual(hopper("RGB").getbands(), ("R", "G", "B")) assert hopper("RGB").getbands() == ("R", "G", "B")
self.assertEqual(hopper("YCbCr").getbands(), ("Y", "Cb", "Cr")) assert hopper("YCbCr").getbands() == ("Y", "Cb", "Cr")
def test_getchannel_wrong_params(self): def test_getchannel_wrong_params(self):
im = hopper() im = hopper()
self.assertRaises(ValueError, im.getchannel, -1) with pytest.raises(ValueError):
self.assertRaises(ValueError, im.getchannel, 3) im.getchannel(-1)
self.assertRaises(ValueError, im.getchannel, "Z") with pytest.raises(ValueError):
self.assertRaises(ValueError, im.getchannel, "1") im.getchannel(3)
with pytest.raises(ValueError):
im.getchannel("Z")
with pytest.raises(ValueError):
im.getchannel("1")
def test_getchannel(self): def test_getchannel(self):
im = hopper("YCbCr") im = hopper("YCbCr")
@ -245,7 +257,7 @@ class TestImage(PillowTestCase):
bbox = im.getbbox() bbox = im.getbbox()
# Assert # Assert
self.assertEqual(bbox, (0, 0, 128, 128)) assert bbox == (0, 0, 128, 128)
def test_ne(self): def test_ne(self):
# Arrange # Arrange
@ -253,7 +265,7 @@ class TestImage(PillowTestCase):
im2 = Image.new("RGB", (25, 25), "white") im2 = Image.new("RGB", (25, 25), "white")
# Act / Assert # Act / Assert
self.assertNotEqual(im1, im2) assert im1 != im2
def test_alpha_composite(self): def test_alpha_composite(self):
# https://stackoverflow.com/questions/3374878 # https://stackoverflow.com/questions/3374878
@ -284,7 +296,7 @@ class TestImage(PillowTestCase):
# Assert # Assert
img_colors = sorted(img.getcolors()) img_colors = sorted(img.getcolors())
self.assertEqual(img_colors, expected_colors) assert img_colors == expected_colors
def test_alpha_inplace(self): def test_alpha_inplace(self):
src = Image.new("RGBA", (128, 128), "blue") src = Image.new("RGBA", (128, 128), "blue")
@ -304,31 +316,35 @@ class TestImage(PillowTestCase):
offset = src.copy() offset = src.copy()
offset.alpha_composite(over, (64, 64)) offset.alpha_composite(over, (64, 64))
assert_image_equal(offset.crop((64, 64, 127, 127)), target.crop((0, 0, 63, 63))) assert_image_equal(offset.crop((64, 64, 127, 127)), target.crop((0, 0, 63, 63)))
self.assertEqual(offset.size, (128, 128)) assert offset.size == (128, 128)
# offset and crop # offset and crop
box = src.copy() box = src.copy()
box.alpha_composite(over, (64, 64), (0, 0, 32, 32)) box.alpha_composite(over, (64, 64), (0, 0, 32, 32))
assert_image_equal(box.crop((64, 64, 96, 96)), target.crop((0, 0, 32, 32))) assert_image_equal(box.crop((64, 64, 96, 96)), target.crop((0, 0, 32, 32)))
assert_image_equal(box.crop((96, 96, 128, 128)), src.crop((0, 0, 32, 32))) assert_image_equal(box.crop((96, 96, 128, 128)), src.crop((0, 0, 32, 32)))
self.assertEqual(box.size, (128, 128)) assert box.size == (128, 128)
# source point # source point
source = src.copy() source = src.copy()
source.alpha_composite(over, (32, 32), (32, 32, 96, 96)) source.alpha_composite(over, (32, 32), (32, 32, 96, 96))
assert_image_equal(source.crop((32, 32, 96, 96)), target.crop((32, 32, 96, 96))) assert_image_equal(source.crop((32, 32, 96, 96)), target.crop((32, 32, 96, 96)))
self.assertEqual(source.size, (128, 128)) assert source.size == (128, 128)
# errors # errors
self.assertRaises(ValueError, source.alpha_composite, over, "invalid source") with pytest.raises(ValueError):
self.assertRaises( source.alpha_composite(over, "invalid source")
ValueError, source.alpha_composite, over, (0, 0), "invalid destination" with pytest.raises(ValueError):
) source.alpha_composite(over, (0, 0), "invalid destination")
self.assertRaises(ValueError, source.alpha_composite, over, 0) with pytest.raises(ValueError):
self.assertRaises(ValueError, source.alpha_composite, over, (0, 0), 0) source.alpha_composite(over, 0)
self.assertRaises(ValueError, source.alpha_composite, over, (0, -1)) with pytest.raises(ValueError):
self.assertRaises(ValueError, source.alpha_composite, over, (0, 0), (0, -1)) source.alpha_composite(over, (0, 0), 0)
with pytest.raises(ValueError):
source.alpha_composite(over, (0, -1))
with pytest.raises(ValueError):
source.alpha_composite(over, (0, 0), (0, -1))
def test_registered_extensions_uninitialized(self): def test_registered_extensions_uninitialized(self):
# Arrange # Arrange
@ -340,11 +356,11 @@ class TestImage(PillowTestCase):
Image.registered_extensions() Image.registered_extensions()
# Assert # Assert
self.assertEqual(Image._initialized, 2) assert Image._initialized == 2
# Restore the original state and assert # Restore the original state and assert
Image.EXTENSION = extension Image.EXTENSION = extension
self.assertTrue(Image.EXTENSION) assert Image.EXTENSION
def test_registered_extensions(self): def test_registered_extensions(self):
# Arrange # Arrange
@ -356,9 +372,9 @@ class TestImage(PillowTestCase):
extensions = Image.registered_extensions() extensions = Image.registered_extensions()
# Assert # Assert
self.assertTrue(extensions) assert extensions
for ext in [".cur", ".icns", ".tif", ".tiff"]: for ext in [".cur", ".icns", ".tif", ".tiff"]:
self.assertIn(ext, extensions) assert ext in extensions
def test_effect_mandelbrot(self): def test_effect_mandelbrot(self):
# Arrange # Arrange
@ -370,7 +386,7 @@ class TestImage(PillowTestCase):
im = Image.effect_mandelbrot(size, extent, quality) im = Image.effect_mandelbrot(size, extent, quality)
# Assert # Assert
self.assertEqual(im.size, (512, 512)) assert im.size == (512, 512)
with Image.open("Tests/images/effect_mandelbrot.png") as im2: with Image.open("Tests/images/effect_mandelbrot.png") as im2:
assert_image_equal(im, im2) assert_image_equal(im, im2)
@ -383,7 +399,8 @@ class TestImage(PillowTestCase):
quality = 1 quality = 1
# Act/Assert # Act/Assert
self.assertRaises(ValueError, Image.effect_mandelbrot, size, extent, quality) with pytest.raises(ValueError):
Image.effect_mandelbrot(size, extent, quality)
def test_effect_noise(self): def test_effect_noise(self):
# Arrange # Arrange
@ -394,8 +411,8 @@ class TestImage(PillowTestCase):
im = Image.effect_noise(size, sigma) im = Image.effect_noise(size, sigma)
# Assert # Assert
self.assertEqual(im.size, (100, 100)) assert im.size == (100, 100)
self.assertEqual(im.mode, "L") assert im.mode == "L"
p0 = im.getpixel((0, 0)) p0 = im.getpixel((0, 0))
p1 = im.getpixel((0, 1)) p1 = im.getpixel((0, 1))
p2 = im.getpixel((0, 2)) p2 = im.getpixel((0, 2))
@ -412,34 +429,34 @@ class TestImage(PillowTestCase):
im2 = im.effect_spread(distance) im2 = im.effect_spread(distance)
# Assert # Assert
self.assertEqual(im.size, (128, 128)) assert im.size == (128, 128)
with Image.open("Tests/images/effect_spread.png") as im3: with Image.open("Tests/images/effect_spread.png") as im3:
assert_image_similar(im2, im3, 110) assert_image_similar(im2, im3, 110)
def test_check_size(self): def test_check_size(self):
# Checking that the _check_size function throws value errors # Checking that the _check_size function throws value errors
# when we want it to. # when we want it to.
with self.assertRaises(ValueError): with pytest.raises(ValueError):
Image.new("RGB", 0) # not a tuple Image.new("RGB", 0) # not a tuple
with self.assertRaises(ValueError): with pytest.raises(ValueError):
Image.new("RGB", (0,)) # Tuple too short Image.new("RGB", (0,)) # Tuple too short
with self.assertRaises(ValueError): with pytest.raises(ValueError):
Image.new("RGB", (-1, -1)) # w,h < 0 Image.new("RGB", (-1, -1)) # w,h < 0
# this should pass with 0 sized images, #2259 # this should pass with 0 sized images, #2259
im = Image.new("L", (0, 0)) im = Image.new("L", (0, 0))
self.assertEqual(im.size, (0, 0)) assert im.size == (0, 0)
im = Image.new("L", (0, 100)) im = Image.new("L", (0, 100))
self.assertEqual(im.size, (0, 100)) assert im.size == (0, 100)
im = Image.new("L", (100, 0)) im = Image.new("L", (100, 0))
self.assertEqual(im.size, (100, 0)) assert im.size == (100, 0)
self.assertTrue(Image.new("RGB", (1, 1))) assert Image.new("RGB", (1, 1))
# Should pass lists too # Should pass lists too
i = Image.new("RGB", [1, 1]) i = Image.new("RGB", [1, 1])
self.assertIsInstance(i.size, tuple) assert isinstance(i.size, tuple)
def test_storage_neg(self): def test_storage_neg(self):
# Storage.c accepted negative values for xsize, ysize. Was # Storage.c accepted negative values for xsize, ysize. Was
@ -447,7 +464,7 @@ class TestImage(PillowTestCase):
# removed Calling directly into core to test the error in # removed Calling directly into core to test the error in
# Storage.c, rather than the size check above # Storage.c, rather than the size check above
with self.assertRaises(ValueError): with pytest.raises(ValueError):
Image.core.fill("RGB", (2, -2), (0, 0, 0)) Image.core.fill("RGB", (2, -2), (0, 0, 0))
def test_offset_not_implemented(self): def test_offset_not_implemented(self):
@ -455,17 +472,20 @@ class TestImage(PillowTestCase):
with hopper() as im: with hopper() as im:
# Act / Assert # Act / Assert
self.assertRaises(NotImplementedError, im.offset, None) with pytest.raises(NotImplementedError):
im.offset(None)
def test_fromstring(self): def test_fromstring(self):
self.assertRaises(NotImplementedError, Image.fromstring) with pytest.raises(NotImplementedError):
Image.fromstring()
def test_linear_gradient_wrong_mode(self): def test_linear_gradient_wrong_mode(self):
# Arrange # Arrange
wrong_mode = "RGB" wrong_mode = "RGB"
# Act / Assert # Act / Assert
self.assertRaises(ValueError, Image.linear_gradient, wrong_mode) with pytest.raises(ValueError):
Image.linear_gradient(wrong_mode)
def test_linear_gradient(self): def test_linear_gradient(self):
@ -477,10 +497,10 @@ class TestImage(PillowTestCase):
im = Image.linear_gradient(mode) im = Image.linear_gradient(mode)
# Assert # Assert
self.assertEqual(im.size, (256, 256)) assert im.size == (256, 256)
self.assertEqual(im.mode, mode) assert im.mode == mode
self.assertEqual(im.getpixel((0, 0)), 0) assert im.getpixel((0, 0)) == 0
self.assertEqual(im.getpixel((255, 255)), 255) assert im.getpixel((255, 255)) == 255
with Image.open(target_file) as target: with Image.open(target_file) as target:
target = target.convert(mode) target = target.convert(mode)
assert_image_equal(im, target) assert_image_equal(im, target)
@ -490,7 +510,8 @@ class TestImage(PillowTestCase):
wrong_mode = "RGB" wrong_mode = "RGB"
# Act / Assert # Act / Assert
self.assertRaises(ValueError, Image.radial_gradient, wrong_mode) with pytest.raises(ValueError):
Image.radial_gradient(wrong_mode)
def test_radial_gradient(self): def test_radial_gradient(self):
@ -502,10 +523,10 @@ class TestImage(PillowTestCase):
im = Image.radial_gradient(mode) im = Image.radial_gradient(mode)
# Assert # Assert
self.assertEqual(im.size, (256, 256)) assert im.size == (256, 256)
self.assertEqual(im.mode, mode) assert im.mode == mode
self.assertEqual(im.getpixel((0, 0)), 255) assert im.getpixel((0, 0)) == 255
self.assertEqual(im.getpixel((128, 128)), 0) assert im.getpixel((128, 128)) == 0
with Image.open(target_file) as target: with Image.open(target_file) as target:
target = target.convert(mode) target = target.convert(mode)
assert_image_equal(im, target) assert_image_equal(im, target)
@ -524,12 +545,13 @@ class TestImage(PillowTestCase):
for ext in exts: for ext in exts:
del Image.EXTENSION[ext] del Image.EXTENSION[ext]
self.assertEqual(ext_individual, ext_multiple) assert ext_individual == ext_multiple
def test_remap_palette(self): def test_remap_palette(self):
# Test illegal image mode # Test illegal image mode
with hopper() as im: with hopper() as im:
self.assertRaises(ValueError, im.remap_palette, None) with pytest.raises(ValueError):
im.remap_palette(None)
def test__new(self): def test__new(self):
im = hopper("RGB") im = hopper("RGB")
@ -542,13 +564,13 @@ class TestImage(PillowTestCase):
def _make_new(base_image, im, palette_result=None): def _make_new(base_image, im, palette_result=None):
new_im = base_image._new(im) new_im = base_image._new(im)
self.assertEqual(new_im.mode, im.mode) assert new_im.mode == im.mode
self.assertEqual(new_im.size, im.size) assert new_im.size == im.size
self.assertEqual(new_im.info, base_image.info) assert new_im.info == base_image.info
if palette_result is not None: if palette_result is not None:
self.assertEqual(new_im.palette.tobytes(), palette_result.tobytes()) assert new_im.palette.tobytes() == palette_result.tobytes()
else: else:
self.assertIsNone(new_im.palette) assert new_im.palette is None
_make_new(im, im_p, im_p.palette) _make_new(im, im_p, im_p.palette)
_make_new(im_p, im, None) _make_new(im_p, im, None)
@ -587,7 +609,7 @@ class TestImage(PillowTestCase):
with Image.open(fp) as im: with Image.open(fp) as im:
im.load() im.load()
self.assertFalse(fp.closed) assert not fp.closed
def test_overrun(self): def test_overrun(self):
for file in [ for file in [
@ -603,14 +625,14 @@ class TestImage(PillowTestCase):
im.load() im.load()
self.assertFail() self.assertFail()
except OSError as e: except OSError as e:
self.assertEqual(str(e), "buffer overrun when reading image file") assert str(e) == "buffer overrun when reading image file"
with Image.open("Tests/images/fli_overrun2.bin") as im: with Image.open("Tests/images/fli_overrun2.bin") as im:
try: try:
im.seek(1) im.seek(1)
self.assertFail() self.assertFail()
except OSError as e: except OSError as e:
self.assertEqual(str(e), "buffer overrun when reading image file") assert str(e) == "buffer overrun when reading image file"
class MockEncoder: class MockEncoder:
@ -627,19 +649,13 @@ class TestRegistry(PillowTestCase):
def test_encode_registry(self): def test_encode_registry(self):
Image.register_encoder("MOCK", mock_encode) Image.register_encoder("MOCK", mock_encode)
self.assertIn("MOCK", Image.ENCODERS) assert "MOCK" in Image.ENCODERS
enc = Image._getencoder("RGB", "MOCK", ("args",), extra=("extra",)) enc = Image._getencoder("RGB", "MOCK", ("args",), extra=("extra",))
self.assertIsInstance(enc, MockEncoder) assert isinstance(enc, MockEncoder)
self.assertEqual(enc.args, ("RGB", "args", "extra")) assert enc.args == ("RGB", "args", "extra")
def test_encode_registry_fail(self): def test_encode_registry_fail(self):
self.assertRaises( with pytest.raises(IOError):
IOError, Image._getencoder("RGB", "DoesNotExist", ("args",), extra=("extra",))
Image._getencoder,
"RGB",
"DoesNotExist",
("args",),
extra=("extra",),
)

View File

@ -5,6 +5,7 @@ import sys
import unittest import unittest
from distutils import ccompiler, sysconfig from distutils import ccompiler, sysconfig
import pytest
from PIL import Image from PIL import Image
from .helper import PillowTestCase, assert_image_equal, hopper, is_win32, on_ci from .helper import PillowTestCase, assert_image_equal, hopper, is_win32, on_ci
@ -55,7 +56,7 @@ class TestImagePutPixel(AccessTest):
pos = x, y pos = x, y
im2.putpixel(pos, im1.getpixel(pos)) im2.putpixel(pos, im1.getpixel(pos))
self.assertFalse(im2.readonly) assert not im2.readonly
assert_image_equal(im1, im2) assert_image_equal(im1, im2)
im2 = Image.new(im1.mode, im1.size, 0) im2 = Image.new(im1.mode, im1.size, 0)
@ -74,8 +75,8 @@ class TestImagePutPixel(AccessTest):
im2 = Image.new(im1.mode, im1.size, 0) im2 = Image.new(im1.mode, im1.size, 0)
width, height = im1.size width, height = im1.size
self.assertEqual(im1.getpixel((0, 0)), im1.getpixel((-width, -height))) assert im1.getpixel((0, 0)) == im1.getpixel((-width, -height))
self.assertEqual(im1.getpixel((-1, -1)), im1.getpixel((width - 1, height - 1))) assert im1.getpixel((-1, -1)) == im1.getpixel((width - 1, height - 1))
for y in range(-1, -im1.size[1] - 1, -1): for y in range(-1, -im1.size[1] - 1, -1):
for x in range(-1, -im1.size[0] - 1, -1): for x in range(-1, -im1.size[0] - 1, -1):
@ -92,7 +93,7 @@ class TestImagePutPixel(AccessTest):
pos = x, y pos = x, y
im2.putpixel(pos, im1.getpixel(pos)) im2.putpixel(pos, im1.getpixel(pos))
self.assertFalse(im2.readonly) assert not im2.readonly
assert_image_equal(im1, im2) assert_image_equal(im1, im2)
im2 = Image.new(im1.mode, im1.size, 0) im2 = Image.new(im1.mode, im1.size, 0)
@ -123,54 +124,45 @@ class TestImageGetPixel(AccessTest):
# check putpixel # check putpixel
im = Image.new(mode, (1, 1), None) im = Image.new(mode, (1, 1), None)
im.putpixel((0, 0), c) im.putpixel((0, 0), c)
self.assertEqual( assert (
im.getpixel((0, 0)), im.getpixel((0, 0)) == c
c, ), "put/getpixel roundtrip failed for mode {}, color {}".format(mode, c)
"put/getpixel roundtrip failed for mode {}, color {}".format(mode, c),
)
# check putpixel negative index # check putpixel negative index
im.putpixel((-1, -1), c) im.putpixel((-1, -1), c)
self.assertEqual( assert im.getpixel((-1, -1)) == c, (
im.getpixel((-1, -1)), "put/getpixel roundtrip negative index failed for mode %s, color %s"
c, % (mode, c)
"put/getpixel roundtrip negative index failed"
" for mode %s, color %s" % (mode, c),
) )
# Check 0 # Check 0
im = Image.new(mode, (0, 0), None) im = Image.new(mode, (0, 0), None)
with self.assertRaises(IndexError): with pytest.raises(IndexError):
im.putpixel((0, 0), c) im.putpixel((0, 0), c)
with self.assertRaises(IndexError): with pytest.raises(IndexError):
im.getpixel((0, 0)) im.getpixel((0, 0))
# Check 0 negative index # Check 0 negative index
with self.assertRaises(IndexError): with pytest.raises(IndexError):
im.putpixel((-1, -1), c) im.putpixel((-1, -1), c)
with self.assertRaises(IndexError): with pytest.raises(IndexError):
im.getpixel((-1, -1)) im.getpixel((-1, -1))
# check initial color # check initial color
im = Image.new(mode, (1, 1), c) im = Image.new(mode, (1, 1), c)
self.assertEqual( assert (
im.getpixel((0, 0)), im.getpixel((0, 0)) == c
c, ), "initial color failed for mode {}, color {} ".format(mode, c)
"initial color failed for mode {}, color {} ".format(mode, c),
)
# check initial color negative index # check initial color negative index
self.assertEqual( assert (
im.getpixel((-1, -1)), im.getpixel((-1, -1)) == c
c, ), "initial color failed with negative index for mode %s, color %s " % (mode, c)
"initial color failed with negative index"
"for mode %s, color %s " % (mode, c),
)
# Check 0 # Check 0
im = Image.new(mode, (0, 0), c) im = Image.new(mode, (0, 0), c)
with self.assertRaises(IndexError): with pytest.raises(IndexError):
im.getpixel((0, 0)) im.getpixel((0, 0))
# Check 0 negative index # Check 0 negative index
with self.assertRaises(IndexError): with pytest.raises(IndexError):
im.getpixel((-1, -1)) im.getpixel((-1, -1))
def test_basic(self): def test_basic(self):
@ -205,7 +197,7 @@ class TestImageGetPixel(AccessTest):
for color in [(255, 0, 0), (255, 0, 0, 255)]: for color in [(255, 0, 0), (255, 0, 0, 255)]:
im = Image.new("P", (1, 1), 0) im = Image.new("P", (1, 1), 0)
im.putpixel((0, 0), color) im.putpixel((0, 0), color)
self.assertEqual(im.convert("RGB").getpixel((0, 0)), (255, 0, 0)) assert im.convert("RGB").getpixel((0, 0)) == (255, 0, 0)
@unittest.skipIf(cffi is None, "No cffi") @unittest.skipIf(cffi is None, "No cffi")
@ -233,7 +225,7 @@ class TestCffi(AccessTest):
w, h = im.size w, h = im.size
for x in range(0, w, 10): for x in range(0, w, 10):
for y in range(0, h, 10): for y in range(0, h, 10):
self.assertEqual(access[(x, y)], caccess[(x, y)]) assert access[(x, y)] == caccess[(x, y)]
# Access an out-of-range pixel # Access an out-of-range pixel
self.assertRaises( self.assertRaises(
@ -280,11 +272,11 @@ class TestCffi(AccessTest):
for x in range(0, w, 10): for x in range(0, w, 10):
for y in range(0, h, 10): for y in range(0, h, 10):
access[(x, y)] = color access[(x, y)] = color
self.assertEqual(color, caccess[(x, y)]) assert color == caccess[(x, y)]
# Attempt to set the value on a read-only image # Attempt to set the value on a read-only image
access = PyAccess.new(im, True) access = PyAccess.new(im, True)
with self.assertRaises(ValueError): with pytest.raises(ValueError):
access[(0, 0)] = color access[(0, 0)] = color
def test_set_vs_c(self): def test_set_vs_c(self):
@ -314,7 +306,7 @@ class TestCffi(AccessTest):
# self._test_set_access(im, 2**13-1) # self._test_set_access(im, 2**13-1)
def test_not_implemented(self): def test_not_implemented(self):
self.assertIsNone(PyAccess.new(hopper("BGR;15"))) assert PyAccess.new(hopper("BGR;15")) is None
# ref https://github.com/python-pillow/Pillow/pull/2009 # ref https://github.com/python-pillow/Pillow/pull/2009
def test_reference_counting(self): def test_reference_counting(self):
@ -325,14 +317,14 @@ class TestCffi(AccessTest):
px = Image.new("L", (size, 1), 0).load() px = Image.new("L", (size, 1), 0).load()
for i in range(size): for i in range(size):
# pixels can contain garbage if image is released # pixels can contain garbage if image is released
self.assertEqual(px[i, 0], 0) assert px[i, 0] == 0
def test_p_putpixel_rgb_rgba(self): def test_p_putpixel_rgb_rgba(self):
for color in [(255, 0, 0), (255, 0, 0, 255)]: for color in [(255, 0, 0), (255, 0, 0, 255)]:
im = Image.new("P", (1, 1), 0) im = Image.new("P", (1, 1), 0)
access = PyAccess.new(im, False) access = PyAccess.new(im, False)
access.putpixel((0, 0), color) access.putpixel((0, 0), color)
self.assertEqual(im.convert("RGB").getpixel((0, 0)), (255, 0, 0)) assert im.convert("RGB").getpixel((0, 0)) == (255, 0, 0)
class TestEmbeddable(unittest.TestCase): class TestEmbeddable(unittest.TestCase):
@ -387,4 +379,4 @@ int main(int argc, char* argv[])
process = subprocess.Popen(["embed_pil.exe"], env=env) process = subprocess.Popen(["embed_pil.exe"], env=env)
process.communicate() process.communicate()
self.assertEqual(process.returncode, 0) assert process.returncode == 0

View File

@ -14,8 +14,8 @@ class TestImageConvert(PillowTestCase):
def test_sanity(self): def test_sanity(self):
def convert(im, mode): def convert(im, mode):
out = im.convert(mode) out = im.convert(mode)
self.assertEqual(out.mode, mode) assert out.mode == mode
self.assertEqual(out.size, im.size) assert out.size == im.size
modes = ( modes = (
"1", "1",
@ -57,7 +57,7 @@ class TestImageConvert(PillowTestCase):
def _test_float_conversion(self, im): def _test_float_conversion(self, im):
orig = im.getpixel((5, 5)) orig = im.getpixel((5, 5))
converted = im.convert("F").getpixel((5, 5)) converted = im.convert("F").getpixel((5, 5))
self.assertEqual(orig, converted) assert orig == converted
def test_8bit(self): def test_8bit(self):
with Image.open("Tests/images/hopper.jpg") as im: with Image.open("Tests/images/hopper.jpg") as im:
@ -87,11 +87,11 @@ class TestImageConvert(PillowTestCase):
f = self.tempfile("temp.png") f = self.tempfile("temp.png")
im_l = im.convert("L") im_l = im.convert("L")
self.assertEqual(im_l.info["transparency"], 0) # undone assert im_l.info["transparency"] == 0 # undone
im_l.save(f) im_l.save(f)
im_rgb = im.convert("RGB") im_rgb = im.convert("RGB")
self.assertEqual(im_rgb.info["transparency"], (0, 0, 0)) # undone assert im_rgb.info["transparency"] == (0, 0, 0) # undone
im_rgb.save(f) im_rgb.save(f)
# ref https://github.com/python-pillow/Pillow/issues/664 # ref https://github.com/python-pillow/Pillow/issues/664
@ -105,9 +105,9 @@ class TestImageConvert(PillowTestCase):
im_rgba = im.convert("RGBA") im_rgba = im.convert("RGBA")
# Assert # Assert
self.assertNotIn("transparency", im_rgba.info) assert "transparency" not in im_rgba.info
# https://github.com/python-pillow/Pillow/issues/2702 # https://github.com/python-pillow/Pillow/issues/2702
self.assertIsNone(im_rgba.palette) assert im_rgba.palette is None
def test_trns_l(self): def test_trns_l(self):
im = hopper("L") im = hopper("L")
@ -116,15 +116,15 @@ class TestImageConvert(PillowTestCase):
f = self.tempfile("temp.png") f = self.tempfile("temp.png")
im_rgb = im.convert("RGB") im_rgb = im.convert("RGB")
self.assertEqual(im_rgb.info["transparency"], (128, 128, 128)) # undone assert im_rgb.info["transparency"] == (128, 128, 128) # undone
im_rgb.save(f) im_rgb.save(f)
im_p = im.convert("P") im_p = im.convert("P")
self.assertIn("transparency", im_p.info) assert "transparency" in im_p.info
im_p.save(f) im_p.save(f)
im_p = pytest.warns(UserWarning, im.convert, "P", palette=Image.ADAPTIVE) im_p = pytest.warns(UserWarning, im.convert, "P", palette=Image.ADAPTIVE)
self.assertNotIn("transparency", im_p.info) assert "transparency" not in im_p.info
im_p.save(f) im_p.save(f)
def test_trns_RGB(self): def test_trns_RGB(self):
@ -134,19 +134,19 @@ class TestImageConvert(PillowTestCase):
f = self.tempfile("temp.png") f = self.tempfile("temp.png")
im_l = im.convert("L") im_l = im.convert("L")
self.assertEqual(im_l.info["transparency"], im_l.getpixel((0, 0))) # undone assert im_l.info["transparency"] == im_l.getpixel((0, 0)) # undone
im_l.save(f) im_l.save(f)
im_p = im.convert("P") im_p = im.convert("P")
self.assertIn("transparency", im_p.info) assert "transparency" in im_p.info
im_p.save(f) im_p.save(f)
im_rgba = im.convert("RGBA") im_rgba = im.convert("RGBA")
self.assertNotIn("transparency", im_rgba.info) assert "transparency" not in im_rgba.info
im_rgba.save(f) im_rgba.save(f)
im_p = pytest.warns(UserWarning, im.convert, "P", palette=Image.ADAPTIVE) im_p = pytest.warns(UserWarning, im.convert, "P", palette=Image.ADAPTIVE)
self.assertNotIn("transparency", im_p.info) assert "transparency" not in im_p.info
im_p.save(f) im_p.save(f)
def test_gif_with_rgba_palette_to_p(self): def test_gif_with_rgba_palette_to_p(self):
@ -154,7 +154,7 @@ class TestImageConvert(PillowTestCase):
with Image.open("Tests/images/hopper.gif") as im: with Image.open("Tests/images/hopper.gif") as im:
im.info["transparency"] = 255 im.info["transparency"] = 255
im.load() im.load()
self.assertEqual(im.palette.mode, "RGBA") assert im.palette.mode == "RGBA"
im_p = im.convert("P") im_p = im.convert("P")
# Should not raise ValueError: unrecognized raw mode # Should not raise ValueError: unrecognized raw mode
@ -178,10 +178,11 @@ class TestImageConvert(PillowTestCase):
0.212671, 0.715160, 0.072169, 0, 0.212671, 0.715160, 0.072169, 0,
0.019334, 0.119193, 0.950227, 0) 0.019334, 0.119193, 0.950227, 0)
# fmt: on # fmt: on
self.assertNotEqual(im.mode, "RGB") assert im.mode != "RGB"
# Act / Assert # Act / Assert
self.assertRaises(ValueError, im.convert, mode="CMYK", matrix=matrix) with pytest.raises(ValueError):
im.convert(mode="CMYK", matrix=matrix)
def test_matrix_wrong_mode(self): def test_matrix_wrong_mode(self):
# Arrange # Arrange
@ -192,10 +193,11 @@ class TestImageConvert(PillowTestCase):
0.212671, 0.715160, 0.072169, 0, 0.212671, 0.715160, 0.072169, 0,
0.019334, 0.119193, 0.950227, 0) 0.019334, 0.119193, 0.950227, 0)
# fmt: on # fmt: on
self.assertEqual(im.mode, "L") assert im.mode == "L"
# Act / Assert # Act / Assert
self.assertRaises(ValueError, im.convert, mode="L", matrix=matrix) with pytest.raises(ValueError):
im.convert(mode="L", matrix=matrix)
def test_matrix_xyz(self): def test_matrix_xyz(self):
def matrix_convert(mode): def matrix_convert(mode):
@ -208,22 +210,22 @@ class TestImageConvert(PillowTestCase):
0.212671, 0.715160, 0.072169, 0, 0.212671, 0.715160, 0.072169, 0,
0.019334, 0.119193, 0.950227, 0) 0.019334, 0.119193, 0.950227, 0)
# fmt: on # fmt: on
self.assertEqual(im.mode, "RGB") assert im.mode == "RGB"
# Act # Act
# Convert an RGB image to the CIE XYZ colour space # Convert an RGB image to the CIE XYZ colour space
converted_im = im.convert(mode=mode, matrix=matrix) converted_im = im.convert(mode=mode, matrix=matrix)
# Assert # Assert
self.assertEqual(converted_im.mode, mode) assert converted_im.mode == mode
self.assertEqual(converted_im.size, im.size) assert converted_im.size == im.size
with Image.open("Tests/images/hopper-XYZ.png") as target: with Image.open("Tests/images/hopper-XYZ.png") as target:
if converted_im.mode == "RGB": if converted_im.mode == "RGB":
assert_image_similar(converted_im, target, 3) assert_image_similar(converted_im, target, 3)
self.assertEqual(converted_im.info["transparency"], (105, 54, 4)) assert converted_im.info["transparency"] == (105, 54, 4)
else: else:
assert_image_similar(converted_im, target.getchannel(0), 1) assert_image_similar(converted_im, target.getchannel(0), 1)
self.assertEqual(converted_im.info["transparency"], 105) assert converted_im.info["transparency"] == 105
matrix_convert("RGB") matrix_convert("RGB")
matrix_convert("L") matrix_convert("L")
@ -237,7 +239,7 @@ class TestImageConvert(PillowTestCase):
0, 1, 0, 0, 0, 1, 0, 0,
0, 0, 1, 0) 0, 0, 1, 0)
# fmt: on # fmt: on
self.assertEqual(im.mode, "RGB") assert im.mode == "RGB"
# Act # Act
# Convert with an identity matrix # Convert with an identity matrix

View File

@ -23,7 +23,7 @@ class TestImagingPaste(PillowTestCase):
px[self.size // 2, self.size - 1], px[self.size // 2, self.size - 1],
px[self.size - 1, self.size - 1], px[self.size - 1, self.size - 1],
] ]
self.assertEqual(actual, expected) assert actual == expected
def assert_9points_paste(self, im, im2, mask, expected): def assert_9points_paste(self, im, im2, mask, expected):
im3 = im.copy() im3 = im.copy()
@ -199,8 +199,8 @@ class TestImagingPaste(PillowTestCase):
hist = im.crop(rect).histogram() hist = im.crop(rect).histogram()
while hist: while hist:
head, hist = hist[:256], hist[256:] head, hist = hist[:256], hist[256:]
self.assertEqual(head[255], 128 * 128) assert head[255] == 128 * 128
self.assertEqual(sum(head[:255]), 0) assert sum(head[:255]) == 0
def test_color_mask_1(self): def test_color_mask_1(self):
for mode in ("RGBA", "RGB", "L"): for mode in ("RGBA", "RGB", "L"):

View File

@ -1,3 +1,4 @@
import pytest
from PIL import Image, ImageMath, ImageMode from PIL import Image, ImageMath, ImageMode
from .helper import PillowTestCase, convert_to_comparable from .helper import PillowTestCase, convert_to_comparable
@ -39,51 +40,51 @@ class TestImageReduce(PillowTestCase):
def test_args_factor(self): def test_args_factor(self):
im = Image.new("L", (10, 10)) im = Image.new("L", (10, 10))
self.assertEqual((4, 4), im.reduce(3).size) assert (4, 4) == im.reduce(3).size
self.assertEqual((4, 10), im.reduce((3, 1)).size) assert (4, 10) == im.reduce((3, 1)).size
self.assertEqual((10, 4), im.reduce((1, 3)).size) assert (10, 4) == im.reduce((1, 3)).size
with self.assertRaises(ValueError): with pytest.raises(ValueError):
im.reduce(0) im.reduce(0)
with self.assertRaises(TypeError): with pytest.raises(TypeError):
im.reduce(2.0) im.reduce(2.0)
with self.assertRaises(ValueError): with pytest.raises(ValueError):
im.reduce((0, 10)) im.reduce((0, 10))
def test_args_box(self): def test_args_box(self):
im = Image.new("L", (10, 10)) im = Image.new("L", (10, 10))
self.assertEqual((5, 5), im.reduce(2, (0, 0, 10, 10)).size) assert (5, 5) == im.reduce(2, (0, 0, 10, 10)).size
self.assertEqual((1, 1), im.reduce(2, (5, 5, 6, 6)).size) assert (1, 1) == im.reduce(2, (5, 5, 6, 6)).size
with self.assertRaises(TypeError): with pytest.raises(TypeError):
im.reduce(2, "stri") im.reduce(2, "stri")
with self.assertRaises(TypeError): with pytest.raises(TypeError):
im.reduce(2, 2) im.reduce(2, 2)
with self.assertRaises(ValueError): with pytest.raises(ValueError):
im.reduce(2, (0, 0, 11, 10)) im.reduce(2, (0, 0, 11, 10))
with self.assertRaises(ValueError): with pytest.raises(ValueError):
im.reduce(2, (0, 0, 10, 11)) im.reduce(2, (0, 0, 10, 11))
with self.assertRaises(ValueError): with pytest.raises(ValueError):
im.reduce(2, (-1, 0, 10, 10)) im.reduce(2, (-1, 0, 10, 10))
with self.assertRaises(ValueError): with pytest.raises(ValueError):
im.reduce(2, (0, -1, 10, 10)) im.reduce(2, (0, -1, 10, 10))
with self.assertRaises(ValueError): with pytest.raises(ValueError):
im.reduce(2, (0, 5, 10, 5)) im.reduce(2, (0, 5, 10, 5))
with self.assertRaises(ValueError): with pytest.raises(ValueError):
im.reduce(2, (5, 0, 5, 10)) im.reduce(2, (5, 0, 5, 10))
def test_unsupported_modes(self): def test_unsupported_modes(self):
im = Image.new("P", (10, 10)) im = Image.new("P", (10, 10))
with self.assertRaises(ValueError): with pytest.raises(ValueError):
im.reduce(3) im.reduce(3)
im = Image.new("1", (10, 10)) im = Image.new("1", (10, 10))
with self.assertRaises(ValueError): with pytest.raises(ValueError):
im.reduce(3) im.reduce(3)
im = Image.new("I;16", (10, 10)) im = Image.new("I;16", (10, 10))
with self.assertRaises(ValueError): with pytest.raises(ValueError):
im.reduce(3) im.reduce(3)
def get_image(self, mode): def get_image(self, mode):
@ -109,7 +110,7 @@ class TestImageReduce(PillowTestCase):
box = (11, 13, 146, 164) box = (11, 13, 146, 164)
reduced = im.reduce(factor, box=box) reduced = im.reduce(factor, box=box)
reference = im.crop(box).reduce(factor) reference = im.crop(box).reduce(factor)
self.assertEqual(reduced, reference) assert reduced == reference
def compare_reduce_with_reference(self, im, factor, average_diff=0.4, max_diff=1): def compare_reduce_with_reference(self, im, factor, average_diff=0.4, max_diff=1):
"""Image.reduce() should look very similar to Image.resize(BOX). """Image.reduce() should look very similar to Image.resize(BOX).
@ -135,13 +136,13 @@ class TestImageReduce(PillowTestCase):
reference.paste(area, (0, 0)) reference.paste(area, (0, 0))
if area_size[0] < reduced.size[0]: if area_size[0] < reduced.size[0]:
self.assertEqual(reduced.size[0] - area_size[0], 1) assert reduced.size[0] - area_size[0] == 1
last_column_box = (area_box[2], 0, im.size[0], area_box[3]) last_column_box = (area_box[2], 0, im.size[0], area_box[3])
last_column = im.resize((1, area_size[1]), Image.BOX, last_column_box) last_column = im.resize((1, area_size[1]), Image.BOX, last_column_box)
reference.paste(last_column, (area_size[0], 0)) reference.paste(last_column, (area_size[0], 0))
if area_size[1] < reduced.size[1]: if area_size[1] < reduced.size[1]:
self.assertEqual(reduced.size[1] - area_size[1], 1) assert reduced.size[1] - area_size[1] == 1
last_row_box = (0, area_box[3], area_box[2], im.size[1]) last_row_box = (0, area_box[3], area_box[2], im.size[1])
last_row = im.resize((area_size[0], 1), Image.BOX, last_row_box) last_row = im.resize((area_size[0], 1), Image.BOX, last_row_box)
reference.paste(last_row, (0, area_size[1])) reference.paste(last_row, (0, area_size[1]))
@ -154,8 +155,8 @@ class TestImageReduce(PillowTestCase):
self.assert_compare_images(reduced, reference, average_diff, max_diff) self.assert_compare_images(reduced, reference, average_diff, max_diff)
def assert_compare_images(self, a, b, max_average_diff, max_diff=255): def assert_compare_images(self, a, b, max_average_diff, max_diff=255):
self.assertEqual(a.mode, b.mode, "got mode %r, expected %r" % (a.mode, b.mode)) assert a.mode == b.mode, "got mode %r, expected %r" % (a.mode, b.mode)
self.assertEqual(a.size, b.size, "got size %r, expected %r" % (a.size, b.size)) assert a.size == b.size, "got size %r, expected %r" % (a.size, b.size)
a, b = convert_to_comparable(a, b) a, b = convert_to_comparable(a, b)
@ -167,22 +168,15 @@ class TestImageReduce(PillowTestCase):
average_diff = sum(i * num for i, num in enumerate(ch_hist)) / ( average_diff = sum(i * num for i, num in enumerate(ch_hist)) / (
a.size[0] * a.size[1] a.size[0] * a.size[1]
) )
self.assertGreaterEqual( msg = "average pixel value difference {:.4f} > expected {:.4f} "
max_average_diff, "for '{}' band".format(average_diff, max_average_diff, band)
average_diff, assert max_average_diff >= average_diff, msg
(
"average pixel value difference {:.4f} > expected {:.4f} "
"for '{}' band"
).format(average_diff, max_average_diff, band),
)
last_diff = [i for i, num in enumerate(ch_hist) if num > 0][-1] last_diff = [i for i, num in enumerate(ch_hist) if num > 0][-1]
self.assertGreaterEqual( assert (
max_diff, max_diff >= last_diff
last_diff, ), "max pixel value difference {} > expected {} for '{}' band".format(
"max pixel value difference {} > expected {} for '{}' band".format( last_diff, max_diff, band
last_diff, max_diff, band
),
) )
def test_mode_L(self): def test_mode_L(self):

View File

@ -1,6 +1,7 @@
import unittest import unittest
from contextlib import contextmanager from contextlib import contextmanager
import pytest
from PIL import Image, ImageDraw from PIL import Image, ImageDraw
from .helper import PillowTestCase, assert_image_equal, assert_image_similar, hopper from .helper import PillowTestCase, assert_image_equal, assert_image_similar, hopper
@ -16,7 +17,7 @@ class TestImagingResampleVulnerability(PillowTestCase):
(size_too_large, size_normal), (size_too_large, size_normal),
(size_normal, size_too_large), (size_normal, size_too_large),
): ):
with self.assertRaises(MemoryError): with pytest.raises(MemoryError):
# any resampling filter will do here # any resampling filter will do here
im.im.resize((xsize, ysize), Image.BILINEAR) im.im.resize((xsize, ysize), Image.BILINEAR)
@ -26,10 +27,10 @@ class TestImagingResampleVulnerability(PillowTestCase):
# Should not crash # Should not crash
im.resize((100, 100)) im.resize((100, 100))
with self.assertRaises(ValueError): with pytest.raises(ValueError):
im.resize((-100, 100)) im.resize((-100, 100))
with self.assertRaises(ValueError): with pytest.raises(ValueError):
im.resize((100, -100)) im.resize((100, -100))
def test_modify_after_resizing(self): def test_modify_after_resizing(self):
@ -39,7 +40,7 @@ class TestImagingResampleVulnerability(PillowTestCase):
# some in-place operation # some in-place operation
copy.paste("black", (0, 0, im.width // 2, im.height // 2)) copy.paste("black", (0, 0, im.width // 2, im.height // 2))
# image should be different # image should be different
self.assertNotEqual(im.tobytes(), copy.tobytes()) assert im.tobytes() != copy.tobytes()
class TestImagingCoreResampleAccuracy(PillowTestCase): class TestImagingCoreResampleAccuracy(PillowTestCase):
@ -84,7 +85,7 @@ class TestImagingCoreResampleAccuracy(PillowTestCase):
message = "\nHave: \n{}\n\nExpected: \n{}".format( message = "\nHave: \n{}\n\nExpected: \n{}".format(
self.serialize_image(case), self.serialize_image(sample) self.serialize_image(case), self.serialize_image(sample)
) )
self.assertEqual(s_px[x, y], c_px[x, y], message) assert s_px[x, y] == c_px[x, y], message
def serialize_image(self, image): def serialize_image(self, image):
s_px = image.load() s_px = image.load()
@ -230,7 +231,7 @@ class CoreResampleConsistencyTest(PillowTestCase):
for y in range(channel.size[1]): for y in range(channel.size[1]):
if px[x, y] != color: if px[x, y] != color:
message = "{} != {} for pixel {}".format(px[x, y], color, (x, y)) message = "{} != {} for pixel {}".format(px[x, y], color, (x, y))
self.assertEqual(px[x, y], color, message) assert px[x, y] == color, message
def test_8u(self): def test_8u(self):
im, color = self.make_case("RGB", (0, 64, 255)) im, color = self.make_case("RGB", (0, 64, 255))
@ -268,11 +269,10 @@ class CoreResampleAlphaCorrectTest(PillowTestCase):
px = i.load() px = i.load()
for y in range(i.size[1]): for y in range(i.size[1]):
used_colors = {px[x, y][0] for x in range(i.size[0])} used_colors = {px[x, y][0] for x in range(i.size[0])}
self.assertEqual( assert 256 == len(
256, used_colors
len(used_colors), ), "All colors should present in resized image. Only {} on {} line.".format(
"All colors should present in resized image. " len(used_colors), y
"Only {} on {} line.".format(len(used_colors), y),
) )
@unittest.skip("current implementation isn't precise enough") @unittest.skip("current implementation isn't precise enough")
@ -311,7 +311,7 @@ class CoreResampleAlphaCorrectTest(PillowTestCase):
message = "pixel at ({}, {}) is differ:\n{}\n{}".format( message = "pixel at ({}, {}) is differ:\n{}\n{}".format(
x, y, px[x, y], clean_pixel x, y, px[x, y], clean_pixel
) )
self.assertEqual(px[x, y][:3], clean_pixel, message) assert px[x, y][:3] == clean_pixel, message
def test_dirty_pixels_rgba(self): def test_dirty_pixels_rgba(self):
case = self.make_dirty_case("RGBA", (255, 255, 0, 128), (0, 0, 255, 0)) case = self.make_dirty_case("RGBA", (255, 255, 0, 128), (0, 0, 255, 0))
@ -335,7 +335,7 @@ class CoreResamplePassesTest(PillowTestCase):
def count(self, diff): def count(self, diff):
count = Image.core.get_stats()["new_count"] count = Image.core.get_stats()["new_count"]
yield yield
self.assertEqual(Image.core.get_stats()["new_count"] - count, diff) assert Image.core.get_stats()["new_count"] - count == diff
def test_horizontal(self): def test_horizontal(self):
im = hopper("L") im = hopper("L")
@ -384,7 +384,7 @@ class CoreResampleCoefficientsTest(PillowTestCase):
px = i.resize((5, i.size[1]), Image.BICUBIC).load() px = i.resize((5, i.size[1]), Image.BICUBIC).load()
if px[2, 0] != test_color // 2: if px[2, 0] != test_color // 2:
self.assertEqual(test_color // 2, px[2, 0]) assert test_color // 2 == px[2, 0]
def test_nonzero_coefficients(self): def test_nonzero_coefficients(self):
# regression test for the wrong coefficients calculation # regression test for the wrong coefficients calculation
@ -393,13 +393,13 @@ class CoreResampleCoefficientsTest(PillowTestCase):
histogram = im.resize((256, 256), Image.BICUBIC).histogram() histogram = im.resize((256, 256), Image.BICUBIC).histogram()
# first channel # first channel
self.assertEqual(histogram[0x100 * 0 + 0x20], 0x10000) assert histogram[0x100 * 0 + 0x20] == 0x10000
# second channel # second channel
self.assertEqual(histogram[0x100 * 1 + 0x40], 0x10000) assert histogram[0x100 * 1 + 0x40] == 0x10000
# third channel # third channel
self.assertEqual(histogram[0x100 * 2 + 0x60], 0x10000) assert histogram[0x100 * 2 + 0x60] == 0x10000
# fourth channel # fourth channel
self.assertEqual(histogram[0x100 * 3 + 0xFF], 0x10000) assert histogram[0x100 * 3 + 0xFF] == 0x10000
class CoreResampleBoxTest(PillowTestCase): class CoreResampleBoxTest(PillowTestCase):
@ -456,7 +456,7 @@ class CoreResampleBoxTest(PillowTestCase):
def test_tiles(self): def test_tiles(self):
with Image.open("Tests/images/flower.jpg") as im: with Image.open("Tests/images/flower.jpg") as im:
self.assertEqual(im.size, (480, 360)) assert im.size == (480, 360)
dst_size = (251, 188) dst_size = (251, 188)
reference = im.resize(dst_size, Image.BICUBIC) reference = im.resize(dst_size, Image.BICUBIC)
@ -468,7 +468,7 @@ class CoreResampleBoxTest(PillowTestCase):
# This test shows advantages of the subpixel resizing # This test shows advantages of the subpixel resizing
# after supersampling (e.g. during JPEG decoding). # after supersampling (e.g. during JPEG decoding).
with Image.open("Tests/images/flower.jpg") as im: with Image.open("Tests/images/flower.jpg") as im:
self.assertEqual(im.size, (480, 360)) assert im.size == (480, 360)
dst_size = (48, 36) dst_size = (48, 36)
# Reference is cropped image resized to destination # Reference is cropped image resized to destination
reference = im.crop((0, 0, 473, 353)).resize(dst_size, Image.BICUBIC) reference = im.crop((0, 0, 473, 353)).resize(dst_size, Image.BICUBIC)
@ -503,7 +503,7 @@ class CoreResampleBoxTest(PillowTestCase):
((40, 50), (10, 20, 50, 70)), ((40, 50), (10, 20, 50, 70)),
]: ]:
res = im.resize(size, Image.LANCZOS, box) res = im.resize(size, Image.LANCZOS, box)
self.assertEqual(res.size, size) assert res.size == size
assert_image_equal(res, im.crop(box), ">>> {} {}".format(size, box)) assert_image_equal(res, im.crop(box), ">>> {} {}".format(size, box))
def test_no_passthrough(self): def test_no_passthrough(self):
@ -517,7 +517,7 @@ class CoreResampleBoxTest(PillowTestCase):
((40, 50), (10.4, 20.4, 50.4, 70.4)), ((40, 50), (10.4, 20.4, 50.4, 70.4)),
]: ]:
res = im.resize(size, Image.LANCZOS, box) res = im.resize(size, Image.LANCZOS, box)
self.assertEqual(res.size, size) assert res.size == size
with self.assertRaisesRegex(AssertionError, r"difference \d"): with self.assertRaisesRegex(AssertionError, r"difference \d"):
# check that the difference at least that much # check that the difference at least that much
assert_image_similar( assert_image_similar(
@ -536,7 +536,7 @@ class CoreResampleBoxTest(PillowTestCase):
((40, 50), (10, 20, 50, 90)), ((40, 50), (10, 20, 50, 90)),
]: ]:
res = im.resize(size, flt, box) res = im.resize(size, flt, box)
self.assertEqual(res.size, size) assert res.size == size
# Borders should be slightly different # Borders should be slightly different
assert_image_similar( assert_image_similar(
res, res,
@ -557,7 +557,7 @@ class CoreResampleBoxTest(PillowTestCase):
((40, 50), (20, 10, 90, 60)), ((40, 50), (20, 10, 90, 60)),
]: ]:
res = im.resize(size, flt, box) res = im.resize(size, flt, box)
self.assertEqual(res.size, size) assert res.size == size
# Borders should be slightly different # Borders should be slightly different
assert_image_similar( assert_image_similar(
res, res,

View File

@ -3,6 +3,7 @@ Tests for resize functionality.
""" """
from itertools import permutations from itertools import permutations
import pytest
from PIL import Image from PIL import Image
from .helper import PillowTestCase, assert_image_equal, assert_image_similar, hopper from .helper import PillowTestCase, assert_image_equal, assert_image_similar, hopper
@ -29,26 +30,23 @@ class TestImagingCoreResize(PillowTestCase):
]: # exotic mode ]: # exotic mode
im = hopper(mode) im = hopper(mode)
r = self.resize(im, (15, 12), Image.NEAREST) r = self.resize(im, (15, 12), Image.NEAREST)
self.assertEqual(r.mode, mode) assert r.mode == mode
self.assertEqual(r.size, (15, 12)) assert r.size == (15, 12)
self.assertEqual(r.im.bands, im.im.bands) assert r.im.bands == im.im.bands
def test_convolution_modes(self): def test_convolution_modes(self):
self.assertRaises( with pytest.raises(ValueError):
ValueError, self.resize, hopper("1"), (15, 12), Image.BILINEAR self.resize(hopper("1"), (15, 12), Image.BILINEAR)
) with pytest.raises(ValueError):
self.assertRaises( self.resize(hopper("P"), (15, 12), Image.BILINEAR)
ValueError, self.resize, hopper("P"), (15, 12), Image.BILINEAR with pytest.raises(ValueError):
) self.resize(hopper("I;16"), (15, 12), Image.BILINEAR)
self.assertRaises(
ValueError, self.resize, hopper("I;16"), (15, 12), Image.BILINEAR
)
for mode in ["L", "I", "F", "RGB", "RGBA", "CMYK", "YCbCr"]: for mode in ["L", "I", "F", "RGB", "RGBA", "CMYK", "YCbCr"]:
im = hopper(mode) im = hopper(mode)
r = self.resize(im, (15, 12), Image.BILINEAR) r = self.resize(im, (15, 12), Image.BILINEAR)
self.assertEqual(r.mode, mode) assert r.mode == mode
self.assertEqual(r.size, (15, 12)) assert r.size == (15, 12)
self.assertEqual(r.im.bands, im.im.bands) assert r.im.bands == im.im.bands
def test_reduce_filters(self): def test_reduce_filters(self):
for f in [ for f in [
@ -60,8 +58,8 @@ class TestImagingCoreResize(PillowTestCase):
Image.LANCZOS, Image.LANCZOS,
]: ]:
r = self.resize(hopper("RGB"), (15, 12), f) r = self.resize(hopper("RGB"), (15, 12), f)
self.assertEqual(r.mode, "RGB") assert r.mode == "RGB"
self.assertEqual(r.size, (15, 12)) assert r.size == (15, 12)
def test_enlarge_filters(self): def test_enlarge_filters(self):
for f in [ for f in [
@ -73,8 +71,8 @@ class TestImagingCoreResize(PillowTestCase):
Image.LANCZOS, Image.LANCZOS,
]: ]:
r = self.resize(hopper("RGB"), (212, 195), f) r = self.resize(hopper("RGB"), (212, 195), f)
self.assertEqual(r.mode, "RGB") assert r.mode == "RGB"
self.assertEqual(r.size, (212, 195)) assert r.size == (212, 195)
def test_endianness(self): def test_endianness(self):
# Make an image with one colored pixel, in one channel. # Make an image with one colored pixel, in one channel.
@ -128,12 +126,13 @@ class TestImagingCoreResize(PillowTestCase):
Image.LANCZOS, Image.LANCZOS,
]: ]:
r = self.resize(Image.new("RGB", (0, 0), "white"), (212, 195), f) r = self.resize(Image.new("RGB", (0, 0), "white"), (212, 195), f)
self.assertEqual(r.mode, "RGB") assert r.mode == "RGB"
self.assertEqual(r.size, (212, 195)) assert r.size == (212, 195)
self.assertEqual(r.getdata()[0], (0, 0, 0)) assert r.getdata()[0] == (0, 0, 0)
def test_unknown_filter(self): def test_unknown_filter(self):
self.assertRaises(ValueError, self.resize, hopper(), (10, 10), 9) with pytest.raises(ValueError):
self.resize(hopper(), (10, 10), 9)
class TestReducingGapResize(PillowTestCase): class TestReducingGapResize(PillowTestCase):
@ -147,10 +146,10 @@ class TestReducingGapResize(PillowTestCase):
im = self.gradients_image.resize((52, 34), Image.BICUBIC) im = self.gradients_image.resize((52, 34), Image.BICUBIC)
assert_image_equal(ref, im) assert_image_equal(ref, im)
with self.assertRaises(ValueError): with pytest.raises(ValueError):
self.gradients_image.resize((52, 34), Image.BICUBIC, reducing_gap=0) self.gradients_image.resize((52, 34), Image.BICUBIC, reducing_gap=0)
with self.assertRaises(ValueError): with pytest.raises(ValueError):
self.gradients_image.resize((52, 34), Image.BICUBIC, reducing_gap=0.99) self.gradients_image.resize((52, 34), Image.BICUBIC, reducing_gap=0.99)
def test_reducing_gap_1(self): def test_reducing_gap_1(self):
@ -164,7 +163,7 @@ class TestReducingGapResize(PillowTestCase):
(52, 34), Image.BICUBIC, box=box, reducing_gap=1.0 (52, 34), Image.BICUBIC, box=box, reducing_gap=1.0
) )
with self.assertRaises(AssertionError): with pytest.raises(AssertionError):
assert_image_equal(ref, im) assert_image_equal(ref, im)
assert_image_similar(ref, im, epsilon) assert_image_similar(ref, im, epsilon)
@ -180,7 +179,7 @@ class TestReducingGapResize(PillowTestCase):
(52, 34), Image.BICUBIC, box=box, reducing_gap=2.0 (52, 34), Image.BICUBIC, box=box, reducing_gap=2.0
) )
with self.assertRaises(AssertionError): with pytest.raises(AssertionError):
assert_image_equal(ref, im) assert_image_equal(ref, im)
assert_image_similar(ref, im, epsilon) assert_image_similar(ref, im, epsilon)
@ -196,7 +195,7 @@ class TestReducingGapResize(PillowTestCase):
(52, 34), Image.BICUBIC, box=box, reducing_gap=3.0 (52, 34), Image.BICUBIC, box=box, reducing_gap=3.0
) )
with self.assertRaises(AssertionError): with pytest.raises(AssertionError):
assert_image_equal(ref, im) assert_image_equal(ref, im)
assert_image_similar(ref, im, epsilon) assert_image_similar(ref, im, epsilon)
@ -227,8 +226,8 @@ class TestImageResize(PillowTestCase):
def test_resize(self): def test_resize(self):
def resize(mode, size): def resize(mode, size):
out = hopper(mode).resize(size) out = hopper(mode).resize(size)
self.assertEqual(out.mode, mode) assert out.mode == mode
self.assertEqual(out.size, size) assert out.size == size
for mode in "1", "P", "L", "RGB", "I", "F": for mode in "1", "P", "L", "RGB", "I", "F":
resize(mode, (112, 103)) resize(mode, (112, 103))
@ -236,13 +235,14 @@ class TestImageResize(PillowTestCase):
# Test unknown resampling filter # Test unknown resampling filter
with hopper() as im: with hopper() as im:
self.assertRaises(ValueError, im.resize, (10, 10), "unknown") with pytest.raises(ValueError):
im.resize((10, 10), "unknown")
def test_default_filter(self): def test_default_filter(self):
for mode in "L", "RGB", "I", "F": for mode in "L", "RGB", "I", "F":
im = hopper(mode) im = hopper(mode)
self.assertEqual(im.resize((20, 20), Image.BICUBIC), im.resize((20, 20))) assert im.resize((20, 20), Image.BICUBIC) == im.resize((20, 20))
for mode in "1", "P": for mode in "1", "P":
im = hopper(mode) im = hopper(mode)
self.assertEqual(im.resize((20, 20), Image.NEAREST), im.resize((20, 20))) assert im.resize((20, 20), Image.NEAREST) == im.resize((20, 20))

View File

@ -9,25 +9,25 @@ class TestImageSplit(PillowTestCase):
layers = hopper(mode).split() layers = hopper(mode).split()
return [(i.mode, i.size[0], i.size[1]) for i in layers] return [(i.mode, i.size[0], i.size[1]) for i in layers]
self.assertEqual(split("1"), [("1", 128, 128)]) assert split("1") == [("1", 128, 128)]
self.assertEqual(split("L"), [("L", 128, 128)]) assert split("L") == [("L", 128, 128)]
self.assertEqual(split("I"), [("I", 128, 128)]) assert split("I") == [("I", 128, 128)]
self.assertEqual(split("F"), [("F", 128, 128)]) assert split("F") == [("F", 128, 128)]
self.assertEqual(split("P"), [("P", 128, 128)]) assert split("P") == [("P", 128, 128)]
self.assertEqual( assert split("RGB") == [("L", 128, 128), ("L", 128, 128), ("L", 128, 128)]
split("RGB"), [("L", 128, 128), ("L", 128, 128), ("L", 128, 128)] assert split("RGBA") == [
) ("L", 128, 128),
self.assertEqual( ("L", 128, 128),
split("RGBA"), ("L", 128, 128),
[("L", 128, 128), ("L", 128, 128), ("L", 128, 128), ("L", 128, 128)], ("L", 128, 128),
) ]
self.assertEqual( assert split("CMYK") == [
split("CMYK"), ("L", 128, 128),
[("L", 128, 128), ("L", 128, 128), ("L", 128, 128), ("L", 128, 128)], ("L", 128, 128),
) ("L", 128, 128),
self.assertEqual( ("L", 128, 128),
split("YCbCr"), [("L", 128, 128), ("L", 128, 128), ("L", 128, 128)] ]
) assert split("YCbCr") == [("L", 128, 128), ("L", 128, 128), ("L", 128, 128)]
def test_split_merge(self): def test_split_merge(self):
def split_merge(mode): def split_merge(mode):
@ -54,9 +54,9 @@ class TestImageSplit(PillowTestCase):
with Image.open(test_file) as im: with Image.open(test_file) as im:
return len(im.split()) return len(im.split())
self.assertEqual(split_open("1"), 1) assert split_open("1") == 1
self.assertEqual(split_open("L"), 1) assert split_open("L") == 1
self.assertEqual(split_open("P"), 1) assert split_open("P") == 1
self.assertEqual(split_open("RGB"), 3) assert split_open("RGB") == 3
if features.check("zlib"): if features.check("zlib"):
self.assertEqual(split_open("RGBA"), 4) assert split_open("RGBA") == 4

View File

@ -1,5 +1,6 @@
import math import math
import pytest
from PIL import Image, ImageTransform from PIL import Image, ImageTransform
from .helper import PillowTestCase, assert_image_equal, assert_image_similar, hopper from .helper import PillowTestCase, assert_image_equal, assert_image_similar, hopper
@ -24,11 +25,11 @@ class TestImageTransform(PillowTestCase):
comment = b"File written by Adobe Photoshop\xa8 4.0" comment = b"File written by Adobe Photoshop\xa8 4.0"
with Image.open("Tests/images/hopper.gif") as im: with Image.open("Tests/images/hopper.gif") as im:
self.assertEqual(im.info["comment"], comment) assert im.info["comment"] == comment
transform = ImageTransform.ExtentTransform((0, 0, 0, 0)) transform = ImageTransform.ExtentTransform((0, 0, 0, 0))
new_im = im.transform((100, 100), transform) new_im = im.transform((100, 100), transform)
self.assertEqual(new_im.info["comment"], comment) assert new_im.info["comment"] == comment
def test_extent(self): def test_extent(self):
im = hopper("RGB") im = hopper("RGB")
@ -79,7 +80,7 @@ class TestImageTransform(PillowTestCase):
fillcolor="red", fillcolor="red",
) )
self.assertEqual(transformed.getpixel((w - 1, h - 1)), pixel) assert transformed.getpixel((w - 1, h - 1)) == pixel
def test_mesh(self): def test_mesh(self):
# this should be a checkerboard of halfsized hoppers in ul, lr # this should be a checkerboard of halfsized hoppers in ul, lr
@ -126,7 +127,7 @@ class TestImageTransform(PillowTestCase):
im_background.paste(im, (0, 0), im) im_background.paste(im, (0, 0), im)
hist = im_background.histogram() hist = im_background.histogram()
self.assertEqual(40 * 10, hist[-1]) assert 40 * 10 == hist[-1]
def test_alpha_premult_resize(self): def test_alpha_premult_resize(self):
def op(im, sz): def op(im, sz):
@ -165,20 +166,15 @@ class TestImageTransform(PillowTestCase):
def test_missing_method_data(self): def test_missing_method_data(self):
with hopper() as im: with hopper() as im:
self.assertRaises(ValueError, im.transform, (100, 100), None) with pytest.raises(ValueError):
im.transform((100, 100), None)
def test_unknown_resampling_filter(self): def test_unknown_resampling_filter(self):
with hopper() as im: with hopper() as im:
(w, h) = im.size (w, h) = im.size
for resample in (Image.BOX, "unknown"): for resample in (Image.BOX, "unknown"):
self.assertRaises( with pytest.raises(ValueError):
ValueError, im.transform((100, 100), Image.EXTENT, (0, 0, w, h), resample)
im.transform,
(100, 100),
Image.EXTENT,
(0, 0, w, h),
resample,
)
class TestImageTransformAffine(PillowTestCase): class TestImageTransformAffine(PillowTestCase):

View File

@ -1,5 +1,6 @@
from io import BytesIO from io import BytesIO
import pytest
from PIL import EpsImagePlugin, Image, ImageFile, features from PIL import EpsImagePlugin, Image, ImageFile, features
from .helper import ( from .helper import (
@ -71,14 +72,15 @@ class TestImageFile(PillowTestCase):
im1, im2 = roundtrip("JPEG") # lossy compression im1, im2 = roundtrip("JPEG") # lossy compression
assert_image(im1, im2.mode, im2.size) assert_image(im1, im2.mode, im2.size)
self.assertRaises(IOError, roundtrip, "PDF") with pytest.raises(IOError):
roundtrip("PDF")
def test_ico(self): def test_ico(self):
with open("Tests/images/python.ico", "rb") as f: with open("Tests/images/python.ico", "rb") as f:
data = f.read() data = f.read()
with ImageFile.Parser() as p: with ImageFile.Parser() as p:
p.feed(data) p.feed(data)
self.assertEqual((48, 48), p.image.size) assert (48, 48) == p.image.size
@skip_unless_feature("zlib") @skip_unless_feature("zlib")
def test_safeblock(self): def test_safeblock(self):
@ -93,10 +95,11 @@ class TestImageFile(PillowTestCase):
assert_image_equal(im1, im2) assert_image_equal(im1, im2)
def test_raise_ioerror(self): def test_raise_ioerror(self):
self.assertRaises(IOError, ImageFile.raise_ioerror, 1) with pytest.raises(IOError):
ImageFile.raise_ioerror(1)
def test_raise_typeerror(self): def test_raise_typeerror(self):
with self.assertRaises(TypeError): with pytest.raises(TypeError):
parser = ImageFile.Parser() parser = ImageFile.Parser()
parser.feed(1) parser.feed(1)
@ -105,17 +108,17 @@ class TestImageFile(PillowTestCase):
input = f.read() input = f.read()
p = ImageFile.Parser() p = ImageFile.Parser()
p.feed(input) p.feed(input)
with self.assertRaises(IOError): with pytest.raises(IOError):
p.close() p.close()
@skip_unless_feature("zlib") @skip_unless_feature("zlib")
def test_truncated_with_errors(self): def test_truncated_with_errors(self):
with Image.open("Tests/images/truncated_image.png") as im: with Image.open("Tests/images/truncated_image.png") as im:
with self.assertRaises(IOError): with pytest.raises(IOError):
im.load() im.load()
# Test that the error is raised if loaded a second time # Test that the error is raised if loaded a second time
with self.assertRaises(IOError): with pytest.raises(IOError):
im.load() im.load()
@skip_unless_feature("zlib") @skip_unless_feature("zlib")
@ -130,7 +133,7 @@ class TestImageFile(PillowTestCase):
@skip_unless_feature("zlib") @skip_unless_feature("zlib")
def test_broken_datastream_with_errors(self): def test_broken_datastream_with_errors(self):
with Image.open("Tests/images/broken_data_stream.png") as im: with Image.open("Tests/images/broken_data_stream.png") as im:
with self.assertRaises(IOError): with pytest.raises(IOError):
im.load() im.load()
@skip_unless_feature("zlib") @skip_unless_feature("zlib")
@ -179,12 +182,13 @@ class TestPyDecoder(PillowTestCase):
im.load() im.load()
self.assertEqual(d.state.xoff, xoff) assert d.state.xoff == xoff
self.assertEqual(d.state.yoff, yoff) assert d.state.yoff == yoff
self.assertEqual(d.state.xsize, xsize) assert d.state.xsize == xsize
self.assertEqual(d.state.ysize, ysize) assert d.state.ysize == ysize
self.assertRaises(ValueError, d.set_as_raw, b"\x00") with pytest.raises(ValueError):
d.set_as_raw(b"\x00")
def test_extents_none(self): def test_extents_none(self):
buf = BytesIO(b"\x00" * 255) buf = BytesIO(b"\x00" * 255)
@ -195,10 +199,10 @@ class TestPyDecoder(PillowTestCase):
im.load() im.load()
self.assertEqual(d.state.xoff, 0) assert d.state.xoff == 0
self.assertEqual(d.state.yoff, 0) assert d.state.yoff == 0
self.assertEqual(d.state.xsize, 200) assert d.state.xsize == 200
self.assertEqual(d.state.ysize, 200) assert d.state.ysize == 200
def test_negsize(self): def test_negsize(self):
buf = BytesIO(b"\x00" * 255) buf = BytesIO(b"\x00" * 255)
@ -207,10 +211,12 @@ class TestPyDecoder(PillowTestCase):
im.tile = [("MOCK", (xoff, yoff, -10, yoff + ysize), 32, None)] im.tile = [("MOCK", (xoff, yoff, -10, yoff + ysize), 32, None)]
self.get_decoder() self.get_decoder()
self.assertRaises(ValueError, im.load) with pytest.raises(ValueError):
im.load()
im.tile = [("MOCK", (xoff, yoff, xoff + xsize, -10), 32, None)] im.tile = [("MOCK", (xoff, yoff, xoff + xsize, -10), 32, None)]
self.assertRaises(ValueError, im.load) with pytest.raises(ValueError):
im.load()
def test_oversize(self): def test_oversize(self):
buf = BytesIO(b"\x00" * 255) buf = BytesIO(b"\x00" * 255)
@ -219,25 +225,27 @@ class TestPyDecoder(PillowTestCase):
im.tile = [("MOCK", (xoff, yoff, xoff + xsize + 100, yoff + ysize), 32, None)] im.tile = [("MOCK", (xoff, yoff, xoff + xsize + 100, yoff + ysize), 32, None)]
self.get_decoder() self.get_decoder()
self.assertRaises(ValueError, im.load) with pytest.raises(ValueError):
im.load()
im.tile = [("MOCK", (xoff, yoff, xoff + xsize, yoff + ysize + 100), 32, None)] im.tile = [("MOCK", (xoff, yoff, xoff + xsize, yoff + ysize + 100), 32, None)]
self.assertRaises(ValueError, im.load) with pytest.raises(ValueError):
im.load()
def test_no_format(self): def test_no_format(self):
buf = BytesIO(b"\x00" * 255) buf = BytesIO(b"\x00" * 255)
im = MockImageFile(buf) im = MockImageFile(buf)
self.assertIsNone(im.format) assert im.format is None
self.assertIsNone(im.get_format_mimetype()) assert im.get_format_mimetype() is None
def test_exif_jpeg(self): def test_exif_jpeg(self):
with Image.open("Tests/images/exif-72dpi-int.jpg") as im: # Little endian with Image.open("Tests/images/exif-72dpi-int.jpg") as im: # Little endian
exif = im.getexif() exif = im.getexif()
self.assertNotIn(258, exif) assert 258 not in exif
self.assertIn(40960, exif) assert 40960 in exif
self.assertEqual(exif[40963], 450) assert exif[40963] == 450
self.assertEqual(exif[11], "gThumb 3.0.1") assert exif[11] == "gThumb 3.0.1"
out = self.tempfile("temp.jpg") out = self.tempfile("temp.jpg")
exif[258] = 8 exif[258] = 8
@ -247,17 +255,17 @@ class TestPyDecoder(PillowTestCase):
im.save(out, exif=exif) im.save(out, exif=exif)
with Image.open(out) as reloaded: with Image.open(out) as reloaded:
reloaded_exif = reloaded.getexif() reloaded_exif = reloaded.getexif()
self.assertEqual(reloaded_exif[258], 8) assert reloaded_exif[258] == 8
self.assertNotIn(40960, exif) assert 40960 not in exif
self.assertEqual(reloaded_exif[40963], 455) assert reloaded_exif[40963] == 455
self.assertEqual(exif[11], "Pillow test") assert exif[11] == "Pillow test"
with Image.open("Tests/images/no-dpi-in-exif.jpg") as im: # Big endian with Image.open("Tests/images/no-dpi-in-exif.jpg") as im: # Big endian
exif = im.getexif() exif = im.getexif()
self.assertNotIn(258, exif) assert 258 not in exif
self.assertIn(40962, exif) assert 40962 in exif
self.assertEqual(exif[40963], 200) assert exif[40963] == 200
self.assertEqual(exif[305], "Adobe Photoshop CC 2017 (Macintosh)") assert exif[305] == "Adobe Photoshop CC 2017 (Macintosh)"
out = self.tempfile("temp.jpg") out = self.tempfile("temp.jpg")
exif[258] = 8 exif[258] = 8
@ -267,17 +275,17 @@ class TestPyDecoder(PillowTestCase):
im.save(out, exif=exif) im.save(out, exif=exif)
with Image.open(out) as reloaded: with Image.open(out) as reloaded:
reloaded_exif = reloaded.getexif() reloaded_exif = reloaded.getexif()
self.assertEqual(reloaded_exif[258], 8) assert reloaded_exif[258] == 8
self.assertNotIn(40960, exif) assert 40960 not in exif
self.assertEqual(reloaded_exif[40963], 455) assert reloaded_exif[40963] == 455
self.assertEqual(exif[305], "Pillow test") assert exif[305] == "Pillow test"
@skip_unless_feature("webp") @skip_unless_feature("webp")
@skip_unless_feature("webp_anim") @skip_unless_feature("webp_anim")
def test_exif_webp(self): def test_exif_webp(self):
with Image.open("Tests/images/hopper.webp") as im: with Image.open("Tests/images/hopper.webp") as im:
exif = im.getexif() exif = im.getexif()
self.assertEqual(exif, {}) assert exif == {}
out = self.tempfile("temp.webp") out = self.tempfile("temp.webp")
exif[258] = 8 exif[258] = 8
@ -287,9 +295,9 @@ class TestPyDecoder(PillowTestCase):
def check_exif(): def check_exif():
with Image.open(out) as reloaded: with Image.open(out) as reloaded:
reloaded_exif = reloaded.getexif() reloaded_exif = reloaded.getexif()
self.assertEqual(reloaded_exif[258], 8) assert reloaded_exif[258] == 8
self.assertEqual(reloaded_exif[40963], 455) assert reloaded_exif[40963] == 455
self.assertEqual(exif[305], "Pillow test") assert exif[305] == "Pillow test"
im.save(out, exif=exif) im.save(out, exif=exif)
check_exif() check_exif()
@ -299,7 +307,7 @@ class TestPyDecoder(PillowTestCase):
def test_exif_png(self): def test_exif_png(self):
with Image.open("Tests/images/exif.png") as im: with Image.open("Tests/images/exif.png") as im:
exif = im.getexif() exif = im.getexif()
self.assertEqual(exif, {274: 1}) assert exif == {274: 1}
out = self.tempfile("temp.png") out = self.tempfile("temp.png")
exif[258] = 8 exif[258] = 8
@ -310,11 +318,14 @@ class TestPyDecoder(PillowTestCase):
with Image.open(out) as reloaded: with Image.open(out) as reloaded:
reloaded_exif = reloaded.getexif() reloaded_exif = reloaded.getexif()
self.assertEqual(reloaded_exif, {258: 8, 40963: 455, 305: "Pillow test"}) assert reloaded_exif == {258: 8, 40963: 455, 305: "Pillow test"}
def test_exif_interop(self): def test_exif_interop(self):
with Image.open("Tests/images/flower.jpg") as im: with Image.open("Tests/images/flower.jpg") as im:
exif = im.getexif() exif = im.getexif()
self.assertEqual( assert exif.get_ifd(0xA005) == {
exif.get_ifd(0xA005), {1: "R98", 2: b"0100", 4097: 2272, 4098: 1704} 1: "R98",
) 2: b"0100",
4097: 2272,
4098: 1704,
}

View File

@ -7,6 +7,7 @@ import unittest
from io import BytesIO from io import BytesIO
from unittest import mock from unittest import mock
import pytest
from PIL import Image, ImageDraw, ImageFont from PIL import Image, ImageDraw, ImageFont
from .helper import ( from .helper import (
@ -69,19 +70,19 @@ class TestImageFont(PillowTestCase):
def test_font_properties(self): def test_font_properties(self):
ttf = self.get_font() ttf = self.get_font()
self.assertEqual(ttf.path, FONT_PATH) assert ttf.path == FONT_PATH
self.assertEqual(ttf.size, FONT_SIZE) assert ttf.size == FONT_SIZE
ttf_copy = ttf.font_variant() ttf_copy = ttf.font_variant()
self.assertEqual(ttf_copy.path, FONT_PATH) assert ttf_copy.path == FONT_PATH
self.assertEqual(ttf_copy.size, FONT_SIZE) assert ttf_copy.size == FONT_SIZE
ttf_copy = ttf.font_variant(size=FONT_SIZE + 1) ttf_copy = ttf.font_variant(size=FONT_SIZE + 1)
self.assertEqual(ttf_copy.size, FONT_SIZE + 1) assert ttf_copy.size == FONT_SIZE + 1
second_font_path = "Tests/fonts/DejaVuSans.ttf" second_font_path = "Tests/fonts/DejaVuSans.ttf"
ttf_copy = ttf.font_variant(font=second_font_path) ttf_copy = ttf.font_variant(font=second_font_path)
self.assertEqual(ttf_copy.path, second_font_path) assert ttf_copy.path == second_font_path
def test_font_with_name(self): def test_font_with_name(self):
self.get_font() self.get_font()
@ -100,7 +101,8 @@ class TestImageFont(PillowTestCase):
# Usage note: making two fonts from the same buffer fails. # Usage note: making two fonts from the same buffer fails.
# shared_bytes = self._font_as_bytes() # shared_bytes = self._font_as_bytes()
# self._render(shared_bytes) # self._render(shared_bytes)
# self.assertRaises(Exception, _render, shared_bytes) # with pytest.raises(Exception):
# _render(shared_bytes)
def test_font_with_open_file(self): def test_font_with_open_file(self):
with open(FONT_PATH, "rb") as f: with open(FONT_PATH, "rb") as f:
@ -126,7 +128,7 @@ class TestImageFont(PillowTestCase):
finally: finally:
ImageFont.core.HAVE_RAQM = have_raqm ImageFont.core.HAVE_RAQM = have_raqm
self.assertEqual(ttf.layout_engine, ImageFont.LAYOUT_BASIC) assert ttf.layout_engine == ImageFont.LAYOUT_BASIC
def _render(self, font): def _render(self, font):
txt = "Hello World!" txt = "Hello World!"
@ -222,14 +224,8 @@ class TestImageFont(PillowTestCase):
ttf = self.get_font() ttf = self.get_font()
# Act/Assert # Act/Assert
self.assertRaises( with pytest.raises(ValueError):
ValueError, draw.multiline_text((0, 0), TEST_TEXT, font=ttf, align="unknown")
draw.multiline_text,
(0, 0),
TEST_TEXT,
font=ttf,
align="unknown",
)
def test_draw_align(self): def test_draw_align(self):
im = Image.new("RGB", (300, 100), "white") im = Image.new("RGB", (300, 100), "white")
@ -244,14 +240,13 @@ class TestImageFont(PillowTestCase):
draw = ImageDraw.Draw(im) draw = ImageDraw.Draw(im)
# Test that textsize() correctly connects to multiline_textsize() # Test that textsize() correctly connects to multiline_textsize()
self.assertEqual( assert draw.textsize(TEST_TEXT, font=ttf) == draw.multiline_textsize(
draw.textsize(TEST_TEXT, font=ttf), TEST_TEXT, font=ttf
draw.multiline_textsize(TEST_TEXT, font=ttf),
) )
# Test that multiline_textsize corresponds to ImageFont.textsize() # Test that multiline_textsize corresponds to ImageFont.textsize()
# for single line text # for single line text
self.assertEqual(ttf.getsize("A"), draw.multiline_textsize("A", font=ttf)) assert ttf.getsize("A") == draw.multiline_textsize("A", font=ttf)
# Test that textsize() can pass on additional arguments # Test that textsize() can pass on additional arguments
# to multiline_textsize() # to multiline_textsize()
@ -263,9 +258,9 @@ class TestImageFont(PillowTestCase):
im = Image.new(mode="RGB", size=(300, 100)) im = Image.new(mode="RGB", size=(300, 100))
draw = ImageDraw.Draw(im) draw = ImageDraw.Draw(im)
self.assertEqual( assert (
draw.textsize("longest line", font=ttf)[0], draw.textsize("longest line", font=ttf)[0]
draw.multiline_textsize("longest line\nline", font=ttf)[0], == draw.multiline_textsize("longest line\nline", font=ttf)[0]
) )
def test_multiline_spacing(self): def test_multiline_spacing(self):
@ -299,8 +294,8 @@ class TestImageFont(PillowTestCase):
box_size_b = draw.textsize(word) box_size_b = draw.textsize(word)
# Check (w,h) of box a is (h,w) of box b # Check (w,h) of box a is (h,w) of box b
self.assertEqual(box_size_a[0], box_size_b[1]) assert box_size_a[0] == box_size_b[1]
self.assertEqual(box_size_a[1], box_size_b[0]) assert box_size_a[1] == box_size_b[0]
def test_unrotated_transposed_font(self): def test_unrotated_transposed_font(self):
img_grey = Image.new("L", (100, 100)) img_grey = Image.new("L", (100, 100))
@ -320,7 +315,7 @@ class TestImageFont(PillowTestCase):
box_size_b = draw.textsize(word) box_size_b = draw.textsize(word)
# Check boxes a and b are same size # Check boxes a and b are same size
self.assertEqual(box_size_a, box_size_b) assert box_size_a == box_size_b
def test_rotated_transposed_font_get_mask(self): def test_rotated_transposed_font_get_mask(self):
# Arrange # Arrange
@ -333,7 +328,7 @@ class TestImageFont(PillowTestCase):
mask = transposed_font.getmask(text) mask = transposed_font.getmask(text)
# Assert # Assert
self.assertEqual(mask.size, (13, 108)) assert mask.size == (13, 108)
def test_unrotated_transposed_font_get_mask(self): def test_unrotated_transposed_font_get_mask(self):
# Arrange # Arrange
@ -346,7 +341,7 @@ class TestImageFont(PillowTestCase):
mask = transposed_font.getmask(text) mask = transposed_font.getmask(text)
# Assert # Assert
self.assertEqual(mask.size, (108, 13)) assert mask.size == (108, 13)
def test_free_type_font_get_name(self): def test_free_type_font_get_name(self):
# Arrange # Arrange
@ -356,7 +351,7 @@ class TestImageFont(PillowTestCase):
name = font.getname() name = font.getname()
# Assert # Assert
self.assertEqual(("FreeMono", "Regular"), name) assert ("FreeMono", "Regular") == name
def test_free_type_font_get_metrics(self): def test_free_type_font_get_metrics(self):
# Arrange # Arrange
@ -366,9 +361,9 @@ class TestImageFont(PillowTestCase):
ascent, descent = font.getmetrics() ascent, descent = font.getmetrics()
# Assert # Assert
self.assertIsInstance(ascent, int) assert isinstance(ascent, int)
self.assertIsInstance(descent, int) assert isinstance(descent, int)
self.assertEqual((ascent, descent), (16, 4)) # too exact check? assert (ascent, descent) == (16, 4) # too exact check?
def test_free_type_font_get_offset(self): def test_free_type_font_get_offset(self):
# Arrange # Arrange
@ -379,7 +374,7 @@ class TestImageFont(PillowTestCase):
offset = font.getoffset(text) offset = font.getoffset(text)
# Assert # Assert
self.assertEqual(offset, (0, 3)) assert offset == (0, 3)
def test_free_type_font_get_mask(self): def test_free_type_font_get_mask(self):
# Arrange # Arrange
@ -390,19 +385,22 @@ class TestImageFont(PillowTestCase):
mask = font.getmask(text) mask = font.getmask(text)
# Assert # Assert
self.assertEqual(mask.size, (108, 13)) assert mask.size == (108, 13)
def test_load_path_not_found(self): def test_load_path_not_found(self):
# Arrange # Arrange
filename = "somefilenamethatdoesntexist.ttf" filename = "somefilenamethatdoesntexist.ttf"
# Act/Assert # Act/Assert
self.assertRaises(IOError, ImageFont.load_path, filename) with pytest.raises(IOError):
self.assertRaises(IOError, ImageFont.truetype, filename) ImageFont.load_path(filename)
with pytest.raises(IOError):
ImageFont.truetype(filename)
def test_load_non_font_bytes(self): def test_load_non_font_bytes(self):
with open("Tests/images/hopper.jpg", "rb") as f: with open("Tests/images/hopper.jpg", "rb") as f:
self.assertRaises(IOError, ImageFont.truetype, f) with pytest.raises(IOError):
ImageFont.truetype(f)
def test_default_font(self): def test_default_font(self):
# Arrange # Arrange
@ -424,7 +422,7 @@ class TestImageFont(PillowTestCase):
# issue #2614 # issue #2614
font = self.get_font() font = self.get_font()
# should not crash. # should not crash.
self.assertEqual((0, 0), font.getsize("")) assert (0, 0) == font.getsize("")
def test_render_empty(self): def test_render_empty(self):
# issue 2666 # issue 2666
@ -440,7 +438,7 @@ class TestImageFont(PillowTestCase):
# should not segfault, should return UnicodeDecodeError # should not segfault, should return UnicodeDecodeError
# issue #2826 # issue #2826
font = ImageFont.load_default() font = ImageFont.load_default()
with self.assertRaises(UnicodeEncodeError): with pytest.raises(UnicodeEncodeError):
font.getsize("") font.getsize("")
@unittest.skipIf(is_pypy(), "failing on PyPy") @unittest.skipIf(is_pypy(), "failing on PyPy")
@ -478,7 +476,7 @@ class TestImageFont(PillowTestCase):
font = ImageFont.truetype(fontname) font = ImageFont.truetype(fontname)
# Make sure it's loaded # Make sure it's loaded
name = font.getname() name = font.getname()
self.assertEqual(("FreeMono", "Regular"), name) assert ("FreeMono", "Regular") == name
@unittest.skipIf(is_win32(), "requires Unix or macOS") @unittest.skipIf(is_win32(), "requires Unix or macOS")
def test_find_linux_font(self): def test_find_linux_font(self):
@ -561,24 +559,24 @@ class TestImageFont(PillowTestCase):
t = self.get_font() t = self.get_font()
# Act / Assert # Act / Assert
self.assertEqual(t.getmetrics(), (16, 4)) assert t.getmetrics() == (16, 4)
self.assertEqual(t.font.ascent, 16) assert t.font.ascent == 16
self.assertEqual(t.font.descent, 4) assert t.font.descent == 4
self.assertEqual(t.font.height, 20) assert t.font.height == 20
self.assertEqual(t.font.x_ppem, 20) assert t.font.x_ppem == 20
self.assertEqual(t.font.y_ppem, 20) assert t.font.y_ppem == 20
self.assertEqual(t.font.glyphs, 4177) assert t.font.glyphs == 4177
self.assertEqual(t.getsize("A"), (12, 16)) assert t.getsize("A") == (12, 16)
self.assertEqual(t.getsize("AB"), (24, 16)) assert t.getsize("AB") == (24, 16)
self.assertEqual(t.getsize("M"), self.metrics["getters"]) assert t.getsize("M") == self.metrics["getters"]
self.assertEqual(t.getsize("y"), (12, 20)) assert t.getsize("y") == (12, 20)
self.assertEqual(t.getsize("a"), (12, 16)) assert t.getsize("a") == (12, 16)
self.assertEqual(t.getsize_multiline("A"), (12, 16)) assert t.getsize_multiline("A") == (12, 16)
self.assertEqual(t.getsize_multiline("AB"), (24, 16)) assert t.getsize_multiline("AB") == (24, 16)
self.assertEqual(t.getsize_multiline("a"), (12, 16)) assert t.getsize_multiline("a") == (12, 16)
self.assertEqual(t.getsize_multiline("ABC\n"), (36, 36)) assert t.getsize_multiline("ABC\n") == (36, 36)
self.assertEqual(t.getsize_multiline("ABC\nA"), (36, 36)) assert t.getsize_multiline("ABC\nA") == (36, 36)
self.assertEqual(t.getsize_multiline("ABC\nAaaa"), (48, 36)) assert t.getsize_multiline("ABC\nAaaa") == (48, 36)
def test_getsize_stroke(self): def test_getsize_stroke(self):
# Arrange # Arrange
@ -586,13 +584,13 @@ class TestImageFont(PillowTestCase):
# Act / Assert # Act / Assert
for stroke_width in [0, 2]: for stroke_width in [0, 2]:
self.assertEqual( assert t.getsize("A", stroke_width=stroke_width) == (
t.getsize("A", stroke_width=stroke_width), 12 + stroke_width * 2,
(12 + stroke_width * 2, 16 + stroke_width * 2), 16 + stroke_width * 2,
) )
self.assertEqual( assert t.getsize_multiline("ABC\nAaaa", stroke_width=stroke_width) == (
t.getsize_multiline("ABC\nAaaa", stroke_width=stroke_width), 48 + stroke_width * 2,
(48 + stroke_width * 2, 36 + stroke_width * 4), 36 + stroke_width * 4,
) )
def test_complex_font_settings(self): def test_complex_font_settings(self):
@ -600,81 +598,80 @@ class TestImageFont(PillowTestCase):
t = self.get_font() t = self.get_font()
# Act / Assert # Act / Assert
if t.layout_engine == ImageFont.LAYOUT_BASIC: if t.layout_engine == ImageFont.LAYOUT_BASIC:
self.assertRaises(KeyError, t.getmask, "абвг", direction="rtl") with pytest.raises(KeyError):
self.assertRaises(KeyError, t.getmask, "абвг", features=["-kern"]) t.getmask("абвг", direction="rtl")
self.assertRaises(KeyError, t.getmask, "абвг", language="sr") with pytest.raises(KeyError):
t.getmask("абвг", features=["-kern"])
with pytest.raises(KeyError):
t.getmask("абвг", language="sr")
def test_variation_get(self): def test_variation_get(self):
font = self.get_font() font = self.get_font()
freetype = distutils.version.StrictVersion(ImageFont.core.freetype2_version) freetype = distutils.version.StrictVersion(ImageFont.core.freetype2_version)
if freetype < "2.9.1": if freetype < "2.9.1":
self.assertRaises(NotImplementedError, font.get_variation_names) with pytest.raises(NotImplementedError):
self.assertRaises(NotImplementedError, font.get_variation_axes) font.get_variation_names()
with pytest.raises(NotImplementedError):
font.get_variation_axes()
return return
self.assertRaises(IOError, font.get_variation_names) with pytest.raises(IOError):
self.assertRaises(IOError, font.get_variation_axes) font.get_variation_names()
with pytest.raises(IOError):
font.get_variation_axes()
font = ImageFont.truetype("Tests/fonts/AdobeVFPrototype.ttf") font = ImageFont.truetype("Tests/fonts/AdobeVFPrototype.ttf")
self.assertEqual( assert font.get_variation_names(), [
font.get_variation_names(), b"ExtraLight",
[ b"Light",
b"ExtraLight", b"Regular",
b"Light", b"Semibold",
b"Regular", b"Bold",
b"Semibold", b"Black",
b"Bold", b"Black Medium Contrast",
b"Black", b"Black High Contrast",
b"Black Medium Contrast", b"Default",
b"Black High Contrast", ]
b"Default", assert font.get_variation_axes() == [
], {"name": b"Weight", "minimum": 200, "maximum": 900, "default": 389},
) {"name": b"Contrast", "minimum": 0, "maximum": 100, "default": 0},
self.assertEqual( ]
font.get_variation_axes(),
[
{"name": b"Weight", "minimum": 200, "maximum": 900, "default": 389},
{"name": b"Contrast", "minimum": 0, "maximum": 100, "default": 0},
],
)
font = ImageFont.truetype("Tests/fonts/TINY5x3GX.ttf") font = ImageFont.truetype("Tests/fonts/TINY5x3GX.ttf")
self.assertEqual( assert font.get_variation_names() == [
font.get_variation_names(), b"20",
[ b"40",
b"20", b"60",
b"40", b"80",
b"60", b"100",
b"80", b"120",
b"100", b"140",
b"120", b"160",
b"140", b"180",
b"160", b"200",
b"180", b"220",
b"200", b"240",
b"220", b"260",
b"240", b"280",
b"260", b"300",
b"280", b"Regular",
b"300", ]
b"Regular", assert font.get_variation_axes() == [
], {"name": b"Size", "minimum": 0, "maximum": 300, "default": 0}
) ]
self.assertEqual(
font.get_variation_axes(),
[{"name": b"Size", "minimum": 0, "maximum": 300, "default": 0}],
)
def test_variation_set_by_name(self): def test_variation_set_by_name(self):
font = self.get_font() font = self.get_font()
freetype = distutils.version.StrictVersion(ImageFont.core.freetype2_version) freetype = distutils.version.StrictVersion(ImageFont.core.freetype2_version)
if freetype < "2.9.1": if freetype < "2.9.1":
self.assertRaises(NotImplementedError, font.set_variation_by_name, "Bold") with pytest.raises(NotImplementedError):
font.set_variation_by_name("Bold")
return return
self.assertRaises(IOError, font.set_variation_by_name, "Bold") with pytest.raises(IOError):
font.set_variation_by_name("Bold")
def _check_text(font, path, epsilon): def _check_text(font, path, epsilon):
im = Image.new("RGB", (100, 75), "white") im = Image.new("RGB", (100, 75), "white")
@ -701,10 +698,12 @@ class TestImageFont(PillowTestCase):
freetype = distutils.version.StrictVersion(ImageFont.core.freetype2_version) freetype = distutils.version.StrictVersion(ImageFont.core.freetype2_version)
if freetype < "2.9.1": if freetype < "2.9.1":
self.assertRaises(NotImplementedError, font.set_variation_by_axes, [100]) with pytest.raises(NotImplementedError):
font.set_variation_by_axes([100])
return return
self.assertRaises(IOError, font.set_variation_by_axes, [500, 50]) with pytest.raises(IOError):
font.set_variation_by_axes([500, 50])
def _check_text(font, path, epsilon): def _check_text(font, path, epsilon):
im = Image.new("RGB", (100, 75), "white") im = Image.new("RGB", (100, 75), "white")

View File

@ -140,7 +140,7 @@ class TestImagecomplextext(PillowTestCase):
assert_image_similar(im, target_img, 0.5) assert_image_similar(im, target_img, 0.5)
liga_size = ttf.getsize("fi", features=["-liga"]) liga_size = ttf.getsize("fi", features=["-liga"])
self.assertEqual(liga_size, (13, 19)) assert liga_size == (13, 19)
def test_kerning_features(self): def test_kerning_features(self):
ttf = ImageFont.truetype(FONT_PATH, FONT_SIZE) ttf = ImageFont.truetype(FONT_PATH, FONT_SIZE)

View File

@ -59,7 +59,7 @@ class TestImageGrabImport(PillowTestCase):
# Assert # Assert
if sys.platform in ["win32", "darwin"]: if sys.platform in ["win32", "darwin"]:
self.assertIsNone(exception) assert exception is None
else: else:
self.assertIsInstance(exception, ImportError) assert isinstance(exception, ImportError)
self.assertEqual(str(exception), "ImageGrab is macOS and Windows only") assert str(exception) == "ImageGrab is macOS and Windows only"

View File

@ -1,4 +1,5 @@
# Test the ImageMorphology functionality # Test the ImageMorphology functionality
import pytest
from PIL import Image, ImageMorph, _imagingmorph from PIL import Image, ImageMorph, _imagingmorph
from .helper import PillowTestCase, assert_image_equal, hopper from .helper import PillowTestCase, assert_image_equal, hopper
@ -45,10 +46,10 @@ class MorphTests(PillowTestCase):
return self.img_to_string(self.string_to_img(im)) return self.img_to_string(self.string_to_img(im))
def assert_img_equal(self, A, B): def assert_img_equal(self, A, B):
self.assertEqual(self.img_to_string(A), self.img_to_string(B)) assert self.img_to_string(A) == self.img_to_string(B)
def assert_img_equal_img_string(self, A, Bstring): def assert_img_equal_img_string(self, A, Bstring):
self.assertEqual(self.img_to_string(A), self.img_string_normalize(Bstring)) assert self.img_to_string(A) == self.img_string_normalize(Bstring)
def test_str_to_img(self): def test_str_to_img(self):
with Image.open("Tests/images/morph_a.png") as im: with Image.open("Tests/images/morph_a.png") as im:
@ -65,30 +66,30 @@ class MorphTests(PillowTestCase):
def test_lut(self): def test_lut(self):
for op in ("corner", "dilation4", "dilation8", "erosion4", "erosion8", "edge"): for op in ("corner", "dilation4", "dilation8", "erosion4", "erosion8", "edge"):
lb = ImageMorph.LutBuilder(op_name=op) lb = ImageMorph.LutBuilder(op_name=op)
self.assertIsNone(lb.get_lut()) assert lb.get_lut() is None
lut = lb.build_lut() lut = lb.build_lut()
with open("Tests/images/%s.lut" % op, "rb") as f: with open("Tests/images/%s.lut" % op, "rb") as f:
self.assertEqual(lut, bytearray(f.read())) assert lut == bytearray(f.read())
def test_no_operator_loaded(self): def test_no_operator_loaded(self):
mop = ImageMorph.MorphOp() mop = ImageMorph.MorphOp()
with self.assertRaises(Exception) as e: with pytest.raises(Exception) as e:
mop.apply(None) mop.apply(None)
self.assertEqual(str(e.exception), "No operator loaded") assert str(e.value) == "No operator loaded"
with self.assertRaises(Exception) as e: with pytest.raises(Exception) as e:
mop.match(None) mop.match(None)
self.assertEqual(str(e.exception), "No operator loaded") assert str(e.value) == "No operator loaded"
with self.assertRaises(Exception) as e: with pytest.raises(Exception) as e:
mop.save_lut(None) mop.save_lut(None)
self.assertEqual(str(e.exception), "No operator loaded") assert str(e.value) == "No operator loaded"
# Test the named patterns # Test the named patterns
def test_erosion8(self): def test_erosion8(self):
# erosion8 # erosion8
mop = ImageMorph.MorphOp(op_name="erosion8") mop = ImageMorph.MorphOp(op_name="erosion8")
count, Aout = mop.apply(self.A) count, Aout = mop.apply(self.A)
self.assertEqual(count, 8) assert count == 8
self.assert_img_equal_img_string( self.assert_img_equal_img_string(
Aout, Aout,
""" """
@ -106,7 +107,7 @@ class MorphTests(PillowTestCase):
# dialation8 # dialation8
mop = ImageMorph.MorphOp(op_name="dilation8") mop = ImageMorph.MorphOp(op_name="dilation8")
count, Aout = mop.apply(self.A) count, Aout = mop.apply(self.A)
self.assertEqual(count, 16) assert count == 16
self.assert_img_equal_img_string( self.assert_img_equal_img_string(
Aout, Aout,
""" """
@ -124,7 +125,7 @@ class MorphTests(PillowTestCase):
# erosion4 # erosion4
mop = ImageMorph.MorphOp(op_name="dilation4") mop = ImageMorph.MorphOp(op_name="dilation4")
count, Aout = mop.apply(self.A) count, Aout = mop.apply(self.A)
self.assertEqual(count, 12) assert count == 12
self.assert_img_equal_img_string( self.assert_img_equal_img_string(
Aout, Aout,
""" """
@ -142,7 +143,7 @@ class MorphTests(PillowTestCase):
# edge # edge
mop = ImageMorph.MorphOp(op_name="edge") mop = ImageMorph.MorphOp(op_name="edge")
count, Aout = mop.apply(self.A) count, Aout = mop.apply(self.A)
self.assertEqual(count, 1) assert count == 1
self.assert_img_equal_img_string( self.assert_img_equal_img_string(
Aout, Aout,
""" """
@ -160,7 +161,7 @@ class MorphTests(PillowTestCase):
# Create a corner detector pattern # Create a corner detector pattern
mop = ImageMorph.MorphOp(patterns=["1:(... ... ...)->0", "4:(00. 01. ...)->1"]) mop = ImageMorph.MorphOp(patterns=["1:(... ... ...)->0", "4:(00. 01. ...)->1"])
count, Aout = mop.apply(self.A) count, Aout = mop.apply(self.A)
self.assertEqual(count, 5) assert count == 5
self.assert_img_equal_img_string( self.assert_img_equal_img_string(
Aout, Aout,
""" """
@ -176,18 +177,18 @@ class MorphTests(PillowTestCase):
# Test the coordinate counting with the same operator # Test the coordinate counting with the same operator
coords = mop.match(self.A) coords = mop.match(self.A)
self.assertEqual(len(coords), 4) assert len(coords) == 4
self.assertEqual(tuple(coords), ((2, 2), (4, 2), (2, 4), (4, 4))) assert tuple(coords) == ((2, 2), (4, 2), (2, 4), (4, 4))
coords = mop.get_on_pixels(Aout) coords = mop.get_on_pixels(Aout)
self.assertEqual(len(coords), 4) assert len(coords) == 4
self.assertEqual(tuple(coords), ((2, 2), (4, 2), (2, 4), (4, 4))) assert tuple(coords) == ((2, 2), (4, 2), (2, 4), (4, 4))
def test_mirroring(self): def test_mirroring(self):
# Test 'M' for mirroring # Test 'M' for mirroring
mop = ImageMorph.MorphOp(patterns=["1:(... ... ...)->0", "M:(00. 01. ...)->1"]) mop = ImageMorph.MorphOp(patterns=["1:(... ... ...)->0", "M:(00. 01. ...)->1"])
count, Aout = mop.apply(self.A) count, Aout = mop.apply(self.A)
self.assertEqual(count, 7) assert count == 7
self.assert_img_equal_img_string( self.assert_img_equal_img_string(
Aout, Aout,
""" """
@ -205,7 +206,7 @@ class MorphTests(PillowTestCase):
# Test 'N' for negate # Test 'N' for negate
mop = ImageMorph.MorphOp(patterns=["1:(... ... ...)->0", "N:(00. 01. ...)->1"]) mop = ImageMorph.MorphOp(patterns=["1:(... ... ...)->0", "N:(00. 01. ...)->1"])
count, Aout = mop.apply(self.A) count, Aout = mop.apply(self.A)
self.assertEqual(count, 8) assert count == 8
self.assert_img_equal_img_string( self.assert_img_equal_img_string(
Aout, Aout,
""" """
@ -223,44 +224,36 @@ class MorphTests(PillowTestCase):
im = hopper("RGB") im = hopper("RGB")
mop = ImageMorph.MorphOp(op_name="erosion8") mop = ImageMorph.MorphOp(op_name="erosion8")
with self.assertRaises(Exception) as e: with pytest.raises(Exception) as e:
mop.apply(im) mop.apply(im)
self.assertEqual( assert str(e.value) == "Image must be binary, meaning it must use mode L"
str(e.exception), "Image must be binary, meaning it must use mode L" with pytest.raises(Exception) as e:
)
with self.assertRaises(Exception) as e:
mop.match(im) mop.match(im)
self.assertEqual( assert str(e.value) == "Image must be binary, meaning it must use mode L"
str(e.exception), "Image must be binary, meaning it must use mode L" with pytest.raises(Exception) as e:
)
with self.assertRaises(Exception) as e:
mop.get_on_pixels(im) mop.get_on_pixels(im)
self.assertEqual( assert str(e.value) == "Image must be binary, meaning it must use mode L"
str(e.exception), "Image must be binary, meaning it must use mode L"
)
def test_add_patterns(self): def test_add_patterns(self):
# Arrange # Arrange
lb = ImageMorph.LutBuilder(op_name="corner") lb = ImageMorph.LutBuilder(op_name="corner")
self.assertEqual(lb.patterns, ["1:(... ... ...)->0", "4:(00. 01. ...)->1"]) assert lb.patterns == ["1:(... ... ...)->0", "4:(00. 01. ...)->1"]
new_patterns = ["M:(00. 01. ...)->1", "N:(00. 01. ...)->1"] new_patterns = ["M:(00. 01. ...)->1", "N:(00. 01. ...)->1"]
# Act # Act
lb.add_patterns(new_patterns) lb.add_patterns(new_patterns)
# Assert # Assert
self.assertEqual( assert lb.patterns == [
lb.patterns, "1:(... ... ...)->0",
[ "4:(00. 01. ...)->1",
"1:(... ... ...)->0", "M:(00. 01. ...)->1",
"4:(00. 01. ...)->1", "N:(00. 01. ...)->1",
"M:(00. 01. ...)->1", ]
"N:(00. 01. ...)->1",
],
)
def test_unknown_pattern(self): def test_unknown_pattern(self):
self.assertRaises(Exception, ImageMorph.LutBuilder, op_name="unknown") with pytest.raises(Exception):
ImageMorph.LutBuilder(op_name="unknown")
def test_pattern_syntax_error(self): def test_pattern_syntax_error(self):
# Arrange # Arrange
@ -269,11 +262,9 @@ class MorphTests(PillowTestCase):
lb.add_patterns(new_patterns) lb.add_patterns(new_patterns)
# Act / Assert # Act / Assert
with self.assertRaises(Exception) as e: with pytest.raises(Exception) as e:
lb.build_lut() lb.build_lut()
self.assertEqual( assert str(e.value) == 'Syntax error in pattern "a pattern with a syntax error"'
str(e.exception), 'Syntax error in pattern "a pattern with a syntax error"'
)
def test_load_invalid_mrl(self): def test_load_invalid_mrl(self):
# Arrange # Arrange
@ -281,9 +272,9 @@ class MorphTests(PillowTestCase):
mop = ImageMorph.MorphOp() mop = ImageMorph.MorphOp()
# Act / Assert # Act / Assert
with self.assertRaises(Exception) as e: with pytest.raises(Exception) as e:
mop.load_lut(invalid_mrl) mop.load_lut(invalid_mrl)
self.assertEqual(str(e.exception), "Wrong size operator file!") assert str(e.value) == "Wrong size operator file!"
def test_roundtrip_mrl(self): def test_roundtrip_mrl(self):
# Arrange # Arrange
@ -296,7 +287,7 @@ class MorphTests(PillowTestCase):
mop.load_lut(tempfile) mop.load_lut(tempfile)
# Act / Assert # Act / Assert
self.assertEqual(mop.lut, initial_lut) assert mop.lut == initial_lut
def test_set_lut(self): def test_set_lut(self):
# Arrange # Arrange
@ -308,20 +299,20 @@ class MorphTests(PillowTestCase):
mop.set_lut(lut) mop.set_lut(lut)
# Assert # Assert
self.assertEqual(mop.lut, lut) assert mop.lut == lut
def test_wrong_mode(self): def test_wrong_mode(self):
lut = ImageMorph.LutBuilder(op_name="corner").build_lut() lut = ImageMorph.LutBuilder(op_name="corner").build_lut()
imrgb = Image.new("RGB", (10, 10)) imrgb = Image.new("RGB", (10, 10))
iml = Image.new("L", (10, 10)) iml = Image.new("L", (10, 10))
with self.assertRaises(RuntimeError): with pytest.raises(RuntimeError):
_imagingmorph.apply(bytes(lut), imrgb.im.id, iml.im.id) _imagingmorph.apply(bytes(lut), imrgb.im.id, iml.im.id)
with self.assertRaises(RuntimeError): with pytest.raises(RuntimeError):
_imagingmorph.apply(bytes(lut), iml.im.id, imrgb.im.id) _imagingmorph.apply(bytes(lut), iml.im.id, imrgb.im.id)
with self.assertRaises(RuntimeError): with pytest.raises(RuntimeError):
_imagingmorph.match(bytes(lut), imrgb.im.id) _imagingmorph.match(bytes(lut), imrgb.im.id)
# Should not raise # Should not raise

View File

@ -1,3 +1,4 @@
import pytest
from PIL import Image, ImageFilter from PIL import Image, ImageFilter
from .helper import PillowTestCase from .helper import PillowTestCase
@ -15,44 +16,52 @@ class TestImageOpsUsm(PillowTestCase):
test_filter = ImageFilter.GaussianBlur(2.0) test_filter = ImageFilter.GaussianBlur(2.0)
i = self.im.filter(test_filter) i = self.im.filter(test_filter)
self.assertEqual(i.mode, "RGB") assert i.mode == "RGB"
self.assertEqual(i.size, (128, 128)) assert i.size == (128, 128)
test_filter = ImageFilter.UnsharpMask(2.0, 125, 8) test_filter = ImageFilter.UnsharpMask(2.0, 125, 8)
i = self.im.filter(test_filter) i = self.im.filter(test_filter)
self.assertEqual(i.mode, "RGB") assert i.mode == "RGB"
self.assertEqual(i.size, (128, 128)) assert i.size == (128, 128)
def test_usm_formats(self): def test_usm_formats(self):
usm = ImageFilter.UnsharpMask usm = ImageFilter.UnsharpMask
self.assertRaises(ValueError, self.im.convert("1").filter, usm) with pytest.raises(ValueError):
self.im.convert("1").filter(usm)
self.im.convert("L").filter(usm) self.im.convert("L").filter(usm)
self.assertRaises(ValueError, self.im.convert("I").filter, usm) with pytest.raises(ValueError):
self.assertRaises(ValueError, self.im.convert("F").filter, usm) self.im.convert("I").filter(usm)
with pytest.raises(ValueError):
self.im.convert("F").filter(usm)
self.im.convert("RGB").filter(usm) self.im.convert("RGB").filter(usm)
self.im.convert("RGBA").filter(usm) self.im.convert("RGBA").filter(usm)
self.im.convert("CMYK").filter(usm) self.im.convert("CMYK").filter(usm)
self.assertRaises(ValueError, self.im.convert("YCbCr").filter, usm) with pytest.raises(ValueError):
self.im.convert("YCbCr").filter(usm)
def test_blur_formats(self): def test_blur_formats(self):
blur = ImageFilter.GaussianBlur blur = ImageFilter.GaussianBlur
self.assertRaises(ValueError, self.im.convert("1").filter, blur) with pytest.raises(ValueError):
self.im.convert("1").filter(blur)
blur(self.im.convert("L")) blur(self.im.convert("L"))
self.assertRaises(ValueError, self.im.convert("I").filter, blur) with pytest.raises(ValueError):
self.assertRaises(ValueError, self.im.convert("F").filter, blur) self.im.convert("I").filter(blur)
with pytest.raises(ValueError):
self.im.convert("F").filter(blur)
self.im.convert("RGB").filter(blur) self.im.convert("RGB").filter(blur)
self.im.convert("RGBA").filter(blur) self.im.convert("RGBA").filter(blur)
self.im.convert("CMYK").filter(blur) self.im.convert("CMYK").filter(blur)
self.assertRaises(ValueError, self.im.convert("YCbCr").filter, blur) with pytest.raises(ValueError):
self.im.convert("YCbCr").filter(blur)
def test_usm_accuracy(self): def test_usm_accuracy(self):
src = self.snakes.convert("RGB") src = self.snakes.convert("RGB")
i = src.filter(ImageFilter.UnsharpMask(5, 1024, 0)) i = src.filter(ImageFilter.UnsharpMask(5, 1024, 0))
# Image should not be changed because it have only 0 and 255 levels. # Image should not be changed because it have only 0 and 255 levels.
self.assertEqual(i.tobytes(), src.tobytes()) assert i.tobytes() == src.tobytes()
def test_blur_accuracy(self): def test_blur_accuracy(self):
@ -73,17 +82,17 @@ class TestImageOpsUsm(PillowTestCase):
(4, 3, 2), (4, 3, 2),
(4, 2, 2), (4, 2, 2),
]: ]:
self.assertGreaterEqual(i.im.getpixel((x, y))[c], 250) assert i.im.getpixel((x, y))[c] >= 250
# Fuzzy match. # Fuzzy match.
def gp(x, y): def gp(x, y):
return i.im.getpixel((x, y)) return i.im.getpixel((x, y))
self.assertTrue(236 <= gp(7, 4)[0] <= 239) assert 236 <= gp(7, 4)[0] <= 239
self.assertTrue(236 <= gp(7, 5)[2] <= 239) assert 236 <= gp(7, 5)[2] <= 239
self.assertTrue(236 <= gp(7, 6)[2] <= 239) assert 236 <= gp(7, 6)[2] <= 239
self.assertTrue(236 <= gp(7, 7)[1] <= 239) assert 236 <= gp(7, 7)[1] <= 239
self.assertTrue(236 <= gp(8, 4)[0] <= 239) assert 236 <= gp(8, 4)[0] <= 239
self.assertTrue(236 <= gp(8, 5)[2] <= 239) assert 236 <= gp(8, 5)[2] <= 239
self.assertTrue(236 <= gp(8, 6)[2] <= 239) assert 236 <= gp(8, 6)[2] <= 239
self.assertTrue(236 <= gp(8, 7)[1] <= 239) assert 236 <= gp(8, 7)[1] <= 239

View File

@ -1,3 +1,4 @@
import pytest
from PIL import Image, ImagePalette from PIL import Image, ImagePalette
from .helper import PillowTestCase, assert_image_equal from .helper import PillowTestCase, assert_image_equal
@ -7,9 +8,8 @@ class TestImagePalette(PillowTestCase):
def test_sanity(self): def test_sanity(self):
ImagePalette.ImagePalette("RGB", list(range(256)) * 3) ImagePalette.ImagePalette("RGB", list(range(256)) * 3)
self.assertRaises( with pytest.raises(ValueError):
ValueError, ImagePalette.ImagePalette, "RGB", list(range(256)) * 2 ImagePalette.ImagePalette("RGB", list(range(256)) * 2)
)
def test_getcolor(self): def test_getcolor(self):
@ -19,11 +19,13 @@ class TestImagePalette(PillowTestCase):
for i in range(256): for i in range(256):
test_map[palette.getcolor((i, i, i))] = i test_map[palette.getcolor((i, i, i))] = i
self.assertEqual(len(test_map), 256) assert len(test_map) == 256
self.assertRaises(ValueError, palette.getcolor, (1, 2, 3)) with pytest.raises(ValueError):
palette.getcolor((1, 2, 3))
# Test unknown color specifier # Test unknown color specifier
self.assertRaises(ValueError, palette.getcolor, "unknown") with pytest.raises(ValueError):
palette.getcolor("unknown")
def test_file(self): def test_file(self):
@ -36,12 +38,12 @@ class TestImagePalette(PillowTestCase):
p = ImagePalette.load(f) p = ImagePalette.load(f)
# load returns raw palette information # load returns raw palette information
self.assertEqual(len(p[0]), 768) assert len(p[0]) == 768
self.assertEqual(p[1], "RGB") assert p[1] == "RGB"
p = ImagePalette.raw(p[1], p[0]) p = ImagePalette.raw(p[1], p[0])
self.assertIsInstance(p, ImagePalette.ImagePalette) assert isinstance(p, ImagePalette.ImagePalette)
self.assertEqual(p.palette, palette.tobytes()) assert p.palette == palette.tobytes()
def test_make_linear_lut(self): def test_make_linear_lut(self):
# Arrange # Arrange
@ -52,11 +54,11 @@ class TestImagePalette(PillowTestCase):
lut = ImagePalette.make_linear_lut(black, white) lut = ImagePalette.make_linear_lut(black, white)
# Assert # Assert
self.assertIsInstance(lut, list) assert isinstance(lut, list)
self.assertEqual(len(lut), 256) assert len(lut) == 256
# Check values # Check values
for i in range(0, len(lut)): for i in range(0, len(lut)):
self.assertEqual(lut[i], i) assert lut[i] == i
def test_make_linear_lut_not_yet_implemented(self): def test_make_linear_lut_not_yet_implemented(self):
# Update after FIXME # Update after FIXME
@ -65,9 +67,8 @@ class TestImagePalette(PillowTestCase):
white = 255 white = 255
# Act # Act
self.assertRaises( with pytest.raises(NotImplementedError):
NotImplementedError, ImagePalette.make_linear_lut, black, white ImagePalette.make_linear_lut(black, white)
)
def test_make_gamma_lut(self): def test_make_gamma_lut(self):
# Arrange # Arrange
@ -77,24 +78,27 @@ class TestImagePalette(PillowTestCase):
lut = ImagePalette.make_gamma_lut(exp) lut = ImagePalette.make_gamma_lut(exp)
# Assert # Assert
self.assertIsInstance(lut, list) assert isinstance(lut, list)
self.assertEqual(len(lut), 256) assert len(lut) == 256
# Check a few values # Check a few values
self.assertEqual(lut[0], 0) assert lut[0] == 0
self.assertEqual(lut[63], 0) assert lut[63] == 0
self.assertEqual(lut[127], 8) assert lut[127] == 8
self.assertEqual(lut[191], 60) assert lut[191] == 60
self.assertEqual(lut[255], 255) assert lut[255] == 255
def test_rawmode_valueerrors(self): def test_rawmode_valueerrors(self):
# Arrange # Arrange
palette = ImagePalette.raw("RGB", list(range(256)) * 3) palette = ImagePalette.raw("RGB", list(range(256)) * 3)
# Act / Assert # Act / Assert
self.assertRaises(ValueError, palette.tobytes) with pytest.raises(ValueError):
self.assertRaises(ValueError, palette.getcolor, (1, 2, 3)) palette.tobytes()
with pytest.raises(ValueError):
palette.getcolor((1, 2, 3))
f = self.tempfile("temp.lut") f = self.tempfile("temp.lut")
self.assertRaises(ValueError, palette.save, f) with pytest.raises(ValueError):
palette.save(f)
def test_getdata(self): def test_getdata(self):
# Arrange # Arrange
@ -105,7 +109,7 @@ class TestImagePalette(PillowTestCase):
mode, data_out = palette.getdata() mode, data_out = palette.getdata()
# Assert # Assert
self.assertEqual(mode, "RGB;L") assert mode == "RGB;L"
def test_rawmode_getdata(self): def test_rawmode_getdata(self):
# Arrange # Arrange
@ -116,8 +120,8 @@ class TestImagePalette(PillowTestCase):
rawmode, data_out = palette.getdata() rawmode, data_out = palette.getdata()
# Assert # Assert
self.assertEqual(rawmode, "RGB") assert rawmode == "RGB"
self.assertEqual(data_in, data_out) assert data_in == data_out
def test_2bit_palette(self): def test_2bit_palette(self):
# issue #2258, 2 bit palettes are corrupted. # issue #2258, 2 bit palettes are corrupted.
@ -132,4 +136,5 @@ class TestImagePalette(PillowTestCase):
assert_image_equal(img, reloaded) assert_image_equal(img, reloaded)
def test_invalid_palette(self): def test_invalid_palette(self):
self.assertRaises(IOError, ImagePalette.load, "Tests/images/hopper.jpg") with pytest.raises(IOError):
ImagePalette.load("Tests/images/hopper.jpg")

View File

@ -1,6 +1,7 @@
import array import array
import struct import struct
import pytest
from PIL import Image, ImagePath from PIL import Image, ImagePath
from .helper import PillowTestCase from .helper import PillowTestCase
@ -12,62 +13,62 @@ class TestImagePath(PillowTestCase):
p = ImagePath.Path(list(range(10))) p = ImagePath.Path(list(range(10)))
# sequence interface # sequence interface
self.assertEqual(len(p), 5) assert len(p) == 5
self.assertEqual(p[0], (0.0, 1.0)) assert p[0] == (0.0, 1.0)
self.assertEqual(p[-1], (8.0, 9.0)) assert p[-1] == (8.0, 9.0)
self.assertEqual(list(p[:1]), [(0.0, 1.0)]) assert list(p[:1]) == [(0.0, 1.0)]
with self.assertRaises(TypeError) as cm: with pytest.raises(TypeError) as cm:
p["foo"] p["foo"]
self.assertEqual(str(cm.exception), "Path indices must be integers, not str") assert str(cm.value) == "Path indices must be integers, not str"
self.assertEqual( assert list(p) == [(0.0, 1.0), (2.0, 3.0), (4.0, 5.0), (6.0, 7.0), (8.0, 9.0)]
list(p), [(0.0, 1.0), (2.0, 3.0), (4.0, 5.0), (6.0, 7.0), (8.0, 9.0)]
)
# method sanity check # method sanity check
self.assertEqual( assert p.tolist() == [
p.tolist(), [(0.0, 1.0), (2.0, 3.0), (4.0, 5.0), (6.0, 7.0), (8.0, 9.0)] (0.0, 1.0),
) (2.0, 3.0),
self.assertEqual( (4.0, 5.0),
p.tolist(1), [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0] (6.0, 7.0),
) (8.0, 9.0),
]
assert p.tolist(1) == [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]
self.assertEqual(p.getbbox(), (0.0, 1.0, 8.0, 9.0)) assert p.getbbox() == (0.0, 1.0, 8.0, 9.0)
self.assertEqual(p.compact(5), 2) assert p.compact(5) == 2
self.assertEqual(list(p), [(0.0, 1.0), (4.0, 5.0), (8.0, 9.0)]) assert list(p) == [(0.0, 1.0), (4.0, 5.0), (8.0, 9.0)]
p.transform((1, 0, 1, 0, 1, 1)) p.transform((1, 0, 1, 0, 1, 1))
self.assertEqual(list(p), [(1.0, 2.0), (5.0, 6.0), (9.0, 10.0)]) assert list(p) == [(1.0, 2.0), (5.0, 6.0), (9.0, 10.0)]
# alternative constructors # alternative constructors
p = ImagePath.Path([0, 1]) p = ImagePath.Path([0, 1])
self.assertEqual(list(p), [(0.0, 1.0)]) assert list(p) == [(0.0, 1.0)]
p = ImagePath.Path([0.0, 1.0]) p = ImagePath.Path([0.0, 1.0])
self.assertEqual(list(p), [(0.0, 1.0)]) assert list(p) == [(0.0, 1.0)]
p = ImagePath.Path([0, 1]) p = ImagePath.Path([0, 1])
self.assertEqual(list(p), [(0.0, 1.0)]) assert list(p) == [(0.0, 1.0)]
p = ImagePath.Path([(0, 1)]) p = ImagePath.Path([(0, 1)])
self.assertEqual(list(p), [(0.0, 1.0)]) assert list(p) == [(0.0, 1.0)]
p = ImagePath.Path(p) p = ImagePath.Path(p)
self.assertEqual(list(p), [(0.0, 1.0)]) assert list(p) == [(0.0, 1.0)]
p = ImagePath.Path(p.tolist(0)) p = ImagePath.Path(p.tolist(0))
self.assertEqual(list(p), [(0.0, 1.0)]) assert list(p) == [(0.0, 1.0)]
p = ImagePath.Path(p.tolist(1)) p = ImagePath.Path(p.tolist(1))
self.assertEqual(list(p), [(0.0, 1.0)]) assert list(p) == [(0.0, 1.0)]
p = ImagePath.Path(array.array("f", [0, 1])) p = ImagePath.Path(array.array("f", [0, 1]))
self.assertEqual(list(p), [(0.0, 1.0)]) assert list(p) == [(0.0, 1.0)]
arr = array.array("f", [0, 1]) arr = array.array("f", [0, 1])
if hasattr(arr, "tobytes"): if hasattr(arr, "tobytes"):
p = ImagePath.Path(arr.tobytes()) p = ImagePath.Path(arr.tobytes())
else: else:
p = ImagePath.Path(arr.tostring()) p = ImagePath.Path(arr.tostring())
self.assertEqual(list(p), [(0.0, 1.0)]) assert list(p) == [(0.0, 1.0)]
def test_overflow_segfault(self): def test_overflow_segfault(self):
# Some Pythons fail getting the argument as an integer, and it falls # Some Pythons fail getting the argument as an integer, and it falls
# through to the sequence. Seeing this on 32-bit Windows. # through to the sequence. Seeing this on 32-bit Windows.
with self.assertRaises((TypeError, MemoryError)): with pytest.raises((TypeError, MemoryError)):
# post patch, this fails with a memory error # post patch, this fails with a memory error
x = evil() x = evil()

View File

@ -52,14 +52,14 @@ class TestImageQt(PillowQtTestCase, PillowTestCase):
elif ImageQt.qt_version == "side2": elif ImageQt.qt_version == "side2":
from PySide2.QtGui import qRgb from PySide2.QtGui import qRgb
self.assertEqual(qRgb(0, 0, 0), qRgba(0, 0, 0, 255)) assert qRgb(0, 0, 0) == qRgba(0, 0, 0, 255)
def checkrgb(r, g, b): def checkrgb(r, g, b):
val = ImageQt.rgb(r, g, b) val = ImageQt.rgb(r, g, b)
val = val % 2 ** 24 # drop the alpha val = val % 2 ** 24 # drop the alpha
self.assertEqual(val >> 16, r) assert val >> 16 == r
self.assertEqual(((val >> 8) % 2 ** 8), g) assert ((val >> 8) % 2 ** 8) == g
self.assertEqual(val % 2 ** 8, b) assert val % 2 ** 8 == b
checkrgb(0, 0, 0) checkrgb(0, 0, 0)
checkrgb(255, 0, 0) checkrgb(255, 0, 0)

View File

@ -1,3 +1,4 @@
import pytest
from PIL import Image, ImageSequence, TiffImagePlugin from PIL import Image, ImageSequence, TiffImagePlugin
from .helper import PillowTestCase, assert_image_equal, hopper, skip_unless_feature from .helper import PillowTestCase, assert_image_equal, hopper, skip_unless_feature
@ -16,32 +17,35 @@ class TestImageSequence(PillowTestCase):
index = 0 index = 0
for frame in seq: for frame in seq:
assert_image_equal(im, frame) assert_image_equal(im, frame)
self.assertEqual(im.tell(), index) assert im.tell() == index
index += 1 index += 1
self.assertEqual(index, 1) assert index == 1
self.assertRaises(AttributeError, ImageSequence.Iterator, 0) with pytest.raises(AttributeError):
ImageSequence.Iterator(0)
def test_iterator(self): def test_iterator(self):
with Image.open("Tests/images/multipage.tiff") as im: with Image.open("Tests/images/multipage.tiff") as im:
i = ImageSequence.Iterator(im) i = ImageSequence.Iterator(im)
for index in range(0, im.n_frames): for index in range(0, im.n_frames):
self.assertEqual(i[index], next(i)) assert i[index] == next(i)
self.assertRaises(IndexError, lambda: i[index + 1]) with pytest.raises(IndexError):
self.assertRaises(StopIteration, next, i) i[index + 1]
with pytest.raises(StopIteration):
next(i)
def test_iterator_min_frame(self): def test_iterator_min_frame(self):
with Image.open("Tests/images/hopper.psd") as im: with Image.open("Tests/images/hopper.psd") as im:
i = ImageSequence.Iterator(im) i = ImageSequence.Iterator(im)
for index in range(1, im.n_frames): for index in range(1, im.n_frames):
self.assertEqual(i[index], next(i)) assert i[index] == next(i)
def _test_multipage_tiff(self): def _test_multipage_tiff(self):
with Image.open("Tests/images/multipage.tiff") as im: with Image.open("Tests/images/multipage.tiff") as im:
for index, frame in enumerate(ImageSequence.Iterator(im)): for index, frame in enumerate(ImageSequence.Iterator(im)):
frame.load() frame.load()
self.assertEqual(index, im.tell()) assert index == im.tell()
frame.convert("RGB") frame.convert("RGB")
def test_tiff(self): def test_tiff(self):
@ -69,23 +73,23 @@ class TestImageSequence(PillowTestCase):
color1 = im.getpalette()[0:3] color1 = im.getpalette()[0:3]
im.seek(0) im.seek(0)
color2 = im.getpalette()[0:3] color2 = im.getpalette()[0:3]
self.assertEqual(color1, color2) assert color1 == color2
def test_all_frames(self): def test_all_frames(self):
# Test a single image # Test a single image
with Image.open("Tests/images/iss634.gif") as im: with Image.open("Tests/images/iss634.gif") as im:
ims = ImageSequence.all_frames(im) ims = ImageSequence.all_frames(im)
self.assertEqual(len(ims), 42) assert len(ims) == 42
for i, im_frame in enumerate(ims): for i, im_frame in enumerate(ims):
self.assertFalse(im_frame is im) assert im_frame is not im
im.seek(i) im.seek(i)
assert_image_equal(im, im_frame) assert_image_equal(im, im_frame)
# Test a series of images # Test a series of images
ims = ImageSequence.all_frames([im, hopper(), im]) ims = ImageSequence.all_frames([im, hopper(), im])
self.assertEqual(len(ims), 85) assert len(ims) == 85
# Test an operation # Test an operation
ims = ImageSequence.all_frames(im, lambda im_frame: im_frame.rotate(90)) ims = ImageSequence.all_frames(im, lambda im_frame: im_frame.rotate(90))

View File

@ -18,7 +18,7 @@ class TestImageWin(PillowTestCase):
dc2 = int(hdc) dc2 = int(hdc)
# Assert # Assert
self.assertEqual(dc2, 50) assert dc2 == 50
def test_hwnd(self): def test_hwnd(self):
# Arrange # Arrange
@ -29,7 +29,7 @@ class TestImageWin(PillowTestCase):
wnd2 = int(hwnd) wnd2 = int(hwnd)
# Assert # Assert
self.assertEqual(wnd2, 50) assert wnd2 == 50
@unittest.skipUnless(is_win32(), "Windows only") @unittest.skipUnless(is_win32(), "Windows only")
@ -42,7 +42,7 @@ class TestImageWinDib(PillowTestCase):
dib = ImageWin.Dib(im) dib = ImageWin.Dib(im)
# Assert # Assert
self.assertEqual(dib.size, im.size) assert dib.size == im.size
def test_dib_mode_string(self): def test_dib_mode_string(self):
# Arrange # Arrange
@ -53,7 +53,7 @@ class TestImageWinDib(PillowTestCase):
dib = ImageWin.Dib(mode, size) dib = ImageWin.Dib(mode, size)
# Assert # Assert
self.assertEqual(dib.size, (128, 128)) assert dib.size == (128, 128)
def test_dib_paste(self): def test_dib_paste(self):
# Arrange # Arrange
@ -67,7 +67,7 @@ class TestImageWinDib(PillowTestCase):
dib.paste(im) dib.paste(im)
# Assert # Assert
self.assertEqual(dib.size, (128, 128)) assert dib.size == (128, 128)
def test_dib_paste_bbox(self): def test_dib_paste_bbox(self):
# Arrange # Arrange
@ -82,7 +82,7 @@ class TestImageWinDib(PillowTestCase):
dib.paste(im, bbox) dib.paste(im, bbox)
# Assert # Assert
self.assertEqual(dib.size, (128, 128)) assert dib.size == (128, 128)
def test_dib_frombytes_tobytes_roundtrip(self): def test_dib_frombytes_tobytes_roundtrip(self):
# Arrange # Arrange
@ -95,7 +95,7 @@ class TestImageWinDib(PillowTestCase):
dib2 = ImageWin.Dib(mode, size) dib2 = ImageWin.Dib(mode, size)
# Confirm they're different # Confirm they're different
self.assertNotEqual(dib1.tobytes(), dib2.tobytes()) assert dib1.tobytes() != dib2.tobytes()
# Act # Act
# Make one the same as the using tobytes()/frombytes() # Make one the same as the using tobytes()/frombytes()
@ -104,4 +104,4 @@ class TestImageWinDib(PillowTestCase):
# Assert # Assert
# Confirm they're the same # Confirm they're the same
self.assertEqual(dib1.tobytes(), dib2.tobytes()) assert dib1.tobytes() == dib2.tobytes()

View File

@ -1,5 +1,6 @@
import sys import sys
import pytest
from PIL import Image from PIL import Image
from .helper import PillowTestCase from .helper import PillowTestCase
@ -20,7 +21,7 @@ class TestLibPack(PillowTestCase):
data_len = data * len(pixels) data_len = data * len(pixels)
data = bytes(range(1, data_len + 1)) data = bytes(range(1, data_len + 1))
self.assertEqual(data, im.tobytes("raw", rawmode)) assert data == im.tobytes("raw", rawmode)
def test_1(self): def test_1(self):
self.assert_pack("1", "1", b"\x01", 0, 0, 0, 0, 0, 0, 0, X) self.assert_pack("1", "1", b"\x01", 0, 0, 0, 0, 0, 0, 0, X)
@ -234,7 +235,7 @@ class TestLibUnpack(PillowTestCase):
im = Image.frombytes(mode, (len(pixels), 1), data, "raw", rawmode, 0, 1) im = Image.frombytes(mode, (len(pixels), 1), data, "raw", rawmode, 0, 1)
for x, pixel in enumerate(pixels): for x, pixel in enumerate(pixels):
self.assertEqual(pixel, im.getpixel((x, 0))) assert pixel == im.getpixel((x, 0))
def test_1(self): def test_1(self):
self.assert_unpack("1", "1", b"\x01", 0, 0, 0, 0, 0, 0, 0, X) self.assert_unpack("1", "1", b"\x01", 0, 0, 0, 0, 0, 0, 0, X)
@ -719,6 +720,9 @@ class TestLibUnpack(PillowTestCase):
self.assert_unpack("CMYK", "CMYK;16N", 8, (1, 3, 5, 7), (9, 11, 13, 15)) self.assert_unpack("CMYK", "CMYK;16N", 8, (1, 3, 5, 7), (9, 11, 13, 15))
def test_value_error(self): def test_value_error(self):
self.assertRaises(ValueError, self.assert_unpack, "L", "L", 0, 0) with pytest.raises(ValueError):
self.assertRaises(ValueError, self.assert_unpack, "RGB", "RGB", 2, 0) self.assert_unpack("L", "L", 0, 0)
self.assertRaises(ValueError, self.assert_unpack, "CMYK", "CMYK", 2, 0) with pytest.raises(ValueError):
self.assert_unpack("RGB", "RGB", 2, 0)
with pytest.raises(ValueError):
self.assert_unpack("CMYK", "CMYK", 2, 0)

View File

@ -9,7 +9,7 @@ class TestModeI16(PillowTestCase):
def verify(self, im1): def verify(self, im1):
im2 = self.original.copy() im2 = self.original.copy()
self.assertEqual(im1.size, im2.size) assert im1.size == im2.size
pix1 = im1.load() pix1 = im1.load()
pix2 = im2.load() pix2 = im2.load()
for y in range(im1.size[1]): for y in range(im1.size[1]):
@ -17,14 +17,8 @@ class TestModeI16(PillowTestCase):
xy = x, y xy = x, y
p1 = pix1[xy] p1 = pix1[xy]
p2 = pix2[xy] p2 = pix2[xy]
self.assertEqual( assert p1 == p2, "got {!r} from mode {} at {}, expected {!r}".format(
p1, p1, im1.mode, xy, p2
p2,
(
"got {!r} from mode {} at {}, expected {!r}".format(
p1, im1.mode, xy, p2
)
),
) )
def test_basic(self): def test_basic(self):
@ -63,10 +57,10 @@ class TestModeI16(PillowTestCase):
self.verify(imOut) self.verify(imOut)
imIn = Image.new(mode, (1, 1), 1) imIn = Image.new(mode, (1, 1), 1)
self.assertEqual(imIn.getpixel((0, 0)), 1) assert imIn.getpixel((0, 0)) == 1
imIn.putpixel((0, 0), 2) imIn.putpixel((0, 0), 2)
self.assertEqual(imIn.getpixel((0, 0)), 2) assert imIn.getpixel((0, 0)) == 2
if mode == "L": if mode == "L":
maximum = 255 maximum = 255
@ -74,10 +68,10 @@ class TestModeI16(PillowTestCase):
maximum = 32767 maximum = 32767
imIn = Image.new(mode, (1, 1), 256) imIn = Image.new(mode, (1, 1), 256)
self.assertEqual(imIn.getpixel((0, 0)), min(256, maximum)) assert imIn.getpixel((0, 0)) == min(256, maximum)
imIn.putpixel((0, 0), 512) imIn.putpixel((0, 0), 512)
self.assertEqual(imIn.getpixel((0, 0)), min(512, maximum)) assert imIn.getpixel((0, 0)) == min(512, maximum)
basic("L") basic("L")
@ -93,10 +87,10 @@ class TestModeI16(PillowTestCase):
order = 1 if Image._ENDIAN == "<" else -1 order = 1 if Image._ENDIAN == "<" else -1
self.assertEqual(tobytes("L"), b"\x01") assert tobytes("L") == b"\x01"
self.assertEqual(tobytes("I;16"), b"\x01\x00") assert tobytes("I;16") == b"\x01\x00"
self.assertEqual(tobytes("I;16B"), b"\x00\x01") assert tobytes("I;16B") == b"\x00\x01"
self.assertEqual(tobytes("I"), b"\x01\x00\x00\x00"[::order]) assert tobytes("I") == b"\x01\x00\x00\x00"[::order]
def test_convert(self): def test_convert(self):

View File

@ -20,7 +20,7 @@ class TestPickle(PillowTestCase):
loaded_im = pickle.load(f) loaded_im = pickle.load(f)
# Assert # Assert
self.assertEqual(im, loaded_im) assert im == loaded_im
def helper_pickle_string( def helper_pickle_string(
self, pickle, protocol=0, test_file="Tests/images/hopper.jpg", mode=None self, pickle, protocol=0, test_file="Tests/images/hopper.jpg", mode=None
@ -34,7 +34,7 @@ class TestPickle(PillowTestCase):
loaded_im = pickle.loads(dumped_string) loaded_im = pickle.loads(dumped_string)
# Assert # Assert
self.assertEqual(im, loaded_im) assert im == loaded_im
def test_pickle_image(self): def test_pickle_image(self):
# Act / Assert # Act / Assert
@ -86,4 +86,4 @@ class TestPickle(PillowTestCase):
loaded_im = pickle.load(f) loaded_im = pickle.load(f)
im.mode = "PA" im.mode = "PA"
self.assertEqual(im, loaded_im) assert im == loaded_im

View File

@ -20,8 +20,8 @@ class TestToQImage(PillowQtTestCase, PillowTestCase):
src = hopper(mode) src = hopper(mode)
data = ImageQt.toqimage(src) data = ImageQt.toqimage(src)
self.assertIsInstance(data, QImage) assert isinstance(data, QImage)
self.assertFalse(data.isNull()) assert not data.isNull()
# reload directly from the qimage # reload directly from the qimage
rt = ImageQt.fromqimage(data) rt = ImageQt.fromqimage(data)

View File

@ -12,8 +12,8 @@ class TestToQPixmap(PillowQPixmapTestCase, PillowTestCase):
for mode in ("1", "RGB", "RGBA", "L", "P"): for mode in ("1", "RGB", "RGBA", "L", "P"):
data = ImageQt.toqpixmap(hopper(mode)) data = ImageQt.toqpixmap(hopper(mode))
self.assertIsInstance(data, QPixmap) assert isinstance(data, QPixmap)
self.assertFalse(data.isNull()) assert not data.isNull()
# Test saving the file # Test saving the file
tempfile = self.tempfile("temp_{}.png".format(mode)) tempfile = self.tempfile("temp_{}.png".format(mode))

View File

@ -11,8 +11,8 @@ class Test_IFDRational(PillowTestCase):
t = IFDRational(num, denom) t = IFDRational(num, denom)
self.assertEqual(target, t) assert target == t
self.assertEqual(t, target) assert t == target
def test_sanity(self): def test_sanity(self):
@ -33,13 +33,13 @@ class Test_IFDRational(PillowTestCase):
xres = IFDRational(72) xres = IFDRational(72)
yres = IFDRational(72) yres = IFDRational(72)
self.assertIsNotNone(xres._val) assert xres._val is not None
self.assertIsNotNone(xres.numerator) assert xres.numerator is not None
self.assertIsNotNone(xres.denominator) assert xres.denominator is not None
self.assertIsNotNone(yres._val) assert yres._val is not None
self.assertTrue(xres and 1) assert xres and 1
self.assertTrue(xres and yres) assert xres and yres
def test_ifd_rational_save(self): def test_ifd_rational_save(self):
methods = (True, False) methods = (True, False)
@ -55,6 +55,4 @@ class Test_IFDRational(PillowTestCase):
im.save(out, dpi=(res, res), compression="raw") im.save(out, dpi=(res, res), compression="raw")
with Image.open(out) as reloaded: with Image.open(out) as reloaded:
self.assertEqual( assert float(IFDRational(301, 1)) == float(reloaded.tag_v2[282])
float(IFDRational(301, 1)), float(reloaded.tag_v2[282])
)