1 # SPDX-License-Identifier: GPL-2.0
3 from __future__ import print_function
18 import ConfigParser as configparser
21 # Allow multiple values in assignment separated by '|'
27 if (a_item == b_item):
29 elif (a_item == '*') or (b_item == '*'):
34 class Fail(Exception):
35 def __init__(self, test, msg):
39 return '\'%s\' - %s' % (self.test.path, self.msg)
41 class Notest(Exception):
42 def __init__(self, test, arch):
46 return '[%s] \'%s\'' % (self.arch, self.test.path)
48 class Unsup(Exception):
49 def __init__(self, test):
52 return '\'%s\'' % self.test.path
84 'exclude_callchain_kernel',
85 'exclude_callchain_user',
97 log.debug(" %s = %s" % (key, val))
100 def __init__(self, name, data, base):
101 log.debug(" Event %s" % name);
107 def equal(self, other):
108 for t in Event.terms:
109 log.debug(" [%s] %s %s" % (t, self[t], other[t]));
110 if t not in self or t not in other:
112 if not data_equal(self[t], other[t]):
117 if 'optional' in self and self['optional'] == '1':
121 def diff(self, other):
122 for t in Event.terms:
123 if t not in self or t not in other:
125 if not data_equal(self[t], other[t]):
126 log.warning("expected %s=%s, got %s" % (t, self[t], other[t]))
128 # Test file description needs to have following sections:
130 # - just single instance in file
131 # - needs to specify:
132 # 'command' - perf command name
133 # 'args' - special command arguments
134 # 'ret' - Skip test if Perf doesn't exit with this value (0 by default)
135 # 'test_ret'- If set to 'true', fail test instead of skipping for 'ret' argument
136 # 'arch' - architecture specific test (optional)
137 # comma separated list, ! at the beginning
139 # 'auxv' - Truthy statement that is evaled in the scope of the auxv map. When false,
140 # the test is skipped. For example 'auxv["AT_HWCAP"] == 10'. (optional)
143 # - one or multiple instances in file
144 # - expected values assignments
146 def __init__(self, path, options):
147 parser = configparser.SafeConfigParser()
150 log.warning("running '%s'" % path)
153 self.test_dir = options.test_dir
154 self.perf = options.perf
155 self.command = parser.get('config', 'command')
156 self.args = parser.get('config', 'args')
159 self.ret = parser.get('config', 'ret')
163 self.test_ret = parser.getboolean('config', 'test_ret', fallback=False)
166 self.arch = parser.get('config', 'arch')
167 log.warning("test limitation '%s'" % self.arch)
171 self.auxv = parser.get('config', 'auxv', fallback=None)
174 log.debug(" loading expected events");
175 self.load_events(path, self.expect)
177 def is_event(self, name):
178 if name.find("event") == -1:
183 def skip_test_auxv(self):
184 def new_auxv(a, pattern):
185 items = list(filter(None, pattern.split(a)))
186 # AT_HWCAP is hex but doesn't have a prefix, so special case it
187 if items[0] == "AT_HWCAP":
188 value = int(items[-1], 16)
191 value = int(items[-1], 0)
194 return (items[0], value)
198 auxv = subprocess.check_output("LD_SHOW_AUXV=1 sleep 0", shell=True) \
199 .decode(sys.stdout.encoding)
200 pattern = re.compile(r"[: ]+")
201 auxv = dict([new_auxv(a, pattern) for a in auxv.splitlines()])
202 return not eval(self.auxv)
204 def skip_test_arch(self, myarch):
205 # If architecture not set always run test
207 # log.warning("test for arch %s is ok" % myarch)
210 # Allow multiple values in assignment separated by ','
211 arch_list = self.arch.split(',')
213 # Handle negated list such as !s390x,ppc
214 if arch_list[0][0] == '!':
215 arch_list[0] = arch_list[0][1:]
216 log.warning("excluded architecture list %s" % arch_list)
217 for arch_item in arch_list:
218 # log.warning("test for %s arch is %s" % (arch_item, myarch))
219 if arch_item == myarch:
223 for arch_item in arch_list:
224 # log.warning("test for architecture '%s' current '%s'" % (arch_item, myarch))
225 if arch_item == myarch:
229 def load_events(self, path, events):
230 parser_event = configparser.SafeConfigParser()
231 parser_event.read(path)
233 # The event record section header contains 'event' word,
234 # optionaly followed by ':' allowing to load 'parent
235 # event' first as a base
236 for section in filter(self.is_event, parser_event.sections()):
238 parser_items = parser_event.items(section);
241 # Read parent event if there's any
243 base = section[section.index(':') + 1:]
244 parser_base = configparser.SafeConfigParser()
245 parser_base.read(self.test_dir + '/' + base)
246 base_items = parser_base.items('event')
248 e = Event(section, parser_items, base_items)
251 def run_cmd(self, tempdir):
252 junk1, junk2, junk3, junk4, myarch = (os.uname())
254 if self.skip_test_arch(myarch):
255 raise Notest(self, myarch)
257 if self.skip_test_auxv():
258 raise Notest(self, "auxv skip")
260 cmd = "PERF_TEST_ATTR=%s %s %s -o %s/perf.data %s" % (tempdir,
261 self.perf, self.command, tempdir, self.args)
262 ret = os.WEXITSTATUS(os.system(cmd))
264 log.info(" '%s' ret '%s', expected '%s'" % (cmd, str(ret), str(self.ret)))
266 if not data_equal(str(ret), str(self.ret)):
268 raise Fail(self, "Perf exit code failure")
272 def compare(self, expect, result):
275 log.debug(" compare");
277 # For each expected event find all matching
278 # events in result. Fail if there's not any.
279 for exp_name, exp_event in expect.items():
282 log.debug(" matching [%s]" % exp_name)
283 for res_name, res_event in result.items():
284 log.debug(" to [%s]" % res_name)
285 if (exp_event.equal(res_event)):
286 exp_list.append(res_name)
289 log.debug(" ->FAIL");
291 log.debug(" match: [%s] matches %s" % (exp_name, str(exp_list)))
293 # we did not any matching event - fail
295 if exp_event.optional():
296 log.debug(" %s does not match, but is optional" % exp_name)
299 log.debug(" res_event is empty");
301 exp_event.diff(res_event)
302 raise Fail(self, 'match failure');
304 match[exp_name] = exp_list
306 # For each defined group in the expected events
307 # check we match the same group in the result.
308 for exp_name, exp_event in expect.items():
309 group = exp_event.group
314 for res_name in match[exp_name]:
315 res_group = result[res_name].group
316 if res_group not in match[group]:
317 raise Fail(self, 'group failure')
319 log.debug(" group: [%s] matches group leader %s" %
320 (exp_name, str(match[group])))
322 log.debug(" matched")
324 def resolve_groups(self, events):
325 for name, event in events.items():
326 group_fd = event['group_fd'];
330 for iname, ievent in events.items():
331 if (ievent['fd'] == group_fd):
333 log.debug('[%s] has group leader [%s]' % (name, iname))
337 tempdir = tempfile.mkdtemp();
340 # run the test script
341 self.run_cmd(tempdir);
343 # load events expectation for the test
344 log.debug(" loading result events");
345 for f in glob.glob(tempdir + '/event*'):
346 self.load_events(f, self.result);
348 # resolve group_fd to event names
349 self.resolve_groups(self.expect);
350 self.resolve_groups(self.result);
352 # do the expectation - results matching - both ways
353 self.compare(self.expect, self.result)
354 self.compare(self.result, self.expect)
358 shutil.rmtree(tempdir)
361 def run_tests(options):
362 for f in glob.glob(options.test_dir + '/' + options.test):
364 Test(f, options).run()
366 log.warning("unsupp %s" % obj.getMsg())
367 except Notest as obj:
368 log.warning("skipped %s" % obj.getMsg())
370 def setup_log(verbose):
372 level = logging.CRITICAL
375 level = logging.WARNING
379 level = logging.DEBUG
381 log = logging.getLogger('test')
383 ch = logging.StreamHandler()
385 formatter = logging.Formatter('%(message)s')
386 ch.setFormatter(formatter)
389 USAGE = '''%s [OPTIONS]
391 -p path # perf binary
392 -t test # single test
397 parser = optparse.OptionParser(usage=USAGE)
399 parser.add_option("-t", "--test",
400 action="store", type="string", dest="test")
401 parser.add_option("-d", "--test-dir",
402 action="store", type="string", dest="test_dir")
403 parser.add_option("-p", "--perf",
404 action="store", type="string", dest="perf")
405 parser.add_option("-v", "--verbose",
406 default=0, action="count", dest="verbose")
408 options, args = parser.parse_args()
410 parser.error('FAILED wrong arguments %s' % ' '.join(args))
413 setup_log(options.verbose)
415 if not options.test_dir:
416 print('FAILED no -d option specified')
420 options.test = 'test*'
426 print("FAILED %s" % obj.getMsg())
431 if __name__ == '__main__':