Merge pull request #2689 from radarhere/tests

Added tests
This commit is contained in:
wiredfool 2017-09-04 11:15:28 +01:00 committed by GitHub
commit 2611b2caa5
66 changed files with 351 additions and 282 deletions

View File

@ -139,16 +139,13 @@ SAVE = {
} }
def _save(im, fp, filename, check=0): def _save(im, fp, filename):
try: try:
rawmode, bits, colormaptype, imagetype = SAVE[im.mode] rawmode, bits, colormaptype, imagetype = SAVE[im.mode]
except KeyError: except KeyError:
raise IOError("cannot write mode %s as TGA" % im.mode) raise IOError("cannot write mode %s as TGA" % im.mode)
if check:
return check
if colormaptype: if colormaptype:
colormapfirst, colormaplength, colormapentry = 0, 256, 24 colormapfirst, colormaplength, colormapentry = 0, 256, 24
else: else:

View File

@ -153,7 +153,7 @@ class WmfStubImageFile(ImageFile.StubImageFile):
def _save(im, fp, filename): def _save(im, fp, filename):
if _handler is None or not hasattr("_handler", "save"): if _handler is None or not hasattr(_handler, "save"):
raise IOError("WMF save handler not installed") raise IOError("WMF save handler not installed")
_handler.save(im, fp, filename) _handler.save(im, fp, filename)

View File

@ -36,7 +36,7 @@ class TestDecompressionBomb(PillowTestCase):
# Act / Assert # Act / Assert
self.assert_warning(Image.DecompressionBombWarning, self.assert_warning(Image.DecompressionBombWarning,
lambda: Image.open(TEST_FILE)) Image.open, TEST_FILE)
class TestDecompressionCrop(PillowTestCase): class TestDecompressionCrop(PillowTestCase):
@ -52,7 +52,7 @@ class TestDecompressionCrop(PillowTestCase):
# same decompression bomb warnings on them. # same decompression bomb warnings on them.
box = (0, 0, self.src.width * 2, self.src.height * 2) box = (0, 0, self.src.width * 2, self.src.height * 2)
self.assert_warning(Image.DecompressionBombWarning, self.assert_warning(Image.DecompressionBombWarning,
lambda: self.src.crop(box)) self.src.crop, box)
if __name__ == '__main__': if __name__ == '__main__':
unittest.main() unittest.main()

View File

@ -51,13 +51,13 @@ class TestFeatures(PillowTestCase):
# Arrange # Arrange
codec = "unsupported_codec" codec = "unsupported_codec"
# Act / Assert # Act / Assert
self.assertRaises(ValueError, lambda: features.check_codec(codec)) self.assertRaises(ValueError, features.check_codec, codec)
def test_unsupported_module(self): def test_unsupported_module(self):
# Arrange # Arrange
module = "unsupported_module" module = "unsupported_module"
# Act / Assert # Act / Assert
self.assertRaises(ValueError, lambda: features.check_module(module)) self.assertRaises(ValueError, features.check_module, module)
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -28,7 +28,7 @@ class TestFileBmp(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, self.assertRaises(SyntaxError,
lambda: BmpImagePlugin.BmpImageFile(fp)) BmpImagePlugin.BmpImageFile, fp)
def test_save_to_bytes(self): def test_save_to_bytes(self):
output = io.BytesIO() output = io.BytesIO()

View File

@ -24,8 +24,7 @@ class TestFileBufrStub(PillowTestCase):
# Act / Assert # Act / Assert
self.assertRaises(SyntaxError, self.assertRaises(SyntaxError,
lambda: BufrStubImagePlugin.BufrStubImageFile, invalid_file)
BufrStubImagePlugin.BufrStubImageFile(invalid_file))
def test_load(self): def test_load(self):
# Arrange # Arrange
@ -40,7 +39,7 @@ class TestFileBufrStub(PillowTestCase):
tmpfile = self.tempfile("temp.bufr") tmpfile = self.tempfile("temp.bufr")
# Act / Assert: stub cannot save without an implemented handler # Act / Assert: stub cannot save without an implemented handler
self.assertRaises(IOError, lambda: im.save(tmpfile)) self.assertRaises(IOError, im.save, tmpfile)
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -21,7 +21,7 @@ class TestFileCur(PillowTestCase):
invalid_file = "Tests/images/flower.jpg" invalid_file = "Tests/images/flower.jpg"
self.assertRaises(SyntaxError, self.assertRaises(SyntaxError,
lambda: CurImagePlugin.CurImageFile(invalid_file)) CurImagePlugin.CurImageFile, invalid_file)
no_cursors_file = "Tests/images/no_cursors.cur" no_cursors_file = "Tests/images/no_cursors.cur"

View File

@ -23,7 +23,7 @@ class TestFileDcx(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, self.assertRaises(SyntaxError,
lambda: DcxImagePlugin.DcxImageFile(fp)) DcxImagePlugin.DcxImageFile, fp)
def test_tell(self): def test_tell(self):
# Arrange # Arrange
@ -58,7 +58,7 @@ class TestFileDcx(PillowTestCase):
frame = 999 # too big on purpose frame = 999 # too big on purpose
# Act / Assert # Act / Assert
self.assertRaises(EOFError, lambda: im.seek(frame)) self.assertRaises(EOFError, im.seek, frame)
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -55,7 +55,7 @@ class TestFileEps(PillowTestCase):
invalid_file = "Tests/images/flower.jpg" invalid_file = "Tests/images/flower.jpg"
self.assertRaises(SyntaxError, self.assertRaises(SyntaxError,
lambda: EpsImagePlugin.EpsImageFile(invalid_file)) EpsImagePlugin.EpsImageFile, invalid_file)
def test_cmyk(self): def test_cmyk(self):
cmyk_image = Image.open("Tests/images/pil_sample_cmyk.eps") cmyk_image = Image.open("Tests/images/pil_sample_cmyk.eps")
@ -97,7 +97,7 @@ 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, lambda: im.save(tmpfile)) self.assertRaises(ValueError, im.save, tmpfile)
def test_render_scale1(self): def test_render_scale1(self):
# We need png support for these render test # We need png support for these render test

View File

@ -24,8 +24,7 @@ class TestFileFitsStub(PillowTestCase):
# Act / Assert # Act / Assert
self.assertRaises(SyntaxError, self.assertRaises(SyntaxError,
lambda: FitsStubImagePlugin.FITSStubImageFile, invalid_file)
FitsStubImagePlugin.FITSStubImageFile(invalid_file))
def test_load(self): def test_load(self):
# Arrange # Arrange
@ -41,10 +40,10 @@ class TestFileFitsStub(PillowTestCase):
dummy_filename = "dummy.filename" dummy_filename = "dummy.filename"
# Act / Assert: stub cannot save without an implemented handler # Act / Assert: stub cannot save without an implemented handler
self.assertRaises(IOError, lambda: im.save(dummy_filename)) self.assertRaises(IOError, im.save, dummy_filename)
self.assertRaises( self.assertRaises(
IOError, IOError,
lambda: FitsStubImagePlugin._save(im, dummy_fp, dummy_filename)) FitsStubImagePlugin._save, im, dummy_fp, dummy_filename)
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -41,7 +41,7 @@ class TestFileFli(PillowTestCase):
invalid_file = "Tests/images/flower.jpg" invalid_file = "Tests/images/flower.jpg"
self.assertRaises(SyntaxError, self.assertRaises(SyntaxError,
lambda: FliImagePlugin.FliImageFile(invalid_file)) FliImagePlugin.FliImageFile, invalid_file)
def test_n_frames(self): def test_n_frames(self):
im = Image.open(static_test_file) im = Image.open(static_test_file)
@ -71,7 +71,7 @@ class TestFileFli(PillowTestCase):
self.assertEqual(im.tell(), 0) self.assertEqual(im.tell(), 0)
# Test seek past end of file # Test seek past end of file
self.assertRaises(EOFError, lambda: im.seek(2)) self.assertRaises(EOFError, im.seek, 2)
def test_seek_tell(self): def test_seek_tell(self):
im = Image.open(animated_test_file) im = Image.open(animated_test_file)

View File

@ -9,12 +9,12 @@ class TestFileFpx(PillowTestCase):
# Test an invalid OLE file # Test an invalid OLE file
invalid_file = "Tests/images/flower.jpg" invalid_file = "Tests/images/flower.jpg"
self.assertRaises(SyntaxError, self.assertRaises(SyntaxError,
lambda: FpxImagePlugin.FpxImageFile(invalid_file)) FpxImagePlugin.FpxImageFile, invalid_file)
# Test a valid OLE file, but not an FPX file # Test a valid OLE file, but not an FPX file
ole_file = "Tests/images/test-ole-file.doc" ole_file = "Tests/images/test-ole-file.doc"
self.assertRaises(SyntaxError, self.assertRaises(SyntaxError,
lambda: FpxImagePlugin.FpxImageFile(ole_file)) FpxImagePlugin.FpxImageFile, ole_file)
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -9,7 +9,7 @@ class TestFileGbr(PillowTestCase):
invalid_file = "Tests/images/flower.jpg" invalid_file = "Tests/images/flower.jpg"
self.assertRaises(SyntaxError, self.assertRaises(SyntaxError,
lambda: GbrImagePlugin.GbrImageFile(invalid_file)) GbrImagePlugin.GbrImageFile, invalid_file)
def test_gbr_file(self): def test_gbr_file(self):
im = Image.open('Tests/images/gbr.gbr') im = Image.open('Tests/images/gbr.gbr')

View File

