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 name, ext = os.path.splitext(os.path.basename(self.cmd[0]))
247 self.trace_file = os.path.abspath(os.path.join(self.results, name + '.trace'))
248 if os.path.exists(self.trace_file):
249 os.remove(self.trace_file)
251 trace_dir = os.path.dirname(self.trace_file)
252 if not os.path.exists(trace_dir):
253 os.makedirs(trace_dir)
256 env = os.environ.copy()
258 system = platform.system()
260 if system == 'Windows':
261 wrapper = _get_build_path('wrappers/opengl32.dll')
262 local_wrapper = os.path.join(os.path.dirname(self.cmd[0]), os.path.basename(wrapper))
263 shutil.copy(wrapper, local_wrapper)
264 env['TRACE_FILE'] = str(self.trace_file)
266 apitrace = _get_build_program('apitrace')
269 '--api', self.api_map[self.api],
270 '--output', self.trace_file,
273 if self.max_frames is not None:
274 env['TRACE_FRAMES'] = str(self.max_frames)
277 p = popen(cmd, env=env, cwd=self.cwd)
280 if local_wrapper is not None:
281 os.remove(local_wrapper)
283 if not os.path.exists(self.trace_file):
284 fail('no trace file generated\n')
286 def checkTrace(self):
287 cmd = [_get_build_program('apitrace'), 'dump', '--color=never', self.trace_file]
288 p = popen(cmd, stdout=subprocess.PIPE)
290 checker = TraceChecker(p.stdout, self.ref_dump, self.verbose)
293 if p.returncode != 0:
294 fail('`apitrace dump` returned code %i' % p.returncode)
296 self.doubleBuffer = checker.doubleBuffer
298 for callNo, refImageFileName in checker.images:
299 self.checkImage(callNo, refImageFileName)
300 for callNo, refStateFileName in checker.states:
301 self.checkState(callNo, refStateFileName)
303 def checkImage(self, callNo, refImageFileName):
304 srcImage = self.getImage(callNo)
305 refImage = Image.open(refImageFileName)
307 from snapdiff import Comparer
308 comparer = Comparer(refImage, srcImage)
309 match = comparer.ae()
311 prefix = '%s.%u' % (self.getNamePrefix(), callNo)
312 srcImageFileName = prefix + '.src.png'
313 srcImage.save(srcImageFileName)
314 diffImageFileName = prefix + '.diff.png'
315 comparer.write_diff(diffImageFileName)
316 fail('snapshot from call %u does not match %s' % (callNo, refImageFileName))
318 def checkState(self, callNo, refStateFileName):
319 srcState = self.getState(callNo)
320 refState = self.getRefState(refStateFileName)
322 from jsondiff import Comparer, Differ
323 comparer = Comparer(ignore_added = True)
324 match = comparer.visit(refState, srcState)
326 prefix = '%s.%u' % (self.getNamePrefix(), callNo)
327 srcStateFileName = prefix + '.src.json'
328 diffStateFileName = prefix + '.diff.json'
329 self.saveState(srcState, srcStateFileName)
330 #diffStateFile = open(diffStateFileName, 'wt')
331 diffStateFile = sys.stdout
332 differ = Differ(diffStateFile, ignore_added = True)
333 differ.visit(refState, srcState)
334 fail('state from call %u does not match %s' % (callNo, refStateFileName))
336 def getRefState(self, refStateFileName):
337 stream = open(refStateFileName, 'rt')
338 from jsondiff import load
342 def getNamePrefix(self):
343 name = os.path.basename(self.ref_dump)
345 index = name.index('.')
352 def saveState(self, state, filename):
353 s = json.dumps(state, sort_keys=True, indent=2)
354 open(filename, 'wt').write(s)
359 if p.returncode != 0:
360 fail('retrace failed with code %i' % (p.returncode))
362 def getImage(self, callNo):
363 state = self.getState(callNo)
364 if self.doubleBuffer:
365 attachments = ['GL_BACK', 'GL_BACK_LEFT', 'GL_BACK_RIGHT', 'GL_COLOR_ATTACHMENT0']
367 attachments = ['GL_FRONT', 'GL_FRONT_LEFT', 'GL_FRONT_RIGHT', 'GL_COLOR_ATTACHMENT0']
368 imageObj = self.getFramebufferAttachment(state, attachments)
369 data = imageObj['__data__']
370 stream = StringIO(base64.b64decode(data))
371 im = Image.open(stream)
375 def getFramebufferAttachment(self, state, attachments):
376 framebufferObj = state['framebuffer']
377 for attachment in attachments:
379 attachmentObj = framebufferObj[attachment]
384 raise Exception("no attachment found")
386 def getState(self, callNo):
388 state = self.stateCache[callNo]
394 p = self._retrace(['-D', str(callNo)])
395 state = json.load(p.stdout, strict=False)
397 if p.returncode != 0:
398 fail('retrace returned code %i' % (p.returncode))
400 self.adjustSrcState(state)
402 self.stateCache[callNo] = state
406 def adjustSrcState(self, state):
407 # Do some adjustments on the obtained state to eliminate failures from
408 # bugs/issues outside of apitrace
411 parameters = state['parameters']
415 # On NVIDIA drivers glGetIntegerv(GL_INDEX_WRITEMASK) returns -1
416 self.replaceState(parameters, 'GL_INDEX_WRITEMASK', 255, -1)
419 if 'Gallium' in parameters['GL_RENDERER'].split():
420 # Gallium drivers have wrong defaults for draw/read buffer state
421 self.replaceState(parameters, 'GL_DRAW_BUFFER', 'GL_BACK_LEFT', 'GL_BACK')
422 self.replaceState(parameters, 'GL_DRAW_BUFFER0', 'GL_BACK_LEFT', 'GL_BACK')
423 self.replaceState(parameters, 'GL_READ_BUFFER', 'GL_BACK_LEFT', 'GL_BACK')
424 self.replaceState(parameters, 'GL_DRAW_BUFFER', 'GL_FRONT_LEFT', 'GL_FRONT')
425 self.replaceState(parameters, 'GL_DRAW_BUFFER0', 'GL_FRONT_LEFT', 'GL_FRONT')
426 self.replaceState(parameters, 'GL_READ_BUFFER', 'GL_FRONT_LEFT', 'GL_FRONT')
428 def adjustRefState(self, state):
429 # Do some adjustments on reference state to eliminate failures from
430 # bugs/issues outside of apitrace
433 parameters = state['parameters']
437 if platform.system() == 'Darwin' or True:
438 # Mac OS X drivers fail on GL_COLOR_SUM
439 # XXX: investigate this
440 self.removeState(parameters, 'GL_COLOR_SUM')
442 def replaceState(self, obj, key, srcValue, dstValue):
448 if value == srcValue:
451 def removeState(self, obj, key):
457 def _retrace(self, args = None, stdout=subprocess.PIPE):
458 retrace = self.api_map[self.api] + 'retrace'
459 cmd = [_get_build_program(retrace)]
460 if self.doubleBuffer:
466 cmd += [self.trace_file]
467 return popen(cmd, stdout=stdout)
481 # Parse command line options
482 optparser = optparse.OptionParser(
483 usage='\n\t%prog [options] -- [TRACE|PROGRAM] ...',
485 optparser.add_option(
488 dest="verbose", default=False,
489 help="verbose output")
490 optparser.add_option(
491 '-a', '--api', metavar='API',
492 type='string', dest='api', default='gl',
494 optparser.add_option(
495 '-B', '--build', metavar='PATH',
496 type='string', dest='build', default='..',
497 help='path to apitrace build')
498 optparser.add_option(
499 '-C', '--directory', metavar='PATH',
500 type='string', dest='cwd', default=None,
501 help='change to directory')
502 optparser.add_option(
503 '-R', '--results', metavar='PATH',
504 type='string', dest='results', default='.',
505 help='results directory [default=%default]')
506 optparser.add_option(
507 '--ref-dump', metavar='PATH',
508 type='string', dest='ref_dump', default=None,
509 help='reference dump')
511 (options, args) = optparser.parse_args(sys.argv[1:])
513 optparser.error('an argument must be specified')
515 if not os.path.exists(options.results):
516 os.makedirs(options.results)
518 sys.path.insert(0, _get_source_path('scripts'))
521 test.verbose = options.verbose
523 if args[0].endswith('.trace'):
524 test.trace_file = args[0]
527 test.cwd = options.cwd
528 test.api = options.api
529 test.ref_dump = options.ref_dump
530 test.results = options.results
535 if __name__ == '__main__':