test.py 51 KB

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