-
-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathtestExport.py
More file actions
460 lines (389 loc) · 18.2 KB
/
Copy pathtestExport.py
File metadata and controls
460 lines (389 loc) · 18.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
"""Tests for the various ``saveImage`` output formats.
Renders some drawings and saves them to a range of extensions
(``.png``, ``.jpg``, ``.gif``, ``.tif``, ``.svg``, ``.pdf``, ``.mp4``,
``.icns``, etc.), then asserts on file size, dimensions, frame count, or
content.
"""
import glob
import os
import random
import sys
import unittest
import AppKit # type: ignore
import PIL
from testSupport import (
DrawBotBaseTest,
StdOutCollector,
TempFile,
TempFolder,
randomSeed,
readData,
tempTestDataDir,
testDataDir,
)
import drawBot
from drawBot.context.tools.gifTools import gifFrameCount
from drawBot.misc import DrawBotError
class ExportTest(DrawBotBaseTest):
def makeTestAnimation(self, numFrames=25, pageWidth=500, pageHeight=500):
randomSeed(0)
drawBot.newDrawing()
for i in range(numFrames):
drawBot.newPage(pageWidth, pageHeight)
drawBot.frameDuration(1 / 25)
drawBot.fill(1)
drawBot.rect(0, 0, pageWidth, pageHeight)
drawBot.fill(0)
drawBot.rect(random.randint(0, 100), random.randint(0, 100), 400, 400)
def makeTestDrawing(self):
drawBot.newDrawing()
drawBot.newPage(500, 500)
drawBot.oval(100, 100, 300, 300)
def _saveImageAndReturnSize(self, extension, **options):
with TempFile(suffix=extension) as tmp:
drawBot.saveImage(tmp.path, **options)
fileSize = os.stat(tmp.path).st_size
return fileSize
def test_with_drawing(self):
drawBot.newDrawing()
self.assertEqual(drawBot.pageCount(), 0)
with drawBot.drawing():
for i in range(10):
drawBot.newPage()
drawBot.rect(10, 10, 10, 10)
self.assertEqual(drawBot.pageCount(), 10)
self.assertEqual(drawBot.pageCount(), 0)
def test_ffmpegCodec(self):
self.makeTestAnimation()
size_h264 = self._saveImageAndReturnSize(".mp4")
size_mpeg4 = self._saveImageAndReturnSize(".mp4", ffmpegCodec="mpeg4")
self.assertLess(size_h264, size_mpeg4, "encoded with h264 is expected to be smaller than with mpeg4")
def test_arbitraryOption(self):
self.makeTestAnimation(1)
with StdOutCollector(captureStdErr=True) as output:
self._saveImageAndReturnSize(".png", someArbitraryOption="foo")
self.assertEqual(
output.lines(),
["*** DrawBot warning: Unrecognized saveImage() option found for PNGContext: someArbitraryOption ***"],
)
def test_export_gif(self):
self.makeTestAnimation(5)
self._saveImageAndReturnSize(".gif")
def test_export_png(self):
self.makeTestDrawing()
self._saveImageAndReturnSize(".png")
def test_export_jpg(self):
self.makeTestDrawing()
self._saveImageAndReturnSize(".jpg")
def test_export_jpeg(self):
self.makeTestDrawing()
self._saveImageAndReturnSize(".jpeg")
def test_export_tif(self):
self.makeTestDrawing()
self._saveImageAndReturnSize(".tif")
def test_export_tiff(self):
self.makeTestDrawing()
self._saveImageAndReturnSize(".tiff")
def test_export_bmp(self):
self.makeTestDrawing()
self._saveImageAndReturnSize(".bmp")
def test_export_pathlib(self):
import pathlib
self.makeTestDrawing()
with TempFile(suffix=".png") as tmp:
drawBot.saveImage(pathlib.Path(tmp.path))
def test_imageResolution(self):
self.makeTestDrawing()
with TempFile(suffix=".png") as tmp:
drawBot.saveImage(tmp.path)
self.assertEqual(drawBot.imageSize(tmp.path), (500, 500))
drawBot.saveImage(tmp.path, imageResolution=144)
self.assertEqual(drawBot.imageSize(tmp.path), (1000, 1000))
drawBot.saveImage(tmp.path, imageResolution=36)
self.assertEqual(drawBot.imageSize(tmp.path), (250, 250))
drawBot.saveImage(tmp.path, imageResolution=18)
self.assertEqual(drawBot.imageSize(tmp.path), (125, 125))
def test_imagePNGInterlaced(self):
self.makeTestDrawing()
defaultSize = self._saveImageAndReturnSize(".png")
interlacedSize = self._saveImageAndReturnSize(".png", imagePNGInterlaced=True)
# XXX Huh, seems to make no difference, output files are identical
self.assertEqual(defaultSize, interlacedSize)
def test_imagePNGGamma(self):
self.makeTestDrawing()
defaultSize = self._saveImageAndReturnSize(".png")
gammaSize = self._saveImageAndReturnSize(".png", imagePNGGamma=0.8)
self.assertLess(defaultSize, gammaSize)
def test_imageJPEGProgressive(self):
self.makeTestDrawing()
defaultSize = self._saveImageAndReturnSize(".jpg")
progressiveSize = self._saveImageAndReturnSize(".jpg", imageJPEGProgressive=True)
self.assertGreater(defaultSize, progressiveSize)
def test_imageJPEGCompressionFactor(self):
self.makeTestDrawing()
lowCompressionSize = self._saveImageAndReturnSize(".jpg", imageJPEGCompressionFactor=1.0)
mediumCompressionSize = self._saveImageAndReturnSize(".jpg", imageJPEGCompressionFactor=0.5)
highCompressionSize = self._saveImageAndReturnSize(".jpg", imageJPEGCompressionFactor=0.0)
self.assertGreater(lowCompressionSize, mediumCompressionSize)
self.assertGreater(mediumCompressionSize, highCompressionSize)
def test_imageTIFFCompressionMethod(self):
self.makeTestDrawing()
defaultCompressionSize = self._saveImageAndReturnSize(".tif")
noCompressionSize = self._saveImageAndReturnSize(".tif", imageTIFFCompressionMethod=None)
packbitsCompressionSize = self._saveImageAndReturnSize(".tif", imageTIFFCompressionMethod="packbits")
packbits2CompressionSize = self._saveImageAndReturnSize(".tif", imageTIFFCompressionMethod=32773)
packbits3CompressionSize = self._saveImageAndReturnSize(".tif", imageTIFFCompressionMethod="PACKBITS")
lzwCompressionSize = self._saveImageAndReturnSize(".tif", imageTIFFCompressionMethod="lzw")
self.assertEqual(defaultCompressionSize, noCompressionSize)
self.assertEqual(packbitsCompressionSize, packbits2CompressionSize)
self.assertEqual(packbitsCompressionSize, packbits3CompressionSize)
self.assertGreater(noCompressionSize, packbitsCompressionSize)
self.assertGreater(packbitsCompressionSize, lzwCompressionSize)
def test_imageFallbackBackgroundColor(self):
self.makeTestDrawing()
with TempFile(suffix=".jpg") as tmp:
drawBot.saveImage(tmp.path, imageJPEGCompressionFactor=1.0)
self.assertEqual(drawBot.imagePixelColor(tmp.path, (5, 5)), (1.0, 1.0, 1.0, 1.0))
with TempFile(suffix=".jpg") as tmp:
drawBot.saveImage(tmp.path, imageJPEGCompressionFactor=1.0, imageFallbackBackgroundColor=(0, 1, 0))
r, g, b, a = drawBot.imagePixelColor(tmp.path, (5, 5))
self.assertEqual((round(r, 2), round(g, 2), round(b, 2)), (0, 1.0, 0))
with TempFile(suffix=".jpg") as tmp:
drawBot.saveImage(
tmp.path, imageJPEGCompressionFactor=1.0, imageFallbackBackgroundColor=AppKit.NSColor.redColor()
)
r, g, b, a = drawBot.imagePixelColor(tmp.path, (5, 5))
# TODO: fix excessive rounding. 2 digits fails on 10.13, at least on Travis
self.assertEqual((round(r, 1), round(g, 1), round(b, 1)), (1, 0.0, 0))
def test_imageAntiAliasing(self):
expectedPath = os.path.join(testDataDir, "expected_imageAntiAliasing.png")
drawBot.newDrawing()
drawBot.size(100, 100)
drawBot.fill(1, 0, 0)
drawBot.oval(10, 10, 40, 80)
drawBot.fill(0)
drawBot.stroke(0)
drawBot.line((-0.5, -0.5), (100.5, 100.5))
drawBot.line((0, 20.5), (100, 20.5))
drawBot.fontSize(20)
drawBot.text("a", (62, 30))
with TempFile(suffix=".png") as tmp:
drawBot.saveImage(tmp.path, antiAliasing=False)
self.assertImageFilesEqual(tmp.path, expectedPath)
def test_imageFontSubpixelQuantization(self):
expectedPath = os.path.join(testDataDir, "expected_imageFontSubpixelQuantization.png")
drawBot.newDrawing()
drawBot.size(30, 30)
drawBot.fontSize(10)
drawBot.font("Skia")
drawBot.fontVariations(wght=0.789)
drawBot.text("abc\nxyz", (6, 18))
with TempFile(suffix=".png") as tmp:
drawBot.saveImage(tmp.path, fontSubpixelQuantization=False)
self.assertImageFilesEqual(tmp.path, expectedPath)
def _testMultipage(self, extension, numFrames, expectedMultipageCount):
self.makeTestAnimation(numFrames)
with TempFolder() as tmpFolder:
with TempFile(suffix=extension, dir=tmpFolder.path) as tmp:
base, ext = os.path.splitext(tmp.path)
pattern = base + "_*" + ext
self.assertEqual(len(glob.glob(pattern)), 0)
drawBot.saveImage(tmp.path)
self.assertEqual(len(glob.glob(pattern)), 0)
drawBot.saveImage(tmp.path, multipage=False)
self.assertEqual(len(glob.glob(pattern)), 0)
drawBot.saveImage(tmp.path, multipage=True)
self.assertEqual(len(glob.glob(pattern)), expectedMultipageCount)
assert not os.path.exists(tmpFolder.path) # verify TempFolder cleanup
def test_multipage_png(self):
self._testMultipage(".png", numFrames=5, expectedMultipageCount=5)
def test_multipage_jpg(self):
self._testMultipage(".jpg", numFrames=6, expectedMultipageCount=6)
def test_multipage_svg(self):
self._testMultipage(".svg", numFrames=7, expectedMultipageCount=7)
def test_multipage_gif(self):
self._testMultipage(".gif", numFrames=8, expectedMultipageCount=0)
def test_multipage_pdf(self):
self._testMultipage(".pdf", numFrames=9, expectedMultipageCount=0)
def test_animatedGIF(self):
self.makeTestAnimation(5)
with TempFile(suffix=".gif") as tmp:
drawBot.saveImage(tmp.path)
self.assertEqual(gifFrameCount(tmp.path), 5)
def test_saveImage_unknownContext(self):
self.makeTestDrawing()
with self.assertRaises(DrawBotError) as cm:
drawBot.saveImage("foo.abcde")
self.assertEqual(cm.exception.args[0], "Could not find a supported context for: 'abcde'")
def test_saveImage_pathList(self):
self.makeTestDrawing()
with self.assertRaises(TypeError) as cm:
drawBot.saveImage(["foo.abcde"], foo=123)
self.assertEqual(
cm.exception.args[0],
"Cannot apply saveImage options to multiple output formats, expected 'str' or 'os.PathLike', got 'list'",
)
def test_saveImage_png_multipage(self):
self.makeTestDrawing()
with StdOutCollector(captureStdErr=True) as output:
self._saveImageAndReturnSize(".png", multipage=False)
self.assertEqual(output.lines(), [])
def test_saveImage_png_ffmpegCodec(self):
self.makeTestDrawing()
with StdOutCollector(captureStdErr=True) as output:
self._saveImageAndReturnSize(".png", ffmpegCodec="mpeg4")
self.assertEqual(
output.lines(),
["*** DrawBot warning: Unrecognized saveImage() option found for PNGContext: ffmpegCodec ***"],
)
def test_saveImage_mp4_ffmpegCodec(self):
self.makeTestDrawing()
with StdOutCollector(captureStdErr=True) as output:
self._saveImageAndReturnSize(".mp4", ffmpegCodec="mpeg4")
self.assertEqual(output.lines(), [])
def test_saveImage_mp4_imageResolution(self):
self.makeTestDrawing()
with StdOutCollector(captureStdErr=True) as output:
self._saveImageAndReturnSize(".mp4", imageResolution=36)
self.assertEqual(output.lines(), [])
def test_saveImage_mp4_imagePNGGamma(self):
self.makeTestDrawing()
with StdOutCollector(captureStdErr=True) as output:
self._saveImageAndReturnSize(".mp4", imagePNGGamma=0.5)
self.assertEqual(output.lines(), [])
def test_saveImage_mp4_imageJPEGCompressionFactor(self):
self.makeTestDrawing()
with StdOutCollector(captureStdErr=True) as output:
self._saveImageAndReturnSize(".mp4", imageJPEGCompressionFactor=0.5)
self.assertEqual(
output.lines(),
[
"*** DrawBot warning: Unrecognized saveImage() option found for MP4Context: imageJPEGCompressionFactor ***"
],
)
def test_saveImage_mp4_multipage(self):
self.makeTestDrawing()
with StdOutCollector(captureStdErr=True) as output:
self._saveImageAndReturnSize(".mp4", multipage=True)
self.assertEqual(
output.lines(), ["*** DrawBot warning: Unrecognized saveImage() option found for MP4Context: multipage ***"]
)
def test_saveImage_multipage_positionalArgument(self):
self.makeTestDrawing()
with TempFile(suffix=".png") as tmp:
with StdOutCollector(captureStdErr=True) as output:
drawBot.saveImage(tmp.path, False)
self.assertEqual(
output.lines(),
[
"*** DrawBot warning: 'multipage' should be a keyword argument: use 'saveImage(path, multipage=True)' ***"
],
)
def test_saveImage_multiplePositionalArguments(self):
self.makeTestDrawing()
with self.assertRaises(TypeError):
drawBot.saveImage("*", False, "foo")
def test_saveImage_multipage_keywordArgument(self):
self.makeTestDrawing()
with TempFile(suffix=".png") as tmp:
with StdOutCollector(captureStdErr=True) as output:
drawBot.saveImage(tmp.path, multipage=False)
self.assertEqual(output.lines(), [])
def test_saveImage_PIL(self):
self.makeTestDrawing()
image = drawBot.saveImage("PIL")
self.assertIsInstance(image, PIL.Image.Image)
images = drawBot.saveImage("PIL", multipage=True)
for image in images:
self.assertIsInstance(image, PIL.Image.Image)
def test_saveImage_NSImage(self):
self.makeTestDrawing()
image = drawBot.saveImage("NSImage")
self.assertIsInstance(image, AppKit.NSImage)
images = drawBot.saveImage("NSImage", multipage=True)
for image in images:
self.assertIsInstance(image, AppKit.NSImage)
def test_saveImage_returnValue(self):
self.makeTestDrawing()
for ext in (".png", ".pdf", ".gif"):
with TempFile(suffix=ext) as tmp:
result = drawBot.saveImage(tmp.path)
self.assertIsNone(result)
for ext in ("PIL", "NSImage"):
result = drawBot.saveImage(ext)
self.assertIsNotNone(result)
def test_oddPageHeight_mp4(self):
# https://github.com/typemytype/drawbot/issues/250
self.makeTestAnimation(1, pageWidth=200, pageHeight=201)
with TempFile(suffix=".mp4") as tmp:
with self.assertRaises(DrawBotError) as cm:
drawBot.saveImage(tmp.path)
self.assertEqual(
cm.exception.args[0], "Exporting to mp4 doesn't support odd pixel dimensions for width and height."
)
def test_oddPageWidth_mp4(self):
# https://github.com/typemytype/drawbot/issues/250
self.makeTestAnimation(1, pageWidth=201, pageHeight=200)
with TempFile(suffix=".mp4") as tmp:
with self.assertRaises(DrawBotError) as cm:
drawBot.saveImage(tmp.path)
self.assertEqual(
cm.exception.args[0], "Exporting to mp4 doesn't support odd pixel dimensions for width and height."
)
def makeTestICNSDrawing(self, formats):
drawBot.newDrawing()
for i, size in enumerate(formats):
drawBot.newPage(size, size)
f = i / (len(formats) + 1)
drawBot.fill(f, f, 1 - f)
drawBot.rect(0, 0, size, size)
def test_export_icns(self):
self.makeTestICNSDrawing([16, 32, 128, 256, 512, 1024])
self._saveImageAndReturnSize(".icns")
def test_export_icons_invalidPageSize(self):
self.makeTestICNSDrawing([15])
with self.assertRaises(DrawBotError) as cm:
self._saveImageAndReturnSize(".icns")
self.assertEqual(
cm.exception.args[0],
"The .icns can not be build with the size '15x15'. Must be either: 16x16, 32x32, 128x128, 256x256, 512x512, 1024x1024",
)
def test_export_svg_fallbackFont(self):
expectedPath = os.path.join(testDataDir, "expected_svgSaveFallback.svg")
drawBot.newDrawing()
drawBot.newPage(100, 100)
drawBot.fallbackFont("Courier")
drawBot.font("Times")
drawBot.text("a", (10, 10))
path = os.path.join(tempTestDataDir, "svgSaveFallback.svg")
drawBot.saveImage(path)
self.assertEqual(
readData(path), readData(expectedPath), "Files %r and %s are not the same" % (path, expectedPath)
)
def test_linkURL_svg(self):
expectedPath = os.path.join(testDataDir, "expected_svgLinkURL.svg")
drawBot.newDrawing()
drawBot.newPage(200, 200)
drawBot.rect(10, 10, 20, 20)
drawBot.linkURL("http://drawbot.com", (10, 10, 20, 20))
path = os.path.join(tempTestDataDir, "svgLinkURL.svg")
drawBot.saveImage(path)
self.assertEqual(
readData(path), readData(expectedPath), "Files %r and %s are not the same" % (path, expectedPath)
)
def test_formattedStringURL_svg(self):
expectedPath = os.path.join(testDataDir, "expected_formattedStringURL.svg")
drawBot.newDrawing()
drawBot.newPage(200, 200)
drawBot.underline("single")
drawBot.url("http://drawbot.com")
drawBot.text("foo", (10, 10))
path = os.path.join(tempTestDataDir, "formattedStringURL.svg")
drawBot.saveImage(path)
self.assertEqual(
readData(path), readData(expectedPath), "Files %r and %s are not the same" % (path, expectedPath)
)
if __name__ == "__main__":
import doctest
doctest.testmod()
sys.exit(unittest.main())