-
-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathtestExamples.py
More file actions
215 lines (168 loc) · 6.82 KB
/
Copy pathtestExamples.py
File metadata and controls
215 lines (168 loc) · 6.82 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
"""Tests for the ``.. downloadcode::`` examples embedded in DrawBot docstrings.
Walks the public API of ``DrawBotDrawingTool``, ``FormattedString``,
``BezierPath``, and ``ImageObject``, extracts every example marked with a
``.. downloadcode:: name.py`` directive in a docstring, and generates a
``test_<name>`` for each one.
"""
import os
import random
import re
import sys
import unittest
import AppKit # type: ignore
from testSupport import StdOutCollector, compareImages, randomSeed, tempTestDataDir, testDataDir, testRootDir
import drawBot
from drawBot.drawBotDrawingTools import DrawBotDrawingTool
_namePattern = re.compile(r"( +).. downloadcode:: ([A-Za-z0-9_]+).py\s*$")
_indentPattern = re.compile(r"( +)")
def _dedent(lines):
minIndentation = 10000
for line in lines:
if not line.strip():
continue
m = _indentPattern.match(line)
if m is not None:
minIndentation = min(minIndentation, len(m.group(1)))
assert minIndentation < 10000
return [line[minIndentation:] for line in lines]
def _collectExamples(modules):
allExamples = {}
names = []
for module in modules:
for n in module.__dict__:
code = None
name = None
indentation = None
if n[0] != "_":
method = getattr(module, n)
if method.__doc__ and "downloadcode" in method.__doc__:
for line in method.__doc__.splitlines() + ["."]:
assert "\t" not in line, (name, repr(line))
if code is None:
m = _namePattern.match(line)
if m is not None:
name = m.group(2)
# print(name)
names.append(name)
indentation = len(m.group(1))
code = []
else:
if not line.strip() and not code:
continue
m = _indentPattern.match(line)
if line.strip() and (m is None or len(m.group(1)) <= indentation):
assert name not in allExamples
allExamples[name] = "\n".join(_dedent(code))
name = None
code = None
indentation = None
else:
code.append(line)
return allExamples
class ExampleTester(unittest.TestCase):
def assertImagesSimilar(self, path1, path2):
similarity = compareImages(path1, path2)
self.assertLessEqual(
similarity, 0.0012, "Images %r and %s are not similar enough: %s" % (path1, path2, similarity)
)
# The examples use an http image path; let's fake it with a local jpeg
mockedImagePath = os.path.join(testRootDir, "data", "drawBot.jpg")
assert os.path.exists(mockedImagePath)
def mockImage(path, position, alpha=1):
if isinstance(path, drawBot.ImageObject):
drawBot.image(path, position, alpha)
else:
drawBot.image(mockedImagePath, position, alpha)
def mockImageSize(path):
return drawBot.imageSize(mockedImagePath)
def mockImagePixelColor(path, xy):
return drawBot.imagePixelColor(mockedImagePath, xy)
def mockVariable(definitions, namespace):
for item in definitions:
name = item["name"]
args = item.get("args", {})
value = args.get("value", None)
if value is None:
# no value is set
uiElement = item["ui"]
if uiElement == "ColorWell":
# in case of a color well
# the default color is black nscolor object
value = AppKit.NSColor.blackColor()
elif uiElement == "Checkbox":
# the default is off
value = False
else:
# fallback to slider value
value = 50
namespace[name] = value
def mockPrintImage(pdf=None):
pass
def mockInstallFont(path):
return "Helvetica"
def mockUninstallFont(path):
pass
def mockRandInt(lo, hi):
# For compatibility between Python 2 and 3
hi += 1
assert lo < hi
extent = hi - lo
return int(lo + extent * random.random())
def _makeTestCase(exampleName, source, doSaveImage):
def test(self):
from drawBot.drawBotDrawingTools import _drawBotDrawingTool
code = compile(source, "<%s>" % exampleName, "exec")
namespace = {}
_drawBotDrawingTool._addToNamespace(namespace)
def mockSaveImage(path, **options):
fileName = "example_mockSaveImage_" + os.path.basename(path)
path = os.path.join(tempTestDataDir, fileName)
drawBot.saveImage(path, **options)
namespace["saveImage"] = mockSaveImage
namespace["image"] = mockImage
namespace["imageSize"] = mockImageSize
namespace["imagePixelColor"] = mockImagePixelColor
namespace["Variable"] = mockVariable
namespace["printImage"] = mockPrintImage
namespace["installFont"] = mockInstallFont
namespace["uninstallFont"] = mockUninstallFont
namespace["randint"] = mockRandInt
randomSeed(0)
drawBot.newDrawing()
with StdOutCollector(captureStdErr=True):
exec(code, namespace)
fileName = "example_%s.png" % exampleName
imagePath = os.path.join(tempTestDataDir, fileName)
expectedImagePath = os.path.join(testDataDir, fileName)
if doSaveImage:
drawBot.saveImage(imagePath)
self.assertImagesSimilar(imagePath, expectedImagePath)
return test
skip = {
"test_imageObject", # skipping, the rendering diff between OS versions is too great
"test_lineHeight", # This fails on Travis. TODO: figure out why.
"test_linkRect", # skipping, we dont compare raw pdf data
}
expectedFailures = {}
dontSaveImage = {"test_imageSize", "test_drawing"}
def _addExampleTests():
allExamples = _collectExamples(
[
DrawBotDrawingTool,
drawBot.FormattedString,
drawBot.BezierPath,
drawBot.ImageObject,
]
)
for exampleName, source in allExamples.items():
testMethodName = "test_%s" % exampleName
testMethod = _makeTestCase(exampleName, source, doSaveImage=testMethodName not in dontSaveImage)
testMethod.__name__ = testMethodName
if testMethodName in expectedFailures:
testMethod = unittest.expectedFailure(testMethod)
if testMethodName in skip:
testMethod = unittest.skip("manual skip")(testMethod)
setattr(ExampleTester, testMethodName, testMethod)
_addExampleTests()
if __name__ == "__main__":
sys.exit(unittest.main())