test.py 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420
  1. #!/usr/bin/env python3
  2. #
  3. # Script to compile and runs tests.
  4. #
  5. # Example:
  6. # ./scripts/test.py runners/test_runner -b
  7. #
  8. # Copyright (c) 2022, The littlefs authors.
  9. # SPDX-License-Identifier: BSD-3-Clause
  10. #
  11. import collections as co
  12. import csv
  13. import errno
  14. import glob
  15. import itertools as it
  16. import math as m
  17. import os
  18. import pty
  19. import re
  20. import shlex
  21. import shutil
  22. import signal
  23. import subprocess as sp
  24. import threading as th
  25. import time
  26. import toml
  27. RUNNER_PATH = './runners/test_runner'
  28. HEADER_PATH = 'runners/test_runner.h'
  29. GDB_TOOL = ['gdb']
  30. VALGRIND_TOOL = ['valgrind']
  31. PERF_SCRIPT = ['./scripts/perf.py']
  32. def openio(path, mode='r', buffering=-1, nb=False):
  33. if path == '-':
  34. if mode == 'r':
  35. return os.fdopen(os.dup(sys.stdin.fileno()), 'r', buffering)
  36. else:
  37. return os.fdopen(os.dup(sys.stdout.fileno()), 'w', buffering)
  38. elif nb and 'a' in mode:
  39. return os.fdopen(os.open(
  40. path,
  41. os.O_WRONLY | os.O_CREAT | os.O_APPEND | os.O_NONBLOCK,
  42. 0o666),
  43. mode,
  44. buffering)
  45. else:
  46. return open(path, mode, buffering)
  47. class TestCase:
  48. # create a TestCase object from a config
  49. def __init__(self, config, args={}):
  50. self.name = config.pop('name')
  51. self.path = config.pop('path')
  52. self.suite = config.pop('suite')
  53. self.lineno = config.pop('lineno', None)
  54. self.if_ = config.pop('if', None)
  55. if isinstance(self.if_, bool):
  56. self.if_ = 'true' if self.if_ else 'false'
  57. self.code = config.pop('code')
  58. self.code_lineno = config.pop('code_lineno', None)
  59. self.in_ = config.pop('in',
  60. config.pop('suite_in', None))
  61. self.reentrant = config.pop('reentrant',
  62. config.pop('suite_reentrant', False))
  63. # figure out defines and build possible permutations
  64. self.defines = set()
  65. self.permutations = []
  66. # defines can be a dict or a list or dicts
  67. suite_defines = config.pop('suite_defines', {})
  68. if not isinstance(suite_defines, list):
  69. suite_defines = [suite_defines]
  70. defines = config.pop('defines', {})
  71. if not isinstance(defines, list):
  72. defines = [defines]
  73. def csplit(v):
  74. # split commas but only outside of parens
  75. parens = 0
  76. i_ = 0
  77. for i in range(len(v)):
  78. if v[i] == ',' and parens == 0:
  79. yield v[i_:i]
  80. i_ = i+1
  81. elif v[i] in '([{':
  82. parens += 1
  83. elif v[i] in '}])':
  84. parens -= 1
  85. if v[i_:].strip():
  86. yield v[i_:]
  87. def parse_define(v):
  88. # a define entry can be a list
  89. if isinstance(v, list):
  90. for v_ in v:
  91. yield from parse_define(v_)
  92. # or a string
  93. elif isinstance(v, str):
  94. # which can be comma-separated values, with optional
  95. # range statements. This matches the runtime define parser in
  96. # the runner itself.
  97. for v_ in csplit(v):
  98. m = re.search(r'\brange\b\s*\('
  99. '(?P<start>[^,\s]*)'
  100. '\s*(?:,\s*(?P<stop>[^,\s]*)'
  101. '\s*(?:,\s*(?P<step>[^,\s]*)\s*)?)?\)',
  102. v_)
  103. if m:
  104. start = (int(m.group('start'), 0)
  105. if m.group('start') else 0)
  106. stop = (int(m.group('stop'), 0)
  107. if m.group('stop') else None)
  108. step = (int(m.group('step'), 0)
  109. if m.group('step') else 1)
  110. if m.lastindex <= 1:
  111. start, stop = 0, start
  112. for x in range(start, stop, step):
  113. yield from parse_define('%s(%d)%s' % (
  114. v_[:m.start()], x, v_[m.end():]))
  115. else:
  116. yield v_
  117. # or a literal value
  118. else:
  119. yield v
  120. # build possible permutations
  121. for suite_defines_ in suite_defines:
  122. self.defines |= suite_defines_.keys()
  123. for defines_ in defines:
  124. self.defines |= defines_.keys()
  125. self.permutations.extend(dict(perm) for perm in it.product(*(
  126. [(k, v) for v in parse_define(vs)]
  127. for k, vs in sorted((suite_defines_ | defines_).items()))))
  128. for k in config.keys():
  129. print('%swarning:%s in %s, found unused key %r' % (
  130. '\x1b[01;33m' if args['color'] else '',
  131. '\x1b[m' if args['color'] else '',
  132. self.name,
  133. k),
  134. file=sys.stderr)
  135. class TestSuite:
  136. # create a TestSuite object from a toml file
  137. def __init__(self, path, args={}):
  138. self.path = path
  139. self.name = os.path.basename(path)
  140. if self.name.endswith('.toml'):
  141. self.name = self.name[:-len('.toml')]
  142. # load toml file and parse test cases
  143. with open(self.path) as f:
  144. # load tests
  145. config = toml.load(f)
  146. # find line numbers
  147. f.seek(0)
  148. case_linenos = []
  149. code_linenos = []
  150. for i, line in enumerate(f):
  151. match = re.match(
  152. '(?P<case>\[\s*cases\s*\.\s*(?P<name>\w+)\s*\])'
  153. '|' '(?P<code>code\s*=)',
  154. line)
  155. if match and match.group('case'):
  156. case_linenos.append((i+1, match.group('name')))
  157. elif match and match.group('code'):
  158. code_linenos.append(i+2)
  159. # sort in case toml parsing did not retain order
  160. case_linenos.sort()
  161. cases = config.pop('cases')
  162. for (lineno, name), (nlineno, _) in it.zip_longest(
  163. case_linenos, case_linenos[1:],
  164. fillvalue=(float('inf'), None)):
  165. code_lineno = min(
  166. (l for l in code_linenos if l >= lineno and l < nlineno),
  167. default=None)
  168. cases[name]['lineno'] = lineno
  169. cases[name]['code_lineno'] = code_lineno
  170. self.if_ = config.pop('if', None)
  171. if isinstance(self.if_, bool):
  172. self.if_ = 'true' if self.if_ else 'false'
  173. self.code = config.pop('code', None)
  174. self.code_lineno = min(
  175. (l for l in code_linenos
  176. if not case_linenos or l < case_linenos[0][0]),
  177. default=None)
  178. # a couple of these we just forward to all cases
  179. defines = config.pop('defines', {})
  180. in_ = config.pop('in', None)
  181. reentrant = config.pop('reentrant', False)
  182. self.cases = []
  183. for name, case in sorted(cases.items(),
  184. key=lambda c: c[1].get('lineno')):
  185. self.cases.append(TestCase(config={
  186. 'name': name,
  187. 'path': path + (':%d' % case['lineno']
  188. if 'lineno' in case else ''),
  189. 'suite': self.name,
  190. 'suite_defines': defines,
  191. 'suite_in': in_,
  192. 'suite_reentrant': reentrant,
  193. **case},
  194. args=args))
  195. # combine per-case defines
  196. self.defines = set.union(*(
  197. set(case.defines) for case in self.cases))
  198. # combine other per-case things
  199. self.reentrant = any(case.reentrant for case in self.cases)
  200. for k in config.keys():
  201. print('%swarning:%s in %s, found unused key %r' % (
  202. '\x1b[01;33m' if args['color'] else '',
  203. '\x1b[m' if args['color'] else '',
  204. self.name,
  205. k),
  206. file=sys.stderr)
  207. def compile(test_paths, **args):
  208. # find .toml files
  209. paths = []
  210. for path in test_paths:
  211. if os.path.isdir(path):
  212. path = path + '/*.toml'
  213. for path in glob.glob(path):
  214. paths.append(path)
  215. if not paths:
  216. print('no test suites found in %r?' % test_paths)
  217. sys.exit(-1)
  218. # load the suites
  219. suites = [TestSuite(path, args) for path in paths]
  220. suites.sort(key=lambda s: s.name)
  221. # check for name conflicts, these will cause ambiguity problems later
  222. # when running tests
  223. seen = {}
  224. for suite in suites:
  225. if suite.name in seen:
  226. print('%swarning:%s conflicting suite %r, %s and %s' % (
  227. '\x1b[01;33m' if args['color'] else '',
  228. '\x1b[m' if args['color'] else '',
  229. suite.name,
  230. suite.path,
  231. seen[suite.name].path),
  232. file=sys.stderr)
  233. seen[suite.name] = suite
  234. for case in suite.cases:
  235. # only allow conflicts if a case and its suite share a name
  236. if case.name in seen and not (
  237. isinstance(seen[case.name], TestSuite)
  238. and seen[case.name].cases == [case]):
  239. print('%swarning:%s conflicting case %r, %s and %s' % (
  240. '\x1b[01;33m' if args['color'] else '',
  241. '\x1b[m' if args['color'] else '',
  242. case.name,
  243. case.path,
  244. seen[case.name].path),
  245. file=sys.stderr)
  246. seen[case.name] = case
  247. # we can only compile one test suite at a time
  248. if not args.get('source'):
  249. if len(suites) > 1:
  250. print('more than one test suite for compilation? (%r)' % test_paths)
  251. sys.exit(-1)
  252. suite = suites[0]
  253. # write generated test source
  254. if 'output' in args:
  255. with openio(args['output'], 'w') as f:
  256. _write = f.write
  257. def write(s):
  258. f.lineno += s.count('\n')
  259. _write(s)
  260. def writeln(s=''):
  261. f.lineno += s.count('\n') + 1
  262. _write(s)
  263. _write('\n')
  264. f.lineno = 1
  265. f.write = write
  266. f.writeln = writeln
  267. f.writeln("// Generated by %s:" % sys.argv[0])
  268. f.writeln("//")
  269. f.writeln("// %s" % ' '.join(sys.argv))
  270. f.writeln("//")
  271. f.writeln()
  272. # include test_runner.h in every generated file
  273. f.writeln("#include \"%s\"" % args['include'])
  274. f.writeln()
  275. # write out generated functions, this can end up in different
  276. # files depending on the "in" attribute
  277. #
  278. # note it's up to the specific generated file to declare
  279. # the test defines
  280. def write_case_functions(f, suite, case):
  281. # create case define functions
  282. if case.defines:
  283. # deduplicate defines by value to try to reduce the
  284. # number of functions we generate
  285. define_cbs = {}
  286. for i, defines in enumerate(case.permutations):
  287. for k, v in sorted(defines.items()):
  288. if v not in define_cbs:
  289. name = ('__test__%s__%s__%s__%d'
  290. % (suite.name, case.name, k, i))
  291. define_cbs[v] = name
  292. f.writeln('intmax_t %s('
  293. '__attribute__((unused)) '
  294. 'void *data) {' % name)
  295. f.writeln(4*' '+'return %s;' % v)
  296. f.writeln('}')
  297. f.writeln()
  298. f.writeln('const test_define_t '
  299. '__test__%s__%s__defines[]['
  300. 'TEST_IMPLICIT_DEFINE_COUNT+%d] = {'
  301. % (suite.name, case.name, len(suite.defines)))
  302. for defines in case.permutations:
  303. f.writeln(4*' '+'{')
  304. for k, v in sorted(defines.items()):
  305. f.writeln(8*' '+'[%-24s] = {%s, NULL},' % (
  306. k+'_i', define_cbs[v]))
  307. f.writeln(4*' '+'},')
  308. f.writeln('};')
  309. f.writeln()
  310. # create case filter function
  311. if suite.if_ is not None or case.if_ is not None:
  312. f.writeln('bool __test__%s__%s__filter(void) {'
  313. % (suite.name, case.name))
  314. f.writeln(4*' '+'return %s;'
  315. % ' && '.join('(%s)' % if_
  316. for if_ in [suite.if_, case.if_]
  317. if if_ is not None))
  318. f.writeln('}')
  319. f.writeln()
  320. # create case run function
  321. f.writeln('void __test__%s__%s__run('
  322. '__attribute__((unused)) struct lfs_config *cfg) {'
  323. % (suite.name, case.name))
  324. f.writeln(4*' '+'// test case %s' % case.name)
  325. if case.code_lineno is not None:
  326. f.writeln(4*' '+'#line %d "%s"'
  327. % (case.code_lineno, suite.path))
  328. f.write(case.code)
  329. if case.code_lineno is not None:
  330. f.writeln(4*' '+'#line %d "%s"'
  331. % (f.lineno+1, args['output']))
  332. f.writeln('}')
  333. f.writeln()
  334. if not args.get('source'):
  335. if suite.code is not None:
  336. if suite.code_lineno is not None:
  337. f.writeln('#line %d "%s"'
  338. % (suite.code_lineno, suite.path))
  339. f.write(suite.code)
  340. if suite.code_lineno is not None:
  341. f.writeln('#line %d "%s"'
  342. % (f.lineno+1, args['output']))
  343. f.writeln()
  344. if suite.defines:
  345. for i, define in enumerate(sorted(suite.defines)):
  346. f.writeln('#ifndef %s' % define)
  347. f.writeln('#define %-24s '
  348. 'TEST_IMPLICIT_DEFINE_COUNT+%d' % (define+'_i', i))
  349. f.writeln('#define %-24s '
  350. 'TEST_DEFINE(%s)' % (define, define+'_i'))
  351. f.writeln('#endif')
  352. f.writeln()
  353. # create case functions
  354. for case in suite.cases:
  355. if case.in_ is None:
  356. write_case_functions(f, suite, case)
  357. else:
  358. if case.defines:
  359. f.writeln('extern const test_define_t '
  360. '__test__%s__%s__defines[]['
  361. 'TEST_IMPLICIT_DEFINE_COUNT+%d];'
  362. % (suite.name, case.name, len(suite.defines)))
  363. if suite.if_ is not None or case.if_ is not None:
  364. f.writeln('extern bool __test__%s__%s__filter('
  365. 'void);'
  366. % (suite.name, case.name))
  367. f.writeln('extern void __test__%s__%s__run('
  368. 'struct lfs_config *cfg);'
  369. % (suite.name, case.name))
  370. f.writeln()
  371. # create suite struct
  372. #
  373. # note we place this in the custom test_suites section with
  374. # minimum alignment, otherwise GCC ups the alignment to
  375. # 32-bytes for some reason
  376. f.writeln('__attribute__((section("_test_suites"), '
  377. 'aligned(1)))')
  378. f.writeln('const struct test_suite __test__%s__suite = {'
  379. % suite.name)
  380. f.writeln(4*' '+'.name = "%s",' % suite.name)
  381. f.writeln(4*' '+'.path = "%s",' % suite.path)
  382. f.writeln(4*' '+'.flags = %s,'
  383. % (' | '.join(filter(None, [
  384. 'TEST_REENTRANT' if suite.reentrant else None]))
  385. or 0))
  386. if suite.defines:
  387. # create suite define names
  388. f.writeln(4*' '+'.define_names = (const char *const['
  389. 'TEST_IMPLICIT_DEFINE_COUNT+%d]){' % (
  390. len(suite.defines)))
  391. for k in sorted(suite.defines):
  392. f.writeln(8*' '+'[%-24s] = "%s",' % (k+'_i', k))
  393. f.writeln(4*' '+'},')
  394. f.writeln(4*' '+'.define_count = '
  395. 'TEST_IMPLICIT_DEFINE_COUNT+%d,' % len(suite.defines))
  396. f.writeln(4*' '+'.cases = (const struct test_case[]){')
  397. for case in suite.cases:
  398. # create case structs
  399. f.writeln(8*' '+'{')
  400. f.writeln(12*' '+'.name = "%s",' % case.name)
  401. f.writeln(12*' '+'.path = "%s",' % case.path)
  402. f.writeln(12*' '+'.flags = %s,'
  403. % (' | '.join(filter(None, [
  404. 'TEST_REENTRANT' if case.reentrant else None]))
  405. or 0))
  406. f.writeln(12*' '+'.permutations = %d,'
  407. % len(case.permutations))
  408. if case.defines:
  409. f.writeln(12*' '+'.defines '
  410. '= (const test_define_t*)__test__%s__%s__defines,'
  411. % (suite.name, case.name))
  412. if suite.if_ is not None or case.if_ is not None:
  413. f.writeln(12*' '+'.filter = __test__%s__%s__filter,'
  414. % (suite.name, case.name))
  415. f.writeln(12*' '+'.run = __test__%s__%s__run,'
  416. % (suite.name, case.name))
  417. f.writeln(8*' '+'},')
  418. f.writeln(4*' '+'},')
  419. f.writeln(4*' '+'.case_count = %d,' % len(suite.cases))
  420. f.writeln('};')
  421. f.writeln()
  422. else:
  423. # copy source
  424. f.writeln('#line 1 "%s"' % args['source'])
  425. with open(args['source']) as sf:
  426. shutil.copyfileobj(sf, f)
  427. f.writeln()
  428. # write any internal tests
  429. for suite in suites:
  430. for case in suite.cases:
  431. if (case.in_ is not None
  432. and os.path.normpath(case.in_)
  433. == os.path.normpath(args['source'])):
  434. # write defines, but note we need to undef any
  435. # new defines since we're in someone else's file
  436. if suite.defines:
  437. for i, define in enumerate(
  438. sorted(suite.defines)):
  439. f.writeln('#ifndef %s' % define)
  440. f.writeln('#define %-24s '
  441. 'TEST_IMPLICIT_DEFINE_COUNT+%d' % (
  442. define+'_i', i))
  443. f.writeln('#define %-24s '
  444. 'TEST_DEFINE(%s)' % (
  445. define, define+'_i'))
  446. f.writeln('#define '
  447. '__TEST__%s__NEEDS_UNDEF' % (
  448. define))
  449. f.writeln('#endif')
  450. f.writeln()
  451. write_case_functions(f, suite, case)
  452. if suite.defines:
  453. for define in sorted(suite.defines):
  454. f.writeln('#ifdef __TEST__%s__NEEDS_UNDEF'
  455. % define)
  456. f.writeln('#undef __TEST__%s__NEEDS_UNDEF'
  457. % define)
  458. f.writeln('#undef %s' % define)
  459. f.writeln('#undef %s' % (define+'_i'))
  460. f.writeln('#endif')
  461. f.writeln()
  462. def find_runner(runner, **args):
  463. cmd = runner.copy()
  464. # run under some external command?
  465. if args.get('exec'):
  466. cmd[:0] = args['exec']
  467. # run under valgrind?
  468. if args.get('valgrind'):
  469. cmd[:0] = args['valgrind_tool'] + [
  470. '--leak-check=full',
  471. '--track-origins=yes',
  472. '--error-exitcode=4',
  473. '-q']
  474. # run under perf?
  475. if args.get('perf'):
  476. cmd[:0] = args['perf_script'] + list(filter(None, [
  477. '-R',
  478. '--perf-freq=%s' % args['perf_freq']
  479. if args.get('perf_freq') else None,
  480. '--perf-period=%s' % args['perf_period']
  481. if args.get('perf_period') else None,
  482. '--perf-events=%s' % args['perf_events']
  483. if args.get('perf_events') else None,
  484. '--perf-tool=%s' % args['perf_tool']
  485. if args.get('perf_tool') else None,
  486. '-o%s' % args['perf']]))
  487. # other context
  488. if args.get('geometry'):
  489. cmd.append('-G%s' % args['geometry'])
  490. if args.get('powerloss'):
  491. cmd.append('-P%s' % args['powerloss'])
  492. if args.get('disk'):
  493. cmd.append('-d%s' % args['disk'])
  494. if args.get('trace'):
  495. cmd.append('-t%s' % args['trace'])
  496. if args.get('read_sleep'):
  497. cmd.append('--read-sleep=%s' % args['read_sleep'])
  498. if args.get('prog_sleep'):
  499. cmd.append('--prog-sleep=%s' % args['prog_sleep'])
  500. if args.get('erase_sleep'):
  501. cmd.append('--erase-sleep=%s' % args['erase_sleep'])
  502. # defines?
  503. if args.get('define'):
  504. for define in args.get('define'):
  505. cmd.append('-D%s' % define)
  506. return cmd
  507. def list_(runner, test_ids=[], **args):
  508. cmd = find_runner(runner, **args) + test_ids
  509. if args.get('summary'): cmd.append('--summary')
  510. if args.get('list_suites'): cmd.append('--list-suites')
  511. if args.get('list_cases'): cmd.append('--list-cases')
  512. if args.get('list_suite_paths'): cmd.append('--list-suite-paths')
  513. if args.get('list_case_paths'): cmd.append('--list-case-paths')
  514. if args.get('list_defines'): cmd.append('--list-defines')
  515. if args.get('list_permutation_defines'):
  516. cmd.append('--list-permutation-defines')
  517. if args.get('list_implicit_defines'):
  518. cmd.append('--list-implicit-defines')
  519. if args.get('list_geometries'): cmd.append('--list-geometries')
  520. if args.get('list_powerlosses'): cmd.append('--list-powerlosses')
  521. if args.get('verbose'):
  522. print(' '.join(shlex.quote(c) for c in cmd))
  523. return sp.call(cmd)
  524. def find_perms(runner_, ids=[], **args):
  525. case_suites = {}
  526. expected_case_perms = co.defaultdict(lambda: 0)
  527. expected_perms = 0
  528. total_perms = 0
  529. # query cases from the runner
  530. cmd = runner_ + ['--list-cases'] + ids
  531. if args.get('verbose'):
  532. print(' '.join(shlex.quote(c) for c in cmd))
  533. proc = sp.Popen(cmd,
  534. stdout=sp.PIPE,
  535. stderr=sp.PIPE if not args.get('verbose') else None,
  536. universal_newlines=True,
  537. errors='replace',
  538. close_fds=False)
  539. pattern = re.compile(
  540. '^(?P<case>[^\s]+)'
  541. '\s+(?P<flags>[^\s]+)'
  542. '\s+(?P<filtered>\d+)/(?P<perms>\d+)')
  543. # skip the first line
  544. for line in it.islice(proc.stdout, 1, None):
  545. m = pattern.match(line)
  546. if m:
  547. filtered = int(m.group('filtered'))
  548. perms = int(m.group('perms'))
  549. expected_case_perms[m.group('case')] += filtered
  550. expected_perms += filtered
  551. total_perms += perms
  552. proc.wait()
  553. if proc.returncode != 0:
  554. if not args.get('verbose'):
  555. for line in proc.stderr:
  556. sys.stdout.write(line)
  557. sys.exit(-1)
  558. # get which suite each case belongs to via paths
  559. cmd = runner_ + ['--list-case-paths'] + ids
  560. if args.get('verbose'):
  561. print(' '.join(shlex.quote(c) for c in cmd))
  562. proc = sp.Popen(cmd,
  563. stdout=sp.PIPE,
  564. stderr=sp.PIPE if not args.get('verbose') else None,
  565. universal_newlines=True,
  566. errors='replace',
  567. close_fds=False)
  568. pattern = re.compile(
  569. '^(?P<case>[^\s]+)'
  570. '\s+(?P<path>[^:]+):(?P<lineno>\d+)')
  571. # skip the first line
  572. for line in it.islice(proc.stdout, 1, None):
  573. m = pattern.match(line)
  574. if m:
  575. path = m.group('path')
  576. # strip path/suffix here
  577. suite = os.path.basename(path)
  578. if suite.endswith('.toml'):
  579. suite = suite[:-len('.toml')]
  580. case_suites[m.group('case')] = suite
  581. proc.wait()
  582. if proc.returncode != 0:
  583. if not args.get('verbose'):
  584. for line in proc.stderr:
  585. sys.stdout.write(line)
  586. sys.exit(-1)
  587. # figure out expected suite perms
  588. expected_suite_perms = co.defaultdict(lambda: 0)
  589. for case, suite in case_suites.items():
  590. expected_suite_perms[suite] += expected_case_perms[case]
  591. return (
  592. case_suites,
  593. expected_suite_perms,
  594. expected_case_perms,
  595. expected_perms,
  596. total_perms)
  597. def find_path(runner_, id, **args):
  598. path = None
  599. # query from runner
  600. cmd = runner_ + ['--list-case-paths', id]
  601. if args.get('verbose'):
  602. print(' '.join(shlex.quote(c) for c in cmd))
  603. proc = sp.Popen(cmd,
  604. stdout=sp.PIPE,
  605. stderr=sp.PIPE if not args.get('verbose') else None,
  606. universal_newlines=True,
  607. errors='replace',
  608. close_fds=False)
  609. pattern = re.compile(
  610. '^(?P<case>[^\s]+)'
  611. '\s+(?P<path>[^:]+):(?P<lineno>\d+)')
  612. # skip the first line
  613. for line in it.islice(proc.stdout, 1, None):
  614. m = pattern.match(line)
  615. if m and path is None:
  616. path_ = m.group('path')
  617. lineno = int(m.group('lineno'))
  618. path = (path_, lineno)
  619. proc.wait()
  620. if proc.returncode != 0:
  621. if not args.get('verbose'):
  622. for line in proc.stderr:
  623. sys.stdout.write(line)
  624. sys.exit(-1)
  625. return path
  626. def find_defines(runner_, id, **args):
  627. # query permutation defines from runner
  628. cmd = runner_ + ['--list-permutation-defines', id]
  629. if args.get('verbose'):
  630. print(' '.join(shlex.quote(c) for c in cmd))
  631. proc = sp.Popen(cmd,
  632. stdout=sp.PIPE,
  633. stderr=sp.PIPE if not args.get('verbose') else None,
  634. universal_newlines=True,
  635. errors='replace',
  636. close_fds=False)
  637. defines = co.OrderedDict()
  638. pattern = re.compile('^(?P<define>\w+)=(?P<value>.+)')
  639. for line in proc.stdout:
  640. m = pattern.match(line)
  641. if m:
  642. define = m.group('define')
  643. value = m.group('value')
  644. defines[define] = value
  645. proc.wait()
  646. if proc.returncode != 0:
  647. if not args.get('verbose'):
  648. for line in proc.stderr:
  649. sys.stdout.write(line)
  650. sys.exit(-1)
  651. return defines
  652. # Thread-safe CSV writer
  653. class TestOutput:
  654. def __init__(self, path, head=None, tail=None):
  655. self.f = openio(path, 'w+', 1)
  656. self.lock = th.Lock()
  657. self.head = head or []
  658. self.tail = tail or []
  659. self.writer = csv.DictWriter(self.f, self.head + self.tail)
  660. self.rows = []
  661. def close(self):
  662. self.f.close()
  663. def __enter__(self):
  664. return self
  665. def __exit__(self, *_):
  666. self.f.close()
  667. def writerow(self, row):
  668. with self.lock:
  669. self.rows.append(row)
  670. if all(k in self.head or k in self.tail for k in row.keys()):
  671. # can simply append
  672. self.writer.writerow(row)
  673. else:
  674. # need to rewrite the file
  675. self.head.extend(row.keys() - (self.head + self.tail))
  676. self.f.seek(0)
  677. self.f.truncate()
  678. self.writer = csv.DictWriter(self.f, self.head + self.tail)
  679. self.writer.writeheader()
  680. for row in self.rows:
  681. self.writer.writerow(row)
  682. # A test failure
  683. class TestFailure(Exception):
  684. def __init__(self, id, returncode, stdout, assert_=None):
  685. self.id = id
  686. self.returncode = returncode
  687. self.stdout = stdout
  688. self.assert_ = assert_
  689. def run_stage(name, runner_, ids, output_, **args):
  690. # get expected suite/case/perm counts
  691. (case_suites,
  692. expected_suite_perms,
  693. expected_case_perms,
  694. expected_perms,
  695. total_perms) = find_perms(runner_, ids, **args)
  696. passed_suite_perms = co.defaultdict(lambda: 0)
  697. passed_case_perms = co.defaultdict(lambda: 0)
  698. passed_perms = 0
  699. powerlosses = 0
  700. failures = []
  701. killed = False
  702. pattern = re.compile('^(?:'
  703. '(?P<op>running|finished|skipped|powerloss) '
  704. '(?P<id>(?P<case>[^:]+)[^\s]*)'
  705. '|' '(?P<path>[^:]+):(?P<lineno>\d+):(?P<op_>assert):'
  706. ' *(?P<message>.*)'
  707. ')$')
  708. locals = th.local()
  709. children = set()
  710. def run_runner(runner_, ids=[]):
  711. nonlocal passed_suite_perms
  712. nonlocal passed_case_perms
  713. nonlocal passed_perms
  714. nonlocal powerlosses
  715. nonlocal locals
  716. # run the tests!
  717. cmd = runner_ + ids
  718. if args.get('verbose'):
  719. print(' '.join(shlex.quote(c) for c in cmd))
  720. mpty, spty = pty.openpty()
  721. proc = sp.Popen(cmd, stdout=spty, stderr=spty, close_fds=False)
  722. os.close(spty)
  723. children.add(proc)
  724. mpty = os.fdopen(mpty, 'r', 1)
  725. stdout = None
  726. last_id = None
  727. last_stdout = []
  728. last_assert = None
  729. try:
  730. while True:
  731. # parse a line for state changes
  732. try:
  733. line = mpty.readline()
  734. except OSError as e:
  735. if e.errno != errno.EIO:
  736. raise
  737. break
  738. if not line:
  739. break
  740. last_stdout.append(line)
  741. if args.get('stdout'):
  742. try:
  743. if not stdout:
  744. stdout = openio(args['stdout'], 'a', 1, nb=True)
  745. stdout.write(line)
  746. except OSError as e:
  747. if e.errno not in [
  748. errno.ENXIO,
  749. errno.EPIPE,
  750. errno.EAGAIN]:
  751. raise
  752. stdout = None
  753. if args.get('verbose'):
  754. sys.stdout.write(line)
  755. m = pattern.match(line)
  756. if m:
  757. op = m.group('op') or m.group('op_')
  758. if op == 'running':
  759. locals.seen_perms += 1
  760. last_id = m.group('id')
  761. last_stdout = []
  762. last_assert = None
  763. elif op == 'powerloss':
  764. last_id = m.group('id')
  765. powerlosses += 1
  766. elif op == 'finished':
  767. case = m.group('case')
  768. suite = case_suites[case]
  769. passed_suite_perms[suite] += 1
  770. passed_case_perms[case] += 1
  771. passed_perms += 1
  772. if output_:
  773. # get defines and write to csv
  774. defines = find_defines(
  775. runner_, m.group('id'), **args)
  776. output_.writerow({
  777. 'suite': suite,
  778. 'case': case,
  779. 'test_passed': '1/1',
  780. **defines})
  781. elif op == 'skipped':
  782. locals.seen_perms += 1
  783. elif op == 'assert':
  784. last_assert = (
  785. m.group('path'),
  786. int(m.group('lineno')),
  787. m.group('message'))
  788. # go ahead and kill the process, aborting takes a while
  789. if args.get('keep_going'):
  790. proc.kill()
  791. except KeyboardInterrupt:
  792. raise TestFailure(last_id, 1, last_stdout)
  793. finally:
  794. children.remove(proc)
  795. mpty.close()
  796. proc.wait()
  797. if proc.returncode != 0:
  798. raise TestFailure(
  799. last_id,
  800. proc.returncode,
  801. last_stdout,
  802. last_assert)
  803. def run_job(runner_, ids=[], start=None, step=None):
  804. nonlocal failures
  805. nonlocal killed
  806. nonlocal locals
  807. start = start or 0
  808. step = step or 1
  809. while start < total_perms:
  810. job_runner = runner_.copy()
  811. if args.get('isolate') or args.get('valgrind'):
  812. job_runner.append('-s%s,%s,%s' % (start, start+step, step))
  813. else:
  814. job_runner.append('-s%s,,%s' % (start, step))
  815. try:
  816. # run the tests
  817. locals.seen_perms = 0
  818. run_runner(job_runner, ids)
  819. assert locals.seen_perms > 0
  820. start += locals.seen_perms*step
  821. except TestFailure as failure:
  822. # keep track of failures
  823. if output_:
  824. case, _ = failure.id.split(':', 1)
  825. suite = case_suites[case]
  826. # get defines and write to csv
  827. defines = find_defines(runner_, failure.id, **args)
  828. output_.writerow({
  829. 'suite': suite,
  830. 'case': case,
  831. 'test_passed': '0/1',
  832. **defines})
  833. # race condition for multiple failures?
  834. if failures and not args.get('keep_going'):
  835. break
  836. failures.append(failure)
  837. if args.get('keep_going') and not killed:
  838. # resume after failed test
  839. assert locals.seen_perms > 0
  840. start += locals.seen_perms*step
  841. continue
  842. else:
  843. # stop other tests
  844. killed = True
  845. for child in children.copy():
  846. child.kill()
  847. break
  848. # parallel jobs?
  849. runners = []
  850. if 'jobs' in args:
  851. for job in range(args['jobs']):
  852. runners.append(th.Thread(
  853. target=run_job, args=(runner_, ids, job, args['jobs']),
  854. daemon=True))
  855. else:
  856. runners.append(th.Thread(
  857. target=run_job, args=(runner_, ids, None, None),
  858. daemon=True))
  859. def print_update(done):
  860. if not args.get('verbose') and (args['color'] or done):
  861. sys.stdout.write('%s%srunning %s%s:%s %s%s' % (
  862. '\r\x1b[K' if args['color'] else '',
  863. '\x1b[?7l' if not done else '',
  864. ('\x1b[32m' if not failures else '\x1b[31m')
  865. if args['color'] else '',
  866. name,
  867. '\x1b[m' if args['color'] else '',
  868. ', '.join(filter(None, [
  869. '%d/%d suites' % (
  870. sum(passed_suite_perms[k] == v
  871. for k, v in expected_suite_perms.items()),
  872. len(expected_suite_perms))
  873. if (not args.get('by_suites')
  874. and not args.get('by_cases')) else None,
  875. '%d/%d cases' % (
  876. sum(passed_case_perms[k] == v
  877. for k, v in expected_case_perms.items()),
  878. len(expected_case_perms))
  879. if not args.get('by_cases') else None,
  880. '%d/%d perms' % (passed_perms, expected_perms),
  881. '%dpls!' % powerlosses
  882. if powerlosses else None,
  883. '%s%d/%d failures%s' % (
  884. '\x1b[31m' if args['color'] else '',
  885. len(failures),
  886. expected_perms,
  887. '\x1b[m' if args['color'] else '')
  888. if failures else None])),
  889. '\x1b[?7h' if not done else '\n'))
  890. sys.stdout.flush()
  891. for r in runners:
  892. r.start()
  893. try:
  894. while any(r.is_alive() for r in runners):
  895. time.sleep(0.01)
  896. print_update(False)
  897. except KeyboardInterrupt:
  898. # this is handled by the runner threads, we just
  899. # need to not abort here
  900. killed = True
  901. finally:
  902. print_update(True)
  903. for r in runners:
  904. r.join()
  905. return (
  906. expected_perms,
  907. passed_perms,
  908. powerlosses,
  909. failures,
  910. killed)
  911. def run(runner, test_ids=[], **args):
  912. # query runner for tests
  913. runner_ = find_runner(runner, **args)
  914. print('using runner: %s' % ' '.join(shlex.quote(c) for c in runner_))
  915. (_,
  916. expected_suite_perms,
  917. expected_case_perms,
  918. expected_perms,
  919. total_perms) = find_perms(runner_, test_ids, **args)
  920. print('found %d suites, %d cases, %d/%d permutations' % (
  921. len(expected_suite_perms),
  922. len(expected_case_perms),
  923. expected_perms,
  924. total_perms))
  925. print()
  926. # automatic job detection?
  927. if args.get('jobs') == 0:
  928. args['jobs'] = len(os.sched_getaffinity(0))
  929. # truncate and open logs here so they aren't disconnected between tests
  930. stdout = None
  931. if args.get('stdout'):
  932. stdout = openio(args['stdout'], 'w', 1)
  933. trace = None
  934. if args.get('trace'):
  935. trace = openio(args['trace'], 'w', 1)
  936. output = None
  937. if args.get('output'):
  938. output = TestOutput(args['output'],
  939. ['suite', 'case'],
  940. ['test_passed'])
  941. # measure runtime
  942. start = time.time()
  943. # spawn runners
  944. expected = 0
  945. passed = 0
  946. powerlosses = 0
  947. failures = []
  948. for by in (expected_case_perms.keys() if args.get('by_cases')
  949. else expected_suite_perms.keys() if args.get('by_suites')
  950. else [None]):
  951. # spawn jobs for stage
  952. (expected_,
  953. passed_,
  954. powerlosses_,
  955. failures_,
  956. killed) = run_stage(
  957. by or 'tests',
  958. runner_,
  959. [by] if by is not None else test_ids,
  960. output,
  961. **args)
  962. # collect passes/failures
  963. expected += expected_
  964. passed += passed_
  965. powerlosses += powerlosses_
  966. failures.extend(failures_)
  967. if (failures and not args.get('keep_going')) or killed:
  968. break
  969. stop = time.time()
  970. if stdout:
  971. stdout.close()
  972. if trace:
  973. trace.close()
  974. if output:
  975. output.close()
  976. # show summary
  977. print()
  978. print('%sdone:%s %s' % (
  979. ('\x1b[32m' if not failures else '\x1b[31m')
  980. if args['color'] else '',
  981. '\x1b[m' if args['color'] else '',
  982. ', '.join(filter(None, [
  983. '%d/%d passed' % (passed, expected),
  984. '%d/%d failed' % (len(failures), expected),
  985. '%dpls!' % powerlosses if powerlosses else None,
  986. 'in %.2fs' % (stop-start)]))))
  987. print()
  988. # print each failure
  989. for failure in failures:
  990. assert failure.id is not None, '%s broken? %r' % (
  991. ' '.join(shlex.quote(c) for c in runner_),
  992. failure)
  993. # get some extra info from runner
  994. path, lineno = find_path(runner_, failure.id, **args)
  995. defines = find_defines(runner_, failure.id, **args)
  996. # show summary of failure
  997. print('%s%s:%d:%sfailure:%s %s%s failed' % (
  998. '\x1b[01m' if args['color'] else '',
  999. path, lineno,
  1000. '\x1b[01;31m' if args['color'] else '',
  1001. '\x1b[m' if args['color'] else '',
  1002. failure.id,
  1003. ' (%s)' % ', '.join('%s=%s' % (k,v) for k,v in defines.items())
  1004. if defines else ''))
  1005. if failure.stdout:
  1006. stdout = failure.stdout
  1007. if failure.assert_ is not None:
  1008. stdout = stdout[:-1]
  1009. for line in stdout[-args.get('context', 5):]:
  1010. sys.stdout.write(line)
  1011. if failure.assert_ is not None:
  1012. path, lineno, message = failure.assert_
  1013. print('%s%s:%d:%sassert:%s %s' % (
  1014. '\x1b[01m' if args['color'] else '',
  1015. path, lineno,
  1016. '\x1b[01;31m' if args['color'] else '',
  1017. '\x1b[m' if args['color'] else '',
  1018. message))
  1019. with open(path) as f:
  1020. line = next(it.islice(f, lineno-1, None)).strip('\n')
  1021. print(line)
  1022. print()
  1023. # drop into gdb?
  1024. if failures and (args.get('gdb')
  1025. or args.get('gdb_case')
  1026. or args.get('gdb_main')):
  1027. failure = failures[0]
  1028. cmd = runner_ + [failure.id]
  1029. if args.get('gdb_main'):
  1030. cmd[:0] = args['gdb_tool'] + [
  1031. '-ex', 'break main',
  1032. '-ex', 'run',
  1033. '--args']
  1034. elif args.get('gdb_case'):
  1035. path, lineno = find_path(runner_, failure.id, **args)
  1036. cmd[:0] = args['gdb_tool'] + [
  1037. '-ex', 'break %s:%d' % (path, lineno),
  1038. '-ex', 'run',
  1039. '--args']
  1040. elif failure.assert_ is not None:
  1041. cmd[:0] = args['gdb_tool'] + [
  1042. '-ex', 'run',
  1043. '-ex', 'frame function raise',
  1044. '-ex', 'up 2',
  1045. '--args']
  1046. else:
  1047. cmd[:0] = args['gdb_tool'] + [
  1048. '-ex', 'run',
  1049. '--args']
  1050. # exec gdb interactively
  1051. if args.get('verbose'):
  1052. print(' '.join(shlex.quote(c) for c in cmd))
  1053. os.execvp(cmd[0], cmd)
  1054. return 1 if failures else 0
  1055. def main(**args):
  1056. # figure out what color should be
  1057. if args.get('color') == 'auto':
  1058. args['color'] = sys.stdout.isatty()
  1059. elif args.get('color') == 'always':
  1060. args['color'] = True
  1061. else:
  1062. args['color'] = False
  1063. if args.get('compile'):
  1064. return compile(**args)
  1065. elif (args.get('summary')
  1066. or args.get('list_suites')
  1067. or args.get('list_cases')
  1068. or args.get('list_suite_paths')
  1069. or args.get('list_case_paths')
  1070. or args.get('list_defines')
  1071. or args.get('list_permutation_defines')
  1072. or args.get('list_implicit_defines')
  1073. or args.get('list_geometries')
  1074. or args.get('list_powerlosses')):
  1075. return list_(**args)
  1076. else:
  1077. return run(**args)
  1078. if __name__ == "__main__":
  1079. import argparse
  1080. import sys
  1081. argparse.ArgumentParser._handle_conflict_ignore = lambda *_: None
  1082. argparse._ArgumentGroup._handle_conflict_ignore = lambda *_: None
  1083. parser = argparse.ArgumentParser(
  1084. description="Build and run tests.",
  1085. allow_abbrev=False,
  1086. conflict_handler='ignore')
  1087. parser.add_argument(
  1088. '-v', '--verbose',
  1089. action='store_true',
  1090. help="Output commands that run behind the scenes.")
  1091. parser.add_argument(
  1092. '--color',
  1093. choices=['never', 'always', 'auto'],
  1094. default='auto',
  1095. help="When to use terminal colors. Defaults to 'auto'.")
  1096. # test flags
  1097. test_parser = parser.add_argument_group('test options')
  1098. test_parser.add_argument(
  1099. 'runner',
  1100. nargs='?',
  1101. type=lambda x: x.split(),
  1102. help="Test runner to use for testing. Defaults to %r." % RUNNER_PATH)
  1103. test_parser.add_argument(
  1104. 'test_ids',
  1105. nargs='*',
  1106. help="Description of tests to run.")
  1107. test_parser.add_argument(
  1108. '-Y', '--summary',
  1109. action='store_true',
  1110. help="Show quick summary.")
  1111. test_parser.add_argument(
  1112. '-l', '--list-suites',
  1113. action='store_true',
  1114. help="List test suites.")
  1115. test_parser.add_argument(
  1116. '-L', '--list-cases',
  1117. action='store_true',
  1118. help="List test cases.")
  1119. test_parser.add_argument(
  1120. '--list-suite-paths',
  1121. action='store_true',
  1122. help="List the path for each test suite.")
  1123. test_parser.add_argument(
  1124. '--list-case-paths',
  1125. action='store_true',
  1126. help="List the path and line number for each test case.")
  1127. test_parser.add_argument(
  1128. '--list-defines',
  1129. action='store_true',
  1130. help="List all defines in this test-runner.")
  1131. test_parser.add_argument(
  1132. '--list-permutation-defines',
  1133. action='store_true',
  1134. help="List explicit defines in this test-runner.")
  1135. test_parser.add_argument(
  1136. '--list-implicit-defines',
  1137. action='store_true',
  1138. help="List implicit defines in this test-runner.")
  1139. test_parser.add_argument(
  1140. '--list-geometries',
  1141. action='store_true',
  1142. help="List the available disk geometries.")
  1143. test_parser.add_argument(
  1144. '--list-powerlosses',
  1145. action='store_true',
  1146. help="List the available power-loss scenarios.")
  1147. test_parser.add_argument(
  1148. '-D', '--define',
  1149. action='append',
  1150. help="Override a test define.")
  1151. test_parser.add_argument(
  1152. '-G', '--geometry',
  1153. help="Comma-separated list of disk geometries to test.")
  1154. test_parser.add_argument(
  1155. '-P', '--powerloss',
  1156. help="Comma-separated list of power-loss scenarios to test.")
  1157. test_parser.add_argument(
  1158. '-d', '--disk',
  1159. help="Direct block device operations to this file.")
  1160. test_parser.add_argument(
  1161. '-t', '--trace',
  1162. help="Direct trace output to this file.")
  1163. test_parser.add_argument(
  1164. '-O', '--stdout',
  1165. help="Direct stdout to this file. Note stderr is already merged here.")
  1166. test_parser.add_argument(
  1167. '-o', '--output',
  1168. help="CSV file to store results.")
  1169. test_parser.add_argument(
  1170. '--read-sleep',
  1171. help="Artificial read delay in seconds.")
  1172. test_parser.add_argument(
  1173. '--prog-sleep',
  1174. help="Artificial prog delay in seconds.")
  1175. test_parser.add_argument(
  1176. '--erase-sleep',
  1177. help="Artificial erase delay in seconds.")
  1178. test_parser.add_argument(
  1179. '-j', '--jobs',
  1180. nargs='?',
  1181. type=lambda x: int(x, 0),
  1182. const=0,
  1183. help="Number of parallel runners to run. 0 runs one runner per core.")
  1184. test_parser.add_argument(
  1185. '-k', '--keep-going',
  1186. action='store_true',
  1187. help="Don't stop on first error.")
  1188. test_parser.add_argument(
  1189. '-i', '--isolate',
  1190. action='store_true',
  1191. help="Run each test permutation in a separate process.")
  1192. test_parser.add_argument(
  1193. '-b', '--by-suites',
  1194. action='store_true',
  1195. help="Step through tests by suite.")
  1196. test_parser.add_argument(
  1197. '-B', '--by-cases',
  1198. action='store_true',
  1199. help="Step through tests by case.")
  1200. test_parser.add_argument(
  1201. '--context',
  1202. type=lambda x: int(x, 0),
  1203. default=5,
  1204. help="Show this many lines of stdout on test failure. "
  1205. "Defaults to 5.")
  1206. test_parser.add_argument(
  1207. '--gdb',
  1208. action='store_true',
  1209. help="Drop into gdb on test failure.")
  1210. test_parser.add_argument(
  1211. '--gdb-case',
  1212. action='store_true',
  1213. help="Drop into gdb on test failure but stop at the beginning "
  1214. "of the failing test case.")
  1215. test_parser.add_argument(
  1216. '--gdb-main',
  1217. action='store_true',
  1218. help="Drop into gdb on test failure but stop at the beginning "
  1219. "of main.")
  1220. test_parser.add_argument(
  1221. '--gdb-tool',
  1222. type=lambda x: x.split(),
  1223. default=GDB_TOOL,
  1224. help="Path to gdb tool to use. Defaults to %r." % GDB_TOOL)
  1225. test_parser.add_argument(
  1226. '--exec',
  1227. type=lambda e: e.split(),
  1228. help="Run under another executable.")
  1229. test_parser.add_argument(
  1230. '--valgrind',
  1231. action='store_true',
  1232. help="Run under Valgrind to find memory errors. Implicitly sets "
  1233. "--isolate.")
  1234. test_parser.add_argument(
  1235. '--valgrind-tool',
  1236. type=lambda x: x.split(),
  1237. default=VALGRIND_TOOL,
  1238. help="Path to Valgrind tool to use. Defaults to %r." % VALGRIND_TOOL)
  1239. test_parser.add_argument(
  1240. '--perf',
  1241. help="Run under Linux's perf to sample performance counters, writing "
  1242. "samples to this file.")
  1243. test_parser.add_argument(
  1244. '--perf-freq',
  1245. help="perf sampling frequency. This is passed directly to the perf "
  1246. "script.")
  1247. test_parser.add_argument(
  1248. '--perf-period',
  1249. help="perf sampling period. This is passed directly to the perf "
  1250. "script.")
  1251. test_parser.add_argument(
  1252. '--perf-events',
  1253. help="perf events to record. This is passed directly to the perf "
  1254. "script.")
  1255. test_parser.add_argument(
  1256. '--perf-script',
  1257. type=lambda x: x.split(),
  1258. default=PERF_SCRIPT,
  1259. help="Path to the perf script to use. Defaults to %r." % PERF_SCRIPT)
  1260. test_parser.add_argument(
  1261. '--perf-tool',
  1262. type=lambda x: x.split(),
  1263. help="Path to the perf tool to use. This is passed directly to the "
  1264. "perf script")
  1265. # compilation flags
  1266. comp_parser = parser.add_argument_group('compilation options')
  1267. comp_parser.add_argument(
  1268. 'test_paths',
  1269. nargs='*',
  1270. help="Description of *.toml files to compile. May be a directory "
  1271. "or a list of paths.")
  1272. comp_parser.add_argument(
  1273. '-c', '--compile',
  1274. action='store_true',
  1275. help="Compile a test suite or source file.")
  1276. comp_parser.add_argument(
  1277. '-s', '--source',
  1278. help="Source file to compile, possibly injecting internal tests.")
  1279. comp_parser.add_argument(
  1280. '--include',
  1281. default=HEADER_PATH,
  1282. help="Inject this header file into every compiled test file. "
  1283. "Defaults to %r." % HEADER_PATH)
  1284. comp_parser.add_argument(
  1285. '-o', '--output',
  1286. help="Output file.")
  1287. # runner/test_paths overlap, so need to do some munging here
  1288. args = parser.parse_intermixed_args()
  1289. args.test_paths = [' '.join(args.runner or [])] + args.test_ids
  1290. args.runner = args.runner or [RUNNER_PATH]
  1291. sys.exit(main(**{k: v
  1292. for k, v in vars(args).items()
  1293. if v is not None}))