~inkscape.dev/inkscape-rendertest/trunk

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
#!/bin/env python
from __future__ import with_statement
from datetime import datetime
from glob import iglob
from optparse import OptionParser
import fnmatch, os, subprocess
import json

# Parse commandline parameters
parser = OptionParser(usage="usage: %prog [options] test*")
parser.add_option("-d", "--directory", dest="directory", help="test directory", default=".")
parser.add_option("-i", "--inkscape", dest="inkscape", help="path to inkscape", default="inkscape")
parser.add_option("--compare-png", dest="comparepng", help="PNG comparison tool", default="")
parser.add_option("--timeout", type="int", dest="timeout", help="Time given to Inkscape to render each file (in seconds)", default=20)
(options, args) = parser.parse_args()
#args = ['bugs']
timestamp = datetime.utcnow().isoformat();

# Directories/tails
testDirectory = os.path.join(os.getcwd(), options.directory)
casesDirectory = os.path.join(testDirectory, 'testcases')
newDirectory = os.path.join(testDirectory, 'output')
passReferencesDirectory = os.path.join(testDirectory, 'references', 'pass')
failReferencesDirectory = os.path.join(testDirectory, 'references', 'fail')
passReferenceTail = '*'
failReferenceTail = '*'
inkscapePath = options.inkscape
executionlog = open('executionlog.txt','wt')
testresults = open('testresults.txt','wt')
try:
    with open('teststatus.json','rt') as f:
        teststatus = json.load(f)
except (IOError,ValueError):
    teststatus = {}

# Get list of all test cases
def getListOfRelativeFilesAndDirs(basedir):
    files = []
    dirs = []
    for (b,dl,fl) in os.walk(basedir):
        relb = b[len(basedir):].lstrip('\\/')
        dirs = dirs+[os.path.join(relb,d) for d in dl]
        files = files+[os.path.join(relb,f) for f in fl]
    return (files,dirs)
def isPatchFile(path):
    (name,ext) = os.path.splitext(path)
    return name.endswith('-patch')
def pathMatches(path,patterns):
    return any([fnmatch.fnmatch(path,p) for p in patterns])
def filterPaths(paths,patterns):
    return filter(lambda path: pathMatches(path,patterns), paths)
def unifyPath(p):
    return p.replace('\\','/')
if args == []:
    testCasePatterns = ['']
else:
    testCasePatterns = args
testCasePatterns = [a+'*' for a in testCasePatterns]
(allTestCases, allTestCaseDirs) = getListOfRelativeFilesAndDirs(casesDirectory)
testCases = filter(lambda rp: not isPatchFile(rp), allTestCases)
testCases = filterPaths(testCases, testCasePatterns)
testCaseDirs = filterPaths(allTestCaseDirs, testCasePatterns)
(existingNewFiles, existingNewDirs) = getListOfRelativeFilesAndDirs(newDirectory)
existingNewFiles = filterPaths(existingNewFiles, testCasePatterns)
existingNewDirs = filterPaths(existingNewDirs, testCasePatterns)

# Clean up the 'new' directory
for f in existingNewFiles:
    os.remove(os.path.join(newDirectory,f))
for d in existingNewDirs:
    os.rmdir(os.path.join(newDirectory,d))

# Flag obsolete tests
allTestCasesSet = set(map(unifyPath, allTestCases))
for case in filter(lambda case:case not in allTestCasesSet,teststatus.iterkeys()):
    teststatus[case][timestamp] = -1

# Test definitions
def quoteCmdLineArgument(arg):
    # This only handles spaces and double quotes
    # Note that is procedure is not completely correct when it comes to
    # escaping backslashes. On Windows this is extraordinarily complicated,
    # so it did not really seem worth the trouble (given that it should only
    # give problems if a (group of) backslashe(s) is followed by double quotes).
    # See: http://msdn.microsoft.com/en-us/library/17w5ykft(VS.71).aspx
    #      (Parsing C++ Command-Line Arguments)
    # The shell might even have additional requirements...
    ret = arg.replace('"','\\"')
    haveToQuote = len(ret)!=len(arg) or ret.find(' ')>=0
    if haveToQuote:
        ret = '"' + ret + '"'
    return ret
def isNewerThan(a,b):
    try:
        newer = os.path.getmtime(a) > os.path.getmtime(b)
    except os.error:
        newer = (os.path.exists(a) and not os.path.exists(b))
    return newer
def ensureDirectoryExists(d):
    try:
        os.makedirs(d)
    except EnvironmentError:
        pass
def executeSilently(cmd):
    result = -1
    header = 'Executing: %s' % cmd
    executionlog.write(header + '\n')
    executionlog.write(('-' * len(header)) + '\n')
    executionlog.flush()
    proc = subprocess.Popen(cmd, stdout=executionlog, stderr=executionlog, shell=True)
    result = proc.wait()
    executionlog.flush()
    executionlog.write('\n')
    return result
def executeSilentlyTimed(cmd, timeout):
    result = -1
    header = 'Executing: %s (timeout after %ds)' % cmd, timeout
    executionlog.write(header + '\n')
    executionlog.write(('-' * len(header)) + '\n')
    executionlog.flush()
    proc = subprocess.Popen(cmd, stdout=executionlog, stderr=executionlog, shell=True)

    st = time.time() 
    while (time.time()-st) < timeout:
        time.sleep(1)
        if proc.poll() is not None:
            break
            
    if proc.poll() is None: # timeout was reached, kill the thing
        proc.kill()
        executionlog.write('>>> KILLED INKSCAPE PROCESS <<<')
        return 666

    result = proc.returncode
    executionlog.flush()
    executionlog.write('\n')
    return result

