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'])
72 env = kwargs.pop('env')
80 if value != os.environ.get(name, None):
81 sys.stdout.write('%s=%s ' % (name, value))
82 env[name] = str(value)
84 sys.stdout.write(' '.join(command) + '\n')
87 return subprocess.Popen(command, *args, env=env, **kwargs)
90 def _get_build_path(path):
91 if options.build is not None:
92 path = os.path.abspath(os.path.join(options.build, path))
93 if not os.path.exists(path):
94 sys.stderr.write('error: %s does not exist\n' % path)
98 def _get_build_program(program):
99 if platform.system() == 'Windows':
101 return _get_build_path(program)
103 def _get_source_path(path):
104 cache = _get_build_path('CMakeCache.txt')
105 for line in open(cache, 'rt'):
106 if line.startswith('CMAKE_HOME_DIRECTORY:INTERNAL='):
107 _, source_root = line.strip().split('=', 1)
108 return os.path.join(source_root, path)
114 def __init__(self, srcStream, refFileName, verbose=False):
115 self.srcStream = srcStream
116 self.refFileName = refFileName
118 self.refStream = open(refFileName, 'rt')
120 self.refStream = None
121 self.verbose = verbose
122 self.doubleBuffer = False
128 call_re = re.compile(r'^([0-9]+) (\w+)\(')
136 self.consumeRefLine()
137 for line in self.srcStream:
140 sys.stdout.write(line + '\n')
141 mo = self.call_re.match(line)
143 self.callNo = int(mo.group(1))
144 function_name = mo.group(2)
145 if function_name.find('SwapBuffers') != -1 or \
146 line.find('kCGLPFADoubleBuffer') != -1:
148 if function_name in ('glFlush', 'glFinish'):
150 srcLine = line[mo.start(2):]
154 if srcLine == self.refLine:
155 self.consumeRefLine()
158 srcLines.append(srcLine)
162 fail('missing call `%s` (found `%s`)' % (self.refLine, srcLines[0]))
164 fail('missing call %s' % self.refLine)
167 self.doubleBuffer = True
169 self.doubleBuffer = False
171 def consumeRefLine(self):
172 if not self.refStream:
177 line = self.refStream.readline()
181 if line.startswith('#'):
182 self.handlePragma(line)
187 def handlePragma(self, line):
188 pragma, rest = line.split(None, 1)
189 if pragma == '#image':
190 imageFileName = self.getAbsPath(rest)
191 self.images.append((self.callNo, imageFileName))
192 elif pragma == '#state':
193 stateFileName = self.getAbsPath(rest)
194 self.states.append((self.callNo, stateFileName))
198 def getAbsPath(self, path):
199 '''Get the absolute from a path relative to the reference filename'''
200 return os.path.abspath(os.path.join(os.path.dirname(self.refFileName), path))
223 '''Run the application standalone, skipping this test if it fails by
229 p = popen(self.cmd, cwd=self.cwd)
232 skip('application returned code %i' % p.returncode)
245 if self.trace_file is None:
246 if self.ref_dump is not None:
250 name, ext = os.path.splitext(os.path.basename(name))
252 name, ext = os.path.splitext(os.path.basename(name))
253 self.trace_file = os.path.abspath(os.path.join(self.results, name + '.trace'))
254 if os.path.exists(self.trace_file):
255 os.remove(self.trace_file)
257 trace_dir = os.path.dirname(self.trace_file)
258 if not os.path.exists(trace_dir):
259 os.makedirs(trace_dir)
262 env = os.environ.copy()
264 system = platform.system()
266 if system == 'Windows':
267 wrapper = _get_build_path('wrappers/opengl32.dll')
268 local_wrapper = os.path.join(os.path.dirname(self.cmd[0]), os.path.basename(wrapper))
269 shutil.copy(wrapper, local_wrapper)
270 env['TRACE_FILE'] = str(self.trace_file)
272 apitrace = _get_build_program('apitrace')
275 '--api', self.api_map[self.api],
276 '--output', self.trace_file,
279 if self.max_frames is not None:
280 env['TRACE_FRAMES'] = str(self.max_frames)
283 p = popen(cmd, env=env, cwd=self.cwd)
286 if local_wrapper is not None:
287 os.remove(local_wrapper)
289 if not os.path.exists(self.trace_file):
290 fail('no trace file generated\n')
292 def checkTrace(self):
293 cmd = [_get_build_program('apitrace'), 'dump', '--color=never', self.trace_file]
294 p = popen(cmd, stdout=subprocess.PIPE)
296 checker = TraceChecker(p.stdout, self.ref_dump, self.verbose)
299 if p.returncode != 0:
300 fail('`apitrace dump` returned code %i' % p.returncode)
302 self.doubleBuffer = checker.doubleBuffer
304 for callNo, refImageFileName in checker.images:
305 self.checkImage(callNo, refImageFileName)
306 for callNo, refStateFileName in checker.states:
307 self.checkState(callNo, refStateFileName)
309 def checkImage(self, callNo, refImageFileName):
310 srcImage = self.getImage(callNo)
311 refImage = Image.open(refImageFileName)
313 from snapdiff import Comparer
314 comparer = Comparer(refImage, srcImage)
315 match = comparer.ae()
317 prefix = '%s.%u' % (self.getNamePrefix(), callNo)
318 srcImageFileName = prefix + '.src.png'
319 srcImage.save(srcImageFileName)
320 diffImageFileName = prefix + '.diff.png'
321 comparer.write_diff(diffImageFileName)
322 fail('snapshot from call %u does not match %s' % (callNo, refImageFileName))
324 def checkState(self, callNo, refStateFileName):
325 srcState = self.getState(callNo)
326 refState = self.getRefState(refStateFileName)
328 from jsondiff import Comparer, Differ
329 comparer = Comparer(ignore_added = True)
330 match = comparer.visit(refState, srcState)
332 prefix = '%s.%u' % (self.getNamePrefix(), callNo)
333 srcStateFileName = prefix + '.src.json'
334 diffStateFileName = prefix + '.diff.json'
335 self.saveState(srcState, srcStateFileName)
336 #diffStateFile = open(diffStateFileName, 'wt')
337 diffStateFile = sys.stdout
338 differ = Differ(diffStateFile, ignore_added = True)
339 differ.visit(refState, srcState)
340 fail('state from call %u does not match %s' % (callNo, refStateFileName))
342 def getRefState(self, refStateFileName):
343 stream = open(refStateFileName, 'rt')
344 from jsondiff import load
348 def getNamePrefix(self):
349 name = os.path.basename(self.ref_dump)
351 index = name.index('.')
358 def saveState(self, state, filename):
359 s = json.dumps(state, sort_keys=True, indent=2)
360 open(filename, 'wt').write(s)
365 if p.returncode != 0:
366 fail('retrace failed with code %i' % (p.returncode))
368 def getImage(self, callNo):
369 state = self.getState(callNo)
370 if self.doubleBuffer:
371 attachments = ['GL_BACK', 'GL_BACK_LEFT', 'GL_BACK_RIGHT', 'GL_COLOR_ATTACHMENT0']
373 attachments = ['GL_FRONT', 'GL_FRONT_LEFT', 'GL_FRONT_RIGHT', 'GL_COLOR_ATTACHMENT0']
374 imageObj = self.getFramebufferAttachment(state, attachments)
375 data = imageObj['__data__']
376 stream = StringIO(base64.b64decode(data))
377 im = Image.open(stream)
381 def getFramebufferAttachment(self, state, attachments):
382 framebufferObj = state['framebuffer']
383 for attachment in attachments:
385 attachmentObj = framebufferObj[attachment]
390 raise Exception("no attachment found")
392 def getState(self, callNo):
394 state = self.stateCache[callNo]
400 p = self._retrace(['-D', str(callNo)])
401 state = json.load(p.stdout, strict=False)
403 if p.returncode != 0:
404 fail('retrace returned code %i' % (p.returncode))
406 self.adjustSrcState(state)
408 self.stateCache[callNo] = state
412 def adjustSrcState(self, state):
413 # Do some adjustments on the obtained state to eliminate failures from
414 # bugs/issues outside of apitrace
417 parameters = state['parameters']
421 # On NVIDIA drivers glGetIntegerv(GL_INDEX_WRITEMASK) returns -1
422 self.replaceState(parameters, 'GL_INDEX_WRITEMASK', 255, -1)
425 if 'Gallium' in parameters['GL_RENDERER'].split():
426 # Gallium drivers have wrong defaults for draw/read buffer state
427 self.replaceState(parameters, 'GL_DRAW_BUFFER', 'GL_BACK_LEFT', 'GL_BACK')
428 self.replaceState(parameters, 'GL_DRAW_BUFFER0', 'GL_BACK_LEFT', 'GL_BACK')
429 self.replaceState(parameters, 'GL_READ_BUFFER', 'GL_BACK_LEFT', 'GL_BACK')
430 self.replaceState(parameters, 'GL_DRAW_BUFFER', 'GL_FRONT_LEFT', 'GL_FRONT')
431 self.replaceState(parameters, 'GL_DRAW_BUFFER0', 'GL_FRONT_LEFT', 'GL_FRONT')
432 self.replaceState(parameters, 'GL_READ_BUFFER', 'GL_FRONT_LEFT', 'GL_FRONT')
434 def adjustRefState(self, state):
435 # Do some adjustments on reference state to eliminate failures from
436 # bugs/issues outside of apitrace
439 parameters = state['parameters']
443 if platform.system() == 'Darwin' or True:
444 # Mac OS X drivers fail on GL_COLOR_SUM
445 # XXX: investigate this
446 self.removeState(parameters, 'GL_COLOR_SUM')
448 def replaceState(self, obj, key, srcValue, dstValue):
454 if value == srcValue:
457 def removeState(self, obj, key):
463 def _retrace(self, args = None, stdout=subprocess.PIPE):
464 retrace = self.api_map[self.api] + 'retrace'
465 cmd = [_get_build_program(retrace)]
466 if self.doubleBuffer:
472 cmd += [self.trace_file]
473 return popen(cmd, stdout=stdout)
487 # Parse command line options
488 optparser = optparse.OptionParser(
489 usage='\n\t%prog [options] -- [TRACE|PROGRAM] ...',
491 optparser.add_option(
494 dest="verbose", default=False,
495 help="verbose output")
496 optparser.add_option(
497 '-a', '--api', metavar='API',
498 type='string', dest='api', default='gl',
500 optparser.add_option(
501 '-B', '--build', metavar='PATH',
502 type='string', dest='build', default='..',
503 help='path to apitrace build')
504 optparser.add_option(
505 '-C', '--directory', metavar='PATH',
506 type='string', dest='cwd', default=None,
507 help='change to directory')
508 optparser.add_option(
509 '-R', '--results', metavar='PATH',
510 type='string', dest='results', default='.',
511 help='results directory [default=%default]')
512 optparser.add_option(
513 '--ref-dump', metavar='PATH',
514 type='string', dest='ref_dump', default=None,
515 help='reference dump')
517 (options, args) = optparser.parse_args(sys.argv[1:])
519 optparser.error('an argument must be specified')
521 if not os.path.exists(options.results):
522 os.makedirs(options.results)
524 sys.path.insert(0, _get_source_path('scripts'))
527 test.verbose = options.verbose
529 if args[0].endswith('.trace'):
530 test.trace_file = args[0]
533 test.cwd = options.cwd
534 test.api = options.api
535 test.ref_dump = options.ref_dump
536 test.results = options.results
541 if __name__ == '__main__':