@ -31,7 +31,7 @@ class TestFileGif(PillowTestCase):
invalid_file = "Tests/images/flower.jpg" invalid_file = "Tests/images/flower.jpg"
self.assertRaises(SyntaxError, self.assertRaises(SyntaxError,
lambda: GifImagePlugin.GifImageFile(invalid_file)) GifImagePlugin.GifImageFile, invalid_file)
def test_optimize(self): def test_optimize(self):
def test_grayscale(optimize): def test_grayscale(optimize):
@ -375,29 +375,31 @@ class TestFileGif(PillowTestCase):
def test_version(self): def test_version(self):
out = self.tempfile('temp.gif') out = self.tempfile('temp.gif')
def assertVersionAfterSave(im, version):
im.save(out)
reread = Image.open(out)
self.assertEqual(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')
im.save(out) assertVersionAfterSave(im, b"GIF87a")
reread = Image.open(out)
self.assertEqual(reread.info["version"], b"GIF87a") # Test setting the version to 89a
im = Image.new('L', (100, 100), '#000')
im.info["version"] = b"89a"
assertVersionAfterSave(im, b"GIF89a")
# Test that adding a GIF89a feature changes the version # Test that adding a GIF89a feature changes the version
im.info["transparency"] = 1 im.info["transparency"] = 1
im.save(out) assertVersionAfterSave(im, b"GIF89a")
reread = Image.open(out)
self.assertEqual(reread.info["version"], b"GIF89a")
# Test that a GIF87a image is also saved in that format # Test that a GIF87a image is also saved in that format
im = Image.open("Tests/images/test.colors.gif") im = Image.open("Tests/images/test.colors.gif")
im.save(out) assertVersionAfterSave(im, b"GIF87a")
reread = Image.open(out)
self.assertEqual(reread.info["version"], b"GIF87a")
# Test that a GIF89a image is also saved in that format # Test that a GIF89a image is also saved in that format
im.info["version"] = b"GIF89a" im.info["version"] = b"GIF89a"
im.save(out) assertVersionAfterSave(im, b"GIF87a")
reread = Image.open(out)
self.assertEqual(reread.info["version"], b"GIF87a")
def test_append_images(self): def test_append_images(self):
out = self.tempfile('temp.gif') out = self.tempfile('temp.gif')

View File

@ -10,13 +10,13 @@ class TestImage(PillowTestCase):
GimpPaletteFile(fp) GimpPaletteFile(fp)
with open('Tests/images/hopper.jpg', 'rb') as fp: with open('Tests/images/hopper.jpg', 'rb') as fp:
self.assertRaises(SyntaxError, lambda: GimpPaletteFile(fp)) self.assertRaises(SyntaxError, GimpPaletteFile, fp)
with open('Tests/images/bad_palette_file.gpl', 'rb') as fp: with open('Tests/images/bad_palette_file.gpl', 'rb') as fp:
self.assertRaises(SyntaxError, lambda: GimpPaletteFile(fp)) self.assertRaises(SyntaxError, GimpPaletteFile, fp)
with open('Tests/images/bad_palette_entry.gpl', 'rb') as fp: with open('Tests/images/bad_palette_entry.gpl', 'rb') as fp:
self.assertRaises(ValueError, lambda: GimpPaletteFile(fp)) self.assertRaises(ValueError, GimpPaletteFile, fp)
def test_get_palette(self): def test_get_palette(self):
# Arrange # Arrange

View File

@ -24,8 +24,7 @@ class TestFileGribStub(PillowTestCase):
# Act / Assert # Act / Assert
self.assertRaises(SyntaxError, self.assertRaises(SyntaxError,
lambda: GribStubImagePlugin.GribStubImageFile, invalid_file)
GribStubImagePlugin.GribStubImageFile(invalid_file))
def test_load(self): def test_load(self):
# Arrange # Arrange
@ -40,7 +39,7 @@ class TestFileGribStub(PillowTestCase):
tmpfile = self.tempfile("temp.grib") tmpfile = self.tempfile("temp.grib")
# Act / Assert: stub cannot save without an implemented handler # Act / Assert: stub cannot save without an implemented handler
self.assertRaises(IOError, lambda: im.save(tmpfile)) self.assertRaises(IOError, im.save, tmpfile)
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -24,8 +24,7 @@ class TestFileHdf5Stub(PillowTestCase):
# Act / Assert # Act / Assert
self.assertRaises(SyntaxError, self.assertRaises(SyntaxError,
lambda: Hdf5StubImagePlugin.HDF5StubImageFile, invalid_file)
Hdf5StubImagePlugin.HDF5StubImageFile(invalid_file))
def test_load(self): def test_load(self):
# Arrange # Arrange
@ -41,10 +40,10 @@ class TestFileHdf5Stub(PillowTestCase):
dummy_filename = "dummy.filename" dummy_filename = "dummy.filename"
# Act / Assert: stub cannot save without an implemented handler # Act / Assert: stub cannot save without an implemented handler
self.assertRaises(IOError, lambda: im.save(dummy_filename)) self.assertRaises(IOError, im.save, dummy_filename)
self.assertRaises( self.assertRaises(
IOError, IOError,
lambda: Hdf5StubImagePlugin._save(im, dummy_fp, dummy_filename)) Hdf5StubImagePlugin._save, im, dummy_fp, dummy_filename)
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -1,7 +1,8 @@
from helper import unittest, PillowTestCase from helper import unittest, PillowTestCase
from PIL import Image from PIL import Image, IcnsImagePlugin
import io
import sys import sys
# sample icon file # sample icon file
@ -82,6 +83,23 @@ class TestFileIcns(PillowTestCase):
self.assertEqual(im2.mode, 'RGBA') self.assertEqual(im2.mode, 'RGBA')
self.assertEqual(im2.size, (wr, hr)) self.assertEqual(im2.size, (wr, hr))
def test_getimage(self):
with open(TEST_FILE, 'rb') as fp:
icns_file = IcnsImagePlugin.IcnsFile(fp)
im = icns_file.getimage()
self.assertEqual(im.mode, "RGBA")
self.assertEqual(im.size, (1024, 1024))
im = icns_file.getimage((512, 512))
self.assertEqual(im.mode, "RGBA")
self.assertEqual(im.size, (512, 512))
def test_not_an_icns_file(self):
with io.BytesIO(b'invalid\n') as fp:
self.assertRaises(SyntaxError,
IcnsImagePlugin.IcnsFile, fp)
if __name__ == '__main__': if __name__ == '__main__':
unittest.main() unittest.main()

View File

@ -18,7 +18,7 @@ class TestFileIco(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, self.assertRaises(SyntaxError,
lambda: IcoImagePlugin.IcoImageFile(fp)) IcoImagePlugin.IcoImageFile, fp)
def test_save_to_bytes(self): def test_save_to_bytes(self):
output = io.BytesIO() output = io.BytesIO()

View File

@ -43,18 +43,27 @@ class TestFileIm(PillowTestCase):
self.assertLess(im.tell(), n_frames) self.assertLess(im.tell(), n_frames)
def test_roundtrip(self): def test_roundtrip(self):
out = self.tempfile('temp.im') for mode in ["RGB", "P"]:
im = hopper() out = self.tempfile('temp.im')
im.save(out) im = hopper(mode)
reread = Image.open(out) im.save(out)
reread = Image.open(out)
self.assert_image_equal(reread, im) self.assert_image_equal(reread, im)
def test_save_unsupported_mode(self):
out = self.tempfile('temp.im')
im = hopper("HSV")
self.assertRaises(ValueError, im.save, out)
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, self.assertRaises(SyntaxError,
lambda: ImImagePlugin.ImImageFile(invalid_file)) ImImagePlugin.ImImageFile, invalid_file)
def test_number(self):
self.assertEqual(1.2, ImImagePlugin.number("1.2"))
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -314,7 +314,7 @@ class TestFileJpeg(PillowTestCase):
self.assertEqual(getsampling(im), (2, 2, 1, 1, 1, 1)) self.assertEqual(getsampling(im), (2, 2, 1, 1, 1, 1))
self.assertRaises( self.assertRaises(
TypeError, lambda: self.roundtrip(hopper(), subsampling="1:1:1")) TypeError, self.roundtrip, hopper(), subsampling="1:1:1")
def test_exif(self): def test_exif(self):
im = Image.open("Tests/images/pil_sample_rgb.jpg") im = Image.open("Tests/images/pil_sample_rgb.jpg")
@ -423,18 +423,18 @@ 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(Exception, lambda: self.roundtrip(im, qtables='a')) self.assertRaises(Exception, self.roundtrip, im, qtables='a')
# sequence wrong length # sequence wrong length
self.assertRaises(Exception, lambda: self.roundtrip(im, qtables=[])) self.assertRaises(Exception, self.roundtrip, im, qtables=[])
# sequence wrong length # sequence wrong length
self.assertRaises(Exception, self.assertRaises(Exception,
lambda: self.roundtrip(im, qtables=[1, 2, 3, 4, 5])) self.roundtrip, im, qtables=[1, 2, 3, 4, 5])
# qtable entry not a sequence # qtable entry not a sequence
self.assertRaises(Exception, lambda: self.roundtrip(im, qtables=[1])) self.assertRaises(Exception, self.roundtrip, im, qtables=[1])
# qtable entry has wrong number of items # qtable entry has wrong number of items
self.assertRaises(Exception, self.assertRaises(Exception,
lambda: self.roundtrip(im, qtables=[[1, 2, 3, 4]])) 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):
@ -479,7 +479,7 @@ class TestFileJpeg(PillowTestCase):
# Act # Act
# Shouldn't raise error # Shouldn't raise error
fn = "Tests/images/sugarshack_bad_mpo_header.jpg" fn = "Tests/images/sugarshack_bad_mpo_header.jpg"
im = self.assert_warning(UserWarning, lambda: Image.open(fn)) im = self.assert_warning(UserWarning, Image.open, fn)
# Assert # Assert
self.assertEqual(im.format, "JPEG") self.assertEqual(im.format, "JPEG")
@ -584,7 +584,7 @@ class TestFileCloseW32(PillowTestCase):
im = Image.open(tmpfile) im = Image.open(tmpfile)
fp = im.fp fp = im.fp
self.assertFalse(fp.closed) self.assertFalse(fp.closed)
self.assertRaises(Exception, lambda: os.remove(tmpfile)) self.assertRaises(Exception, os.remove, tmpfile)
im.load() im.load()
self.assertTrue(fp.closed) self.assertTrue(fp.closed)
# this should not fail, as load should have closed the file. # this should not fail, as load should have closed the file.

View File