def testRenderSVGtoPNG(name, ext):
    outputName = name + '.png'
    patchFile = os.path.join(casesDirectory, name + '-patch' + ext)
    patchOutput = os.path.join(passReferencesDirectory, name + '-patch.png')
    if os.path.exists(patchFile):
        if isNewerThan(patchFile,patchOutput):
            ensureDirectoryExists(os.path.dirname(patchOutput))
            inkscapeCmd = '%(inkscape)s -e "%(output)s" "%(input)s"' % \
                          {'inkscape': inkscapePath, 'output': patchOutput, 'input': patchFile}
            print "Rendering patch for %s" % name
            result = executeSilently(inkscapeCmd)
            if result != 0:
                return {'result': 40, 'output': outputName}
    elif os.path.exists(patchOutput):
        print "Removing old patch for %s" % name
        os.remove(patchOutput)
    output = os.path.join(newDirectory, outputName)
    ensureDirectoryExists(os.path.split(output)[0])
    inkscapeCmd = '%(inkscape)s -e "%(output)s" "%(input)s"' % \
                  {'inkscape': inkscapePath, 'output': output, 'input': os.path.join(casesDirectory,name+ext)}
    # execute inkscapeCmd, but make sure it does not take longer than x seconds
    result = executeSilentlyTimed(inkscapeCmd, )
    return {'result': result, 'output': outputName}

def testRender(name, ext):
    outputName = name+'.png'
    patchFile = os.path.join(casesDirectory, name+'-patch'+ext)
    patchOutput = os.path.join(passReferencesDirectory, name+'-patch.png')
    if os.path.exists(patchFile):
        if isNewerThan(patchFile,patchOutput):
            ensureDirectoryExists(os.path.dirname(patchOutput))
            inkscapeCmd = '%(inkscape)s -e "%(output)s" "%(input)s"' % \
                          {'inkscape': inkscapePath, 'output': patchOutput, 'input': patchFile}
            print "Rendering patch for %s" % name
            result = executeSilently(inkscapeCmd)
            if result != 0:
                return {'result': 40, 'output': outputName}
    elif os.path.exists(patchOutput):
        print "Removing old patch for %s" % name
        os.remove(patchOutput)
    output = os.path.join(newDirectory, outputName)
    passReferencePattern = os.path.join(passReferencesDirectory, name+passReferenceTail)
    failReferencePattern = os.path.join(failReferencesDirectory, name+failReferenceTail)
    ensureDirectoryExists(os.path.split(output)[0])
    inkscapeCmd = '%(inkscape)s -e "%(output)s" "%(input)s"' % \
                  {'inkscape': inkscapePath, 'output': output, 'input': os.path.join(casesDirectory,name+ext)}
    comparison = (' -compare %s' % quoteCmdLineArgument(options.comparepng)) if len(options.comparepng)>0 else ''
    references = ''.join(' -pass "%s"' % r for r in iglob(passReferencePattern)) + \
                 ''.join(' -fail "%s"' % r for r in iglob(failReferencePattern))
    result = executeSilently('./tester %(cmd)s "%(output)s"%(comparison)s%(references)s' % \
                             {'cmd': quoteCmdLineArgument(inkscapeCmd), \
                              'output': output, 'comparison': comparison, \
                              'references': references})
    return {'result': result, 'output': outputName}

# Perform tests
def extensionOf(tc):
    (path,ext) = os.path.splitext(tc)
    return ext

testHandlers = {'.svg':testRenderSVGtoPNG}
resultCodes = {0: 'Pass', 1: 'Fail', 2: 'New', 3: 'No references', \
               10: 'Error', 11: 'Crash', \
               20: 'Syntax error', 21: 'Unable to stat/open file', \
               30: 'Compare error', 31: 'Compare crash',
               40: 'Error creating reference from patch',
               666: 'Timeout'}
resultCounts = {}
for relpath in testCases:
    (name,ext) = os.path.splitext(relpath)
    handler = testHandlers.get(ext)
    if handler is not None:
        ret = handler(name, ext)
        result = ret['result']
        textResult = '%(name)s: %(result)s' % \
                     {'name': name, \
                      'result': resultCodes.get(result, 'Unknown (%d)' % result)}
        print textResult
        testresults.write(textResult + '\n')
        teststatus.setdefault(unifyPath(relpath),{})[timestamp] = result;
        resultCounts[result] = resultCounts.setdefault(result,0)+1
if len(resultCounts) == 0:
    print "There were no tests!"
else:
    print "Totals:"
    for r,c in resultCounts.iteritems():
        print "  %u %s" % (c, resultCodes[r])
    if resultCounts.get(2,0)>0 or resultCounts.get(3,0)>0:
        print "There were new results and/or test cases without references, please judge the corresponding files in the output directory and put them in either the references/fail directory (if the output is not correct) or the references/pass directory (if the output is correct) and commit."

# Cleanup
executionlog.close()
testresults.close()
with open('teststatus.json','wt') as f:
    json.dump(teststatus, f, indent=2, sort_keys=True)
#    json.dump(teststatus, f, separators=(',',':'))