test.py 43 KB

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