Merge pull request #5 from hugovk/unittest1merge

More tests and merge with upstream
This commit is contained in:
Hugo 2014-06-08 13:49:00 +03:00
commit 0940f0b043
71 changed files with 1560 additions and 1298 deletions

View File

@ -29,14 +29,14 @@ script:
- python setup.py build_ext --inplace - python setup.py build_ext --inplace
# Don't cover PyPy: it fails intermittently and is x5.8 slower (#640) # Don't cover PyPy: it fails intermittently and is x5.8 slower (#640)
- if [ "$TRAVIS_PYTHON_VERSION" == "pypy" ]; then python selftest.py; fi - if [ "$TRAVIS_PYTHON_VERSION" == "pypy" ]; then time python selftest.py; fi
- if [ "$TRAVIS_PYTHON_VERSION" == "pypy" ]; then nosetests test/; fi - if [ "$TRAVIS_PYTHON_VERSION" == "pypy" ]; then time nosetests test/; fi
- if [ "$TRAVIS_PYTHON_VERSION" == "pypy" ]; then python Tests/run.py; fi - if [ "$TRAVIS_PYTHON_VERSION" == "pypy" ]; then time python Tests/run.py; fi
# Cover the others # Cover the others
- if [ "$TRAVIS_PYTHON_VERSION" != "pypy" ]; then coverage run --append --include=PIL/* selftest.py; fi - if [ "$TRAVIS_PYTHON_VERSION" != "pypy" ]; then time coverage run --append --include=PIL/* selftest.py; fi
- if [ "$TRAVIS_PYTHON_VERSION" != "pypy" ]; then coverage run --append --include=PIL/* -m nose test/; fi - if [ "$TRAVIS_PYTHON_VERSION" != "pypy" ]; then time coverage run --append --include=PIL/* -m nose test/; fi
- if [ "$TRAVIS_PYTHON_VERSION" != "pypy" ]; then python Tests/run.py --coverage; fi - if [ "$TRAVIS_PYTHON_VERSION" != "pypy" ]; then time python Tests/run.py --coverage; fi
after_success: after_success:

View File

@ -522,7 +522,7 @@ class Image:
""" """
Closes the file pointer, if possible. Closes the file pointer, if possible.
This operation will destroy the image core and release it's memory. This operation will destroy the image core and release its memory.
The image data will be unusable afterward. The image data will be unusable afterward.
This function is only required to close images that have not This function is only required to close images that have not

View File

@ -1,86 +0,0 @@
from tester import *
from PIL import Image
import os
base = os.path.join('Tests', 'images', 'bmp')
def get_files(d, ext='.bmp'):
return [os.path.join(base,d,f) for f
in os.listdir(os.path.join(base, d)) if ext in f]
def test_bad():
""" These shouldn't crash/dos, but they shouldn't return anything either """
for f in get_files('b'):
try:
im = Image.open(f)
im.load()
except Exception as msg:
pass
# print ("Bad Image %s: %s" %(f,msg))
def test_questionable():
""" These shouldn't crash/dos, but its not well defined that these are in spec """
for f in get_files('q'):
try:
im = Image.open(f)
im.load()
except Exception as msg:
pass
# print ("Bad Image %s: %s" %(f,msg))
def test_good():
""" These should all work. There's a set of target files in the
html directory that we can compare against. """
# Target files, if they're not just replacing the extension
file_map = { 'pal1wb.bmp': 'pal1.png',
'pal4rle.bmp': 'pal4.png',
'pal8-0.bmp': 'pal8.png',
'pal8rle.bmp': 'pal8.png',
'pal8topdown.bmp': 'pal8.png',
'pal8nonsquare.bmp': 'pal8nonsquare-v.png',
'pal8os2.bmp': 'pal8.png',
'pal8os2sp.bmp': 'pal8.png',
'pal8os2v2.bmp': 'pal8.png',
'pal8os2v2-16.bmp': 'pal8.png',
'pal8v4.bmp': 'pal8.png',
'pal8v5.bmp': 'pal8.png',
'rgb16-565pal.bmp': 'rgb16-565.png',
'rgb24pal.bmp': 'rgb24.png',
'rgb32.bmp': 'rgb24.png',
'rgb32bf.bmp': 'rgb24.png'
}
def get_compare(f):
(head, name) = os.path.split(f)
if name in file_map:
return os.path.join(base, 'html', file_map[name])
(name,ext) = os.path.splitext(name)
return os.path.join(base, 'html', "%s.png"%name)
for f in get_files('g'):
try:
im = Image.open(f)
im.load()
compare = Image.open(get_compare(f))
compare.load()
if im.mode == 'P':
# assert image similar doesn't really work
# with paletized image, since the palette might
# be differently ordered for an equivalent image.
im = im.convert('RGBA')
compare = im.convert('RGBA')
assert_image_similar(im, compare,5)
except Exception as msg:
# there are three here that are unsupported:
unsupported = (os.path.join(base, 'g', 'rgb32bf.bmp'),
os.path.join(base, 'g', 'pal8rle.bmp'),
os.path.join(base, 'g', 'pal4rle.bmp'))
if f not in unsupported:
assert_true(False, "Unsupported Image %s: %s" %(f,msg))

View File

@ -1,66 +0,0 @@
from tester import *
from PIL import Image
# sample icon file
file = "Images/pillow.icns"
data = open(file, "rb").read()
enable_jpeg2k = hasattr(Image.core, 'jp2klib_version')
def test_sanity():
# Loading this icon by default should result in the largest size
# (512x512@2x) being loaded
im = Image.open(file)
im.load()
assert_equal(im.mode, "RGBA")
assert_equal(im.size, (1024, 1024))
assert_equal(im.format, "ICNS")
def test_sizes():
# Check that we can load all of the sizes, and that the final pixel
# dimensions are as expected
im = Image.open(file)
for w,h,r in im.info['sizes']:
wr = w * r
hr = h * r
im2 = Image.open(file)
im2.size = (w, h, r)
im2.load()
assert_equal(im2.mode, 'RGBA')
assert_equal(im2.size, (wr, hr))
def test_older_icon():
# This icon was made with Icon Composer rather than iconutil; it still
# uses PNG rather than JP2, however (since it was made on 10.9).
im = Image.open('Tests/images/pillow2.icns')
for w,h,r in im.info['sizes']:
wr = w * r
hr = h * r
im2 = Image.open('Tests/images/pillow2.icns')
im2.size = (w, h, r)
im2.load()
assert_equal(im2.mode, 'RGBA')
assert_equal(im2.size, (wr, hr))
def test_jp2_icon():
# This icon was made by using Uli Kusterer's oldiconutil to replace
# the PNG images with JPEG 2000 ones. The advantage of doing this is
# that OS X 10.5 supports JPEG 2000 but not PNG; some commercial
# software therefore does just this.
# (oldiconutil is here: https://github.com/uliwitness/oldiconutil)
if not enable_jpeg2k:
return
im = Image.open('Tests/images/pillow3.icns')
for w,h,r in im.info['sizes']:
wr = w * r
hr = h * r
im2 = Image.open('Tests/images/pillow3.icns')
im2.size = (w, h, r)
im2.load()
assert_equal(im2.mode, 'RGBA')
assert_equal(im2.size, (wr, hr))

View File

@ -1,14 +0,0 @@
from tester import *
from PIL import Image
# sample ppm stream
file = "Images/lena.ico"
data = open(file, "rb").read()
def test_sanity():
im = Image.open(file)
im.load()
assert_equal(im.mode, "RGBA")
assert_equal(im.size, (16, 16))
assert_equal(im.format, "ICO")

View File

@ -1,14 +0,0 @@
from tester import *
from PIL import Image
# sample ppm stream
file = "Images/lena.psd"
data = open(file, "rb").read()
def test_sanity():
im = Image.open(file)
im.load()
assert_equal(im.mode, "RGB")
assert_equal(im.size, (128, 128))
assert_equal(im.format, "PSD")

View File

@ -1,14 +0,0 @@
from tester import *
from PIL import Image
# sample ppm stream
file = "Images/lena.xpm"
data = open(file, "rb").read()
def test_sanity():
im = Image.open(file)
im.load()
assert_equal(im.mode, "P")
assert_equal(im.size, (128, 128))
assert_equal(im.format, "XPM")

View File

@ -1,13 +0,0 @@
from tester import *
from PIL import Image, FontFile, BdfFontFile
filename = "Images/courB08.bdf"
def test_sanity():
file = open(filename, "rb")
font = BdfFontFile.BdfFontFile(file)
assert_true(isinstance(font, FontFile.FontFile))
assert_equal(len([_f for _f in font.glyph if _f]), 190)

View File

@ -1,41 +0,0 @@
from tester import *
from PIL import Image
def test_white():
i = Image.open('Tests/images/lab.tif')
bits = i.load()
assert_equal(i.mode, 'LAB')
assert_equal(i.getbands(), ('L','A', 'B'))
k = i.getpixel((0,0))
assert_equal(k, (255,128,128))
L = i.getdata(0)
a = i.getdata(1)
b = i.getdata(2)
assert_equal(list(L), [255]*100)
assert_equal(list(a), [128]*100)
assert_equal(list(b), [128]*100)
def test_green():
# l= 50 (/100), a = -100 (-128 .. 128) b=0 in PS
# == RGB: 0, 152, 117
i = Image.open('Tests/images/lab-green.tif')
k = i.getpixel((0,0))
assert_equal(k, (128,28,128))
def test_red():
# l= 50 (/100), a = 100 (-128 .. 128) b=0 in PS
# == RGB: 255, 0, 124
i = Image.open('Tests/images/lab-red.tif')
k = i.getpixel((0,0))
assert_equal(k, (128,228,128))

View File

@ -1,15 +0,0 @@
from tester import *
from PIL import Image
def test_getbands():
assert_equal(Image.new("1", (1, 1)).getbands(), ("1",))
assert_equal(Image.new("L", (1, 1)).getbands(), ("L",))
assert_equal(Image.new("I", (1, 1)).getbands(), ("I",))
assert_equal(Image.new("F", (1, 1)).getbands(), ("F",))
assert_equal(Image.new("P", (1, 1)).getbands(), ("P",))
assert_equal(Image.new("RGB", (1, 1)).getbands(), ("R", "G", "B"))
assert_equal(Image.new("RGBA", (1, 1)).getbands(), ("R", "G", "B", "A"))
assert_equal(Image.new("CMYK", (1, 1)).getbands(), ("C", "M", "Y", "K"))
assert_equal(Image.new("YCbCr", (1, 1)).getbands(), ("Y", "Cb", "Cr"))

View File

@ -1,64 +0,0 @@
from tester import *
from PIL import Image
def test_getcolors():
def getcolors(mode, limit=None):
im = lena(mode)
if limit:
colors = im.getcolors(limit)
else:
colors = im.getcolors()
if colors:
return len(colors)
return None
assert_equal(getcolors("1"), 2)
assert_equal(getcolors("L"), 193)
assert_equal(getcolors("I"), 193)
assert_equal(getcolors("F"), 193)
assert_equal(getcolors("P"), 54) # fixed palette
assert_equal(getcolors("RGB"), None)
assert_equal(getcolors("RGBA"), None)
assert_equal(getcolors("CMYK"), None)
assert_equal(getcolors("YCbCr"), None)
assert_equal(getcolors("L", 128), None)
assert_equal(getcolors("L", 1024), 193)
assert_equal(getcolors("RGB", 8192), None)
assert_equal(getcolors("RGB", 16384), 14836)
assert_equal(getcolors("RGB", 100000), 14836)
assert_equal(getcolors("RGBA", 16384), 14836)
assert_equal(getcolors("CMYK", 16384), 14836)
assert_equal(getcolors("YCbCr", 16384), 11995)
# --------------------------------------------------------------------
def test_pack():
# Pack problems for small tables (@PIL209)
im = lena().quantize(3).convert("RGB")
expected = [(3236, (227, 183, 147)), (6297, (143, 84, 81)), (6851, (208, 143, 112))]
A = im.getcolors(maxcolors=2)
assert_equal(A, None)
A = im.getcolors(maxcolors=3)
A.sort()
assert_equal(A, expected)
A = im.getcolors(maxcolors=4)
A.sort()
assert_equal(A, expected)
A = im.getcolors(maxcolors=8)
A.sort()
assert_equal(A, expected)
A = im.getcolors(maxcolors=16)
A.sort()
assert_equal(A, expected)

View File

@ -1,17 +0,0 @@
from tester import *
from PIL import Image
def test_extrema():
def extrema(mode):
return lena(mode).getextrema()
assert_equal(extrema("1"), (0, 255))
assert_equal(extrema("L"), (40, 235))
assert_equal(extrema("I"), (40, 235))
assert_equal(extrema("F"), (40.0, 235.0))
assert_equal(extrema("P"), (11, 218)) # fixed palette
assert_equal(extrema("RGB"), ((61, 255), (26, 234), (44, 223)))
assert_equal(extrema("RGBA"), ((61, 255), (26, 234), (44, 223), (255, 255)))
assert_equal(extrema("CMYK"), ((0, 194), (21, 229), (32, 211), (0, 0)))

View File

@ -1,19 +0,0 @@
from tester import *
from PIL import Image
def test_palette():
def palette(mode):
p = lena(mode).getpalette()
if p:
return p[:10]
return None
assert_equal(palette("1"), None)
assert_equal(palette("L"), None)
assert_equal(palette("I"), None)
assert_equal(palette("F"), None)
assert_equal(palette("P"), [0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
assert_equal(palette("RGB"), None)
assert_equal(palette("RGBA"), None)
assert_equal(palette("CMYK"), None)
assert_equal(palette("YCbCr"), None)

View File

@ -1,27 +0,0 @@
from tester import *
from PIL import Image
def test_sanity():
im = lena()
assert_no_exception(lambda: im.mode)
def test_properties():
def check(mode, *result):
signature = (
Image.getmodebase(mode), Image.getmodetype(mode),
Image.getmodebands(mode), Image.getmodebandnames(mode),
)
assert_equal(signature, result)
check("1", "L", "L", 1, ("1",))
check("L", "L", "L", 1, ("L",))
check("P", "RGB", "L", 1, ("P",))
check("I", "L", "I", 1, ("I",))
check("F", "L", "F", 1, ("F",))
check("RGB", "RGB", "L", 3, ("R", "G", "B"))
check("RGBA", "RGB", "L", 4, ("R", "G", "B", "A"))
check("RGBX", "RGB", "L", 4, ("R", "G", "B", "X"))
check("RGBX", "RGB", "L", 4, ("R", "G", "B", "X"))
check("CMYK", "RGB", "L", 4, ("C", "M", "Y", "K"))
check("YCbCr", "RGB", "L", 3, ("Y", "Cb", "Cr"))

View File

@ -1,16 +0,0 @@
from tester import *
from PIL import Image
def test_offset():
im1 = lena()
im2 = assert_warning(DeprecationWarning, lambda: im1.offset(10))
assert_equal(im1.getpixel((0, 0)), im2.getpixel((10, 10)))
im2 = assert_warning(DeprecationWarning, lambda: im1.offset(10, 20))
assert_equal(im1.getpixel((0, 0)), im2.getpixel((10, 20)))
im2 = assert_warning(DeprecationWarning, lambda: im1.offset(20, 20))
assert_equal(im1.getpixel((0, 0)), im2.getpixel((20, 20)))

View File

@ -1,5 +0,0 @@
from tester import *
from PIL import Image
success()

View File

@ -1,43 +0,0 @@
from tester import *
from PIL import Image
def test_interface():
im = Image.new("RGBA", (1, 1), (1, 2, 3, 0))
assert_equal(im.getpixel((0, 0)), (1, 2, 3, 0))
im = Image.new("RGBA", (1, 1), (1, 2, 3))
assert_equal(im.getpixel((0, 0)), (1, 2, 3, 255))
im.putalpha(Image.new("L", im.size, 4))
assert_equal(im.getpixel((0, 0)), (1, 2, 3, 4))
im.putalpha(5)
assert_equal(im.getpixel((0, 0)), (1, 2, 3, 5))
def test_promote():
im = Image.new("L", (1, 1), 1)
assert_equal(im.getpixel((0, 0)), 1)
im.putalpha(2)
assert_equal(im.mode, 'LA')
assert_equal(im.getpixel((0, 0)), (1, 2))
im = Image.new("RGB", (1, 1), (1, 2, 3))
assert_equal(im.getpixel((0, 0)), (1, 2, 3))
im.putalpha(4)
assert_equal(im.mode, 'RGBA')
assert_equal(im.getpixel((0, 0)), (1, 2, 3, 4))
def test_readonly():
im = Image.new("RGB", (1, 1), (1, 2, 3))
im.readonly = 1
im.putalpha(4)
assert_false(im.readonly)
assert_equal(im.mode, 'RGBA')
assert_equal(im.getpixel((0, 0)), (1, 2, 3, 4))

View File

@ -1,27 +0,0 @@
from tester import *
from PIL import Image
def test_sanity():
im = lena()
im = im.quantize()
assert_image(im, "P", im.size)
im = lena()
im = im.quantize(palette=lena("P"))
assert_image(im, "P", im.size)
def test_octree_quantize():
im = lena()
im = im.quantize(100, Image.FASTOCTREE)
assert_image(im, "P", im.size)
assert len(im.getcolors()) == 100
def test_rgba_quantize():
im = lena('RGBA')
assert_no_exception(lambda: im.quantize())
assert_exception(Exception, lambda: im.quantize(method=0))

View File

@ -1,12 +0,0 @@
from tester import *
from PIL import Image
def test_resize():
def resize(mode, size):
out = lena(mode).resize(size)
assert_equal(out.mode, mode)
assert_equal(out.size, size)
for mode in "1", "P", "L", "RGB", "I", "F":
yield_test(resize, mode, (100, 100))
yield_test(resize, mode, (200, 200))

View File

@ -1,15 +0,0 @@
from tester import *
from PIL import Image
def test_rotate():
def rotate(mode):
im = lena(mode)
out = im.rotate(45)
assert_equal(out.mode, mode)
assert_equal(out.size, im.size) # default rotate clips output
out = im.rotate(45, expand=1)
assert_equal(out.mode, mode)
assert_true(out.size != im.size)
for mode in "1", "P", "L", "RGB", "I", "F":
yield_test(rotate, mode)

View File

@ -1,5 +0,0 @@
from tester import *
from PIL import Image
success()

View File

@ -1,5 +0,0 @@
from tester import *
from PIL import Image
success()

View File

@ -1,5 +0,0 @@
from tester import *
from PIL import Image
success()

View File

@ -1,5 +0,0 @@
from tester import *
from PIL import Image
success()

View File

@ -1,36 +0,0 @@
from tester import *
from PIL import Image
def test_sanity():
im = lena()
im.thumbnail((100, 100))
assert_image(im, im.mode, (100, 100))
def test_aspect():
im = lena()
im.thumbnail((100, 100))
assert_image(im, im.mode, (100, 100))
im = lena().resize((128, 256))
im.thumbnail((100, 100))
assert_image(im, im.mode, (50, 100))
im = lena().resize((128, 256))
im.thumbnail((50, 100))
assert_image(im, im.mode, (50, 100))
im = lena().resize((256, 128))
im.thumbnail((100, 100))
assert_image(im, im.mode, (100, 50))
im = lena().resize((256, 128))
im.thumbnail((100, 50))
assert_image(im, im.mode, (100, 50))
im = lena().resize((128, 128))
im.thumbnail((100, 100))
assert_image(im, im.mode, (100, 100))

View File

@ -1,116 +0,0 @@
from tester import *
from PIL import Image
def test_extent():
im = lena('RGB')
(w,h) = im.size
transformed = im.transform(im.size, Image.EXTENT,
(0,0,
w//2,h//2), # ul -> lr
Image.BILINEAR)
scaled = im.resize((w*2, h*2), Image.BILINEAR).crop((0,0,w,h))
assert_image_similar(transformed, scaled, 10) # undone -- precision?
def test_quad():
# one simple quad transform, equivalent to scale & crop upper left quad
im = lena('RGB')
(w,h) = im.size
transformed = im.transform(im.size, Image.QUAD,
(0,0,0,h//2,
w//2,h//2,w//2,0), # ul -> ccw around quad
Image.BILINEAR)
scaled = im.resize((w*2, h*2), Image.BILINEAR).crop((0,0,w,h))
assert_image_equal(transformed, scaled)
def test_mesh():
# this should be a checkerboard of halfsized lenas in ul, lr
im = lena('RGBA')
(w,h) = im.size
transformed = im.transform(im.size, Image.MESH,
[((0,0,w//2,h//2), # box
(0,0,0,h,
w,h,w,0)), # ul -> ccw around quad
((w//2,h//2,w,h), # box
(0,0,0,h,
w,h,w,0))], # ul -> ccw around quad
Image.BILINEAR)
#transformed.save('transformed.png')
scaled = im.resize((w//2, h//2), Image.BILINEAR)
checker = Image.new('RGBA', im.size)
checker.paste(scaled, (0,0))
checker.paste(scaled, (w//2,h//2))
assert_image_equal(transformed, checker)
# now, check to see that the extra area is (0,0,0,0)
blank = Image.new('RGBA', (w//2,h//2), (0,0,0,0))
assert_image_equal(blank, transformed.crop((w//2,0,w,h//2)))
assert_image_equal(blank, transformed.crop((0,h//2,w//2,h)))
def _test_alpha_premult(op):
# create image with half white, half black, with the black half transparent.
# do op,
# there should be no darkness in the white section.
im = Image.new('RGBA', (10,10), (0,0,0,0));
im2 = Image.new('RGBA', (5,10), (255,255,255,255));
im.paste(im2, (0,0))
im = op(im, (40,10))
im_background = Image.new('RGB', (40,10), (255,255,255))
im_background.paste(im, (0,0), im)
hist = im_background.histogram()
assert_equal(40*10, hist[-1])
def test_alpha_premult_resize():
def op (im, sz):
return im.resize(sz, Image.LINEAR)
_test_alpha_premult(op)
def test_alpha_premult_transform():
def op(im, sz):
(w,h) = im.size
return im.transform(sz, Image.EXTENT,
(0,0,
w,h),
Image.BILINEAR)
_test_alpha_premult(op)
def test_blank_fill():
# attempting to hit
# https://github.com/python-pillow/Pillow/issues/254 reported
#
# issue is that transforms with transparent overflow area
# contained junk from previous images, especially on systems with
# constrained memory. So, attempt to fill up memory with a
# pattern, free it, and then run the mesh test again. Using a 1Mp
# image with 4 bands, for 4 megs of data allocated, x 64. OMM (64
# bit 12.04 VM with 512 megs available, this fails with Pillow <
# a0eaf06cc5f62a6fb6de556989ac1014ff3348ea
#
# Running by default, but I'd totally understand not doing it in
# the future
foo = [Image.new('RGBA',(1024,1024), (a,a,a,a))
for a in range(1,65)]
# Yeah. Watch some JIT optimize this out.
foo = None
test_mesh()

View File

@ -1,5 +0,0 @@
from tester import *
from PIL import Image
success()

View File

@ -1,203 +0,0 @@
from tester import *
from PIL import Image
try:
from PIL import ImageCms
ImageCms.core.profile_open
except ImportError:
skip()
SRGB = "Tests/icc/sRGB.icm"
def test_sanity():
# basic smoke test.
# this mostly follows the cms_test outline.
v = ImageCms.versions() # should return four strings
assert_equal(v[0], '1.0.0 pil')
assert_equal(list(map(type, v)), [str, str, str, str])
# internal version number
assert_match(ImageCms.core.littlecms_version, "\d+\.\d+$")
i = ImageCms.profileToProfile(lena(), SRGB, SRGB)
assert_image(i, "RGB", (128, 128))
i = lena()
ImageCms.profileToProfile(i, SRGB, SRGB, inPlace=True)
assert_image(i, "RGB", (128, 128))
t = ImageCms.buildTransform(SRGB, SRGB, "RGB", "RGB")
i = ImageCms.applyTransform(lena(), t)
assert_image(i, "RGB", (128, 128))
i = lena()
t = ImageCms.buildTransform(SRGB, SRGB, "RGB", "RGB")
ImageCms.applyTransform(lena(), t, inPlace=True)
assert_image(i, "RGB", (128, 128))
p = ImageCms.createProfile("sRGB")
o = ImageCms.getOpenProfile(SRGB)
t = ImageCms.buildTransformFromOpenProfiles(p, o, "RGB", "RGB")
i = ImageCms.applyTransform(lena(), t)
assert_image(i, "RGB", (128, 128))
t = ImageCms.buildProofTransform(SRGB, SRGB, SRGB, "RGB", "RGB")
assert_equal(t.inputMode, "RGB")
assert_equal(t.outputMode, "RGB")
i = ImageCms.applyTransform(lena(), t)
assert_image(i, "RGB", (128, 128))
# test PointTransform convenience API
lena().point(t)
def test_name():
# get profile information for file
assert_equal(ImageCms.getProfileName(SRGB).strip(),
'IEC 61966-2.1 Default RGB colour space - sRGB')
def test_info():
assert_equal(ImageCms.getProfileInfo(SRGB).splitlines(),
['sRGB IEC61966-2.1', '',
'Copyright (c) 1998 Hewlett-Packard Company', ''])
def test_copyright():
assert_equal(ImageCms.getProfileCopyright(SRGB).strip(),
'Copyright (c) 1998 Hewlett-Packard Company')
def test_manufacturer():
assert_equal(ImageCms.getProfileManufacturer(SRGB).strip(),
'IEC http://www.iec.ch')
def test_model():
assert_equal(ImageCms.getProfileModel(SRGB).strip(),
'IEC 61966-2.1 Default RGB colour space - sRGB')
def test_description():
assert_equal(ImageCms.getProfileDescription(SRGB).strip(),
'sRGB IEC61966-2.1')
def test_intent():
assert_equal(ImageCms.getDefaultIntent(SRGB), 0)
assert_equal(ImageCms.isIntentSupported(
SRGB, ImageCms.INTENT_ABSOLUTE_COLORIMETRIC,
ImageCms.DIRECTION_INPUT), 1)
def test_profile_object():
# same, using profile object
p = ImageCms.createProfile("sRGB")
# assert_equal(ImageCms.getProfileName(p).strip(),
# 'sRGB built-in - (lcms internal)')
# assert_equal(ImageCms.getProfileInfo(p).splitlines(),
# ['sRGB built-in', '', 'WhitePoint : D65 (daylight)', '', ''])
assert_equal(ImageCms.getDefaultIntent(p), 0)
assert_equal(ImageCms.isIntentSupported(
p, ImageCms.INTENT_ABSOLUTE_COLORIMETRIC,
ImageCms.DIRECTION_INPUT), 1)
def test_extensions():
# extensions
i = Image.open("Tests/images/rgb.jpg")
p = ImageCms.getOpenProfile(BytesIO(i.info["icc_profile"]))
assert_equal(ImageCms.getProfileName(p).strip(),
'IEC 61966-2.1 Default RGB colour space - sRGB')
def test_exceptions():
# the procedural pyCMS API uses PyCMSError for all sorts of errors
assert_exception(
ImageCms.PyCMSError,
lambda: ImageCms.profileToProfile(lena(), "foo", "bar"))
assert_exception(
ImageCms.PyCMSError,
lambda: ImageCms.buildTransform("foo", "bar", "RGB", "RGB"))
assert_exception(
ImageCms.PyCMSError,
lambda: ImageCms.getProfileName(None))
assert_exception(
ImageCms.PyCMSError,
lambda: ImageCms.isIntentSupported(SRGB, None, None))
def test_display_profile():
# try fetching the profile for the current display device
assert_no_exception(lambda: ImageCms.get_display_profile())
def test_lab_color_profile():
ImageCms.createProfile("LAB", 5000)
ImageCms.createProfile("LAB", 6500)
def test_simple_lab():
i = Image.new('RGB', (10, 10), (128, 128, 128))
pLab = ImageCms.createProfile("LAB")
t = ImageCms.buildTransform(SRGB, pLab, "RGB", "LAB")
i_lab = ImageCms.applyTransform(i, t)
assert_equal(i_lab.mode, 'LAB')
k = i_lab.getpixel((0, 0))
assert_equal(k, (137, 128, 128)) # not a linear luminance map. so L != 128
L = i_lab.getdata(0)
a = i_lab.getdata(1)
b = i_lab.getdata(2)
assert_equal(list(L), [137] * 100)
assert_equal(list(a), [128] * 100)
assert_equal(list(b), [128] * 100)
def test_lab_color():
pLab = ImageCms.createProfile("LAB")
t = ImageCms.buildTransform(SRGB, pLab, "RGB", "LAB")
# Need to add a type mapping for some PIL type to TYPE_Lab_8 in
# findLCMSType, and have that mapping work back to a PIL mode (likely RGB).
i = ImageCms.applyTransform(lena(), t)
assert_image(i, "LAB", (128, 128))
# i.save('temp.lab.tif') # visually verified vs PS.
target = Image.open('Tests/images/lena.Lab.tif')
assert_image_similar(i, target, 30)
def test_lab_srgb():
pLab = ImageCms.createProfile("LAB")
t = ImageCms.buildTransform(pLab, SRGB, "LAB", "RGB")
img = Image.open('Tests/images/lena.Lab.tif')
img_srgb = ImageCms.applyTransform(img, t)
# img_srgb.save('temp.srgb.tif') # visually verified vs ps.
assert_image_similar(lena(), img_srgb, 30)
def test_lab_roundtrip():
# check to see if we're at least internally consistent.
pLab = ImageCms.createProfile("LAB")
t = ImageCms.buildTransform(SRGB, pLab, "RGB", "LAB")
t2 = ImageCms.buildTransform(pLab, SRGB, "LAB", "RGB")
i = ImageCms.applyTransform(lena(), t)
out = ImageCms.applyTransform(i, t2)
assert_image_similar(lena(), out, 2)

View File

@ -1,54 +0,0 @@
from tester import *
from PIL import Image
from PIL import ImageColor
# --------------------------------------------------------------------
# sanity
assert_equal((255, 0, 0), ImageColor.getrgb("#f00"))
assert_equal((255, 0, 0), ImageColor.getrgb("#ff0000"))
assert_equal((255, 0, 0), ImageColor.getrgb("rgb(255,0,0)"))
assert_equal((255, 0, 0), ImageColor.getrgb("rgb(255, 0, 0)"))
assert_equal((255, 0, 0), ImageColor.getrgb("rgb(100%,0%,0%)"))
assert_equal((255, 0, 0), ImageColor.getrgb("hsl(0, 100%, 50%)"))
assert_equal((255, 0, 0, 0), ImageColor.getrgb("rgba(255,0,0,0)"))
assert_equal((255, 0, 0, 0), ImageColor.getrgb("rgba(255, 0, 0, 0)"))
assert_equal((255, 0, 0), ImageColor.getrgb("red"))
# --------------------------------------------------------------------
# look for rounding errors (based on code by Tim Hatch)
for color in list(ImageColor.colormap.keys()):
expected = Image.new("RGB", (1, 1), color).convert("L").getpixel((0, 0))
actual = Image.new("L", (1, 1), color).getpixel((0, 0))
assert_equal(expected, actual)
assert_equal((0, 0, 0), ImageColor.getcolor("black", "RGB"))
assert_equal((255, 255, 255), ImageColor.getcolor("white", "RGB"))
assert_equal((0, 255, 115), ImageColor.getcolor("rgba(0, 255, 115, 33)", "RGB"))
Image.new("RGB", (1, 1), "white")
assert_equal((0, 0, 0, 255), ImageColor.getcolor("black", "RGBA"))
assert_equal((255, 255, 255, 255), ImageColor.getcolor("white", "RGBA"))
assert_equal((0, 255, 115, 33), ImageColor.getcolor("rgba(0, 255, 115, 33)", "RGBA"))
Image.new("RGBA", (1, 1), "white")
assert_equal(0, ImageColor.getcolor("black", "L"))
assert_equal(255, ImageColor.getcolor("white", "L"))
assert_equal(162, ImageColor.getcolor("rgba(0, 255, 115, 33)", "L"))
Image.new("L", (1, 1), "white")
assert_equal(0, ImageColor.getcolor("black", "1"))
assert_equal(255, ImageColor.getcolor("white", "1"))
# The following test is wrong, but is current behavior
# The correct result should be 255 due to the mode 1
assert_equal(162, ImageColor.getcolor("rgba(0, 255, 115, 33)", "1"))
# Correct behavior
# assert_equal(255, ImageColor.getcolor("rgba(0, 255, 115, 33)", "1"))
Image.new("1", (1, 1), "white")
assert_equal((0, 255), ImageColor.getcolor("black", "LA"))
assert_equal((255, 255), ImageColor.getcolor("white", "LA"))
assert_equal((162, 33), ImageColor.getcolor("rgba(0, 255, 115, 33)", "LA"))
Image.new("LA", (1, 1), "white")

View File

@ -1,24 +0,0 @@
from tester import *
from PIL import Image
from PIL import ImageFileIO
def test_fileio():
class DumbFile:
def __init__(self, data):
self.data = data
def read(self, bytes=None):
assert_equal(bytes, None)
return self.data
def close(self):
pass
im1 = lena()
io = ImageFileIO.ImageFileIO(DumbFile(tostring(im1, "PPM")))
im2 = Image.open(io)
assert_image_equal(im1, im2)

View File

@ -1,23 +0,0 @@
from tester import *
from PIL import Image
from PIL import ImageMode
ImageMode.getmode("1")
ImageMode.getmode("L")
ImageMode.getmode("P")
ImageMode.getmode("RGB")
ImageMode.getmode("I")
ImageMode.getmode("F")
m = ImageMode.getmode("1")
assert_equal(m.mode, "1")
assert_equal(m.bands, ("1",))
assert_equal(m.basemode, "L")
assert_equal(m.basetype, "L")
m = ImageMode.getmode("RGB")
assert_equal(m.mode, "RGB")
assert_equal(m.bands, ("R", "G", "B"))
assert_equal(m.basemode, "RGB")
assert_equal(m.basetype, "L")

View File

@ -1,81 +0,0 @@
from tester import *
from PIL import Image
from PIL import ImageOps
class Deformer:
def getmesh(self, im):
x, y = im.size
return [((0, 0, x, y), (0, 0, x, 0, x, y, y, 0))]
deformer = Deformer()
def test_sanity():
ImageOps.autocontrast(lena("L"))
ImageOps.autocontrast(lena("RGB"))
ImageOps.autocontrast(lena("L"), cutoff=10)
ImageOps.autocontrast(lena("L"), ignore=[0, 255])
ImageOps.colorize(lena("L"), (0, 0, 0), (255, 255, 255))
ImageOps.colorize(lena("L"), "black", "white")
ImageOps.crop(lena("L"), 1)
ImageOps.crop(lena("RGB"), 1)
ImageOps.deform(lena("L"), deformer)
ImageOps.deform(lena("RGB"), deformer)
ImageOps.equalize(lena("L"))
ImageOps.equalize(lena("RGB"))
ImageOps.expand(lena("L"), 1)
ImageOps.expand(lena("RGB"), 1)
ImageOps.expand(lena("L"), 2, "blue")
ImageOps.expand(lena("RGB"), 2, "blue")
ImageOps.fit(lena("L"), (128, 128))
ImageOps.fit(lena("RGB"), (128, 128))
ImageOps.flip(lena("L"))
ImageOps.flip(lena("RGB"))
ImageOps.grayscale(lena("L"))
ImageOps.grayscale(lena("RGB"))
ImageOps.invert(lena("L"))
ImageOps.invert(lena("RGB"))
ImageOps.mirror(lena("L"))
ImageOps.mirror(lena("RGB"))
ImageOps.posterize(lena("L"), 4)
ImageOps.posterize(lena("RGB"), 4)
ImageOps.solarize(lena("L"))
ImageOps.solarize(lena("RGB"))
success()
def test_1pxfit():
# Division by zero in equalize if image is 1 pixel high
newimg = ImageOps.fit(lena("RGB").resize((1,1)), (35,35))
assert_equal(newimg.size,(35,35))
newimg = ImageOps.fit(lena("RGB").resize((1,100)), (35,35))
assert_equal(newimg.size,(35,35))
newimg = ImageOps.fit(lena("RGB").resize((100,1)), (35,35))
assert_equal(newimg.size,(35,35))
def test_pil163():
# Division by zero in equalize if < 255 pixels in image (@PIL163)
i = lena("RGB").resize((15, 16))
ImageOps.equalize(i.convert("L"))
ImageOps.equalize(i.convert("P"))
ImageOps.equalize(i.convert("RGB"))
success()

View File

@ -1,6 +0,0 @@
from tester import *
from PIL import Image
from PIL import ImageShow
success()

View File

@ -1,9 +0,0 @@
from tester import *
from PIL import Image
try:
from PIL import ImageTk
except (OSError, ImportError) as v:
skip(v)
success()

View File

@ -1,18 +0,0 @@
from tester import *
from PIL import Image
from PIL import ImageTransform
im = Image.new("L", (100, 100))
seq = tuple(range(10))
def test_sanity():
transform = ImageTransform.AffineTransform(seq[:6])
assert_no_exception(lambda: im.transform((100, 100), transform))
transform = ImageTransform.ExtentTransform(seq[:4])
assert_no_exception(lambda: im.transform((100, 100), transform))
transform = ImageTransform.QuadTransform(seq[:8])
assert_no_exception(lambda: im.transform((100, 100), transform))
transform = ImageTransform.MeshTransform([(seq[:4], seq[:8])])
assert_no_exception(lambda: im.transform((100, 100), transform))

View File

@ -1,6 +0,0 @@
from tester import *
from PIL import Image
from PIL import ImageWin
success()

View File

@ -1,138 +0,0 @@
from tester import *
from PIL import Image
def pack():
pass # not yet
def test_pack():
def pack(mode, rawmode):
if len(mode) == 1:
im = Image.new(mode, (1, 1), 1)
else:
im = Image.new(mode, (1, 1), (1, 2, 3, 4)[:len(mode)])
if py3:
return list(im.tobytes("raw", rawmode))
else:
return [ord(c) for c in im.tobytes("raw", rawmode)]
order = 1 if Image._ENDIAN == '<' else -1
assert_equal(pack("1", "1"), [128])
assert_equal(pack("1", "1;I"), [0])
assert_equal(pack("1", "1;R"), [1])
assert_equal(pack("1", "1;IR"), [0])
assert_equal(pack("L", "L"), [1])
assert_equal(pack("I", "I"), [1, 0, 0, 0][::order])
assert_equal(pack("F", "F"), [0, 0, 128, 63][::order])
assert_equal(pack("LA", "LA"), [1, 2])
assert_equal(pack("RGB", "RGB"), [1, 2, 3])
assert_equal(pack("RGB", "RGB;L"), [1, 2, 3])
assert_equal(pack("RGB", "BGR"), [3, 2, 1])
assert_equal(pack("RGB", "RGBX"), [1, 2, 3, 255]) # 255?
assert_equal(pack("RGB", "BGRX"), [3, 2, 1, 0])
assert_equal(pack("RGB", "XRGB"), [0, 1, 2, 3])
assert_equal(pack("RGB", "XBGR"), [0, 3, 2, 1])
assert_equal(pack("RGBX", "RGBX"), [1, 2, 3, 4]) # 4->255?
assert_equal(pack("RGBA", "RGBA"), [1, 2, 3, 4])
assert_equal(pack("CMYK", "CMYK"), [1, 2, 3, 4])
assert_equal(pack("YCbCr", "YCbCr"), [1, 2, 3])
def test_unpack():
def unpack(mode, rawmode, bytes_):
im = None
if py3:
data = bytes(range(1,bytes_+1))
else:
data = ''.join(chr(i) for i in range(1,bytes_+1))
im = Image.frombytes(mode, (1, 1), data, "raw", rawmode, 0, 1)
return im.getpixel((0, 0))
def unpack_1(mode, rawmode, value):
assert mode == "1"
im = None
if py3:
im = Image.frombytes(mode, (8, 1), bytes([value]), "raw", rawmode, 0, 1)
else:
im = Image.frombytes(mode, (8, 1), chr(value), "raw", rawmode, 0, 1)
return tuple(im.getdata())
X = 255
assert_equal(unpack_1("1", "1", 1), (0,0,0,0,0,0,0,X))
assert_equal(unpack_1("1", "1;I", 1), (X,X,X,X,X,X,X,0))
assert_equal(unpack_1("1", "1;R", 1), (X,0,0,0,0,0,0,0))
assert_equal(unpack_1("1", "1;IR", 1), (0,X,X,X,X,X,X,X))
assert_equal(unpack_1("1", "1", 170), (X,0,X,0,X,0,X,0))
assert_equal(unpack_1("1", "1;I", 170), (0,X,0,X,0,X,0,X))
assert_equal(unpack_1("1", "1;R", 170), (0,X,0,X,0,X,0,X))
assert_equal(unpack_1("1", "1;IR", 170), (X,0,X,0,X,0,X,0))
assert_equal(unpack("L", "L;2", 1), 0)
assert_equal(unpack("L", "L;4", 1), 0)
assert_equal(unpack("L", "L", 1), 1)
assert_equal(unpack("L", "L;I", 1), 254)
assert_equal(unpack("L", "L;R", 1), 128)
assert_equal(unpack("L", "L;16", 2), 2) # little endian
assert_equal(unpack("L", "L;16B", 2), 1) # big endian
assert_equal(unpack("LA", "LA", 2), (1, 2))
assert_equal(unpack("LA", "LA;L", 2), (1, 2))
assert_equal(unpack("RGB", "RGB", 3), (1, 2, 3))
assert_equal(unpack("RGB", "RGB;L", 3), (1, 2, 3))
assert_equal(unpack("RGB", "RGB;R", 3), (128, 64, 192))
assert_equal(unpack("RGB", "RGB;16B", 6), (1, 3, 5)) # ?
assert_equal(unpack("RGB", "BGR", 3), (3, 2, 1))
assert_equal(unpack("RGB", "RGB;15", 2), (8, 131, 0))
assert_equal(unpack("RGB", "BGR;15", 2), (0, 131, 8))
assert_equal(unpack("RGB", "RGB;16", 2), (8, 64, 0))
assert_equal(unpack("RGB", "BGR;16", 2), (0, 64, 8))
assert_equal(unpack("RGB", "RGB;4B", 2), (17, 0, 34))
assert_equal(unpack("RGB", "RGBX", 4), (1, 2, 3))
assert_equal(unpack("RGB", "BGRX", 4), (3, 2, 1))
assert_equal(unpack("RGB", "XRGB", 4), (2, 3, 4))
assert_equal(unpack("RGB", "XBGR", 4), (4, 3, 2))
assert_equal(unpack("RGBA", "RGBA", 4), (1, 2, 3, 4))
assert_equal(unpack("RGBA", "BGRA", 4), (3, 2, 1, 4))
assert_equal(unpack("RGBA", "ARGB", 4), (2, 3, 4, 1))
assert_equal(unpack("RGBA", "ABGR", 4), (4, 3, 2, 1))
assert_equal(unpack("RGBA", "RGBA;15", 2), (8, 131, 0, 0))
assert_equal(unpack("RGBA", "BGRA;15", 2), (0, 131, 8, 0))
assert_equal(unpack("RGBA", "RGBA;4B", 2), (17, 0, 34, 0))
assert_equal(unpack("RGBX", "RGBX", 4), (1, 2, 3, 4)) # 4->255?
assert_equal(unpack("RGBX", "BGRX", 4), (3, 2, 1, 255))
assert_equal(unpack("RGBX", "XRGB", 4), (2, 3, 4, 255))
assert_equal(unpack("RGBX", "XBGR", 4), (4, 3, 2, 255))
assert_equal(unpack("RGBX", "RGB;15", 2), (8, 131, 0, 255))
assert_equal(unpack("RGBX", "BGR;15", 2), (0, 131, 8, 255))
assert_equal(unpack("RGBX", "RGB;4B", 2), (17, 0, 34, 255))
assert_equal(unpack("CMYK", "CMYK", 4), (1, 2, 3, 4))
assert_equal(unpack("CMYK", "CMYK;I", 4), (254, 253, 252, 251))
assert_exception(ValueError, lambda: unpack("L", "L", 0))
assert_exception(ValueError, lambda: unpack("RGB", "RGB", 2))
assert_exception(ValueError, lambda: unpack("CMYK", "CMYK", 2))
run()

View File

@ -1,31 +0,0 @@
from tester import *
from PIL import Image
import locale
# ref https://github.com/python-pillow/Pillow/issues/272
## on windows, in polish locale:
## import locale
## print locale.setlocale(locale.LC_ALL, 'polish')
## import string
## print len(string.whitespace)
## print ord(string.whitespace[6])
## Polish_Poland.1250
## 7
## 160
# one of string.whitespace is not freely convertable into ascii.
path = "Images/lena.jpg"
def test_sanity():
assert_no_exception(lambda: Image.open(path))
try:
locale.setlocale(locale.LC_ALL, "polish")
except:
skip('polish locale not available')
import string
assert_no_exception(lambda: Image.open(path))

View File

@ -60,18 +60,23 @@ class PillowTestCase(unittest.TestCase):
def assert_warning(self, warn_class, func): def assert_warning(self, warn_class, func):
import warnings import warnings
result = None
with warnings.catch_warnings(record=True) as w: with warnings.catch_warnings(record=True) as w:
# Cause all warnings to always be triggered. # Cause all warnings to always be triggered.
warnings.simplefilter("always") warnings.simplefilter("always")
# Hopefully trigger a warning. # Hopefully trigger a warning.
func() result = func()
# Verify some things. # Verify some things.
self.assertEqual(len(w), 1) self.assertGreaterEqual(len(w), 1)
assert issubclass(w[-1].category, warn_class) found = False
self.assertIn("deprecated", str(w[-1].message)) for v in w:
if issubclass(v.category, warn_class):
found = True
break
self.assertTrue(found)
return result
# # require that deprecation warnings are triggered # # require that deprecation warnings are triggered
# import warnings # import warnings
@ -171,7 +176,8 @@ def tostring(im, format, **options):
def lena(mode="RGB", cache={}): def lena(mode="RGB", cache={}):
from PIL import Image from PIL import Image
im = cache.get(mode) im = None
# im = cache.get(mode)
if im is None: if im is None:
if mode == "RGB": if mode == "RGB":
im = Image.open("Images/lena.ppm") im = Image.open("Images/lena.ppm")
@ -181,7 +187,7 @@ def lena(mode="RGB", cache={}):
im = lena("I").convert(mode) im = lena("I").convert(mode)
else: else:
im = lena("RGB").convert(mode) im = lena("RGB").convert(mode)
cache[mode] = im # cache[mode] = im
return im return im

View File

@ -0,0 +1,94 @@
from helper import unittest, PillowTestCase
from PIL import Image
import os
base = os.path.join('Tests', 'images', 'bmp')
class TestImage(PillowTestCase):
def get_files(self, d, ext='.bmp'):
return [os.path.join(base, d, f) for f
in os.listdir(os.path.join(base, d)) if ext in f]
def test_bad(self):
""" These shouldn't crash/dos, but they shouldn't return anything
either """
for f in self.get_files('b'):
try:
im = Image.open(f)
im.load()
except Exception: # as msg:
pass
# print ("Bad Image %s: %s" %(f,msg))
def test_questionable(self):
""" These shouldn't crash/dos, but its not well defined that these
are in spec """
for f in self.get_files('q'):
try:
im = Image.open(f)
im.load()
except Exception: # as msg:
pass
# print ("Bad Image %s: %s" %(f,msg))
def test_good(self):
""" These should all work. There's a set of target files in the
html directory that we can compare against. """
# Target files, if they're not just replacing the extension
file_map = {'pal1wb.bmp': 'pal1.png',
'pal4rle.bmp': 'pal4.png',
'pal8-0.bmp': 'pal8.png',
'pal8rle.bmp': 'pal8.png',
'pal8topdown.bmp': 'pal8.png',
'pal8nonsquare.bmp': 'pal8nonsquare-v.png',
'pal8os2.bmp': 'pal8.png',
'pal8os2sp.bmp': 'pal8.png',
'pal8os2v2.bmp': 'pal8.png',
'pal8os2v2-16.bmp': 'pal8.png',
'pal8v4.bmp': 'pal8.png',
'pal8v5.bmp': 'pal8.png',
'rgb16-565pal.bmp': 'rgb16-565.png',
'rgb24pal.bmp': 'rgb24.png',
'rgb32.bmp': 'rgb24.png',
'rgb32bf.bmp': 'rgb24.png'
}
def get_compare(f):
(head, name) = os.path.split(f)
if name in file_map:
return os.path.join(base, 'html', file_map[name])
(name, ext) = os.path.splitext(name)
return os.path.join(base, 'html', "%s.png" % name)
for f in self.get_files('g'):
try:
im = Image.open(f)
im.load()
compare = Image.open(get_compare(f))
compare.load()
if im.mode == 'P':
# assert image similar doesn't really work
# with paletized image, since the palette might
# be differently ordered for an equivalent image.
im = im.convert('RGBA')
compare = im.convert('RGBA')
self.assert_image_similar(im, compare, 5)
except Exception as msg:
# there are three here that are unsupported:
unsupported = (os.path.join(base, 'g', 'rgb32bf.bmp'),
os.path.join(base, 'g', 'pal8rle.bmp'),
os.path.join(base, 'g', 'pal4rle.bmp'))
if f not in unsupported:
self.assertTrue(
False, "Unsupported Image %s: %s" % (f, msg))
if __name__ == '__main__':
unittest.main()
# End of file

74
test/test_file_icns.py Normal file
View File

@ -0,0 +1,74 @@
from helper import unittest, PillowTestCase
from PIL import Image
# sample icon file
file = "Images/pillow.icns"
data = open(file, "rb").read()
enable_jpeg2k = hasattr(Image.core, 'jp2klib_version')
class TestFileIcns(PillowTestCase):
def test_sanity(self):
# Loading this icon by default should result in the largest size
# (512x512@2x) being loaded
im = Image.open(file)
im.load()
self.assertEqual(im.mode, "RGBA")
self.assertEqual(im.size, (1024, 1024))
self.assertEqual(im.format, "ICNS")
def test_sizes(self):
# Check that we can load all of the sizes, and that the final pixel
# dimensions are as expected
im = Image.open(file)
for w, h, r in im.info['sizes']:
wr = w * r
hr = h * r
im2 = Image.open(file)
im2.size = (w, h, r)
im2.load()
self.assertEqual(im2.mode, 'RGBA')
self.assertEqual(im2.size, (wr, hr))
def test_older_icon(self):
# This icon was made with Icon Composer rather than iconutil; it still
# uses PNG rather than JP2, however (since it was made on 10.9).
im = Image.open('Tests/images/pillow2.icns')
for w, h, r in im.info['sizes']:
wr = w * r
hr = h * r
im2 = Image.open('Tests/images/pillow2.icns')
im2.size = (w, h, r)
im2.load()
self.assertEqual(im2.mode, 'RGBA')
self.assertEqual(im2.size, (wr, hr))
def test_jp2_icon(self):
# This icon was made by using Uli Kusterer's oldiconutil to replace
# the PNG images with JPEG 2000 ones. The advantage of doing this is
# that OS X 10.5 supports JPEG 2000 but not PNG; some commercial
# software therefore does just this.
# (oldiconutil is here: https://github.com/uliwitness/oldiconutil)
if not enable_jpeg2k:
return
im = Image.open('Tests/images/pillow3.icns')
for w, h, r in im.info['sizes']:
wr = w * r
hr = h * r
im2 = Image.open('Tests/images/pillow3.icns')
im2.size = (w, h, r)
im2.load()
self.assertEqual(im2.mode, 'RGBA')
self.assertEqual(im2.size, (wr, hr))
if __name__ == '__main__':
unittest.main()
# End of file

23
test/test_file_ico.py Normal file
View File

@ -0,0 +1,23 @@
from helper import unittest, PillowTestCase
from PIL import Image
# sample ppm stream
file = "Images/lena.ico"
data = open(file, "rb").read()
class TestFileIco(PillowTestCase):
def test_sanity(self):
im = Image.open(file)
im.load()
self.assertEqual(im.mode, "RGBA")
self.assertEqual(im.size, (16, 16))
self.assertEqual(im.format, "ICO")
if __name__ == '__main__':
unittest.main()
# End of file

23
test/test_file_psd.py Normal file
View File

@ -0,0 +1,23 @@
from helper import unittest, PillowTestCase
from PIL import Image
# sample ppm stream
file = "Images/lena.psd"
data = open(file, "rb").read()
class TestImagePsd(PillowTestCase):
def test_sanity(self):
im = Image.open(file)
im.load()
self.assertEqual(im.mode, "RGB")
self.assertEqual(im.size, (128, 128))
self.assertEqual(im.format, "PSD")
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,4 +1,4 @@
from tester import * from helper import unittest, PillowTestCase
from PIL import Image from PIL import Image
@ -25,10 +25,20 @@ static char basic_bits[] = {
}; };
""" """
def test_pil151():
class TestFileXbm(PillowTestCase):
def test_pil151(self):
from io import BytesIO
im = Image.open(BytesIO(PIL151)) im = Image.open(BytesIO(PIL151))
assert_no_exception(lambda: im.load()) im.load()
assert_equal(im.mode, '1') self.assertEqual(im.mode, '1')
assert_equal(im.size, (32, 32)) self.assertEqual(im.size, (32, 32))
if __name__ == '__main__':
unittest.main()
# End of file

23
test/test_file_xpm.py Normal file
View File

@ -0,0 +1,23 @@
from helper import unittest, PillowTestCase
from PIL import Image
# sample ppm stream
file = "Images/lena.xpm"
data = open(file, "rb").read()
class TestFileXpm(PillowTestCase):
def test_sanity(self):
im = Image.open(file)
im.load()
self.assertEqual(im.mode, "P")
self.assertEqual(im.size, (128, 128))
self.assertEqual(im.format, "XPM")
if __name__ == '__main__':
unittest.main()
# End of file

22
test/test_font_bdf.py Normal file
View File

@ -0,0 +1,22 @@
from helper import unittest, PillowTestCase
from PIL import FontFile, BdfFontFile
filename = "Images/courB08.bdf"
class TestImage(PillowTestCase):
def test_sanity(self):
file = open(filename, "rb")
font = BdfFontFile.BdfFontFile(file)
self.assertIsInstance(font, FontFile.FontFile)
self.assertEqual(len([_f for _f in font.glyph if _f]), 190)
if __name__ == '__main__':
unittest.main()
# End of file

48
test/test_format_lab.py Normal file
View File

@ -0,0 +1,48 @@
from helper import unittest, PillowTestCase
from PIL import Image
class TestFormatLab(PillowTestCase):
def test_white(self):
i = Image.open('Tests/images/lab.tif')
i.load()
self.assertEqual(i.mode, 'LAB')
self.assertEqual(i.getbands(), ('L', 'A', 'B'))
k = i.getpixel((0, 0))
self.assertEqual(k, (255, 128, 128))
L = i.getdata(0)
a = i.getdata(1)
b = i.getdata(2)
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
i = Image.open('Tests/images/lab-green.tif')
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
i = Image.open('Tests/images/lab-red.tif')
k = i.getpixel((0, 0))
self.assertEqual(k, (128, 228, 128))
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -0,0 +1,26 @@
from helper import unittest, PillowTestCase
from PIL import Image
class TestImageGetBands(PillowTestCase):
def test_getbands(self):
self.assertEqual(Image.new("1", (1, 1)).getbands(), ("1",))
self.assertEqual(Image.new("L", (1, 1)).getbands(), ("L",))
self.assertEqual(Image.new("I", (1, 1)).getbands(), ("I",))
self.assertEqual(Image.new("F", (1, 1)).getbands(), ("F",))
self.assertEqual(Image.new("P", (1, 1)).getbands(), ("P",))
self.assertEqual(Image.new("RGB", (1, 1)).getbands(), ("R", "G", "B"))
self.assertEqual(
Image.new("RGBA", (1, 1)).getbands(), ("R", "G", "B", "A"))
self.assertEqual(
Image.new("CMYK", (1, 1)).getbands(), ("C", "M", "Y", "K"))
self.assertEqual(
Image.new("YCbCr", (1, 1)).getbands(), ("Y", "Cb", "Cr"))
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -0,0 +1,74 @@
from helper import unittest, PillowTestCase, lena
class TestImage(PillowTestCase):
def test_getcolors(self):
def getcolors(mode, limit=None):
im = lena(mode)
if limit:
colors = im.getcolors(limit)
else:
colors = im.getcolors()
if colors:
return len(colors)
return None
self.assertEqual(getcolors("1"), 2)
self.assertEqual(getcolors("L"), 193)
self.assertEqual(getcolors("I"), 193)
self.assertEqual(getcolors("F"), 193)
self.assertEqual(getcolors("P"), 54) # fixed palette
self.assertEqual(getcolors("RGB"), None)
self.assertEqual(getcolors("RGBA"), None)
self.assertEqual(getcolors("CMYK"), None)
self.assertEqual(getcolors("YCbCr"), None)
self.assertEqual(getcolors("L", 128), None)
self.assertEqual(getcolors("L", 1024), 193)
self.assertEqual(getcolors("RGB", 8192), None)
self.assertEqual(getcolors("RGB", 16384), 14836)
self.assertEqual(getcolors("RGB", 100000), 14836)
self.assertEqual(getcolors("RGBA", 16384), 14836)
self.assertEqual(getcolors("CMYK", 16384), 14836)
self.assertEqual(getcolors("YCbCr", 16384), 11995)
# --------------------------------------------------------------------
def test_pack(self):
# Pack problems for small tables (@PIL209)
im = lena().quantize(3).convert("RGB")
expected = [
(3236, (227, 183, 147)),
(6297, (143, 84, 81)),
(6851, (208, 143, 112))]
A = im.getcolors(maxcolors=2)
self.assertEqual(A, None)
A = im.getcolors(maxcolors=3)
A.sort()
self.assertEqual(A, expected)
A = im.getcolors(maxcolors=4)
A.sort()
self.assertEqual(A, expected)
A = im.getcolors(maxcolors=8)
A.sort()
self.assertEqual(A, expected)
A = im.getcolors(maxcolors=16)
A.sort()
self.assertEqual(A, expected)
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -0,0 +1,27 @@
from helper import unittest, PillowTestCase, lena
class TestImageGetExtrema(PillowTestCase):
def test_extrema(self):
def extrema(mode):
return lena(mode).getextrema()
self.assertEqual(extrema("1"), (0, 255))
self.assertEqual(extrema("L"), (40, 235))
self.assertEqual(extrema("I"), (40, 235))
self.assertEqual(extrema("F"), (40.0, 235.0))
self.assertEqual(extrema("P"), (11, 218)) # fixed palette
self.assertEqual(
extrema("RGB"), ((61, 255), (26, 234), (44, 223)))
self.assertEqual(
extrema("RGBA"), ((61, 255), (26, 234), (44, 223), (255, 255)))
self.assertEqual(
extrema("CMYK"), ((0, 194), (21, 229), (32, 211), (0, 0)))
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -0,0 +1,26 @@
from helper import unittest, PillowTestCase, lena
class TestImageGetPalette(PillowTestCase):
def test_palette(self):
def palette(mode):
p = lena(mode).getpalette()
if p:
return p[:10]
return None
self.assertEqual(palette("1"), None)
self.assertEqual(palette("L"), None)
self.assertEqual(palette("I"), None)
self.assertEqual(palette("F"), None)
self.assertEqual(palette("P"), [0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
self.assertEqual(palette("RGB"), None)
self.assertEqual(palette("RGBA"), None)
self.assertEqual(palette("CMYK"), None)
self.assertEqual(palette("YCbCr"), None)
if __name__ == '__main__':
unittest.main()
# End of file

36
test/test_image_mode.py Normal file
View File

@ -0,0 +1,36 @@
from helper import unittest, PillowTestCase, lena
from PIL import Image
class TestImage(PillowTestCase):
def test_sanity(self):
im = lena()
im.mode
def test_properties(self):
def check(mode, *result):
signature = (
Image.getmodebase(mode), Image.getmodetype(mode),
Image.getmodebands(mode), Image.getmodebandnames(mode),
)
self.assertEqual(signature, result)
check("1", "L", "L", 1, ("1",))
check("L", "L", "L", 1, ("L",))
check("P", "RGB", "L", 1, ("P",))
check("I", "L", "I", 1, ("I",))
check("F", "L", "F", 1, ("F",))
check("RGB", "RGB", "L", 3, ("R", "G", "B"))
check("RGBA", "RGB", "L", 4, ("R", "G", "B", "A"))
check("RGBX", "RGB", "L", 4, ("R", "G", "B", "X"))
check("RGBX", "RGB", "L", 4, ("R", "G", "B", "X"))
check("CMYK", "RGB", "L", 4, ("C", "M", "Y", "K"))
check("YCbCr", "RGB", "L", 3, ("Y", "Cb", "Cr"))
if __name__ == '__main__':
unittest.main()
# End of file

25
test/test_image_offset.py Normal file
View File

@ -0,0 +1,25 @@
from helper import unittest, PillowTestCase, lena
class TestImage(PillowTestCase):
def test_offset(self):
im1 = lena()
im2 = self.assert_warning(DeprecationWarning, lambda: im1.offset(10))
self.assertEqual(im1.getpixel((0, 0)), im2.getpixel((10, 10)))
im2 = self.assert_warning(
DeprecationWarning, lambda: im1.offset(10, 20))
self.assertEqual(im1.getpixel((0, 0)), im2.getpixel((10, 20)))
im2 = self.assert_warning(
DeprecationWarning, lambda: im1.offset(20, 20))
self.assertEqual(im1.getpixel((0, 0)), im2.getpixel((20, 20)))
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -0,0 +1,52 @@
from helper import unittest, PillowTestCase
from PIL import Image
class TestImagePutAlpha(PillowTestCase):
def test_interface(self):
im = Image.new("RGBA", (1, 1), (1, 2, 3, 0))
self.assertEqual(im.getpixel((0, 0)), (1, 2, 3, 0))
im = Image.new("RGBA", (1, 1), (1, 2, 3))
self.assertEqual(im.getpixel((0, 0)), (1, 2, 3, 255))
im.putalpha(Image.new("L", im.size, 4))
self.assertEqual(im.getpixel((0, 0)), (1, 2, 3, 4))
im.putalpha(5)
self.assertEqual(im.getpixel((0, 0)), (1, 2, 3, 5))
def test_promote(self):
im = Image.new("L", (1, 1), 1)
self.assertEqual(im.getpixel((0, 0)), 1)
im.putalpha(2)
self.assertEqual(im.mode, 'LA')
self.assertEqual(im.getpixel((0, 0)), (1, 2))
im = Image.new("RGB", (1, 1), (1, 2, 3))
self.assertEqual(im.getpixel((0, 0)), (1, 2, 3))
im.putalpha(4)
self.assertEqual(im.mode, 'RGBA')
self.assertEqual(im.getpixel((0, 0)), (1, 2, 3, 4))
def test_readonly(self):
im = Image.new("RGB", (1, 1), (1, 2, 3))
im.readonly = 1
im.putalpha(4)
self.assertFalse(im.readonly)
self.assertEqual(im.mode, 'RGBA')
self.assertEqual(im.getpixel((0, 0)), (1, 2, 3, 4))
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -0,0 +1,35 @@
from helper import unittest, PillowTestCase, lena
from PIL import Image
class TestImage(PillowTestCase):
def test_sanity(self):
im = lena()
im = im.quantize()
self.assert_image(im, "P", im.size)
im = lena()
im = im.quantize(palette=lena("P"))
self.assert_image(im, "P", im.size)
def test_octree_quantize(self):
im = lena()
im = im.quantize(100, Image.FASTOCTREE)
self.assert_image(im, "P", im.size)
assert len(im.getcolors()) == 100
def test_rgba_quantize(self):
im = lena('RGBA')
im.quantize()
self.assertRaises(Exception, lambda: im.quantize(method=0))
if __name__ == '__main__':
unittest.main()
# End of file

19
test/test_image_resize.py Normal file
View File

@ -0,0 +1,19 @@
from helper import unittest, PillowTestCase, lena
class TestImageResize(PillowTestCase):
def test_resize(self):
def resize(mode, size):
out = lena(mode).resize(size)
self.assertEqual(out.mode, mode)
self.assertEqual(out.size, size)
for mode in "1", "P", "L", "RGB", "I", "F":
resize(mode, (100, 100))
resize(mode, (200, 200))
if __name__ == '__main__':
unittest.main()
# End of file

22
test/test_image_rotate.py Normal file
View File

@ -0,0 +1,22 @@
from helper import unittest, PillowTestCase, lena
class TestImageRotate(PillowTestCase):
def test_rotate(self):
def rotate(mode):
im = lena(mode)
out = im.rotate(45)
self.assertEqual(out.mode, mode)
self.assertEqual(out.size, im.size) # default rotate clips output
out = im.rotate(45, expand=1)
self.assertEqual(out.mode, mode)
self.assertNotEqual(out.size, im.size)
for mode in "1", "P", "L", "RGB", "I", "F":
rotate(mode)
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -0,0 +1,43 @@
from helper import unittest, PillowTestCase, lena
class TestImageThumbnail(PillowTestCase):
def test_sanity(self):
im = lena()
im.thumbnail((100, 100))
self.assert_image(im, im.mode, (100, 100))
def test_aspect(self):
im = lena()
im.thumbnail((100, 100))
self.assert_image(im, im.mode, (100, 100))
im = lena().resize((128, 256))
im.thumbnail((100, 100))
self.assert_image(im, im.mode, (50, 100))
im = lena().resize((128, 256))
im.thumbnail((50, 100))
self.assert_image(im, im.mode, (50, 100))
im = lena().resize((256, 128))
im.thumbnail((100, 100))
self.assert_image(im, im.mode, (100, 50))
im = lena().resize((256, 128))
im.thumbnail((100, 50))
self.assert_image(im, im.mode, (100, 50))
im = lena().resize((128, 128))
im.thumbnail((100, 100))
self.assert_image(im, im.mode, (100, 100))
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -0,0 +1,125 @@
from helper import unittest, PillowTestCase, lena
from PIL import Image
class TestImageTransform(PillowTestCase):
def test_extent(self):
im = lena('RGB')
(w, h) = im.size
transformed = im.transform(im.size, Image.EXTENT,
(0, 0,
w//2, h//2), # ul -> lr
Image.BILINEAR)
scaled = im.resize((w*2, h*2), Image.BILINEAR).crop((0, 0, w, h))
# undone -- precision?
self.assert_image_similar(transformed, scaled, 10)
def test_quad(self):
# one simple quad transform, equivalent to scale & crop upper left quad
im = lena('RGB')
(w, h) = im.size
transformed = im.transform(im.size, Image.QUAD,
(0, 0, 0, h//2,
# ul -> ccw around quad:
w//2, h//2, w//2, 0),
Image.BILINEAR)
scaled = im.resize((w*2, h*2), Image.BILINEAR).crop((0, 0, w, h))
self.assert_image_equal(transformed, scaled)
def test_mesh(self):
# this should be a checkerboard of halfsized lenas in ul, lr
im = lena('RGBA')
(w, h) = im.size
transformed = im.transform(im.size, Image.MESH,
[((0, 0, w//2, h//2), # box
(0, 0, 0, h,
w, h, w, 0)), # ul -> ccw around quad
((w//2, h//2, w, h), # box
(0, 0, 0, h,
w, h, w, 0))], # ul -> ccw around quad
Image.BILINEAR)
# transformed.save('transformed.png')
scaled = im.resize((w//2, h//2), Image.BILINEAR)
checker = Image.new('RGBA', im.size)
checker.paste(scaled, (0, 0))
checker.paste(scaled, (w//2, h//2))
self.assert_image_equal(transformed, checker)
# now, check to see that the extra area is (0, 0, 0, 0)
blank = Image.new('RGBA', (w//2, h//2), (0, 0, 0, 0))
self.assert_image_equal(blank, transformed.crop((w//2, 0, w, h//2)))
self.assert_image_equal(blank, transformed.crop((0, h//2, w//2, h)))
def _test_alpha_premult(self, op):
# create image with half white, half black,
# with the black half transparent.
# do op,
# there should be no darkness in the white section.
im = Image.new('RGBA', (10, 10), (0, 0, 0, 0))
im2 = Image.new('RGBA', (5, 10), (255, 255, 255, 255))
im.paste(im2, (0, 0))
im = op(im, (40, 10))
im_background = Image.new('RGB', (40, 10), (255, 255, 255))
im_background.paste(im, (0, 0), im)
hist = im_background.histogram()
self.assertEqual(40*10, hist[-1])
def test_alpha_premult_resize(self):
def op(im, sz):
return im.resize(sz, Image.LINEAR)
self._test_alpha_premult(op)
def test_alpha_premult_transform(self):
def op(im, sz):
(w, h) = im.size
return im.transform(sz, Image.EXTENT,
(0, 0,
w, h),
Image.BILINEAR)
self._test_alpha_premult(op)
def test_blank_fill(self):
# attempting to hit
# https://github.com/python-pillow/Pillow/issues/254 reported
#
# issue is that transforms with transparent overflow area
# contained junk from previous images, especially on systems with
# constrained memory. So, attempt to fill up memory with a
# pattern, free it, and then run the mesh test again. Using a 1Mp
# image with 4 bands, for 4 megs of data allocated, x 64. OMM (64
# bit 12.04 VM with 512 megs available, this fails with Pillow <
# a0eaf06cc5f62a6fb6de556989ac1014ff3348ea
#
# Running by default, but I'd totally understand not doing it in
# the future
foo = [Image.new('RGBA', (1024, 1024), (a, a, a, a))
for a in range(1, 65)]
# Yeah. Watch some JIT optimize this out.
foo = None
self.test_mesh()
if __name__ == '__main__':
unittest.main()
# End of file

214
test/test_imagecms.py Normal file
View File

@ -0,0 +1,214 @@
from helper import unittest, PillowTestCase, lena
from PIL import Image
try:
from PIL import ImageCms
ImageCms.core.profile_open
except ImportError as v:
# Skipped via setUp()
pass
SRGB = "Tests/icc/sRGB.icm"
class TestImage(PillowTestCase):
def setUp(self):
try:
from PIL import ImageCms
except ImportError as v:
self.skipTest(v)
def test_sanity(self):
# basic smoke test.
# this mostly follows the cms_test outline.
v = ImageCms.versions() # should return four strings
self.assertEqual(v[0], '1.0.0 pil')
self.assertEqual(list(map(type, v)), [str, str, str, str])
# internal version number
self.assertRegexpMatches(ImageCms.core.littlecms_version, "\d+\.\d+$")
i = ImageCms.profileToProfile(lena(), SRGB, SRGB)
self.assert_image(i, "RGB", (128, 128))
i = lena()
ImageCms.profileToProfile(i, SRGB, SRGB, inPlace=True)
self.assert_image(i, "RGB", (128, 128))
t = ImageCms.buildTransform(SRGB, SRGB, "RGB", "RGB")
i = ImageCms.applyTransform(lena(), t)
self.assert_image(i, "RGB", (128, 128))
i = lena()
t = ImageCms.buildTransform(SRGB, SRGB, "RGB", "RGB")
ImageCms.applyTransform(lena(), t, inPlace=True)
self.assert_image(i, "RGB", (128, 128))
p = ImageCms.createProfile("sRGB")
o = ImageCms.getOpenProfile(SRGB)
t = ImageCms.buildTransformFromOpenProfiles(p, o, "RGB", "RGB")
i = ImageCms.applyTransform(lena(), t)
self.assert_image(i, "RGB", (128, 128))
t = ImageCms.buildProofTransform(SRGB, SRGB, SRGB, "RGB", "RGB")
self.assertEqual(t.inputMode, "RGB")
self.assertEqual(t.outputMode, "RGB")
i = ImageCms.applyTransform(lena(), t)
self.assert_image(i, "RGB", (128, 128))
# test PointTransform convenience API
lena().point(t)
def test_name(self):
# get profile information for file
self.assertEqual(
ImageCms.getProfileName(SRGB).strip(),
'IEC 61966-2.1 Default RGB colour space - sRGB')
def test_info(self):
self.assertEqual(
ImageCms.getProfileInfo(SRGB).splitlines(), [
'sRGB IEC61966-2.1', '',
'Copyright (c) 1998 Hewlett-Packard Company', ''])
def test_copyright(self):
self.assertEqual(
ImageCms.getProfileCopyright(SRGB).strip(),
'Copyright (c) 1998 Hewlett-Packard Company')
def test_manufacturer(self):
self.assertEqual(
ImageCms.getProfileManufacturer(SRGB).strip(),
'IEC http://www.iec.ch')
def test_model(self):
self.assertEqual(
ImageCms.getProfileModel(SRGB).strip(),
'IEC 61966-2.1 Default RGB colour space - sRGB')
def test_description(self):
self.assertEqual(
ImageCms.getProfileDescription(SRGB).strip(),
'sRGB IEC61966-2.1')
def test_intent(self):
self.assertEqual(ImageCms.getDefaultIntent(SRGB), 0)
self.assertEqual(ImageCms.isIntentSupported(
SRGB, ImageCms.INTENT_ABSOLUTE_COLORIMETRIC,
ImageCms.DIRECTION_INPUT), 1)
def test_profile_object(self):
# same, using profile object
p = ImageCms.createProfile("sRGB")
# self.assertEqual(ImageCms.getProfileName(p).strip(),
# 'sRGB built-in - (lcms internal)')
# self.assertEqual(ImageCms.getProfileInfo(p).splitlines(),
# ['sRGB built-in', '', 'WhitePoint : D65 (daylight)', '', ''])
self.assertEqual(ImageCms.getDefaultIntent(p), 0)
self.assertEqual(ImageCms.isIntentSupported(
p, ImageCms.INTENT_ABSOLUTE_COLORIMETRIC,
ImageCms.DIRECTION_INPUT), 1)
def test_extensions(self):
# extensions
from io import BytesIO
i = Image.open("Tests/images/rgb.jpg")
p = ImageCms.getOpenProfile(BytesIO(i.info["icc_profile"]))
self.assertEqual(
ImageCms.getProfileName(p).strip(),
'IEC 61966-2.1 Default RGB colour space - sRGB')
def test_exceptions(self):
# the procedural pyCMS API uses PyCMSError for all sorts of errors
self.assertRaises(
ImageCms.PyCMSError,
lambda: ImageCms.profileToProfile(lena(), "foo", "bar"))
self.assertRaises(
ImageCms.PyCMSError,
lambda: ImageCms.buildTransform("foo", "bar", "RGB", "RGB"))
self.assertRaises(
ImageCms.PyCMSError,
lambda: ImageCms.getProfileName(None))
self.assertRaises(
ImageCms.PyCMSError,
lambda: ImageCms.isIntentSupported(SRGB, None, None))
def test_display_profile(self):
# try fetching the profile for the current display device
ImageCms.get_display_profile()
def test_lab_color_profile(self):
ImageCms.createProfile("LAB", 5000)
ImageCms.createProfile("LAB", 6500)
def test_simple_lab(self):
i = Image.new('RGB', (10, 10), (128, 128, 128))
pLab = ImageCms.createProfile("LAB")
t = ImageCms.buildTransform(SRGB, pLab, "RGB", "LAB")
i_lab = ImageCms.applyTransform(i, t)
self.assertEqual(i_lab.mode, 'LAB')
k = i_lab.getpixel((0, 0))
# not a linear luminance map. so L != 128:
self.assertEqual(k, (137, 128, 128))
L = i_lab.getdata(0)
a = i_lab.getdata(1)
b = i_lab.getdata(2)
self.assertEqual(list(L), [137] * 100)
self.assertEqual(list(a), [128] * 100)
self.assertEqual(list(b), [128] * 100)
def test_lab_color(self):
pLab = ImageCms.createProfile("LAB")
t = ImageCms.buildTransform(SRGB, pLab, "RGB", "LAB")
# Need to add a type mapping for some PIL type to TYPE_Lab_8 in
# findLCMSType, and have that mapping work back to a PIL mode
# (likely RGB).
i = ImageCms.applyTransform(lena(), t)
self.assert_image(i, "LAB", (128, 128))
# i.save('temp.lab.tif') # visually verified vs PS.
target = Image.open('Tests/images/lena.Lab.tif')
self.assert_image_similar(i, target, 30)
def test_lab_srgb(self):
pLab = ImageCms.createProfile("LAB")
t = ImageCms.buildTransform(pLab, SRGB, "LAB", "RGB")
img = Image.open('Tests/images/lena.Lab.tif')
img_srgb = ImageCms.applyTransform(img, t)
# img_srgb.save('temp.srgb.tif') # visually verified vs ps.
self.assert_image_similar(lena(), img_srgb, 30)
def test_lab_roundtrip(self):
# check to see if we're at least internally consistent.
pLab = ImageCms.createProfile("LAB")
t = ImageCms.buildTransform(SRGB, pLab, "RGB", "LAB")
t2 = ImageCms.buildTransform(pLab, SRGB, "LAB", "RGB")
i = ImageCms.applyTransform(lena(), t)
out = ImageCms.applyTransform(i, t2)
self.assert_image_similar(lena(), out, 2)
if __name__ == '__main__':
unittest.main()
# End of file

71
test/test_imagecolor.py Normal file
View File

@ -0,0 +1,71 @@
from helper import unittest, PillowTestCase
from PIL import Image
from PIL import ImageColor
class TestImageColor(PillowTestCase):
def test_sanity(self):
self.assertEqual((255, 0, 0), ImageColor.getrgb("#f00"))
self.assertEqual((255, 0, 0), ImageColor.getrgb("#ff0000"))
self.assertEqual((255, 0, 0), ImageColor.getrgb("rgb(255,0,0)"))
self.assertEqual((255, 0, 0), ImageColor.getrgb("rgb(255, 0, 0)"))
self.assertEqual((255, 0, 0), ImageColor.getrgb("rgb(100%,0%,0%)"))
self.assertEqual((255, 0, 0), ImageColor.getrgb("hsl(0, 100%, 50%)"))
self.assertEqual((255, 0, 0, 0), ImageColor.getrgb("rgba(255,0,0,0)"))
self.assertEqual(
(255, 0, 0, 0), ImageColor.getrgb("rgba(255, 0, 0, 0)"))
self.assertEqual((255, 0, 0), ImageColor.getrgb("red"))
# look for rounding errors (based on code by Tim Hatch)
def test_rounding_errors(self):
for color in list(ImageColor.colormap.keys()):
expected = Image.new(
"RGB", (1, 1), color).convert("L").getpixel((0, 0))
actual = Image.new("L", (1, 1), color).getpixel((0, 0))
self.assertEqual(expected, actual)
self.assertEqual((0, 0, 0), ImageColor.getcolor("black", "RGB"))
self.assertEqual((255, 255, 255), ImageColor.getcolor("white", "RGB"))
self.assertEqual(
(0, 255, 115), ImageColor.getcolor("rgba(0, 255, 115, 33)", "RGB"))
Image.new("RGB", (1, 1), "white")
self.assertEqual((0, 0, 0, 255), ImageColor.getcolor("black", "RGBA"))
self.assertEqual(
(255, 255, 255, 255), ImageColor.getcolor("white", "RGBA"))
self.assertEqual(
(0, 255, 115, 33),
ImageColor.getcolor("rgba(0, 255, 115, 33)", "RGBA"))
Image.new("RGBA", (1, 1), "white")
self.assertEqual(0, ImageColor.getcolor("black", "L"))
self.assertEqual(255, ImageColor.getcolor("white", "L"))
self.assertEqual(
162, ImageColor.getcolor("rgba(0, 255, 115, 33)", "L"))
Image.new("L", (1, 1), "white")
self.assertEqual(0, ImageColor.getcolor("black", "1"))
self.assertEqual(255, ImageColor.getcolor("white", "1"))
# The following test is wrong, but is current behavior
# The correct result should be 255 due to the mode 1
self.assertEqual(
162, ImageColor.getcolor("rgba(0, 255, 115, 33)", "1"))
# Correct behavior
# self.assertEqual(
# 255, ImageColor.getcolor("rgba(0, 255, 115, 33)", "1"))
Image.new("1", (1, 1), "white")
self.assertEqual((0, 255), ImageColor.getcolor("black", "LA"))
self.assertEqual((255, 255), ImageColor.getcolor("white", "LA"))
self.assertEqual(
(162, 33), ImageColor.getcolor("rgba(0, 255, 115, 33)", "LA"))
Image.new("LA", (1, 1), "white")
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -4,6 +4,8 @@ from PIL import Image
from PIL import ImageColor from PIL import ImageColor
from PIL import ImageDraw from PIL import ImageDraw
import sys
# Image size # Image size
w, h = 100, 100 w, h = 100, 100
@ -225,7 +227,11 @@ class TestImageDraw(PillowTestCase):
self.assert_image_equal( self.assert_image_equal(
im, Image.open("Tests/images/imagedraw_floodfill.png")) im, Image.open("Tests/images/imagedraw_floodfill.png"))
@unittest.skipIf(hasattr(sys, 'pypy_version_info'),
"Causes fatal RPython error on PyPy")
def test_floodfill_border(self): def test_floodfill_border(self):
# floodfill() is experimental
# Arrange # Arrange
im = Image.new("RGB", (w, h)) im = Image.new("RGB", (w, h))
draw = ImageDraw.Draw(im) draw = ImageDraw.Draw(im)

33
test/test_imagefileio.py Normal file
View File

@ -0,0 +1,33 @@
from helper import unittest, PillowTestCase, lena, tostring
from PIL import Image
from PIL import ImageFileIO
class TestImageFileIo(PillowTestCase):
def test_fileio(self):
class DumbFile:
def __init__(self, data):
self.data = data
def read(self, bytes=None):
assert(bytes is None)
return self.data
def close(self):
pass
im1 = lena()
io = ImageFileIO.ImageFileIO(DumbFile(tostring(im1, "PPM")))
im2 = Image.open(io)
self.assert_image_equal(im1, im2)
if __name__ == '__main__':
unittest.main()
# End of file

32
test/test_imagemode.py Normal file
View File

@ -0,0 +1,32 @@
from helper import unittest, PillowTestCase
from PIL import ImageMode
class TestImage(PillowTestCase):
def test_sanity(self):
ImageMode.getmode("1")
ImageMode.getmode("L")
ImageMode.getmode("P")
ImageMode.getmode("RGB")
ImageMode.getmode("I")
ImageMode.getmode("F")
m = ImageMode.getmode("1")
self.assertEqual(m.mode, "1")
self.assertEqual(m.bands, ("1",))
self.assertEqual(m.basemode, "L")
self.assertEqual(m.basetype, "L")
m = ImageMode.getmode("RGB")
self.assertEqual(m.mode, "RGB")
self.assertEqual(m.bands, ("R", "G", "B"))
self.assertEqual(m.basemode, "RGB")
self.assertEqual(m.basetype, "L")
if __name__ == '__main__':
unittest.main()
# End of file

85
test/test_imageops.py Normal file
View File

@ -0,0 +1,85 @@
from helper import unittest, PillowTestCase, lena
from PIL import ImageOps
class TestImageOps(PillowTestCase):
class Deformer:
def getmesh(self, im):
x, y = im.size
return [((0, 0, x, y), (0, 0, x, 0, x, y, y, 0))]
deformer = Deformer()
def test_sanity(self):
ImageOps.autocontrast(lena("L"))
ImageOps.autocontrast(lena("RGB"))
ImageOps.autocontrast(lena("L"), cutoff=10)
ImageOps.autocontrast(lena("L"), ignore=[0, 255])
ImageOps.colorize(lena("L"), (0, 0, 0), (255, 255, 255))
ImageOps.colorize(lena("L"), "black", "white")
ImageOps.crop(lena("L"), 1)
ImageOps.crop(lena("RGB"), 1)
ImageOps.deform(lena("L"), self.deformer)
ImageOps.deform(lena("RGB"), self.deformer)
ImageOps.equalize(lena("L"))
ImageOps.equalize(lena("RGB"))
ImageOps.expand(lena("L"), 1)
ImageOps.expand(lena("RGB"), 1)
ImageOps.expand(lena("L"), 2, "blue")
ImageOps.expand(lena("RGB"), 2, "blue")
ImageOps.fit(lena("L"), (128, 128))
ImageOps.fit(lena("RGB"), (128, 128))
ImageOps.flip(lena("L"))
ImageOps.flip(lena("RGB"))
ImageOps.grayscale(lena("L"))
ImageOps.grayscale(lena("RGB"))
ImageOps.invert(lena("L"))
ImageOps.invert(lena("RGB"))
ImageOps.mirror(lena("L"))
ImageOps.mirror(lena("RGB"))
ImageOps.posterize(lena("L"), 4)
ImageOps.posterize(lena("RGB"), 4)
ImageOps.solarize(lena("L"))
ImageOps.solarize(lena("RGB"))
def test_1pxfit(self):
# Division by zero in equalize if image is 1 pixel high
newimg = ImageOps.fit(lena("RGB").resize((1, 1)), (35, 35))
self.assertEqual(newimg.size, (35, 35))
newimg = ImageOps.fit(lena("RGB").resize((1, 100)), (35, 35))
self.assertEqual(newimg.size, (35, 35))
newimg = ImageOps.fit(lena("RGB").resize((100, 1)), (35, 35))
self.assertEqual(newimg.size, (35, 35))
def test_pil163(self):
# Division by zero in equalize if < 255 pixels in image (@PIL163)
i = lena("RGB").resize((15, 16))
ImageOps.equalize(i.convert("L"))
ImageOps.equalize(i.convert("P"))
ImageOps.equalize(i.convert("RGB"))
if __name__ == '__main__':
unittest.main()
# End of file

18
test/test_imageshow.py Normal file
View File

@ -0,0 +1,18 @@
from helper import unittest, PillowTestCase
from PIL import Image
from PIL import ImageShow
class TestImage(PillowTestCase):
def test_sanity(self):
dir(Image)
dir(ImageShow)
pass
if __name__ == '__main__':
unittest.main()
# End of file

17
test/test_imagetk.py Normal file
View File

@ -0,0 +1,17 @@
from helper import unittest, PillowTestCase
class TestImageTk(PillowTestCase):
def test_import(self):
try:
from PIL import ImageTk
dir(ImageTk)
except (OSError, ImportError) as v:
self.skipTest(v)
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -0,0 +1,27 @@
from helper import unittest, PillowTestCase
from PIL import Image
from PIL import ImageTransform
class TestImageTransform(PillowTestCase):
def test_sanity(self):
im = Image.new("L", (100, 100))
seq = tuple(range(10))
transform = ImageTransform.AffineTransform(seq[:6])
im.transform((100, 100), transform)
transform = ImageTransform.ExtentTransform(seq[:4])
im.transform((100, 100), transform)
transform = ImageTransform.QuadTransform(seq[:8])
im.transform((100, 100), transform)
transform = ImageTransform.MeshTransform([(seq[:4], seq[:8])])
im.transform((100, 100), transform)
if __name__ == '__main__':
unittest.main()
# End of file

18
test/test_imagewin.py Normal file
View File

@ -0,0 +1,18 @@
from helper import unittest, PillowTestCase, lena
from PIL import Image
from PIL import ImageWin
class TestImage(PillowTestCase):
def test_sanity(self):
dir(Image)
dir(ImageWin)
pass
if __name__ == '__main__':
unittest.main()
# End of file

147
test/test_lib_pack.py Normal file
View File

@ -0,0 +1,147 @@
from helper import unittest, PillowTestCase, py3
from PIL import Image
class TestLibPack(PillowTestCase):
def pack(self):
pass # not yet
def test_pack(self):
def pack(mode, rawmode):
if len(mode) == 1:
im = Image.new(mode, (1, 1), 1)
else:
im = Image.new(mode, (1, 1), (1, 2, 3, 4)[:len(mode)])
if py3:
return list(im.tobytes("raw", rawmode))
else:
return [ord(c) for c in im.tobytes("raw", rawmode)]
order = 1 if Image._ENDIAN == '<' else -1
self.assertEqual(pack("1", "1"), [128])
self.assertEqual(pack("1", "1;I"), [0])
self.assertEqual(pack("1", "1;R"), [1])
self.assertEqual(pack("1", "1;IR"), [0])
self.assertEqual(pack("L", "L"), [1])
self.assertEqual(pack("I", "I"), [1, 0, 0, 0][::order])
self.assertEqual(pack("F", "F"), [0, 0, 128, 63][::order])
self.assertEqual(pack("LA", "LA"), [1, 2])
self.assertEqual(pack("RGB", "RGB"), [1, 2, 3])
self.assertEqual(pack("RGB", "RGB;L"), [1, 2, 3])
self.assertEqual(pack("RGB", "BGR"), [3, 2, 1])
self.assertEqual(pack("RGB", "RGBX"), [1, 2, 3, 255]) # 255?
self.assertEqual(pack("RGB", "BGRX"), [3, 2, 1, 0])
self.assertEqual(pack("RGB", "XRGB"), [0, 1, 2, 3])
self.assertEqual(pack("RGB", "XBGR"), [0, 3, 2, 1])
self.assertEqual(pack("RGBX", "RGBX"), [1, 2, 3, 4]) # 4->255?
self.assertEqual(pack("RGBA", "RGBA"), [1, 2, 3, 4])
self.assertEqual(pack("CMYK", "CMYK"), [1, 2, 3, 4])
self.assertEqual(pack("YCbCr", "YCbCr"), [1, 2, 3])
def test_unpack(self):
def unpack(mode, rawmode, bytes_):
im = None
if py3:
data = bytes(range(1, bytes_+1))
else:
data = ''.join(chr(i) for i in range(1, bytes_+1))
im = Image.frombytes(mode, (1, 1), data, "raw", rawmode, 0, 1)
return im.getpixel((0, 0))
def unpack_1(mode, rawmode, value):
assert mode == "1"
im = None
if py3:
im = Image.frombytes(
mode, (8, 1), bytes([value]), "raw", rawmode, 0, 1)
else:
im = Image.frombytes(
mode, (8, 1), chr(value), "raw", rawmode, 0, 1)
return tuple(im.getdata())
X = 255
self.assertEqual(unpack_1("1", "1", 1), (0, 0, 0, 0, 0, 0, 0, X))
self.assertEqual(unpack_1("1", "1;I", 1), (X, X, X, X, X, X, X, 0))
self.assertEqual(unpack_1("1", "1;R", 1), (X, 0, 0, 0, 0, 0, 0, 0))
self.assertEqual(unpack_1("1", "1;IR", 1), (0, X, X, X, X, X, X, X))
self.assertEqual(unpack_1("1", "1", 170), (X, 0, X, 0, X, 0, X, 0))
self.assertEqual(unpack_1("1", "1;I", 170), (0, X, 0, X, 0, X, 0, X))
self.assertEqual(unpack_1("1", "1;R", 170), (0, X, 0, X, 0, X, 0, X))
self.assertEqual(unpack_1("1", "1;IR", 170), (X, 0, X, 0, X, 0, X, 0))
self.assertEqual(unpack("L", "L;2", 1), 0)
self.assertEqual(unpack("L", "L;4", 1), 0)
self.assertEqual(unpack("L", "L", 1), 1)
self.assertEqual(unpack("L", "L;I", 1), 254)
self.assertEqual(unpack("L", "L;R", 1), 128)
self.assertEqual(unpack("L", "L;16", 2), 2) # little endian
self.assertEqual(unpack("L", "L;16B", 2), 1) # big endian
self.assertEqual(unpack("LA", "LA", 2), (1, 2))
self.assertEqual(unpack("LA", "LA;L", 2), (1, 2))
self.assertEqual(unpack("RGB", "RGB", 3), (1, 2, 3))
self.assertEqual(unpack("RGB", "RGB;L", 3), (1, 2, 3))
self.assertEqual(unpack("RGB", "RGB;R", 3), (128, 64, 192))
self.assertEqual(unpack("RGB", "RGB;16B", 6), (1, 3, 5)) # ?
self.assertEqual(unpack("RGB", "BGR", 3), (3, 2, 1))
self.assertEqual(unpack("RGB", "RGB;15", 2), (8, 131, 0))
self.assertEqual(unpack("RGB", "BGR;15", 2), (0, 131, 8))
self.assertEqual(unpack("RGB", "RGB;16", 2), (8, 64, 0))
self.assertEqual(unpack("RGB", "BGR;16", 2), (0, 64, 8))
self.assertEqual(unpack("RGB", "RGB;4B", 2), (17, 0, 34))
self.assertEqual(unpack("RGB", "RGBX", 4), (1, 2, 3))
self.assertEqual(unpack("RGB", "BGRX", 4), (3, 2, 1))
self.assertEqual(unpack("RGB", "XRGB", 4), (2, 3, 4))
self.assertEqual(unpack("RGB", "XBGR", 4), (4, 3, 2))
self.assertEqual(unpack("RGBA", "RGBA", 4), (1, 2, 3, 4))
self.assertEqual(unpack("RGBA", "BGRA", 4), (3, 2, 1, 4))
self.assertEqual(unpack("RGBA", "ARGB", 4), (2, 3, 4, 1))
self.assertEqual(unpack("RGBA", "ABGR", 4), (4, 3, 2, 1))
self.assertEqual(unpack("RGBA", "RGBA;15", 2), (8, 131, 0, 0))
self.assertEqual(unpack("RGBA", "BGRA;15", 2), (0, 131, 8, 0))
self.assertEqual(unpack("RGBA", "RGBA;4B", 2), (17, 0, 34, 0))
self.assertEqual(unpack("RGBX", "RGBX", 4), (1, 2, 3, 4)) # 4->255?
self.assertEqual(unpack("RGBX", "BGRX", 4), (3, 2, 1, 255))
self.assertEqual(unpack("RGBX", "XRGB", 4), (2, 3, 4, 255))
self.assertEqual(unpack("RGBX", "XBGR", 4), (4, 3, 2, 255))
self.assertEqual(unpack("RGBX", "RGB;15", 2), (8, 131, 0, 255))
self.assertEqual(unpack("RGBX", "BGR;15", 2), (0, 131, 8, 255))
self.assertEqual(unpack("RGBX", "RGB;4B", 2), (17, 0, 34, 255))
self.assertEqual(unpack("CMYK", "CMYK", 4), (1, 2, 3, 4))
self.assertEqual(unpack("CMYK", "CMYK;I", 4), (254, 253, 252, 251))
self.assertRaises(ValueError, lambda: unpack("L", "L", 0))
self.assertRaises(ValueError, lambda: unpack("RGB", "RGB", 2))
self.assertRaises(ValueError, lambda: unpack("CMYK", "CMYK", 2))
if __name__ == '__main__':
unittest.main()
# End of file

39
test/test_locale.py Normal file
View File

@ -0,0 +1,39 @@
from helper import unittest, PillowTestCase, lena
from PIL import Image
import locale
# ref https://github.com/python-pillow/Pillow/issues/272
# on windows, in polish locale:
# import locale
# print locale.setlocale(locale.LC_ALL, 'polish')
# import string
# print len(string.whitespace)
# print ord(string.whitespace[6])
# Polish_Poland.1250
# 7
# 160
# one of string.whitespace is not freely convertable into ascii.
path = "Images/lena.jpg"
class TestLocale(PillowTestCase):
def test_sanity(self):
Image.open(path)
try:
locale.setlocale(locale.LC_ALL, "polish")
except:
unittest.skip('Polish locale not available')
Image.open(path)
if __name__ == '__main__':
unittest.main()
# End of file