test.py 53 KB

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