@ -44,8 +44,7 @@ class TestFileJpeg2k(PillowTestCase):
invalid_file = "Tests/images/flower.jpg" invalid_file = "Tests/images/flower.jpg"
self.assertRaises(SyntaxError, self.assertRaises(SyntaxError,
lambda: Jpeg2KImagePlugin.Jpeg2KImageFile, invalid_file)
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:

View File

@ -362,10 +362,9 @@ class TestFileLibTiff(LibTiffTestCase):
im = hopper('RGB') im = hopper('RGB')
out = self.tempfile('temp.tif') out = self.tempfile('temp.tif')
self.assertRaises( self.assertRaises(IOError, im.save, out, compression='tiff_ccitt')
IOError, lambda: im.save(out, compression='tiff_ccitt')) self.assertRaises(IOError, im.save, out, compression='group3')
self.assertRaises(IOError, lambda: im.save(out, compression='group3')) self.assertRaises(IOError, im.save, out, compression='group4')
self.assertRaises(IOError, lambda: 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")
@ -373,10 +372,10 @@ class TestFileLibTiff(LibTiffTestCase):
os.fstat(fn) os.fstat(fn)
im.load() # this should close it. im.load() # this should close it.
self.assertRaises(OSError, lambda: os.fstat(fn)) self.assertRaises(OSError, os.fstat, fn)
im = None # this should force even more closed. im = None # this should force even more closed.
self.assertRaises(OSError, lambda: os.fstat(fn)) self.assertRaises(OSError, os.fstat, fn)
self.assertRaises(OSError, lambda: os.close(fn)) self.assertRaises(OSError, os.close, fn)
def test_multipage(self): def test_multipage(self):
# issue #862 # issue #862

View File

@ -9,8 +9,7 @@ class TestFileMcIdas(PillowTestCase):
invalid_file = "Tests/images/flower.jpg" invalid_file = "Tests/images/flower.jpg"
self.assertRaises(SyntaxError, self.assertRaises(SyntaxError,
lambda: McIdasImagePlugin.McIdasImageFile, invalid_file)
McIdasImagePlugin.McIdasImageFile(invalid_file))
def test_valid_file(self): def test_valid_file(self):
# Arrange # Arrange

View File

@ -42,19 +42,19 @@ class TestFileMic(PillowTestCase):
im.seek(0) im.seek(0)
self.assertEqual(im.tell(), 0) self.assertEqual(im.tell(), 0)
self.assertRaises(EOFError, lambda: im.seek(99)) self.assertRaises(EOFError, im.seek, 99)
self.assertEqual(im.tell(), 0) self.assertEqual(im.tell(), 0)
def test_invalid_file(self): def test_invalid_file(self):
# Test an invalid OLE file # Test an invalid OLE file
invalid_file = "Tests/images/flower.jpg" invalid_file = "Tests/images/flower.jpg"
self.assertRaises(SyntaxError, self.assertRaises(SyntaxError,
lambda: MicImagePlugin.MicImageFile(invalid_file)) MicImagePlugin.MicImageFile, invalid_file)
# Test a valid OLE file, but not a MIC file # Test a valid OLE file, but not a MIC file
ole_file = "Tests/images/test-ole-file.doc" ole_file = "Tests/images/test-ole-file.doc"
self.assertRaises(SyntaxError, self.assertRaises(SyntaxError,
lambda: MicImagePlugin.MicImageFile(ole_file)) MicImagePlugin.MicImageFile, ole_file)
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -26,7 +26,7 @@ class TestFileMsp(PillowTestCase):
invalid_file = "Tests/images/flower.jpg" invalid_file = "Tests/images/flower.jpg"
self.assertRaises(SyntaxError, self.assertRaises(SyntaxError,
lambda: MspImagePlugin.MspImageFile(invalid_file)) MspImagePlugin.MspImageFile, invalid_file)
def test_bad_checksum(self): def test_bad_checksum(self):
# Arrange # Arrange
@ -35,7 +35,7 @@ class TestFileMsp(PillowTestCase):
# Act / Assert # Act / Assert
self.assertRaises(SyntaxError, self.assertRaises(SyntaxError,
lambda: MspImagePlugin.MspImageFile(bad_checksum)) MspImagePlugin.MspImageFile, bad_checksum)
def test_open_windows_v1(self): def test_open_windows_v1(self):
# Arrange # Arrange
@ -77,7 +77,7 @@ class TestFileMsp(PillowTestCase):
filename = self.tempfile("temp.msp") filename = self.tempfile("temp.msp")
# Act/Assert # Act/Assert
self.assertRaises(IOError, lambda: im.save(filename)) self.assertRaises(IOError, im.save, filename)
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -51,7 +51,7 @@ class TestFilePalm(PillowTestCase):
mode = "RGB" mode = "RGB"
# Act / Assert # Act / Assert
self.assertRaises(IOError, lambda: self.helper_save_as_palm(mode)) self.assertRaises(IOError, self.helper_save_as_palm, mode)
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -21,13 +21,14 @@ class TestFilePcx(PillowTestCase):
# Test an unsupported mode # Test an unsupported mode
f = self.tempfile("temp.pcx") f = self.tempfile("temp.pcx")
self.assertRaises(ValueError, lambda: hopper("RGBA").save(f)) im = hopper("RGBA")
self.assertRaises(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, self.assertRaises(SyntaxError,
lambda: PcxImagePlugin.PcxImageFile(invalid_file)) 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.

View File

@ -59,7 +59,7 @@ class TestFilePdf(PillowTestCase):
im = hopper("LA") im = hopper("LA")
outfile = self.tempfile("temp_LA.pdf") outfile = self.tempfile("temp_LA.pdf")
self.assertRaises(ValueError, lambda: im.save(outfile)) self.assertRaises(ValueError, im.save, outfile)
def test_save_all(self): def test_save_all(self):
# Single frame image # Single frame image

View File

@ -22,7 +22,7 @@ class TestFilePixar(PillowTestCase):
self.assertRaises( self.assertRaises(
SyntaxError, SyntaxError,
lambda: PixarImagePlugin.PixarImageFile(invalid_file)) PixarImagePlugin.PixarImageFile, invalid_file)
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -87,14 +87,14 @@ class TestFilePng(PillowTestCase):
invalid_file = "Tests/images/flower.jpg" invalid_file = "Tests/images/flower.jpg"
self.assertRaises(SyntaxError, self.assertRaises(SyntaxError,
lambda: PngImagePlugin.PngImageFile(invalid_file)) 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, lambda: Image.open(test_file)) self.assertRaises(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)
@ -424,7 +424,7 @@ class TestFilePng(PillowTestCase):
data = b'\x89' + fd.read() data = b'\x89' + fd.read()
pngfile = BytesIO(data) pngfile = BytesIO(data)
self.assertRaises(IOError, lambda: Image.open(pngfile)) self.assertRaises(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.
@ -505,17 +505,17 @@ class TestFilePng(PillowTestCase):
im.convert("P").save(test_file, dpi=(100, 100)) im.convert("P").save(test_file, dpi=(100, 100))
chunks = [] chunks = []
fp = open(test_file, "rb") with open(test_file, "rb") as fp:
fp.read(8) fp.read(8)
png = PngImagePlugin.PngStream(fp) png = PngImagePlugin.PngStream(fp)
while True: while True:
cid, pos, length = png.read() cid, pos, length = png.read()
chunks.append(cid) chunks.append(cid)
try: try:
s = png.call(cid, pos, length) s = png.call(cid, pos, length)
except EOFError: except EOFError:
break break
png.crc(cid, s) png.crc(cid, s)
# https://www.w3.org/TR/PNG/#5ChunkOrdering # https://www.w3.org/TR/PNG/#5ChunkOrdering
# IHDR - shall be first # IHDR - shall be first
@ -531,6 +531,12 @@ class TestFilePng(PillowTestCase):
# pHYs - before IDAT # pHYs - before IDAT
self.assertLess(chunks.index(b"pHYs"), chunks.index(b"IDAT")) self.assertLess(chunks.index(b"pHYs"), chunks.index(b"IDAT"))
def test_getchunks(self):
im = hopper()
chunks = PngImagePlugin.getchunks(im)
self.assertEqual(len(chunks), 3)
@unittest.skipIf(sys.platform.startswith('win32'), "requires Unix or MacOS") @unittest.skipIf(sys.platform.startswith('win32'), "requires Unix or MacOS")
class TestTruncatedPngPLeaks(PillowTestCase): class TestTruncatedPngPLeaks(PillowTestCase):

View File

@ -39,7 +39,7 @@ class TestFilePpm(PillowTestCase):
with open(path, 'w') as f: with open(path, 'w') as f:
f.write('P6') f.write('P6')
self.assertRaises(ValueError, lambda: Image.open(path)) self.assertRaises(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

View File

@ -21,7 +21,7 @@ class TestImagePsd(PillowTestCase):
invalid_file = "Tests/images/flower.jpg" invalid_file = "Tests/images/flower.jpg"
self.assertRaises(SyntaxError, self.assertRaises(SyntaxError,
lambda: PsdImagePlugin.PsdImageFile(invalid_file)) PsdImagePlugin.PsdImageFile, invalid_file)
def test_n_frames(self): def test_n_frames(self):
im = Image.open("Tests/images/hopper_merged.psd") im = Image.open("Tests/images/hopper_merged.psd")
@ -66,7 +66,7 @@ class TestImagePsd(PillowTestCase):
def test_seek_eoferror(self): def test_seek_eoferror(self):
im = Image.open(test_file) im = Image.open(test_file)
self.assertRaises(EOFError, lambda: im.seek(-1)) self.assertRaises(EOFError, im.seek, -1)
def test_icc_profile(self): def test_icc_profile(self):
im = Image.open(test_file) im = Image.open(test_file)

View File

@ -42,8 +42,7 @@ class TestFileSgi(PillowTestCase):
invalid_file = "Tests/images/flower.jpg" invalid_file = "Tests/images/flower.jpg"
self.assertRaises(ValueError, self.assertRaises(ValueError,
lambda: SgiImagePlugin.SgiImageFile, invalid_file)
SgiImagePlugin.SgiImageFile(invalid_file))
def test_write(self): def test_write(self):
def roundtrip(img): def roundtrip(img):
@ -62,14 +61,14 @@ class TestFileSgi(PillowTestCase):
im = hopper('LA') im = hopper('LA')
out = self.tempfile('temp.sgi') out = self.tempfile('temp.sgi')
self.assertRaises(ValueError, lambda: im.save(out, format='sgi')) self.assertRaises(ValueError, im.save, out, format='sgi')
def test_incorrect_number_of_bands(self): def test_incorrect_number_of_bands(self):
im = hopper('YCbCr') im = hopper('YCbCr')
im.mode = 'RGB' im.mode = 'RGB'
out = self.tempfile('temp.sgi') out = self.tempfile('temp.sgi')
self.assertRaises(ValueError, lambda: im.save(out, format='sgi')) self.assertRaises(ValueError, im.save, out, format='sgi')
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -84,12 +84,12 @@ class TestImageSpider(PillowTestCase):
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, lambda: Image.open(invalid_file)) self.assertRaises(IOError, Image.open, invalid_file)
def test_nonstack_file(self): def test_nonstack_file(self):
im = Image.open(TEST_FILE) im = Image.open(TEST_FILE)
self.assertRaises(EOFError, lambda: im.seek(0)) self.assertRaises(EOFError, im.seek, 0)
def test_nonstack_dos(self): def test_nonstack_dos(self):
im = Image.open(TEST_FILE) im = Image.open(TEST_FILE)

View File

@ -24,7 +24,7 @@ class TestFileSun(PillowTestCase):
invalid_file = "Tests/images/flower.jpg" invalid_file = "Tests/images/flower.jpg"
self.assertRaises(SyntaxError, self.assertRaises(SyntaxError,
lambda: SunImagePlugin.SunImageFile(invalid_file)) SunImagePlugin.SunImageFile, invalid_file)
def test_im1(self): def test_im1(self):
im = Image.open('Tests/images/sunraster.im1') im = Image.open('Tests/images/sunraster.im1')

View File

@ -85,6 +85,10 @@ class TestFileTiff(PillowTestCase):
im = Image.open("Tests/images/copyleft.tiff") im = Image.open("Tests/images/copyleft.tiff")
self.assertEqual(im.mode, 'RGB') self.assertEqual(im.mode, 'RGB')
def test_set_legacy_api(self):
with self.assertRaises(Exception):
ImageFileDirectory_v2.legacy_api = None
def test_xyres_tiff(self): def test_xyres_tiff(self):
filename = "Tests/images/pil168.tif" filename = "Tests/images/pil168.tif"
im = Image.open(filename) im = Image.open(filename)
@ -140,11 +144,11 @@ class TestFileTiff(PillowTestCase):
invalid_file = "Tests/images/flower.jpg" invalid_file = "Tests/images/flower.jpg"
self.assertRaises(SyntaxError, self.assertRaises(SyntaxError,
lambda: TiffImagePlugin.TiffImageFile(invalid_file)) TiffImagePlugin.TiffImageFile, invalid_file)
TiffImagePlugin.PREFIXES.append(b"\xff\xd8\xff\xe0") TiffImagePlugin.PREFIXES.append(b"\xff\xd8\xff\xe0")
self.assertRaises(SyntaxError, self.assertRaises(SyntaxError,
lambda: TiffImagePlugin.TiffImageFile(invalid_file)) TiffImagePlugin.TiffImageFile, invalid_file)
TiffImagePlugin.PREFIXES.pop() TiffImagePlugin.PREFIXES.pop()
def test_bad_exif(self): def test_bad_exif(self):
@ -163,7 +167,7 @@ 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, lambda: im.save(outfile)) self.assertRaises(IOError, im.save, outfile)
def test_little_endian(self): def test_little_endian(self):
im = Image.open('Tests/images/16bit.cropped.tif') im = Image.open('Tests/images/16bit.cropped.tif')
@ -340,7 +344,7 @@ class TestFileTiff(PillowTestCase):
filename = "Tests/images/pil136.tiff" filename = "Tests/images/pil136.tiff"
im = Image.open(filename) im = Image.open(filename)
self.assertEqual(im.tell(), 0) self.assertEqual(im.tell(), 0)
self.assertRaises(EOFError, lambda: im.seek(1)) self.assertRaises(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
@ -495,12 +499,12 @@ class TestFileTiff(PillowTestCase):
with Image.open("Tests/images/uint16_1_4660.tif") as im: with Image.open("Tests/images/uint16_1_4660.tif") as im:
im.save(tmpfile) im.save(tmpfile)
f = open(tmpfile, 'rb') with open(tmpfile, 'rb') as f:
im = Image.open(f) im = Image.open(f)
fp = im.fp fp = im.fp
self.assertFalse(fp.closed) self.assertFalse(fp.closed)
im.load() im.load()
self.assertFalse(fp.closed) self.assertFalse(fp.closed)
@unittest.skipUnless(sys.platform.startswith('win32'), "Windows only") @unittest.skipUnless(sys.platform.startswith('win32'), "Windows only")
class TestFileTiffW32(PillowTestCase): class TestFileTiffW32(PillowTestCase):
@ -515,7 +519,7 @@ class TestFileTiffW32(PillowTestCase):
im = Image.open(tmpfile) im = Image.open(tmpfile)
fp = im.fp fp = im.fp
self.assertFalse(fp.closed) self.assertFalse(fp.closed)
self.assertRaises(Exception, lambda: os.remove(tmpfile)) self.assertRaises(Exception, os.remove, tmpfile)
im.load() im.load()
self.assertTrue(fp.closed) self.assertTrue(fp.closed)

View File

@ -161,7 +161,7 @@ class TestFileTiffMetadata(PillowTestCase):
head = f.read(8) head = f.read(8)
info = TiffImagePlugin.ImageFileDirectory(head) info = TiffImagePlugin.ImageFileDirectory(head)
try: try:
self.assert_warning(UserWarning, lambda: info.load(f)) self.assert_warning(UserWarning, info.load, f)
except struct.error: except struct.error:
self.fail("Should not be struct errors there.") self.fail("Should not be struct errors there.")

View File

@ -75,7 +75,8 @@ class TestFileWebp(PillowTestCase):
def test_write_unsupported_mode(self): def test_write_unsupported_mode(self):
temp_file = self.tempfile("temp.webp") temp_file = self.tempfile("temp.webp")
self.assertRaises(IOError, lambda: hopper("L").save(temp_file)) im = hopper("L")
self.assertRaises(IOError, im.save, temp_file)
def test_WebPEncode_with_invalid_args(self): def test_WebPEncode_with_invalid_args(self):
self.assertRaises(TypeError, _webp.WebPEncode) self.assertRaises(TypeError, _webp.WebPEncode)

View File

@ -1,5 +1,7 @@
from helper import unittest, PillowTestCase, hopper from helper import unittest, PillowTestCase, hopper
from PIL import Image from PIL import Image
from PIL import WmfImagePlugin
class TestFileWmf(PillowTestCase): class TestFileWmf(PillowTestCase):
@ -26,12 +28,29 @@ class TestFileWmf(PillowTestCase):
imref.load() imref.load()
self.assert_image_similar(im, imref, 2.0) self.assert_image_similar(im, imref, 2.0)
def test_register_handler(self):
class TestHandler:
methodCalled = False
def save(self, im, fp, filename):
self.methodCalled = True
handler = TestHandler()
WmfImagePlugin.register_handler(handler)
im = hopper()
tmpfile = self.tempfile("temp.wmf")
im.save(tmpfile)
self.assertTrue(handler.methodCalled)
# Restore the state before this test
WmfImagePlugin.register_handler(None)
def test_save(self): def test_save(self):
im = hopper() im = hopper()
for ext in [".wmf", ".emf"]: for ext in [".wmf", ".emf"]:
tmpfile = self.tempfile("temp"+ext) tmpfile = self.tempfile("temp"+ext)
self.assertRaises(IOError, lambda: im.save(tmpfile)) self.assertRaises(IOError, im.save, tmpfile)
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -21,7 +21,7 @@ class TestFileXpm(PillowTestCase):
invalid_file = "Tests/images/flower.jpg" invalid_file = "Tests/images/flower.jpg"
self.assertRaises(SyntaxError, self.assertRaises(SyntaxError,
lambda: XpmImagePlugin.XpmImageFile(invalid_file)) XpmImagePlugin.XpmImageFile, invalid_file)
def test_load_read(self): def test_load_read(self):
# Arrange # Arrange

View File

@ -25,8 +25,7 @@ class TestFileXVThumb(PillowTestCase):
# Act / Assert # Act / Assert
self.assertRaises(SyntaxError, self.assertRaises(SyntaxError,
lambda: XVThumbImagePlugin.XVThumbImageFile, bad_file)
XVThumbImagePlugin.XVThumbImageFile(bad_file))
def test_invalid_file(self): def test_invalid_file(self):
# Arrange # Arrange
@ -34,8 +33,7 @@ class TestFileXVThumb(PillowTestCase):
# Act / Assert # Act / Assert
self.assertRaises(SyntaxError, self.assertRaises(SyntaxError,
lambda: XVThumbImagePlugin.XVThumbImageFile, invalid_file)
XVThumbImagePlugin.XVThumbImageFile(invalid_file))
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -9,15 +9,15 @@ class TestFontBdf(PillowTestCase):
def test_sanity(self): def test_sanity(self):
test_file = open(filename, "rb") with open(filename, "rb") as test_file:
font = BdfFontFile.BdfFontFile(test_file) font = BdfFontFile.BdfFontFile(test_file)
self.assertIsInstance(font, FontFile.FontFile) self.assertIsInstance(font, FontFile.FontFile)
self.assertEqual(len([_f for _f in font.glyph if _f]), 190) self.assertEqual(len([_f for _f in font.glyph if _f]), 190)
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, lambda: BdfFontFile.BdfFontFile(fp)) self.assertRaises(SyntaxError, BdfFontFile.BdfFontFile, fp)
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -17,8 +17,8 @@ class TestFontPcf(PillowTestCase):
self.skipTest("zlib support not available") self.skipTest("zlib support not available")
def save_font(self): def save_font(self):
test_file = open(fontname, "rb") with open(fontname, "rb") as test_file:
font = PcfFontFile.PcfFontFile(test_file) font = PcfFontFile.PcfFontFile(test_file)
self.assertIsInstance(font, FontFile.FontFile) self.assertIsInstance(font, FontFile.FontFile)
self.assertEqual(len([_f for _f in font.glyph if _f]), 192) self.assertEqual(len([_f for _f in font.glyph if _f]), 192)
@ -32,7 +32,7 @@ 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, lambda: PcfFontFile.PcfFontFile(fp)) self.assertRaises(SyntaxError, PcfFontFile.PcfFontFile, fp)
def xtest_draw(self): def xtest_draw(self):

View File

@ -47,10 +47,9 @@ class TestImage(PillowTestCase):
self.assertEqual(im2.getcolors(), [(10000, 0)]) self.assertEqual(im2.getcolors(), [(10000, 0)])
self.assertEqual(im3.getcolors(), [(10000, 0)]) self.assertEqual(im3.getcolors(), [(10000, 0)])
self.assertRaises(ValueError, lambda: Image.new("X", (100, 100))) self.assertRaises(ValueError, Image.new, "X", (100, 100))
self.assertRaises(ValueError, lambda: Image.new("", (100, 100))) self.assertRaises(ValueError, Image.new, "", (100, 100))
# self.assertRaises( # self.assertRaises(MemoryError, Image.new, "L", (1000000, 1000000))
# MemoryError, lambda: 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))
@ -68,7 +67,10 @@ class TestImage(PillowTestCase):
else: else:
import io import io
im = io.BytesIO(b'') im = io.BytesIO(b'')
self.assertRaises(IOError, lambda: Image.open(im)) self.assertRaises(IOError, Image.open, im)
def test_bad_mode(self):
self.assertRaises(ValueError, Image.open, "filename", "bad mode")
@unittest.skipIf(sys.version_info < (3, 4), @unittest.skipIf(sys.version_info < (3, 4),
"pathlib only available in Python 3.4 or later") "pathlib only available in Python 3.4 or later")
@ -109,7 +111,7 @@ 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, lambda: im.save(temp_file)) self.assertRaises(ValueError, im.save, temp_file)
def test_internals(self): def test_internals(self):
@ -273,6 +275,20 @@ class TestImage(PillowTestCase):
target.crop((32, 32, 96, 96))) target.crop((32, 32, 96, 96)))
self.assertEqual(source.size, (128, 128)) self.assertEqual(source.size, (128, 128))
# errors
self.assertRaises(ValueError,
source.alpha_composite, over, "invalid source")
self.assertRaises(ValueError,
source.alpha_composite, over, (0, 0), "invalid destination")
self.assertRaises(ValueError,
source.alpha_composite, over, (0))
self.assertRaises(ValueError,
source.alpha_composite, over, (0, 0), (0))
self.assertRaises(ValueError,
source.alpha_composite, over, (0, -1))
self.assertRaises(ValueError,
source.alpha_composite, over, (0, 0), (0, -1))
def test_registered_extensions_uninitialized(self): def test_registered_extensions_uninitialized(self):
# Arrange # Arrange
Image._initialized = 0 Image._initialized = 0
@ -327,7 +343,7 @@ class TestImage(PillowTestCase):
# Act/Assert # Act/Assert
self.assertRaises( self.assertRaises(
ValueError, ValueError,
lambda: Image.effect_mandelbrot(size, extent, quality)) Image.effect_mandelbrot, size, extent, quality)
def test_effect_noise(self): def test_effect_noise(self):
# Arrange # Arrange
@ -388,7 +404,7 @@ class TestImage(PillowTestCase):
im = hopper() im = hopper()
# Act / Assert # Act / Assert
self.assertRaises(NotImplementedError, lambda: im.offset(None)) self.assertRaises(NotImplementedError, im.offset, None)
def test_fromstring(self): def test_fromstring(self):
self.assertRaises(NotImplementedError, Image.fromstring) self.assertRaises(NotImplementedError, Image.fromstring)
@ -399,8 +415,7 @@ class TestImage(PillowTestCase):
# Act / Assert # Act / Assert
self.assertRaises(ValueError, self.assertRaises(ValueError,
lambda: Image.linear_gradient(wrong_mode)) Image.linear_gradient, wrong_mode)
return
def test_linear_gradient(self): def test_linear_gradient(self):
@ -425,8 +440,7 @@ class TestImage(PillowTestCase):
# Act / Assert # Act / Assert
self.assertRaises(ValueError, self.assertRaises(ValueError,
lambda: Image.radial_gradient(wrong_mode)) Image.radial_gradient, wrong_mode)
return
def test_radial_gradient(self): def test_radial_gradient(self):
@ -445,6 +459,11 @@ class TestImage(PillowTestCase):
target = Image.open(target_file).convert(mode) target = Image.open(target_file).convert(mode)
self.assert_image_equal(im, target) self.assert_image_equal(im, target)
def test_remap_palette(self):
# Test illegal image mode
im = hopper()
self.assertRaises(ValueError, im.remap_palette, None)
def test__new(self): def test__new(self):
from PIL import ImagePalette from PIL import ImagePalette
@ -496,10 +515,10 @@ class TestRegistry(PillowTestCase):
self.assertEqual(enc.args, ('RGB', 'args', 'extra')) self.assertEqual(enc.args, ('RGB', 'args', 'extra'))
def test_encode_registry_fail(self): def test_encode_registry_fail(self):
self.assertRaises(IOError, lambda: Image._getencoder('RGB', self.assertRaises(IOError, Image._getencoder, 'RGB',
'DoesNotExist', 'DoesNotExist',
('args',), ('args',),
extra=('extra',))) extra=('extra',))
if __name__ == '__main__': if __name__ == '__main__':
unittest.main() unittest.main()

