test.py 51 KB

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