Convert some tests to pytest style

To better follow conventional pytest style, this removes the outer
wrapper class in favor of a function for some tests. These tests were
picked as they are relatively simple and presented no barriers to a
quick port. The assert* methods are replaced with assert statements.
When necessary, a fixture is used to create a temporary directory.

This commit does not convert the entire test suite to this style as some
test classes use methods or other advanced features that are difficult
to automatically convert. The goal is to address these issues in
followup commits.

Refs #4193
This commit is contained in:
Jon Dufresne 2019-11-03 14:18:55 -08:00
parent 3aa5d56bae
commit 2c50723f14
20 changed files with 485 additions and 477 deletions

View File

@ -1,23 +1,19 @@
import PIL import PIL
import PIL.Image import PIL.Image
from .helper import PillowTestCase
def test_sanity():
# Make sure we have the binary extension
PIL.Image.core.new("L", (100, 100))
class TestSanity(PillowTestCase): # Create an image and do stuff with it.
def test_sanity(self): im = PIL.Image.new("1", (100, 100))
assert (im.mode, im.size) == ("1", (100, 100))
assert len(im.tobytes()) == 1300
# Make sure we have the binary extension # Create images in all remaining major modes.
PIL.Image.core.new("L", (100, 100)) PIL.Image.new("L", (100, 100))
PIL.Image.new("P", (100, 100))
# Create an image and do stuff with it. PIL.Image.new("RGB", (100, 100))
im = PIL.Image.new("1", (100, 100)) PIL.Image.new("I", (100, 100))
self.assertEqual((im.mode, im.size), ("1", (100, 100))) PIL.Image.new("F", (100, 100))
self.assertEqual(len(im.tobytes()), 1300)
# Create images in all remaining major modes.
PIL.Image.new("L", (100, 100))
PIL.Image.new("P", (100, 100))
PIL.Image.new("RGB", (100, 100))
PIL.Image.new("I", (100, 100))
PIL.Image.new("F", (100, 100))

View File

@ -1,23 +1,22 @@
from PIL import _binary from PIL import _binary
from .helper import PillowTestCase
def test_standard():
assert _binary.i8(b"*") == 42
assert _binary.o8(42) == b"*"
class TestBinary(PillowTestCase): def test_little_endian():
def test_standard(self): assert _binary.i16le(b"\xff\xff\x00\x00") == 65535
self.assertEqual(_binary.i8(b"*"), 42) assert _binary.i32le(b"\xff\xff\x00\x00") == 65535
self.assertEqual(_binary.o8(42), b"*")
def test_little_endian(self): assert _binary.o16le(65535) == b"\xff\xff"
self.assertEqual(_binary.i16le(b"\xff\xff\x00\x00"), 65535) assert _binary.o32le(65535) == b"\xff\xff\x00\x00"
self.assertEqual(_binary.i32le(b"\xff\xff\x00\x00"), 65535)
self.assertEqual(_binary.o16le(65535), b"\xff\xff")
self.assertEqual(_binary.o32le(65535), b"\xff\xff\x00\x00")
def test_big_endian(self): def test_big_endian():
self.assertEqual(_binary.i16be(b"\x00\x00\xff\xff"), 0) assert _binary.i16be(b"\x00\x00\xff\xff") == 0
self.assertEqual(_binary.i32be(b"\x00\x00\xff\xff"), 65535) assert _binary.i32be(b"\x00\x00\xff\xff") == 65535
self.assertEqual(_binary.o16be(65535), b"\xff\xff") assert _binary.o16be(65535) == b"\xff\xff"
self.assertEqual(_binary.o32be(65535), b"\x00\x00\xff\xff") assert _binary.o32be(65535) == b"\x00\x00\xff\xff"

View File