View File

@ -107,7 +107,7 @@ class TestImageConvert(PillowTestCase):
p = self.assert_warning( p = self.assert_warning(
UserWarning, UserWarning,
lambda: im.convert('P', palette=Image.ADAPTIVE)) im.convert, 'P', palette=Image.ADAPTIVE)
self.assertNotIn('transparency', p.info) self.assertNotIn('transparency', p.info)
p.save(f) p.save(f)
@ -131,7 +131,7 @@ class TestImageConvert(PillowTestCase):
p = self.assert_warning( p = self.assert_warning(
UserWarning, UserWarning,
lambda: im.convert('P', palette=Image.ADAPTIVE)) im.convert, 'P', palette=Image.ADAPTIVE)
self.assertNotIn('transparency', p.info) self.assertNotIn('transparency', p.info)
p.save(f) p.save(f)
@ -155,7 +155,7 @@ class TestImageConvert(PillowTestCase):
# Act / Assert # Act / Assert
self.assertRaises(ValueError, self.assertRaises(ValueError,
lambda: im.convert(mode='CMYK', matrix=matrix)) im.convert, mode='CMYK', matrix=matrix)
def test_matrix_wrong_mode(self): def test_matrix_wrong_mode(self):
# Arrange # Arrange
@ -168,7 +168,7 @@ class TestImageConvert(PillowTestCase):
# Act / Assert # Act / Assert
self.assertRaises(ValueError, self.assertRaises(ValueError,
lambda: im.convert(mode='L', matrix=matrix)) im.convert, mode='L', matrix=matrix)
def test_matrix_xyz(self): def test_matrix_xyz(self):

