2 ##########################################################################
4 # Copyright 2011 Jose Fonseca
7 # Permission is hereby granted, free of charge, to any person obtaining a copy
8 # of this software and associated documentation files (the "Software"), to deal
9 # in the Software without restriction, including without limitation the rights
10 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 # copies of the Software, and to permit persons to whom the Software is
12 # furnished to do so, subject to the following conditions:
14 # The above copyright notice and this permission notice shall be included in
15 # all copies or substantial portions of the Software.
17 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 ##########################################################################/
27 '''Main test driver.'''
44 from cStringIO import StringIO
46 from StringIO import StringIO
49 def _exit(status, code, reason=None):
53 reason = ' (%s)' % reason
54 sys.stdout.write('%s%s\n' % (status, reason))
57 def fail(reason=None):
58 _exit('FAIL', 1, reason)
60 def skip(reason=None):
61 _exit('SKIP', 0, reason)
63 def pass_(reason=None):
64 _exit('PASS', 0, reason)
67 def popen(command, *args, **kwargs):
68 if kwargs.get('cwd', None) is not None:
69 sys.stdout.write('cd %s && ' % kwargs['cwd'])
71 for name, value in kwargs['env'].iteritems():
72 if value != os.environ.get(name, None):
73 sys.stdout.write('%s=%s ' % (name, value))
74 sys.stdout.write(' '.join(command) + '\n')
76 return subprocess.Popen(command, *args, **kwargs)
79 def _get_build_path(path):
80 if options.build is not None:
81 path = os.path.abspath(os.path.join(options.build, path))
82 if not os.path.exists(path):
83 sys.stderr.write('error: %s does not exist\n' % path)
87 def _get_build_program(program):
88 if platform.system() == 'Windows':
90 return _get_build_path(program)
92 def _get_source_path(path):
93 cache = _get_build_path('CMakeCache.txt')
94 for line in open(cache, 'rt'):
95 if line.startswith('CMAKE_HOME_DIRECTORY:INTERNAL='):
96 _, source_root = line.strip().split('=', 1)
97 return os.path.join(source_root, path)
103 def __init__(self, srcStream, refFileName, verbose=False):
104 self.srcStream = srcStream
105 self.refFileName = refFileName
107 self.refStream = open(refFileName, 'rt')
109 self.refStream = None
110 self.verbose = verbose
111 self.doubleBuffer = False
117 call_re = re.compile(r'^([0-9]+) (\w+)\(')
125 self.consumeRefLine()
126 for line in self.srcStream:
129 sys.stdout.write(line + '\n')
130 mo = self.call_re.match(line)
132 self.call_no = int(mo.group(1))
133 function_name = mo.group(2)
134 if function_name.find('SwapBuffers') != -1 or \
135 line.find('kCGLPFADoubleBuffer') != -1:
137 if function_name in ('glFlush', 'glFinish'):
139 srcLine = line[mo.start(2):]
143 if srcLine == self.refLine:
144 self.consumeRefLine()
147 srcLines.append(srcLine)
151 fail('missing call `%s` (found `%s`)' % (self.refLine, srcLines[0]))
153 fail('missing call %s' % self.refLine)
156 self.doubleBuffer = True
158 self.doubleBuffer = False
160 def consumeRefLine(self):
161 if not self.refStream:
166 line = self.refStream.readline()
170 if line.startswith('#'):
171 self.handlePragma(line)
176 def handlePragma(self, line):
177 pragma, rest = line.split(None, 1)
178 if pragma == '#image':
179 imageFileName = self.getAbsPath(rest)
180 self.images.append((self.callNo, imageFileName))
181 elif pragma == '#state':
182 stateFileName = self.getAbsPath(rest)
183 self.states.append((self.callNo, stateFileName))
187 def getAbsPath(self, path):
188 '''Get the absolute from a path relative to the reference filename'''
189 return os.path.abspath(os.path.join(os.path.dirname(self.refFileName), path))
212 '''Run the application standalone, skipping this test if it fails by
218 p = popen(self.cmd, cwd=self.cwd)
221 skip('application returned code %i' % p.returncode)
234 if self.trace_file is None:
235 name = os.path.basename(self.cmd[0])
236 self.trace_file = os.path.abspath(os.path.join(self.results, name + '.trace'))
237 if os.path.exists(self.trace_file):
238 os.remove(self.trace_file)
240 trace_dir = os.path.dirname(self.trace_file)
241 if not os.path.exists(trace_dir):
242 os.makedirs(trace_dir)
245 env = os.environ.copy()
247 system = platform.system()
249 if system == 'Windows':
250 wrapper = _get_build_path('wrappers/opengl32.dll')
251 local_wrapper = os.path.join(os.path.dirname(self.cmd[0]), os.path.basename(wrapper))
252 shutil.copy(wrapper, local_wrapper)
253 env['TRACE_FILE'] = self.trace_file
255 apitrace = _get_build_program('apitrace')
258 '--api', self.api_map[self.api],
259 '--output', self.trace_file,
262 if self.max_frames is not None:
263 env['TRACE_FRAMES'] = str(self.max_frames)
266 p = popen(cmd, env=env, cwd=self.cwd)
269 if local_wrapper is not None:
270 os.remove(local_wrapper)
272 if not os.path.exists(self.trace_file):
273 fail('no trace file generated\n')
275 def checkTrace(self):
276 cmd = [_get_build_program('apitrace'), 'dump', '--color=never', self.trace_file]
277 p = popen(cmd, stdout=subprocess.PIPE)
279 checker = TraceChecker(p.stdout, self.ref_dump, self.verbose)
282 if p.returncode != 0:
283 fail('`apitrace dump` returned code %i' % p.returncode)
285 self.doubleBuffer = checker.doubleBuffer
287 for callNo, refImageFileName in checker.images:
288 self.checkImage(callNo, refImageFileName)
289 for callNo, refStateFileName in checker.states:
290 self.checkState(callNo, refStateFileName)
292 def checkImage(self, callNo, refImageFileName):
293 srcImage = self.getImage(callNo)
294 refImage = Image.open(refImageFileName)
296 from snapdiff import Comparer
297 comparer = Comparer(refImage, srcImage)
298 match = comparer.ae()
300 prefix = '%s.%u' % (self.getNamePrefix(), callNo)
301 srcImageFileName = prefix + '.src.png'
302 diffImageFileName = prefix + '.diff.png'
303 comparer.write_diff(diffImageFileName)
304 fail('snapshot from call %u does not match %s' % (callNo, refImageFileName))
306 def checkState(self, callNo, refStateFileName):
307 srcState = self.getState(callNo)
308 refState = json.load(open(refStateFileName, 'rt'), strict=False)
310 from jsondiff import Comparer, Differ
311 comparer = Comparer(ignore_added = True)
312 match = comparer.visit(refState, srcState)
314 prefix = '%s.%u' % (self.getNamePrefix(), callNo)
315 srcStateFileName = prefix + '.src.json'
316 diffStateFileName = prefix + '.diff.json'
317 self.saveState(srcState, srcStateFileName)
318 #diffStateFile = open(diffStateFileName, 'wt')
319 diffStateFile = sys.stdout
320 differ = Differ(diffStateFile, ignore_added = True)
321 differ.visit(refState, srcState)
322 fail('state from call %u does not match %s' % (callNo, refStateFileName))
324 def getNamePrefix(self):
325 name = os.path.basename(self.ref_dump)
327 index = name.index('.')
334 def saveState(self, state, filename):
335 s = json.dumps(state, sort_keys=True, indent=2)
336 open(filename, 'wt').write(s)
341 if p.returncode != 0:
342 fail('retrace failed with code %i' % (p.returncode))
344 def getImage(self, callNo):
345 state = self.getState(callNo)
346 if self.doubleBuffer:
347 attachments = ['GL_BACK', 'GL_BACK_LEFT', 'GL_BACK_RIGHT', 'GL_COLOR_ATTACHMENT0']
349 attachments = ['GL_FRONT', 'GL_FRONT_LEFT', 'GL_FRONT_RIGHT', 'GL_COLOR_ATTACHMENT0']
350 imageObj = self.getFramebufferAttachment(state, attachments)
351 data = imageObj['__data__']
352 stream = StringIO(base64.b64decode(data))
353 im = Image.open(stream)
357 def getFramebufferAttachment(self, state, attachments):
358 framebufferObj = state['framebuffer']
359 for attachment in attachments:
361 attachmentObj = framebufferObj[attachment]
366 raise Exception("no attachment found")
368 def getState(self, callNo):
370 state = self.stateCache[callNo]
376 p = self._retrace(['-D', str(callNo)])
377 state = json.load(p.stdout, strict=False)
379 if p.returncode != 0:
380 fail('retrace returned code %i' % (p.returncode))
382 self.stateCache[callNo] = state
386 def _retrace(self, args = None, stdout=subprocess.PIPE):
387 retrace = self.api_map[self.api] + 'retrace'
388 cmd = [_get_build_path(retrace)]
389 if self.doubleBuffer:
395 cmd += [self.trace_file]
396 return popen(cmd, stdout=stdout)
410 # Parse command line options
411 optparser = optparse.OptionParser(
412 usage='\n\t%prog [options] -- [TRACE|PROGRAM] ...',
414 optparser.add_option(
417 dest="verbose", default=False,
418 help="verbose output")
419 optparser.add_option(
420 '-a', '--api', metavar='API',
421 type='string', dest='api', default='gl',
423 optparser.add_option(
424 '-B', '--build', metavar='PATH',
425 type='string', dest='build', default='..',
426 help='path to apitrace build')
427 optparser.add_option(
428 '-C', '--directory', metavar='PATH',
429 type='string', dest='cwd', default=None,
430 help='change to directory')
431 optparser.add_option(
432 '-R', '--results', metavar='PATH',
433 type='string', dest='results', default='.',
434 help='results directory [default=%default]')
435 optparser.add_option(
436 '--ref-dump', metavar='PATH',
437 type='string', dest='ref_dump', default=None,
438 help='reference dump')
440 (options, args) = optparser.parse_args(sys.argv[1:])
442 optparser.error('an argument must be specified')
444 if not os.path.exists(options.results):
445 os.makedirs(options.results)
447 sys.path.insert(0, _get_source_path('scripts'))
450 test.verbose = options.verbose
452 if args[0].endswith('.trace'):
453 test.trace_file = args[0]
456 test.cwd = options.cwd
457 test.api = options.api
458 test.ref_dump = options.ref_dump
459 test.results = options.results
464 if __name__ == '__main__':