@ -14,12 +14,11 @@ sample.putdata(sum([
# fmt: on # fmt: on
class TestBoxBlurApi(PillowTestCase): def test_imageops_box_blur():
def test_imageops_box_blur(self): i = sample.filter(ImageFilter.BoxBlur(1))
i = sample.filter(ImageFilter.BoxBlur(1)) assert i.mode == sample.mode
self.assertEqual(i.mode, sample.mode) assert i.size == sample.size
self.assertEqual(i.size, sample.size) assert isinstance(i, Image.Image)
self.assertIsInstance(i, Image.Image)
class TestBoxBlur(PillowTestCase): class TestBoxBlur(PillowTestCase):

View File

@ -6,29 +6,29 @@ from PIL import Image
from .helper import PillowTestCase, is_pypy from .helper import PillowTestCase, is_pypy
class TestCoreStats(PillowTestCase): def test_get_stats():
def test_get_stats(self): # Create at least one image
# Create at least one image Image.new("RGB", (10, 10))
Image.new("RGB", (10, 10))
stats = Image.core.get_stats() stats = Image.core.get_stats()
self.assertIn("new_count", stats) assert "new_count" in stats
self.assertIn("reused_blocks", stats) assert "reused_blocks" in stats
self.assertIn("freed_blocks", stats) assert "freed_blocks" in stats
self.assertIn("allocated_blocks", stats) assert "allocated_blocks" in stats
self.assertIn("reallocated_blocks", stats) assert "reallocated_blocks" in stats
self.assertIn("blocks_cached", stats) assert "blocks_cached" in stats
def test_reset_stats(self):
Image.core.reset_stats()
stats = Image.core.get_stats() def test_reset_stats():
self.assertEqual(stats["new_count"], 0) Image.core.reset_stats()
self.assertEqual(stats["reused_blocks"], 0)
self.assertEqual(stats["freed_blocks"], 0) stats = Image.core.get_stats()
self.assertEqual(stats["allocated_blocks"], 0) assert stats["new_count"] == 0
self.assertEqual(stats["reallocated_blocks"], 0) assert stats["reused_blocks"] == 0
self.assertEqual(stats["blocks_cached"], 0) assert stats["freed_blocks"] == 0
assert stats["allocated_blocks"] == 0
assert stats["reallocated_blocks"] == 0
assert stats["blocks_cached"] == 0
class TestCoreMemory(PillowTestCase): class TestCoreMemory(PillowTestCase):

View File

@ -1,42 +1,46 @@
import pytest
from PIL import BufrStubImagePlugin, Image from PIL import BufrStubImagePlugin, Image
from .helper import PillowTestCase, hopper from .helper import hopper
TEST_FILE = "Tests/images/gfs.t06z.rassda.tm00.bufr_d" TEST_FILE = "Tests/images/gfs.t06z.rassda.tm00.bufr_d"
class TestFileBufrStub(PillowTestCase): def test_open():
def test_open(self): # Act
# Act with Image.open(TEST_FILE) as im:
with Image.open(TEST_FILE) as im:
# Assert # Assert
self.assertEqual(im.format, "BUFR") assert im.format == "BUFR"
# Dummy data from the stub # Dummy data from the stub
self.assertEqual(im.mode, "F") assert im.mode == "F"
self.assertEqual(im.size, (1, 1)) assert im.size == (1, 1)
def test_invalid_file(self):
# Arrange
invalid_file = "Tests/images/flower.jpg"
# Act / Assert def test_invalid_file():
self.assertRaises( # Arrange
SyntaxError, BufrStubImagePlugin.BufrStubImageFile, invalid_file invalid_file = "Tests/images/flower.jpg"
)
def test_load(self): # Act / Assert
# Arrange with pytest.raises(SyntaxError):
with Image.open(TEST_FILE) as im: BufrStubImagePlugin.BufrStubImageFile(invalid_file)
# Act / Assert: stub cannot load without an implemented handler
self.assertRaises(IOError, im.load)
def test_save(self): def test_load():
# Arrange # Arrange
im = hopper() with Image.open(TEST_FILE) as im:
tmpfile = self.tempfile("temp.bufr")
# Act / Assert: stub cannot save without an implemented handler # Act / Assert: stub cannot load without an implemented handler
self.assertRaises(IOError, im.save, tmpfile) with pytest.raises(IOError):
im.load()
def test_save(tmp_path):
# Arrange
im = hopper()
tmpfile = str(tmp_path / "temp.bufr")
# Act / Assert: stub cannot save without an implemented handler
with pytest.raises(IOError):
im.save(tmpfile)

View File

@ -1,125 +1,133 @@
from PIL import ContainerIO, Image from PIL import ContainerIO, Image
from .helper import PillowTestCase, hopper from .helper import hopper
TEST_FILE = "Tests/images/dummy.container" TEST_FILE = "Tests/images/dummy.container"
class TestFileContainer(PillowTestCase): def test_sanity():
def test_sanity(self): dir(Image)
dir(Image) dir(ContainerIO)
dir(ContainerIO)
def test_isatty(self):
with hopper() as im:
container = ContainerIO.ContainerIO(im, 0, 0)
self.assertFalse(container.isatty()) def test_isatty():
with hopper() as im:
container = ContainerIO.ContainerIO(im, 0, 0)
def test_seek_mode_0(self): assert container.isatty() is False
# Arrange
mode = 0
with open(TEST_FILE) as fh:
container = ContainerIO.ContainerIO(fh, 22, 100)
# Act
container.seek(33, mode)
container.seek(33, mode)
# Assert def test_seek_mode_0():
self.assertEqual(container.tell(), 33) # Arrange
mode = 0
with open(TEST_FILE) as fh:
container = ContainerIO.ContainerIO(fh, 22, 100)
def test_seek_mode_1(self): # Act
# Arrange container.seek(33, mode)
mode = 1 container.seek(33, mode)
with open(TEST_FILE) as fh:
container = ContainerIO.ContainerIO(fh, 22, 100)
# Act # Assert
container.seek(33, mode) assert container.tell() == 33
container.seek(33, mode)
# Assert
self.assertEqual(container.tell(), 66)
def test_seek_mode_2(self): def test_seek_mode_1():
# Arrange # Arrange
mode = 2 mode = 1
with open(TEST_FILE) as fh: with open(TEST_FILE) as fh:
container = ContainerIO.ContainerIO(fh, 22, 100) container = ContainerIO.ContainerIO(fh, 22, 100)
# Act # Act
container.seek(33, mode) container.seek(33, mode)
container.seek(33, mode) container.seek(33, mode)
# Assert # Assert
self.assertEqual(container.tell(), 100) assert container.tell() == 66
def test_read_n0(self):
# Arrange
with open(TEST_FILE) as fh:
container = ContainerIO.ContainerIO(fh, 22, 100)
# Act def test_seek_mode_2():
container.seek(81) # Arrange
data = container.read() mode = 2
with open(TEST_FILE) as fh:
container = ContainerIO.ContainerIO(fh, 22, 100)
# Assert # Act
self.assertEqual(data, "7\nThis is line 8\n") container.seek(33, mode)
container.seek(33, mode)
def test_read_n(self): # Assert
# Arrange assert container.tell() == 100
with open(TEST_FILE) as fh:
container = ContainerIO.ContainerIO(fh, 22, 100)
# Act
container.seek(81)
data = container.read(3)
# Assert def test_read_n0():
self.assertEqual(data, "7\nT") # Arrange
with open(TEST_FILE) as fh:
container = ContainerIO.ContainerIO(fh, 22, 100)
def test_read_eof(self): # Act
# Arrange container.seek(81)
with open(TEST_FILE) as fh: data = container.read()
container = ContainerIO.ContainerIO(fh, 22, 100)
# Act # Assert
container.seek(100) assert data == "7\nThis is line 8\n"
data = container.read()
# Assert
self.assertEqual(data, "")
def test_readline(self): def test_read_n():
# Arrange # Arrange
with open(TEST_FILE) as fh: with open(TEST_FILE) as fh:
container = ContainerIO.ContainerIO(fh, 0, 120) container = ContainerIO.ContainerIO(fh, 22, 100)
# Act # Act
data = container.readline() container.seek(81)
data = container.read(3)
# Assert # Assert
self.assertEqual(data, "This is line 1\n") assert data == "7\nT"
def test_readlines(self):
# Arrange
expected = [
"This is line 1\n",
"This is line 2\n",
"This is line 3\n",
"This is line 4\n",
"This is line 5\n",
"This is line 6\n",
"This is line 7\n",
"This is line 8\n",
]
with open(TEST_FILE) as fh:
container = ContainerIO.ContainerIO(fh, 0, 120)
# Act def test_read_eof():
data = container.readlines() # Arrange
with open(TEST_FILE) as fh:
container = ContainerIO.ContainerIO(fh, 22, 100)
# Assert # Act
container.seek(100)
data = container.read()
self.assertEqual(data, expected) # Assert
assert data == ""
def test_readline():
# Arrange
with open(TEST_FILE) as fh:
container = ContainerIO.ContainerIO(fh, 0, 120)
# Act
data = container.readline()
# Assert
assert data == "This is line 1\n"
def test_readlines():
# Arrange
expected = [
"This is line 1\n",
"This is line 2\n",
"This is line 3\n",
"This is line 4\n",
"This is line 5\n",
"This is line 6\n",
"This is line 7\n",
"This is line 8\n",
]
with open(TEST_FILE) as fh:
container = ContainerIO.ContainerIO(fh, 0, 120)
# Act
data = container.readlines()
# Assert
assert data == expected

View File

@ -1,20 +1,22 @@
import pytest
from PIL import GdImageFile, UnidentifiedImageError from PIL import GdImageFile, UnidentifiedImageError
from .helper import PillowTestCase
TEST_GD_FILE = "Tests/images/hopper.gd" TEST_GD_FILE = "Tests/images/hopper.gd"
class TestFileGd(PillowTestCase): def test_sanity():
def test_sanity(self): with GdImageFile.open(TEST_GD_FILE) as im:
with GdImageFile.open(TEST_GD_FILE) as im: assert im.size == (128, 128)
self.assertEqual(im.size, (128, 128)) assert im.format == "GD"
self.assertEqual(im.format, "GD")
def test_bad_mode(self):
self.assertRaises(ValueError, GdImageFile.open, TEST_GD_FILE, "bad mode")
def test_invalid_file(self): def test_bad_mode():
invalid_file = "Tests/images/flower.jpg" with pytest.raises(ValueError):
GdImageFile.open(TEST_GD_FILE, "bad mode")
self.assertRaises(UnidentifiedImageError, GdImageFile.open, invalid_file)
def test_invalid_file():
invalid_file = "Tests/images/flower.jpg"
with pytest.raises(UnidentifiedImageError):
GdImageFile.open(invalid_file)

View File

@ -1,29 +1,31 @@
import pytest
from PIL.GimpPaletteFile import GimpPaletteFile from PIL.GimpPaletteFile import GimpPaletteFile
from .helper import PillowTestCase
def test_sanity():
with open("Tests/images/test.gpl", "rb") as fp:
GimpPaletteFile(fp)
class TestImage(PillowTestCase): with open("Tests/images/hopper.jpg", "rb") as fp:
def test_sanity(self): with pytest.raises(SyntaxError):
with open("Tests/images/test.gpl", "rb") as fp:
GimpPaletteFile(fp) GimpPaletteFile(fp)
with open("Tests/images/hopper.jpg", "rb") as fp: with open("Tests/images/bad_palette_file.gpl", "rb") as fp:
self.assertRaises(SyntaxError, GimpPaletteFile, fp) with pytest.raises(SyntaxError):
GimpPaletteFile(fp)
with open("Tests/images/bad_palette_file.gpl", "rb") as fp: with open("Tests/images/bad_palette_entry.gpl", "rb") as fp:
self.assertRaises(SyntaxError, GimpPaletteFile, fp) with pytest.raises(ValueError):
GimpPaletteFile(fp)
with open("Tests/images/bad_palette_entry.gpl", "rb") as fp:
self.assertRaises(ValueError, GimpPaletteFile, fp)
def test_get_palette(self): def test_get_palette():
# Arrange # Arrange
with open("Tests/images/custom_gimp_palette.gpl", "rb") as fp: with open("Tests/images/custom_gimp_palette.gpl", "rb") as fp:
palette_file = GimpPaletteFile(fp) palette_file = GimpPaletteFile(fp)
# Act # Act
palette, mode = palette_file.getpalette() palette, mode = palette_file.getpalette()
# Assert # Assert
self.assertEqual(mode, "RGB") assert mode == "RGB"

View File

@ -1,18 +1,15 @@
from PIL import WalImageFile from PIL import WalImageFile
from .helper import PillowTestCase
def test_open():
# Arrange
TEST_FILE = "Tests/images/hopper.wal"
class TestFileWal(PillowTestCase): # Act
def test_open(self): im = WalImageFile.open(TEST_FILE)
# Arrange
TEST_FILE = "Tests/images/hopper.wal"
# Act # Assert
im = WalImageFile.open(TEST_FILE) assert im.format == "WAL"
assert im.format_description == "Quake2 Texture"
# Assert assert im.mode == "P"
self.assertEqual(im.format, "WAL") assert im.size == (128, 128)
self.assertEqual(im.format_description, "Quake2 Texture")
self.assertEqual(im.mode, "P")
self.assertEqual(im.size, (128, 128))

View File

@ -1,39 +1,38 @@
from PIL import Image from PIL import Image
from .helper import PillowTestCase
def test_white():
with Image.open("Tests/images/lab.tif") as i:
i.load()
assert i.mode == "LAB"
assert i.getbands() == ("L", "A", "B")
k = i.getpixel((0, 0))
L = i.getdata(0)
a = i.getdata(1)
b = i.getdata(2)
assert k == (255, 128, 128)
assert list(L) == [255] * 100
assert list(a) == [128] * 100
assert list(b) == [128] * 100
class TestFormatLab(PillowTestCase): def test_green():
def test_white(self): # l= 50 (/100), a = -100 (-128 .. 128) b=0 in PS
with Image.open("Tests/images/lab.tif") as i: # == RGB: 0, 152, 117
i.load() with Image.open("Tests/images/lab-green.tif") as i:
k = i.getpixel((0, 0))
assert k == (128, 28, 128)
self.assertEqual(i.mode, "LAB")
self.assertEqual(i.getbands(), ("L", "A", "B")) def test_red():
# l= 50 (/100), a = 100 (-128 .. 128) b=0 in PS
k = i.getpixel((0, 0)) # == RGB: 255, 0, 124
with Image.open("Tests/images/lab-red.tif") as i:
L = i.getdata(0) k = i.getpixel((0, 0))
a = i.getdata(1) assert k == (128, 228, 128)
b = i.getdata(2)
self.assertEqual(k, (255, 128, 128))
self.assertEqual(list(L), [255] * 100)
self.assertEqual(list(a), [128] * 100)
self.assertEqual(list(b), [128] * 100)
def test_green(self):
# l= 50 (/100), a = -100 (-128 .. 128) b=0 in PS
# == RGB: 0, 152, 117
with Image.open("Tests/images/lab-green.tif") as i:
k = i.getpixel((0, 0))
self.assertEqual(k, (128, 28, 128))
def test_red(self):
# l= 50 (/100), a = 100 (-128 .. 128) b=0 in PS
# == RGB: 255, 0, 124
with Image.open("Tests/images/lab-red.tif") as i:
k = i.getpixel((0, 0))
self.assertEqual(k, (128, 228, 128))

View File

@ -1,16 +1,13 @@
from PIL import Image from PIL import Image
from .helper import PillowTestCase
def test_getbands():
class TestImageGetBands(PillowTestCase): assert Image.new("1", (1, 1)).getbands() == ("1",)
def test_getbands(self): assert Image.new("L", (1, 1)).getbands() == ("L",)
self.assertEqual(Image.new("1", (1, 1)).getbands(), ("1",)) assert Image.new("I", (1, 1)).getbands() == ("I",)
self.assertEqual(Image.new("L", (1, 1)).getbands(), ("L",)) assert Image.new("F", (1, 1)).getbands() == ("F",)
self.assertEqual(Image.new("I", (1, 1)).getbands(), ("I",)) assert Image.new("P", (1, 1)).getbands() == ("P",)
self.assertEqual(Image.new("F", (1, 1)).getbands(), ("F",)) assert Image.new("RGB", (1, 1)).getbands() == ("R", "G", "B")
self.assertEqual(Image.new("P", (1, 1)).getbands(), ("P",)) assert Image.new("RGBA", (1, 1)).getbands() == ("R", "G", "B", "A")
self.assertEqual(Image.new("RGB", (1, 1)).getbands(), ("R", "G", "B")) assert Image.new("CMYK", (1, 1)).getbands() == ("C", "M", "Y", "K")
self.assertEqual(Image.new("RGBA", (1, 1)).getbands(), ("R", "G", "B", "A")) assert Image.new("YCbCr", (1, 1)).getbands() == ("Y", "Cb", "Cr")
self.assertEqual(Image.new("CMYK", (1, 1)).getbands(), ("C", "M", "Y", "K"))
self.assertEqual(Image.new("YCbCr", (1, 1)).getbands(), ("Y", "Cb", "Cr"))

View File

@ -1,38 +1,38 @@
from PIL import Image from PIL import Image
from .helper import PillowTestCase, hopper from .helper import hopper
class TestImageGetBbox(PillowTestCase): def test_sanity():
def test_sanity(self):
bbox = hopper().getbbox() bbox = hopper().getbbox()
self.assertIsInstance(bbox, tuple) assert isinstance(bbox, tuple)
def test_bbox(self):
# 8-bit mode def test_bbox():
im = Image.new("L", (100, 100), 0)
self.assertIsNone(im.getbbox())
im.paste(255, (10, 25, 90, 75)) # 8-bit mode
self.assertEqual(im.getbbox(), (10, 25, 90, 75)) im = Image.new("L", (100, 100), 0)
assert im.getbbox() is None
im.paste(255, (25, 10, 75, 90)) im.paste(255, (10, 25, 90, 75))
self.assertEqual(im.getbbox(), (10, 10, 90, 90)) assert im.getbbox() == (10, 25, 90, 75)
im.paste(255, (-10, -10, 110, 110)) im.paste(255, (25, 10, 75, 90))
self.assertEqual(im.getbbox(), (0, 0, 100, 100)) assert im.getbbox() == (10, 10, 90, 90)
# 32-bit mode im.paste(255, (-10, -10, 110, 110))
im = Image.new("RGB", (100, 100), 0) assert im.getbbox() == (0, 0, 100, 100)
self.assertIsNone(im.getbbox())
im.paste(255, (10, 25, 90, 75)) # 32-bit mode
self.assertEqual(im.getbbox(), (10, 25, 90, 75)) im = Image.new("RGB", (100, 100), 0)
assert im.getbbox() is None
im.paste(255, (25, 10, 75, 90)) im.paste(255, (10, 25, 90, 75))
self.assertEqual(im.getbbox(), (10, 10, 90, 90)) assert im.getbbox() == (10, 25, 90, 75)
im.paste(255, (-10, -10, 110, 110)) im.paste(255, (25, 10, 75, 90))
self.assertEqual(im.getbbox(), (0, 0, 100, 100)) assert im.getbbox() == (10, 10, 90, 90)
im.paste(255, (-10, -10, 110, 110))
assert im.getbbox() == (0, 0, 100, 100)

View File

@ -1,10 +1,9 @@
from .helper import PillowTestCase, hopper from .helper import hopper
class TestImageGetIm(PillowTestCase): def test_sanity():
def test_sanity(self): im = hopper()
im = hopper() type_repr = repr(type(im.getim()))
type_repr = repr(type(im.getim()))
self.assertIn("PyCapsule", type_repr) assert "PyCapsule" in type_repr
self.assertIsInstance(im.im.id, int) assert isinstance(im.im.id, int)

View File

@ -1,20 +1,19 @@
from .helper import PillowTestCase, hopper from .helper import hopper
class TestImageGetPalette(PillowTestCase): def test_palette():
def test_palette(self): def palette(mode):
def palette(mode): p = hopper(mode).getpalette()
p = hopper(mode).getpalette() if p:
if p: return p[:10]
return p[:10] return None
return None
self.assertIsNone(palette("1")) assert palette("1") is None
self.assertIsNone(palette("L")) assert palette("L") is None
self.assertIsNone(palette("I")) assert palette("I") is None
self.assertIsNone(palette("F")) assert palette("F") is None
self.assertEqual(palette("P"), [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) assert palette("P") == [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
self.assertIsNone(palette("RGB")) assert palette("RGB") is None
self.assertIsNone(palette("RGBA")) assert palette("RGBA") is None
self.assertIsNone(palette("CMYK")) assert palette("CMYK") is None
self.assertIsNone(palette("YCbCr")) assert palette("YCbCr") is None

View File

@ -1,33 +1,40 @@
import pytest
from PIL import ImagePalette from PIL import ImagePalette
from .helper import PillowTestCase, hopper from .helper import hopper
class TestImagePutPalette(PillowTestCase): def test_putpalette():
def test_putpalette(self): def palette(mode):
def palette(mode): im = hopper(mode).copy()
im = hopper(mode).copy() im.putpalette(list(range(256)) * 3)
im.putpalette(list(range(256)) * 3) p = im.getpalette()
p = im.getpalette() if p:
if p: return im.mode, p[:10]
return im.mode, p[:10] return im.mode
return im.mode
self.assertRaises(ValueError, palette, "1") with pytest.raises(ValueError):
for mode in ["L", "LA", "P", "PA"]: palette("1")
self.assertEqual( for mode in ["L", "LA", "P", "PA"]:
palette(mode), assert palette(mode) == (
("PA" if "A" in mode else "P", [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), "PA" if "A" in mode else "P",
) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
self.assertRaises(ValueError, palette, "I") )
self.assertRaises(ValueError, palette, "F") with pytest.raises(ValueError):
self.assertRaises(ValueError, palette, "RGB") palette("I")
self.assertRaises(ValueError, palette, "RGBA") with pytest.raises(ValueError):
self.assertRaises(ValueError, palette, "YCbCr") palette("F")
with pytest.raises(ValueError):
palette("RGB")
with pytest.raises(ValueError):
palette("RGBA")
with pytest.raises(ValueError):
palette("YCbCr")
def test_imagepalette(self):
im = hopper("P") def test_imagepalette():
im.putpalette(ImagePalette.negative()) im = hopper("P")
im.putpalette(ImagePalette.random()) im.putpalette(ImagePalette.negative())
im.putpalette(ImagePalette.sepia()) im.putpalette(ImagePalette.random())
im.putpalette(ImagePalette.wedge()) im.putpalette(ImagePalette.sepia())
im.putpalette(ImagePalette.wedge())

View File

@ -1,7 +1,6 @@
from .helper import PillowTestCase, hopper from .helper import hopper
class TestImageToBytes(PillowTestCase): def test_sanity():
def test_sanity(self): data = hopper().tobytes()
data = hopper().tobytes() assert isinstance(data, bytes)
self.assertIsInstance(data, bytes)

View File

@ -1,55 +1,59 @@
import pytest
from PIL import Image, ImageStat from PIL import Image, ImageStat
from .helper import PillowTestCase, hopper from .helper import hopper
class TestImageStat(PillowTestCase): def test_sanity():
def test_sanity(self):
im = hopper() im = hopper()
st = ImageStat.Stat(im) st = ImageStat.Stat(im)
st = ImageStat.Stat(im.histogram()) st = ImageStat.Stat(im.histogram())
st = ImageStat.Stat(im, Image.new("1", im.size, 1)) st = ImageStat.Stat(im, Image.new("1", im.size, 1))
# Check these run. Exceptions will cause failures. # Check these run. Exceptions will cause failures.
st.extrema st.extrema
st.sum st.sum
st.mean st.mean
st.median st.median
st.rms st.rms
st.sum2 st.sum2
st.var st.var
st.stddev st.stddev
self.assertRaises(AttributeError, lambda: st.spam) with pytest.raises(AttributeError):
st.spam()
self.assertRaises(TypeError, ImageStat.Stat, 1) with pytest.raises(TypeError):
ImageStat.Stat(1)
def test_hopper(self):
im = hopper() def test_hopper():
st = ImageStat.Stat(im) im = hopper()
# verify a few values st = ImageStat.Stat(im)
self.assertEqual(st.extrema[0], (0, 255))
self.assertEqual(st.median[0], 72)
self.assertEqual(st.sum[0], 1470218)
self.assertEqual(st.sum[1], 1311896)
self.assertEqual(st.sum[2], 1563008)
def test_constant(self): # verify a few values
assert st.extrema[0] == (0, 255)
assert st.median[0] == 72
assert st.sum[0] == 1470218
assert st.sum[1] == 1311896
assert st.sum[2] == 1563008
im = Image.new("L", (128, 128), 128)
st = ImageStat.Stat(im) def test_constant():
self.assertEqual(st.extrema[0], (128, 128)) im = Image.new("L", (128, 128), 128)
self.assertEqual(st.sum[0], 128 ** 3)
self.assertEqual(st.sum2[0], 128 ** 4) st = ImageStat.Stat(im)
self.assertEqual(st.mean[0], 128)
self.assertEqual(st.median[0], 128) assert st.extrema[0] == (128, 128)
self.assertEqual(st.rms[0], 128) assert st.sum[0] == 128 ** 3
self.assertEqual(st.var[0], 0) assert st.sum2[0] == 128 ** 4
self.assertEqual(st.stddev[0], 0) assert st.mean[0] == 128
assert st.median[0] == 128
assert st.rms[0] == 128
assert st.var[0] == 0
assert st.stddev[0] == 0

View File

@ -1,10 +1,8 @@
import locale import locale
import unittest
import pytest
from PIL import Image from PIL import Image
from .helper import PillowTestCase
# ref https://github.com/python-pillow/Pillow/issues/272 # ref https://github.com/python-pillow/Pillow/issues/272
# on windows, in polish locale: # on windows, in polish locale:
@ -23,17 +21,16 @@ from .helper import PillowTestCase
path = "Tests/images/hopper.jpg" path = "Tests/images/hopper.jpg"
class TestLocale(PillowTestCase): def test_sanity():
def test_sanity(self): with Image.open(path):
pass
try:
locale.setlocale(locale.LC_ALL, "polish")
except locale.Error:
pytest.skip("Polish locale not available")
try:
with Image.open(path): with Image.open(path):
pass pass
try: finally:
locale.setlocale(locale.LC_ALL, "polish") locale.setlocale(locale.LC_ALL, (None, None))
except locale.Error:
unittest.skip("Polish locale not available")
try:
with Image.open(path):
pass
finally:
locale.setlocale(locale.LC_ALL, (None, None))

View File

@ -1,34 +1,32 @@
import os import os
import subprocess import subprocess
import sys import sys
from unittest import TestCase
class TestMain(TestCase): def test_main():
def test_main(self): out = subprocess.check_output([sys.executable, "-m", "PIL"]).decode("utf-8")
out = subprocess.check_output([sys.executable, "-m", "PIL"]).decode("utf-8") lines = out.splitlines()
lines = out.splitlines() assert lines[0] == "-" * 68
self.assertEqual(lines[0], "-" * 68) assert lines[1].startswith("Pillow ")
self.assertTrue(lines[1].startswith("Pillow ")) assert lines[2].startswith("Python ")
self.assertTrue(lines[2].startswith("Python ")) lines = lines[3:]
lines = lines[3:] while lines[0].startswith(" "):
while lines[0].startswith(" "): lines = lines[1:]
lines = lines[1:] assert lines[0] == "-" * 68
self.assertEqual(lines[0], "-" * 68) assert lines[1].startswith("Python modules loaded from ")
self.assertTrue(lines[1].startswith("Python modules loaded from ")) assert lines[2].startswith("Binary modules loaded from ")
self.assertTrue(lines[2].startswith("Binary modules loaded from ")) assert lines[3] == "-" * 68
self.assertEqual(lines[3], "-" * 68) jpeg = (
jpeg = ( os.linesep
os.linesep + "-" * 68
+ "-" * 68 + os.linesep
+ os.linesep + "JPEG image/jpeg"
+ "JPEG image/jpeg" + os.linesep
+ os.linesep + "Extensions: .jfif, .jpe, .jpeg, .jpg"
+ "Extensions: .jfif, .jpe, .jpeg, .jpg" + os.linesep
+ os.linesep + "Features: open, save"
+ "Features: open, save" + os.linesep
+ os.linesep + "-" * 68
+ "-" * 68 + os.linesep
+ os.linesep )
) assert jpeg in out
self.assertIn(jpeg, out)

View File

@ -1,70 +1,72 @@
import unittest import pytest
from PIL import _util from PIL import _util
from .helper import PillowTestCase
def test_is_path():
# Arrange
fp = "filename.ext"
# Act
it_is = _util.isPath(fp)
# Assert
assert it_is
class TestUtil(PillowTestCase): @pytest.mark.skipif(not _util.py36, reason="os.path support for Paths added in 3.6")
def test_is_path(self): def test_path_obj_is_path():
# Arrange # Arrange
fp = "filename.ext" from pathlib import Path
# Act test_path = Path("filename.ext")
it_is = _util.isPath(fp)
# Assert # Act
self.assertTrue(it_is) it_is = _util.isPath(test_path)
@unittest.skipUnless(_util.py36, "os.path support for Paths added in 3.6") # Assert
def test_path_obj_is_path(self): assert it_is
# Arrange
from pathlib import Path
test_path = Path("filename.ext")
# Act def test_is_not_path(tmp_path):
it_is = _util.isPath(test_path) # Arrange
with (tmp_path / "temp.ext").open("w") as fp:
pass
# Assert # Act
self.assertTrue(it_is) it_is_not = _util.isPath(fp)
def test_is_not_path(self): # Assert
# Arrange assert not it_is_not
filename = self.tempfile("temp.ext")
fp = open(filename, "w").close()
# Act
it_is_not = _util.isPath(fp)
# Assert def test_is_directory():
self.assertFalse(it_is_not) # Arrange
directory = "Tests"
def test_is_directory(self): # Act
# Arrange it_is = _util.isDirectory(directory)
directory = "Tests"
# Act # Assert
it_is = _util.isDirectory(directory) assert it_is
# Assert
self.assertTrue(it_is)
def test_is_not_directory(self): def test_is_not_directory():
# Arrange # Arrange
text = "abc" text = "abc"
# Act # Act
it_is_not = _util.isDirectory(text) it_is_not = _util.isDirectory(text)
# Assert # Assert
self.assertFalse(it_is_not) assert not it_is_not
def test_deferred_error(self):
# Arrange
# Act def test_deferred_error():
thing = _util.deferred_error(ValueError("Some error text")) # Arrange
# Assert # Act
self.assertRaises(ValueError, lambda: thing.some_attr) thing = _util.deferred_error(ValueError("Some error text"))
# Assert
with pytest.raises(ValueError):
thing.some_attr