View File

@ -34,7 +34,7 @@ class TestImageFilter(PillowTestCase):
filter(ImageFilter.UnsharpMask) filter(ImageFilter.UnsharpMask)
filter(ImageFilter.UnsharpMask(10)) filter(ImageFilter.UnsharpMask(10))
self.assertRaises(TypeError, lambda: filter("hello")) self.assertRaises(TypeError, filter, "hello")
def test_crash(self): def test_crash(self):
@ -83,7 +83,7 @@ class TestImageFilter(PillowTestCase):
self.assertEqual(rankfilter("1"), (0, 4, 8)) self.assertEqual(rankfilter("1"), (0, 4, 8))
self.assertEqual(rankfilter("L"), (0, 4, 8)) self.assertEqual(rankfilter("L"), (0, 4, 8))
self.assertRaises(ValueError, lambda: rankfilter("P")) self.assertRaises(ValueError, rankfilter, "P")
self.assertEqual(rankfilter("RGB"), ((0, 0, 0), (4, 0, 0), (8, 0, 0))) self.assertEqual(rankfilter("RGB"), ((0, 0, 0), (4, 0, 0), (8, 0, 0)))
self.assertEqual(rankfilter("I"), (0, 4, 8)) self.assertEqual(rankfilter("I"), (0, 4, 8))
self.assertEqual(rankfilter("F"), (0.0, 4.0, 8.0)) self.assertEqual(rankfilter("F"), (0.0, 4.0, 8.0))

View File

@ -11,6 +11,9 @@ class TestImageFromBytes(PillowTestCase):
self.assert_image_equal(im1, im2) self.assert_image_equal(im1, im2)
def test_not_implemented(self):
self.assertRaises(NotImplementedError, Image.fromstring)
if __name__ == '__main__': if __name__ == '__main__':
unittest.main() unittest.main()

View File

@ -19,7 +19,7 @@ class TestImageLoad(PillowTestCase):
im = Image.open("Tests/images/hopper.gif") im = Image.open("Tests/images/hopper.gif")
im.close() im.close()
self.assertRaises(ValueError, im.load) self.assertRaises(ValueError, im.load)
self.assertRaises(ValueError, lambda: im.getpixel((0, 0))) self.assertRaises(ValueError, im.getpixel, (0, 0))
def test_contextmanager(self): def test_contextmanager(self):
fn = None fn = None
@ -27,7 +27,7 @@ class TestImageLoad(PillowTestCase):
fn = im.fp.fileno() fn = im.fp.fileno()
os.fstat(fn) os.fstat(fn)
self.assertRaises(OSError, lambda: os.fstat(fn)) self.assertRaises(OSError, os.fstat, fn)
if __name__ == '__main__': if __name__ == '__main__':
unittest.main() unittest.main()

View File

