test.py 49 KB

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