@ -6,17 +6,17 @@ class TestImagePoint(PillowTestCase):
def test_sanity(self): def test_sanity(self):
im = hopper() im = hopper()
self.assertRaises(ValueError, lambda: im.point(list(range(256)))) self.assertRaises(ValueError, im.point, list(range(256)))
im.point(list(range(256))*3) im.point(list(range(256))*3)
im.point(lambda x: x) im.point(lambda x: x)
im = im.convert("I") im = im.convert("I")
self.assertRaises(ValueError, lambda: im.point(list(range(256)))) self.assertRaises(ValueError, im.point, list(range(256)))
im.point(lambda x: x*1) im.point(lambda x: x*1)
im.point(lambda x: x+1) im.point(lambda x: x+1)
im.point(lambda x: x*1+1) im.point(lambda x: x*1+1)
self.assertRaises(TypeError, lambda: im.point(lambda x: x-1)) self.assertRaises(TypeError, im.point, lambda x: x-1)
self.assertRaises(TypeError, lambda: im.point(lambda x: x/1)) self.assertRaises(TypeError, im.point, lambda x: x/1)
def test_16bit_lut(self): def test_16bit_lut(self):
""" Tests for 16 bit -> 8 bit lut for converting I->L images """ Tests for 16 bit -> 8 bit lut for converting I->L images
@ -36,7 +36,8 @@ class TestImagePoint(PillowTestCase):
self.assert_image_equal(out.convert('L'), im.point(int_lut, 'L')) self.assert_image_equal(out.convert('L'), im.point(int_lut, 'L'))
def test_f_mode(self): def test_f_mode(self):
self.assertRaises(ValueError, lambda: hopper('F').point(None)) im = hopper('F')
self.assertRaises(ValueError, im.point, None)
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -13,14 +13,14 @@ class TestImagePutPalette(PillowTestCase):
if p: if p:
return im.mode, p[:10] return im.mode, p[:10]
return im.mode return im.mode
self.assertRaises(ValueError, lambda: palette("1")) self.assertRaises(ValueError, palette, "1")
self.assertEqual(palette("L"), ("P", [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])) self.assertEqual(palette("L"), ("P", [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))
self.assertEqual(palette("P"), ("P", [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])) self.assertEqual(palette("P"), ("P", [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))
self.assertRaises(ValueError, lambda: palette("I")) self.assertRaises(ValueError, palette, "I")
self.assertRaises(ValueError, lambda: palette("F")) self.assertRaises(ValueError, palette, "F")
self.assertRaises(ValueError, lambda: palette("RGB")) self.assertRaises(ValueError, palette, "RGB")
self.assertRaises(ValueError, lambda: palette("RGBA")) self.assertRaises(ValueError, palette, "RGBA")
self.assertRaises(ValueError, lambda: palette("YCbCr")) self.assertRaises(ValueError, palette, "YCbCr")
def test_imagepalette(self): def test_imagepalette(self):
im = hopper("P") im = hopper("P")

View File

@ -39,7 +39,7 @@ class TestImageQuantize(PillowTestCase):
def test_rgba_quantize(self): def test_rgba_quantize(self):
image = hopper('RGBA') image = hopper('RGBA')
image.quantize() image.quantize()
self.assertRaises(Exception, lambda: image.quantize(method=0)) self.assertRaises(Exception, image.quantize, method=0)
def test_quantize(self): def test_quantize(self):
image = Image.open('Tests/images/caption_6_33_22.png').convert('RGB') image = Image.open('Tests/images/caption_6_33_22.png').convert('RGB')

View File

@ -112,6 +112,10 @@ class TestImageResize(PillowTestCase):
resize(mode, (112, 103)) resize(mode, (112, 103))
resize(mode, (188, 214)) resize(mode, (188, 214))
# Test unknown resampling filter
im = hopper()
self.assertRaises(ValueError, im.resize, (10, 10), "unknown")
if __name__ == '__main__': if __name__ == '__main__':
unittest.main() unittest.main()

View File

@ -141,8 +141,8 @@ class TestImageTransform(PillowTestCase):
self.test_mesh() self.test_mesh()
def test_missing_method_data(self): def test_missing_method_data(self):
self.assertRaises(ValueError, lambda: im = hopper()
hopper().transform((100, 100), None)) self.assertRaises(ValueError, im.transform, (100, 100), None)
class TestImageTransformAffine(PillowTestCase): class TestImageTransformAffine(PillowTestCase):

View File

@ -144,20 +144,26 @@ class TestImageCms(PillowTestCase):
'IEC 61966-2.1 Default RGB colour space - sRGB') 'IEC 61966-2.1 Default RGB colour space - sRGB')
def test_exceptions(self): def test_exceptions(self):
# Test mode mismatch
psRGB = ImageCms.createProfile("sRGB")
pLab = ImageCms.createProfile("LAB")
t = ImageCms.buildTransform(pLab, psRGB, "LAB", "RGB")
self.assertRaises(ValueError, t.apply_in_place, hopper("RGBA"))
# the procedural pyCMS API uses PyCMSError for all sorts of errors # the procedural pyCMS API uses PyCMSError for all sorts of errors
self.assertRaises( self.assertRaises(
ImageCms.PyCMSError, ImageCms.PyCMSError,
lambda: ImageCms.profileToProfile(hopper(), "foo", "bar")) ImageCms.profileToProfile, hopper(), "foo", "bar")
self.assertRaises( self.assertRaises(
ImageCms.PyCMSError, ImageCms.PyCMSError,
lambda: ImageCms.buildTransform("foo", "bar", "RGB", "RGB")) ImageCms.buildTransform, "foo", "bar", "RGB", "RGB")
self.assertRaises( self.assertRaises(
ImageCms.PyCMSError, ImageCms.PyCMSError,
lambda: ImageCms.getProfileName(None)) ImageCms.getProfileName, None)
self.skip_missing() self.skip_missing()
self.assertRaises( self.assertRaises(
ImageCms.PyCMSError, ImageCms.PyCMSError,
lambda: ImageCms.isIntentSupported(SRGB, None, None)) ImageCms.isIntentSupported, SRGB, None, None)
def test_display_profile(self): def test_display_profile(self):
# try fetching the profile for the current display device # try fetching the profile for the current display device
@ -167,6 +173,14 @@ class TestImageCms(PillowTestCase):
ImageCms.createProfile("LAB", 5000) ImageCms.createProfile("LAB", 5000)
ImageCms.createProfile("LAB", 6500) ImageCms.createProfile("LAB", 6500)
def test_unsupported_color_space(self):
self.assertRaises(ImageCms.PyCMSError,
ImageCms.createProfile, "unsupported")
def test_invalid_color_temperature(self):
self.assertRaises(ImageCms.PyCMSError,
ImageCms.createProfile, "LAB", "invalid")
def test_simple_lab(self): def test_simple_lab(self):
i = Image.new('RGB', (10, 10), (128, 128, 128)) i = Image.new('RGB', (10, 10), (128, 128, 128))

View File

@ -51,13 +51,11 @@ class TestImageDraw(PillowTestCase):
draw = ImageDraw.Draw(im) draw = ImageDraw.Draw(im)
draw.line(((0, 0)), fill=(0, 0, 0)) draw.line(((0, 0)), fill=(0, 0, 0))
del draw
def test_mode_mismatch(self): def test_mode_mismatch(self):
im = hopper("RGB").copy() im = hopper("RGB").copy()
self.assertRaises(ValueError, self.assertRaises(ValueError, ImageDraw.ImageDraw, im, mode="L")
lambda: ImageDraw.ImageDraw(im, mode="L"))
def helper_arc(self, bbox, start, end): def helper_arc(self, bbox, start, end):
# Arrange # Arrange
@ -66,7 +64,6 @@ class TestImageDraw(PillowTestCase):
# Act # Act
draw.arc(bbox, start, end) draw.arc(bbox, start, end)
del draw
# Assert # Assert
self.assert_image_similar( self.assert_image_similar(
@ -89,7 +86,6 @@ class TestImageDraw(PillowTestCase):
# Act # Act
draw.arc(BBOX1, start=start, end=end) draw.arc(BBOX1, start=start, end=end)
del draw
# Assert # Assert
self.assert_image_equal( self.assert_image_equal(
@ -105,7 +101,6 @@ class TestImageDraw(PillowTestCase):
# Act # Act
draw.arc(BBOX1, start=start, end=end) draw.arc(BBOX1, start=start, end=end)
del draw
# Assert # Assert
self.assert_image_similar( self.assert_image_similar(
@ -119,7 +114,6 @@ class TestImageDraw(PillowTestCase):
# Act # Act
draw.bitmap((10, 10), small) draw.bitmap((10, 10), small)
del draw
# Assert # Assert
self.assert_image_equal( self.assert_image_equal(
@ -133,7 +127,6 @@ class TestImageDraw(PillowTestCase):
# Act # Act
draw.chord(bbox, start, end, fill="red", outline="yellow") draw.chord(bbox, start, end, fill="red", outline="yellow")
del draw
# Assert # Assert
self.assert_image_similar(im, Image.open(expected), 1) self.assert_image_similar(im, Image.open(expected), 1)
@ -156,7 +149,6 @@ class TestImageDraw(PillowTestCase):
# Act # Act
draw.ellipse(bbox, fill="green", outline="blue") draw.ellipse(bbox, fill="green", outline="blue")
del draw
# Assert # Assert
self.assert_image_similar(im, Image.open(expected), 1) self.assert_image_similar(im, Image.open(expected), 1)
@ -176,7 +168,6 @@ class TestImageDraw(PillowTestCase):
# Act # Act
draw.ellipse(((0, 0), (W-1, H)), fill="white") draw.ellipse(((0, 0), (W-1, H)), fill="white")
del draw
# Assert # Assert
self.assert_image_similar( self.assert_image_similar(
@ -189,7 +180,6 @@ class TestImageDraw(PillowTestCase):
# Act # Act
draw.line(points, fill="yellow", width=2) draw.line(points, fill="yellow", width=2)
del draw
# Assert # Assert
self.assert_image_equal( self.assert_image_equal(
@ -217,7 +207,6 @@ class TestImageDraw(PillowTestCase):
s.line(x0, y0) s.line(x0, y0)
draw.shape(s, fill=1) draw.shape(s, fill=1)
del draw
# Assert # Assert
self.assert_image_equal( self.assert_image_equal(
@ -239,7 +228,6 @@ class TestImageDraw(PillowTestCase):
s.line(x0, y0) s.line(x0, y0)
draw.shape(s, outline="blue") draw.shape(s, outline="blue")
del draw
# Assert # Assert
self.assert_image_equal( self.assert_image_equal(
@ -252,7 +240,6 @@ class TestImageDraw(PillowTestCase):
# Act # Act
draw.pieslice(bbox, start, end, fill="white", outline="blue") draw.pieslice(bbox, start, end, fill="white", outline="blue")
del draw
# Assert # Assert
self.assert_image_similar( self.assert_image_similar(
@ -273,7 +260,6 @@ class TestImageDraw(PillowTestCase):
# Act # Act
draw.point(points, fill="yellow") draw.point(points, fill="yellow")
del draw
# Assert # Assert
self.assert_image_equal( self.assert_image_equal(
@ -292,7 +278,6 @@ class TestImageDraw(PillowTestCase):
# Act # Act
draw.polygon(points, fill="red", outline="blue") draw.polygon(points, fill="red", outline="blue")
del draw
# Assert # Assert
self.assert_image_equal( self.assert_image_equal(
@ -316,7 +301,6 @@ class TestImageDraw(PillowTestCase):
# Act # Act
draw.polygon(KITE_POINTS, fill="blue", outline="yellow") draw.polygon(KITE_POINTS, fill="blue", outline="yellow")
del draw
# Assert # Assert
self.assert_image_equal(im, Image.open(expected)) self.assert_image_equal(im, Image.open(expected))
@ -328,7 +312,6 @@ class TestImageDraw(PillowTestCase):
# Act # Act
draw.rectangle(bbox, fill="black", outline="green") draw.rectangle(bbox, fill="black", outline="green")
del draw
# Assert # Assert
self.assert_image_equal( self.assert_image_equal(
@ -350,7 +333,6 @@ class TestImageDraw(PillowTestCase):
# Act # Act
draw.rectangle(bbox, fill="orange") draw.rectangle(bbox, fill="orange")
del draw
# Assert # Assert
self.assert_image_similar(im, Image.open(expected), 1) self.assert_image_similar(im, Image.open(expected), 1)
@ -377,7 +359,6 @@ class TestImageDraw(PillowTestCase):
# Test that filling outside the image does not change the image # Test that filling outside the image does not change the image
ImageDraw.floodfill(im, (W, H), red) ImageDraw.floodfill(im, (W, H), red)
self.assert_image_equal(im, im_floodfill) self.assert_image_equal(im, im_floodfill)
del draw
@unittest.skipIf(hasattr(sys, 'pypy_version_info'), @unittest.skipIf(hasattr(sys, 'pypy_version_info'),
"Causes fatal RPython error on PyPy") "Causes fatal RPython error on PyPy")
@ -394,7 +375,6 @@ class TestImageDraw(PillowTestCase):
ImageDraw.floodfill( ImageDraw.floodfill(
im, centre_point, ImageColor.getrgb("red"), im, centre_point, ImageColor.getrgb("red"),
border=ImageColor.getrgb("black")) border=ImageColor.getrgb("black"))
del draw
# Assert # Assert
self.assert_image_equal( self.assert_image_equal(
@ -414,7 +394,6 @@ class TestImageDraw(PillowTestCase):
ImageDraw.floodfill( ImageDraw.floodfill(
im, centre_point, ImageColor.getrgb("red"), im, centre_point, ImageColor.getrgb("red"),
thresh=30) thresh=30)
del draw
# Assert # Assert
self.assert_image_equal( self.assert_image_equal(
@ -577,7 +556,6 @@ class TestImageDraw(PillowTestCase):
# Act # Act
draw.line([(50, 50), (50, 50)], width=3) draw.line([(50, 50), (50, 50)], width=3)
del draw
# Assert # Assert
self.assert_image_similar(im, Image.open(expected), 1) self.assert_image_similar(im, Image.open(expected), 1)

View File

@ -69,7 +69,7 @@ class TestImageFile(PillowTestCase):
im1, im2 = roundtrip("JPEG") # lossy compression im1, im2 = roundtrip("JPEG") # lossy compression
self.assert_image(im1, im2.mode, im2.size) self.assert_image(im1, im2.mode, im2.size)
self.assertRaises(IOError, lambda: roundtrip("PDF")) self.assertRaises(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:
@ -93,7 +93,7 @@ class TestImageFile(PillowTestCase):
self.assert_image_equal(im1, im2) self.assert_image_equal(im1, im2)
def test_raise_ioerror(self): def test_raise_ioerror(self):
self.assertRaises(IOError, lambda: ImageFile.raise_ioerror(1)) self.assertRaises(IOError, ImageFile.raise_ioerror, 1)
def test_raise_typeerror(self): def test_raise_typeerror(self):
with self.assertRaises(TypeError): with self.assertRaises(TypeError):
@ -182,7 +182,7 @@ class TestPyDecoder(PillowTestCase):
self.assertEqual(d.state.xsize, xsize) self.assertEqual(d.state.xsize, xsize)
self.assertEqual(d.state.ysize, ysize) self.assertEqual(d.state.ysize, ysize)
self.assertRaises(ValueError, lambda: d.set_as_raw(b'\x00')) self.assertRaises(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)

View File

@ -106,7 +106,7 @@ 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, lambda: _render(shared_bytes)) # self.assertRaises(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:
@ -141,7 +141,6 @@ class TestImageFont(PillowTestCase):
size = draw.textsize(txt, ttf) size = draw.textsize(txt, ttf)
draw.text((10, 10), txt, font=ttf) draw.text((10, 10), txt, font=ttf)
draw.rectangle((10, 10, 10 + size[0], 10 + size[1])) draw.rectangle((10, 10, 10 + size[0], 10 + size[1]))
del draw
target = 'Tests/images/rectangle_surrounding_text.png' target = 'Tests/images/rectangle_surrounding_text.png'
target_img = Image.open(target) target_img = Image.open(target)
@ -188,7 +187,6 @@ class TestImageFont(PillowTestCase):
draw.text((0, 0), TEST_TEXT, fill=None, font=ttf, anchor=None, draw.text((0, 0), TEST_TEXT, fill=None, font=ttf, anchor=None,
spacing=4, align="left") spacing=4, align="left")
draw.text((0, 0), TEST_TEXT, None, ttf, None, 4, "left") draw.text((0, 0), TEST_TEXT, None, ttf, None, 4, "left")
del draw
# Test align center and right # Test align center and right
for align, ext in {"center": "_center", for align, ext in {"center": "_center",
@ -196,7 +194,6 @@ 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)
draw.multiline_text((0, 0), TEST_TEXT, font=ttf, align=align) draw.multiline_text((0, 0), TEST_TEXT, font=ttf, align=align)
del draw
target = 'Tests/images/multiline_text'+ext+'.png' target = 'Tests/images/multiline_text'+ext+'.png'
target_img = Image.open(target) target_img = Image.open(target)
@ -211,9 +208,9 @@ class TestImageFont(PillowTestCase):
# Act/Assert # Act/Assert
self.assertRaises(AssertionError, self.assertRaises(AssertionError,
lambda: draw.multiline_text((0, 0), TEST_TEXT, draw.multiline_text, (0, 0), TEST_TEXT,
font=ttf, font=ttf,
align="unknown")) 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')
@ -221,7 +218,6 @@ class TestImageFont(PillowTestCase):
ttf = self.get_font() ttf = self.get_font()
line = "some text" line = "some text"
draw.text((100, 40), line, (0, 0, 0), font=ttf, align='left') draw.text((100, 40), line, (0, 0, 0), font=ttf, align='left')
del draw
def test_multiline_size(self): def test_multiline_size(self):
ttf = self.get_font() ttf = self.get_font()
@ -236,7 +232,6 @@ class TestImageFont(PillowTestCase):
# to multiline_textsize() # to multiline_textsize()
draw.textsize(TEST_TEXT, font=ttf, spacing=4) draw.textsize(TEST_TEXT, font=ttf, spacing=4)
draw.textsize(TEST_TEXT, ttf, 4) draw.textsize(TEST_TEXT, ttf, 4)
del draw
def test_multiline_width(self): def test_multiline_width(self):
ttf = self.get_font() ttf = self.get_font()
@ -246,7 +241,6 @@ class TestImageFont(PillowTestCase):
self.assertEqual(draw.textsize("longest line", font=ttf)[0], self.assertEqual(draw.textsize("longest line", font=ttf)[0],
draw.multiline_textsize("longest line\nline", draw.multiline_textsize("longest line\nline",
font=ttf)[0]) font=ttf)[0])
del draw
def test_multiline_spacing(self): def test_multiline_spacing(self):
ttf = self.get_font() ttf = self.get_font()
@ -254,7 +248,6 @@ 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)
draw.multiline_text((0, 0), TEST_TEXT, font=ttf, spacing=10) draw.multiline_text((0, 0), TEST_TEXT, font=ttf, spacing=10)
del draw
target = 'Tests/images/multiline_text_spacing.png' target = 'Tests/images/multiline_text_spacing.png'
target_img = Image.open(target) target_img = Image.open(target)
@ -279,7 +272,6 @@ class TestImageFont(PillowTestCase):
# Rotated font # Rotated font
draw.font = transposed_font draw.font = transposed_font
box_size_b = draw.textsize(word) box_size_b = draw.textsize(word)
del draw
# 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]) self.assertEqual(box_size_a[0], box_size_b[1])
@ -302,7 +294,6 @@ class TestImageFont(PillowTestCase):
# Rotated font # Rotated font
draw.font = transposed_font draw.font = transposed_font
box_size_b = draw.textsize(word) box_size_b = draw.textsize(word)
del draw
# Check boxes a and b are same size # Check boxes a and b are same size
self.assertEqual(box_size_a, box_size_b) self.assertEqual(box_size_a, box_size_b)
@ -384,7 +375,7 @@ class TestImageFont(PillowTestCase):
filename = "somefilenamethatdoesntexist.ttf" filename = "somefilenamethatdoesntexist.ttf"
# Act/Assert # Act/Assert
self.assertRaises(IOError, lambda: ImageFont.load_path(filename)) self.assertRaises(IOError, ImageFont.load_path, filename)
def test_default_font(self): def test_default_font(self):
# Arrange # Arrange
@ -398,7 +389,6 @@ class TestImageFont(PillowTestCase):
# Act # Act
default_font = ImageFont.load_default() default_font = ImageFont.load_default()
draw.text((10, 10), txt, font=default_font) draw.text((10, 10), txt, font=default_font)
del draw
# Assert # Assert
self.assert_image_equal(im, target_img) self.assert_image_equal(im, target_img)

View File

@ -81,9 +81,9 @@ class MorphTests(PillowTestCase):
def test_no_operator_loaded(self): def test_no_operator_loaded(self):
mop = ImageMorph.MorphOp() mop = ImageMorph.MorphOp()
self.assertRaises(Exception, lambda: mop.apply(None)) self.assertRaises(Exception, mop.apply, None)
self.assertRaises(Exception, lambda: mop.match(None)) self.assertRaises(Exception, mop.match, None)
self.assertRaises(Exception, lambda: mop.save_lut(None)) self.assertRaises(Exception, mop.save_lut, None)
# Test the named patterns # Test the named patterns
def test_erosion8(self): def test_erosion8(self):
@ -214,9 +214,9 @@ class MorphTests(PillowTestCase):
im = hopper('RGB') im = hopper('RGB')
mop = ImageMorph.MorphOp(op_name="erosion8") mop = ImageMorph.MorphOp(op_name="erosion8")
self.assertRaises(Exception, lambda: mop.apply(im)) self.assertRaises(Exception, mop.apply, im)
self.assertRaises(Exception, lambda: mop.match(im)) self.assertRaises(Exception, mop.match, im)
self.assertRaises(Exception, lambda: mop.get_on_pixels(im)) self.assertRaises(Exception, mop.get_on_pixels, im)
def test_add_patterns(self): def test_add_patterns(self):
# Arrange # Arrange
@ -240,7 +240,7 @@ class MorphTests(PillowTestCase):
def test_unknown_pattern(self): def test_unknown_pattern(self):
self.assertRaises( self.assertRaises(
Exception, Exception,
lambda: ImageMorph.LutBuilder(op_name='unknown')) ImageMorph.LutBuilder, op_name='unknown')
def test_pattern_syntax_error(self): def test_pattern_syntax_error(self):
# Arrange # Arrange
@ -249,9 +249,7 @@ class MorphTests(PillowTestCase):
lb.add_patterns(new_patterns) lb.add_patterns(new_patterns)
# Act / Assert # Act / Assert
self.assertRaises( self.assertRaises(Exception, lb.build_lut)
Exception,
lambda: lb.build_lut())
def test_load_invalid_mrl(self): def test_load_invalid_mrl(self):
# Arrange # Arrange
@ -259,7 +257,7 @@ class MorphTests(PillowTestCase):
mop = ImageMorph.MorphOp() mop = ImageMorph.MorphOp()
# Act / Assert # Act / Assert
self.assertRaises(Exception, lambda: mop.load_lut(invalid_mrl)) self.assertRaises(Exception, mop.load_lut, invalid_mrl)
def test_roundtrip_mrl(self): def test_roundtrip_mrl(self):
# Arrange # Arrange

View File

@ -37,26 +37,26 @@ class TestImageOpsUsm(PillowTestCase):
def test_usm_formats(self): def test_usm_formats(self):
usm = ImageOps.unsharp_mask usm = ImageOps.unsharp_mask
self.assertRaises(ValueError, lambda: usm(im.convert("1"))) self.assertRaises(ValueError, usm, im.convert("1"))
usm(im.convert("L")) usm(im.convert("L"))
self.assertRaises(ValueError, lambda: usm(im.convert("I"))) self.assertRaises(ValueError, usm, im.convert("I"))
self.assertRaises(ValueError, lambda: usm(im.convert("F"))) self.assertRaises(ValueError, usm, im.convert("F"))
usm(im.convert("RGB")) usm(im.convert("RGB"))
usm(im.convert("RGBA")) usm(im.convert("RGBA"))
usm(im.convert("CMYK")) usm(im.convert("CMYK"))
self.assertRaises(ValueError, lambda: usm(im.convert("YCbCr"))) self.assertRaises(ValueError, usm, im.convert("YCbCr"))
def test_blur_formats(self): def test_blur_formats(self):
blur = ImageOps.gaussian_blur blur = ImageOps.gaussian_blur
self.assertRaises(ValueError, lambda: blur(im.convert("1"))) self.assertRaises(ValueError, blur, im.convert("1"))
blur(im.convert("L")) blur(im.convert("L"))
self.assertRaises(ValueError, lambda: blur(im.convert("I"))) self.assertRaises(ValueError, blur, im.convert("I"))
self.assertRaises(ValueError, lambda: blur(im.convert("F"))) self.assertRaises(ValueError, blur, im.convert("F"))
blur(im.convert("RGB")) blur(im.convert("RGB"))
blur(im.convert("RGBA")) blur(im.convert("RGBA"))
blur(im.convert("CMYK")) blur(im.convert("CMYK"))
self.assertRaises(ValueError, lambda: blur(im.convert("YCbCr"))) self.assertRaises(ValueError, blur, im.convert("YCbCr"))
def test_usm_accuracy(self): def test_usm_accuracy(self):

View File

@ -2,56 +2,54 @@ from helper import unittest, PillowTestCase
from PIL import ImagePalette, Image from PIL import ImagePalette, Image
ImagePalette = ImagePalette.ImagePalette
class TestImagePalette(PillowTestCase): class TestImagePalette(PillowTestCase):
def test_sanity(self): def test_sanity(self):
ImagePalette("RGB", list(range(256))*3) ImagePalette.ImagePalette("RGB", list(range(256))*3)
self.assertRaises( self.assertRaises(ValueError,
ValueError, lambda: ImagePalette("RGB", list(range(256))*2)) ImagePalette.ImagePalette, "RGB", list(range(256))*2)
def test_getcolor(self): def test_getcolor(self):
palette = ImagePalette() palette = ImagePalette.ImagePalette()
test_map = {} test_map = {}
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) self.assertEqual(len(test_map), 256)
self.assertRaises(ValueError, lambda: palette.getcolor((1, 2, 3))) self.assertRaises(ValueError, palette.getcolor, (1, 2, 3))
# Test unknown color specifier
self.assertRaises(ValueError, palette.getcolor, "unknown")
def test_file(self): def test_file(self):
palette = ImagePalette("RGB", list(range(256))*3) palette = ImagePalette.ImagePalette("RGB", list(range(256))*3)
f = self.tempfile("temp.lut") f = self.tempfile("temp.lut")
palette.save(f) palette.save(f)
from PIL.ImagePalette import load, raw p = ImagePalette.load(f)
p = load(f)
# load returns raw palette information # load returns raw palette information
self.assertEqual(len(p[0]), 768) self.assertEqual(len(p[0]), 768)
self.assertEqual(p[1], "RGB") self.assertEqual(p[1], "RGB")
p = raw(p[1], p[0]) p = ImagePalette.raw(p[1], p[0])
self.assertIsInstance(p, ImagePalette) self.assertIsInstance(p, ImagePalette.ImagePalette)
self.assertEqual(p.palette, palette.tobytes()) self.assertEqual(p.palette, palette.tobytes())
def test_make_linear_lut(self): def test_make_linear_lut(self):
# Arrange # Arrange
from PIL.ImagePalette import make_linear_lut
black = 0 black = 0
white = 255 white = 255
# Act # Act
lut = make_linear_lut(black, white) lut = ImagePalette.make_linear_lut(black, white)
# Assert # Assert
self.assertIsInstance(lut, list) self.assertIsInstance(lut, list)
@ -63,22 +61,19 @@ class TestImagePalette(PillowTestCase):
def test_make_linear_lut_not_yet_implemented(self): def test_make_linear_lut_not_yet_implemented(self):
# Update after FIXME # Update after FIXME
# Arrange # Arrange
from PIL.ImagePalette import make_linear_lut
black = 1 black = 1
white = 255 white = 255
# Act # Act
self.assertRaises( self.assertRaises(NotImplementedError,
NotImplementedError, ImagePalette.make_linear_lut, black, white)
lambda: make_linear_lut(black, white))
def test_make_gamma_lut(self): def test_make_gamma_lut(self):
# Arrange # Arrange
from PIL.ImagePalette import make_gamma_lut
exp = 5 exp = 5
# Act # Act
lut = make_gamma_lut(exp) lut = ImagePalette.make_gamma_lut(exp)
# Assert # Assert
self.assertIsInstance(lut, list) self.assertIsInstance(lut, list)
@ -92,19 +87,18 @@ class TestImagePalette(PillowTestCase):
def test_rawmode_valueerrors(self): def test_rawmode_valueerrors(self):
# Arrange # Arrange
from PIL.ImagePalette import raw palette = ImagePalette.raw("RGB", list(range(256))*3)
palette = raw("RGB", list(range(256))*3)
# Act / Assert # Act / Assert
self.assertRaises(ValueError, palette.tobytes) self.assertRaises(ValueError, palette.tobytes)
self.assertRaises(ValueError, lambda: palette.getcolor((1, 2, 3))) self.assertRaises(ValueError, palette.getcolor, (1, 2, 3))
f = self.tempfile("temp.lut") f = self.tempfile("temp.lut")
self.assertRaises(ValueError, lambda: palette.save(f)) self.assertRaises(ValueError, palette.save, f)
def test_getdata(self): def test_getdata(self):
# Arrange # Arrange
data_in = list(range(256))*3 data_in = list(range(256))*3
palette = ImagePalette("RGB", data_in) palette = ImagePalette.ImagePalette("RGB", data_in)
# Act # Act
mode, data_out = palette.getdata() mode, data_out = palette.getdata()
@ -114,9 +108,8 @@ class TestImagePalette(PillowTestCase):
def test_rawmode_getdata(self): def test_rawmode_getdata(self):
# Arrange # Arrange
from PIL.ImagePalette import raw
data_in = list(range(256))*3 data_in = list(range(256))*3
palette = raw("RGB", data_in) palette = ImagePalette.raw("RGB", data_in)
# Act # Act
rawmode, data_out = palette.getdata() rawmode, data_out = palette.getdata()
@ -138,6 +131,10 @@ class TestImagePalette(PillowTestCase):
self.assert_image_equal(img, reloaded) self.assert_image_equal(img, reloaded)
def test_invalid_palette(self):
self.assertRaises(IOError,
ImagePalette.load, "Tests/images/hopper.jpg")
if __name__ == '__main__': if __name__ == '__main__':
unittest.main() unittest.main()

View File

@ -22,7 +22,7 @@ class TestImageSequence(PillowTestCase):
self.assertEqual(index, 1) self.assertEqual(index, 1)
self.assertRaises(AttributeError, lambda: ImageSequence.Iterator(0)) self.assertRaises(AttributeError, ImageSequence.Iterator, 0)
def test_iterator(self): def test_iterator(self):
im = Image.open('Tests/images/multipage.tiff') im = Image.open('Tests/images/multipage.tiff')
@ -30,7 +30,7 @@ class TestImageSequence(PillowTestCase):
for index in range(0, im.n_frames): for index in range(0, im.n_frames):
self.assertEqual(i[index], next(i)) self.assertEqual(i[index], next(i))
self.assertRaises(IndexError, lambda: i[index+1]) self.assertRaises(IndexError, lambda: i[index+1])
self.assertRaises(StopIteration, lambda: next(i)) self.assertRaises(StopIteration, next, i)
def _test_multipage_tiff(self): def _test_multipage_tiff(self):
im = Image.open('Tests/images/multipage.tiff') im = Image.open('Tests/images/multipage.tiff')

View File

@ -1,4 +1,4 @@
from helper import unittest, PillowTestCase from helper import unittest, PillowTestCase, hopper
from PIL import Image from PIL import Image
from PIL import ImageShow from PIL import ImageShow
@ -10,12 +10,30 @@ class TestImageShow(PillowTestCase):
dir(Image) dir(Image)
dir(ImageShow) dir(ImageShow)
def test_register(self):
# Test registering a viewer that is not a class
ImageShow.register("not a class")
def test_show(self):
class TestViewer:
methodCalled = False
def show(self, image, title=None, **options):
self.methodCalled = True
return True
viewer = TestViewer()
ImageShow.register(viewer, -1)
im = hopper()
self.assertTrue(ImageShow.show(im))
self.assertTrue(viewer.methodCalled)
def test_viewer(self): def test_viewer(self):
viewer = ImageShow.Viewer() viewer = ImageShow.Viewer()
self.assertIsNone(viewer.get_format(None)) self.assertIsNone(viewer.get_format(None))
self.assertRaises(NotImplementedError, lambda: viewer.get_command(None)) self.assertRaises(NotImplementedError, viewer.get_command, None)
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -26,7 +26,7 @@ class TestImageStat(PillowTestCase):
self.assertRaises(AttributeError, lambda: st.spam) self.assertRaises(AttributeError, lambda: st.spam)
self.assertRaises(TypeError, lambda: ImageStat.Stat(1)) self.assertRaises(TypeError, ImageStat.Stat, 1)
def test_hopper(self): def test_hopper(self):

View File

@ -29,8 +29,8 @@ class TestLibImage(PillowTestCase):
im.im.setmode("RGB") im.im.setmode("RGB")
self.assertEqual(im.im.getpixel((0, 0)), (1, 2, 3)) self.assertEqual(im.im.getpixel((0, 0)), (1, 2, 3))
self.assertRaises(ValueError, lambda: im.im.setmode("L")) self.assertRaises(ValueError, im.im.setmode, "L")
self.assertRaises(ValueError, lambda: im.im.setmode("RGBABCDE")) self.assertRaises(ValueError, im.im.setmode, "RGBABCDE")
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -86,12 +86,12 @@ class TestNumpy(PillowTestCase):
self.assert_image(to_image(numpy.int32), "I", TEST_IMAGE_SIZE) self.assert_image(to_image(numpy.int32), "I", TEST_IMAGE_SIZE)
# Check 64-bit integer formats # Check 64-bit integer formats
self.assertRaises(TypeError, lambda: to_image(numpy.uint64)) self.assertRaises(TypeError, to_image, numpy.uint64)
self.assertRaises(TypeError, lambda: to_image(numpy.int64)) self.assertRaises(TypeError, to_image, numpy.int64)
# Check floating-point formats # Check floating-point formats
self.assert_image(to_image(numpy.float), "F", TEST_IMAGE_SIZE) self.assert_image(to_image(numpy.float), "F", TEST_IMAGE_SIZE)
self.assertRaises(TypeError, lambda: to_image(numpy.float16)) self.assertRaises(TypeError, to_image, numpy.float16)
self.assert_image(to_image(numpy.float32), "F", TEST_IMAGE_SIZE) self.assert_image(to_image(numpy.float32), "F", TEST_IMAGE_SIZE)
self.assert_image(to_image(numpy.float64), "F", TEST_IMAGE_SIZE) self.assert_image(to_image(numpy.float64), "F", TEST_IMAGE_SIZE)