test.py 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003
  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. TEST_PATHS = ['tests']
  21. RUNNER_PATH = './runners/test_runner'
  22. SUITE_PROLOGUE = """
  23. #include "runners/test_runner.h"
  24. #include "bd/lfs_testbd.h"
  25. #include <stdio.h>
  26. """
  27. CASE_PROLOGUE = """
  28. """
  29. CASE_EPILOGUE = """
  30. """
  31. def testpath(path):
  32. path, *_ = path.split('#', 1)
  33. return path
  34. def testsuite(path):
  35. suite = testpath(path)
  36. suite = os.path.basename(suite)
  37. if suite.endswith('.toml'):
  38. suite = suite[:-len('.toml')]
  39. return suite
  40. def testcase(path):
  41. _, case, *_ = path.split('#', 2)
  42. return '%s#%s' % (testsuite(path), case)
  43. def openio(path, mode='r'):
  44. if path == '-':
  45. if 'r' in mode:
  46. return os.fdopen(os.dup(sys.stdin.fileno()), 'r')
  47. else:
  48. return os.fdopen(os.dup(sys.stdout.fileno()), 'w')
  49. else:
  50. return open(path, mode)
  51. class TestCase:
  52. # create a TestCase object from a config
  53. def __init__(self, config, args={}):
  54. self.name = config.pop('name')
  55. self.path = config.pop('path')
  56. self.suite = config.pop('suite')
  57. self.lineno = config.pop('lineno', None)
  58. self.if_ = config.pop('if', None)
  59. if isinstance(self.if_, bool):
  60. self.if_ = 'true' if self.if_ else 'false'
  61. self.code = config.pop('code')
  62. self.code_lineno = config.pop('code_lineno', None)
  63. self.in_ = config.pop('in',
  64. config.pop('suite_in', None))
  65. self.normal = config.pop('normal',
  66. config.pop('suite_normal', True))
  67. self.reentrant = config.pop('reentrant',
  68. config.pop('suite_reentrant', False))
  69. # figure out defines and build possible permutations
  70. self.defines = set()
  71. self.permutations = []
  72. suite_defines = config.pop('suite_defines', {})
  73. if not isinstance(suite_defines, list):
  74. suite_defines = [suite_defines]
  75. defines = config.pop('defines', {})
  76. if not isinstance(defines, list):
  77. defines = [defines]
  78. # build possible permutations
  79. for suite_defines_ in suite_defines:
  80. self.defines |= suite_defines_.keys()
  81. for defines_ in defines:
  82. self.defines |= defines_.keys()
  83. self.permutations.extend(map(dict, it.product(*(
  84. [(k, v) for v in (vs if isinstance(vs, list) else [vs])]
  85. for k, vs in sorted(
  86. (suite_defines_ | defines_).items())))))
  87. for k in config.keys():
  88. print('\x1b[01;33mwarning:\x1b[m in %s, found unused key %r'
  89. % (self.id(), k),
  90. file=sys.stderr)
  91. def id(self):
  92. return '%s#%s' % (self.suite, self.name)
  93. class TestSuite:
  94. # create a TestSuite object from a toml file
  95. def __init__(self, path, args={}):
  96. self.name = testsuite(path)
  97. self.path = testpath(path)
  98. # load toml file and parse test cases
  99. with open(self.path) as f:
  100. # load tests
  101. config = toml.load(f)
  102. # find line numbers
  103. f.seek(0)
  104. case_linenos = []
  105. code_linenos = []
  106. for i, line in enumerate(f):
  107. match = re.match(
  108. '(?P<case>\[\s*cases\s*\.\s*(?P<name>\w+)\s*\])'
  109. '|' '(?P<code>code\s*=)',
  110. line)
  111. if match and match.group('case'):
  112. case_linenos.append((i+1, match.group('name')))
  113. elif match and match.group('code'):
  114. code_linenos.append(i+2)
  115. # sort in case toml parsing did not retain order
  116. case_linenos.sort()
  117. cases = config.pop('cases')
  118. for (lineno, name), (nlineno, _) in it.zip_longest(
  119. case_linenos, case_linenos[1:],
  120. fillvalue=(float('inf'), None)):
  121. code_lineno = min(
  122. (l for l in code_linenos if l >= lineno and l < nlineno),
  123. default=None)
  124. cases[name]['lineno'] = lineno
  125. cases[name]['code_lineno'] = code_lineno
  126. self.if_ = config.pop('if', None)
  127. if isinstance(self.if_, bool):
  128. self.if_ = 'true' if self.if_ else 'false'
  129. self.code = config.pop('code', None)
  130. self.code_lineno = min(
  131. (l for l in code_linenos
  132. if not case_linenos or l < case_linenos[0][0]),
  133. default=None)
  134. # a couple of these we just forward to all cases
  135. defines = config.pop('defines', {})
  136. in_ = config.pop('in', None)
  137. normal = config.pop('normal', True)
  138. reentrant = config.pop('reentrant', False)
  139. self.cases = []
  140. for name, case in sorted(cases.items(),
  141. key=lambda c: c[1].get('lineno')):
  142. self.cases.append(TestCase(config={
  143. 'name': name,
  144. 'path': path + (':%d' % case['lineno']
  145. if 'lineno' in case else ''),
  146. 'suite': self.name,
  147. 'suite_defines': defines,
  148. 'suite_in': in_,
  149. 'suite_normal': normal,
  150. 'suite_reentrant': reentrant,
  151. **case}))
  152. # combine per-case defines
  153. self.defines = set.union(*(
  154. set(case.defines) for case in self.cases))
  155. # combine other per-case things
  156. self.normal = any(case.normal for case in self.cases)
  157. self.reentrant = any(case.reentrant for case in self.cases)
  158. for k in config.keys():
  159. print('\x1b[01;33mwarning:\x1b[m in %s, found unused key %r'
  160. % (self.id(), k),
  161. file=sys.stderr)
  162. def id(self):
  163. return self.name
  164. def compile(**args):
  165. # find .toml files
  166. paths = []
  167. for path in args.get('test_ids', TEST_PATHS):
  168. if os.path.isdir(path):
  169. path = path + '/*.toml'
  170. for path in glob.glob(path):
  171. paths.append(path)
  172. if not paths:
  173. print('no test suites found in %r?' % args['test_ids'])
  174. sys.exit(-1)
  175. if not args.get('source'):
  176. if len(paths) > 1:
  177. print('more than one test suite for compilation? (%r)'
  178. % args['test_ids'])
  179. sys.exit(-1)
  180. # load our suite
  181. suite = TestSuite(paths[0])
  182. else:
  183. # load all suites
  184. suites = [TestSuite(path) for path in paths]
  185. suites.sort(key=lambda s: s.name)
  186. # write generated test source
  187. if 'output' in args:
  188. with openio(args['output'], 'w') as f:
  189. _write = f.write
  190. def write(s):
  191. f.lineno += s.count('\n')
  192. _write(s)
  193. def writeln(s=''):
  194. f.lineno += s.count('\n') + 1
  195. _write(s)
  196. _write('\n')
  197. f.lineno = 1
  198. f.write = write
  199. f.writeln = writeln
  200. # redirect littlefs tracing
  201. f.writeln('#define LFS_TRACE_(fmt, ...) do { \\')
  202. f.writeln(8*' '+'extern FILE *test_trace; \\')
  203. f.writeln(8*' '+'if (test_trace) { \\')
  204. f.writeln(12*' '+'fprintf(test_trace, '
  205. '"%s:%d:trace: " fmt "%s\\n", \\')
  206. f.writeln(20*' '+'__FILE__, __LINE__, __VA_ARGS__); \\')
  207. f.writeln(8*' '+'} \\')
  208. f.writeln(4*' '+'} while (0)')
  209. f.writeln('#define LFS_TRACE(...) LFS_TRACE_(__VA_ARGS__, "")')
  210. f.writeln('#define LFS_TESTBD_TRACE(...) '
  211. 'LFS_TRACE_(__VA_ARGS__, "")')
  212. f.writeln()
  213. # write out generated functions, this can end up in different
  214. # files depending on the "in" attribute
  215. #
  216. # note it's up to the specific generated file to declare
  217. # the test defines
  218. def write_case_functions(f, suite, case):
  219. # create case define functions
  220. if case.defines:
  221. # deduplicate defines by value to try to reduce the
  222. # number of functions we generate
  223. define_cbs = {}
  224. for i, defines in enumerate(case.permutations):
  225. for k, v in sorted(defines.items()):
  226. if v not in define_cbs:
  227. name = ('__test__%s__%s__%s__%d'
  228. % (suite.name, case.name, k, i))
  229. define_cbs[v] = name
  230. f.writeln('intmax_t %s(void) {' % name)
  231. f.writeln(4*' '+'return %s;' % v)
  232. f.writeln('}')
  233. f.writeln()
  234. f.writeln('intmax_t (*const *const '
  235. '__test__%s__%s__defines[])(void) = {'
  236. % (suite.name, case.name))
  237. for defines in case.permutations:
  238. f.writeln(4*' '+'(intmax_t (*const[])(void)){')
  239. for define in sorted(suite.defines):
  240. f.writeln(8*' '+'%s,' % (
  241. define_cbs[defines[define]]
  242. if define in defines
  243. else 'NULL'))
  244. f.writeln(4*' '+'},')
  245. f.writeln('};')
  246. f.writeln()
  247. # create case filter function
  248. if suite.if_ is not None or case.if_ is not None:
  249. f.writeln('bool __test__%s__%s__filter(void) {'
  250. % (suite.name, case.name))
  251. f.writeln(4*' '+'return %s;'
  252. % ' && '.join('(%s)' % if_
  253. for if_ in [suite.if_, case.if_]
  254. if if_ is not None))
  255. f.writeln('}')
  256. f.writeln()
  257. # create case run function
  258. f.writeln('void __test__%s__%s__run('
  259. '__attribute__((unused)) struct lfs_config *cfg) {'
  260. % (suite.name, case.name))
  261. if CASE_PROLOGUE.strip():
  262. f.writeln(4*' '+'%s'
  263. % CASE_PROLOGUE.strip().replace('\n', '\n'+4*' '))
  264. f.writeln()
  265. f.writeln(4*' '+'// test case %s' % case.id())
  266. if case.code_lineno is not None:
  267. f.writeln(4*' '+'#line %d "%s"'
  268. % (case.code_lineno, suite.path))
  269. f.write(case.code)
  270. if case.code_lineno is not None:
  271. f.writeln(4*' '+'#line %d "%s"'
  272. % (f.lineno+1, args['output']))
  273. if CASE_EPILOGUE.strip():
  274. f.writeln()
  275. f.writeln(4*' '+'%s'
  276. % CASE_EPILOGUE.strip().replace('\n', '\n'+4*' '))
  277. f.writeln('}')
  278. f.writeln()
  279. if not args.get('source'):
  280. # write test suite prologue
  281. f.writeln('%s' % SUITE_PROLOGUE.strip())
  282. f.writeln()
  283. if suite.code is not None:
  284. if suite.code_lineno is not None:
  285. f.writeln('#line %d "%s"'
  286. % (suite.code_lineno, suite.path))
  287. f.write(suite.code)
  288. if suite.code_lineno is not None:
  289. f.writeln('#line %d "%s"'
  290. % (f.lineno+1, args['output']))
  291. f.writeln()
  292. if suite.defines:
  293. for i, define in enumerate(sorted(suite.defines)):
  294. f.writeln('#ifndef %s' % define)
  295. f.writeln('#define %-24s test_define(%d)'
  296. % (define, i))
  297. f.writeln('#endif')
  298. f.writeln()
  299. # create case functions
  300. for case in suite.cases:
  301. if case.in_ is None:
  302. write_case_functions(f, suite, case)
  303. else:
  304. if case.defines:
  305. f.writeln('extern intmax_t (*const *const '
  306. '__test__%s__%s__defines[])(void);'
  307. % (suite.name, case.name))
  308. if suite.if_ is not None or case.if_ is not None:
  309. f.writeln('extern bool __test__%s__%s__filter('
  310. 'void);'
  311. % (suite.name, case.name))
  312. f.writeln('extern void __test__%s__%s__run('
  313. 'struct lfs_config *cfg);'
  314. % (suite.name, case.name))
  315. f.writeln()
  316. # create suite struct
  317. f.writeln('__attribute__((section("_test_suites")))')
  318. f.writeln('const struct test_suite __test__%s__suite = {'
  319. % suite.name)
  320. f.writeln(4*' '+'.id = "%s",' % suite.id())
  321. f.writeln(4*' '+'.name = "%s",' % suite.name)
  322. f.writeln(4*' '+'.path = "%s",' % suite.path)
  323. f.writeln(4*' '+'.types = %s,'
  324. % ' | '.join(filter(None, [
  325. 'TEST_NORMAL' if suite.normal else None,
  326. 'TEST_REENTRANT' if suite.reentrant else None])))
  327. if suite.defines:
  328. # create suite define names
  329. f.writeln(4*' '+'.define_names = (const char *const[]){')
  330. for k in sorted(suite.defines):
  331. f.writeln(8*' '+'"%s",' % k)
  332. f.writeln(4*' '+'},')
  333. f.writeln(4*' '+'.define_count = %d,' % len(suite.defines))
  334. f.writeln(4*' '+'.cases = (const struct test_case[]){')
  335. for case in suite.cases:
  336. # create case structs
  337. f.writeln(8*' '+'{')
  338. f.writeln(12*' '+'.id = "%s",' % case.id())
  339. f.writeln(12*' '+'.name = "%s",' % case.name)
  340. f.writeln(12*' '+'.path = "%s",' % case.path)
  341. f.writeln(12*' '+'.types = %s,'
  342. % ' | '.join(filter(None, [
  343. 'TEST_NORMAL' if case.normal else None,
  344. 'TEST_REENTRANT' if case.reentrant else None])))
  345. f.writeln(12*' '+'.permutations = %d,'
  346. % len(case.permutations))
  347. if case.defines:
  348. f.writeln(12*' '+'.defines = __test__%s__%s__defines,'
  349. % (suite.name, case.name))
  350. if suite.if_ is not None or case.if_ is not None:
  351. f.writeln(12*' '+'.filter = __test__%s__%s__filter,'
  352. % (suite.name, case.name))
  353. f.writeln(12*' '+'.run = __test__%s__%s__run,'
  354. % (suite.name, case.name))
  355. f.writeln(8*' '+'},')
  356. f.writeln(4*' '+'},')
  357. f.writeln(4*' '+'.case_count = %d,' % len(suite.cases))
  358. f.writeln('};')
  359. f.writeln()
  360. else:
  361. # copy source
  362. f.writeln('#line 1 "%s"' % args['source'])
  363. with open(args['source']) as sf:
  364. shutil.copyfileobj(sf, f)
  365. f.writeln()
  366. f.write(SUITE_PROLOGUE)
  367. f.writeln()
  368. # write any internal tests
  369. for suite in suites:
  370. for case in suite.cases:
  371. if (case.in_ is not None
  372. and os.path.normpath(case.in_)
  373. == os.path.normpath(args['source'])):
  374. # write defines, but note we need to undef any
  375. # new defines since we're in someone else's file
  376. if suite.defines:
  377. for i, define in enumerate(
  378. sorted(suite.defines)):
  379. f.writeln('#ifndef %s' % define)
  380. f.writeln('#define %-24s test_define(%d)'
  381. % (define, i))
  382. f.writeln('#define __TEST__%s__NEEDS_UNDEF'
  383. % define)
  384. f.writeln('#endif')
  385. f.writeln()
  386. write_case_functions(f, suite, case)
  387. if suite.defines:
  388. for define in sorted(suite.defines):
  389. f.writeln('#ifdef __TEST__%s__NEEDS_UNDEF'
  390. % define)
  391. f.writeln('#undef __TEST__%s__NEEDS_UNDEF'
  392. % define)
  393. f.writeln('#undef %s' % define)
  394. f.writeln('#endif')
  395. f.writeln()
  396. def runner(**args):
  397. cmd = args['runner'].copy()
  398. cmd.extend(args.get('test_ids'))
  399. # run under some external command?
  400. cmd[:0] = args.get('exec', [])
  401. # run under valgrind?
  402. if args.get('valgrind'):
  403. cmd[:0] = filter(None, [
  404. 'valgrind',
  405. '--leak-check=full',
  406. '--track-origins=yes',
  407. '--error-exitcode=4',
  408. '-q'])
  409. # filter tests?
  410. if args.get('normal'): cmd.append('-n')
  411. if args.get('reentrant'): cmd.append('-r')
  412. if args.get('geometry'):
  413. cmd.append('-G%s' % args.get('geometry'))
  414. # defines?
  415. if args.get('define'):
  416. for define in args.get('define'):
  417. cmd.append('-D%s' % define)
  418. return cmd
  419. def list_(**args):
  420. cmd = runner(**args)
  421. if args.get('summary'): cmd.append('--summary')
  422. if args.get('list_suites'): cmd.append('--list-suites')
  423. if args.get('list_cases'): cmd.append('--list-cases')
  424. if args.get('list_paths'): cmd.append('--list-paths')
  425. if args.get('list_defines'): cmd.append('--list-defines')
  426. if args.get('list_geometries'): cmd.append('--list-geometries')
  427. if args.get('verbose'):
  428. print(' '.join(shlex.quote(c) for c in cmd))
  429. sys.exit(sp.call(cmd))
  430. def find_cases(runner_, **args):
  431. # query from runner
  432. cmd = runner_ + ['--list-cases']
  433. if args.get('verbose'):
  434. print(' '.join(shlex.quote(c) for c in cmd))
  435. proc = sp.Popen(cmd,
  436. stdout=sp.PIPE,
  437. stderr=sp.PIPE if not args.get('verbose') else None,
  438. universal_newlines=True,
  439. errors='replace')
  440. expected_suite_perms = co.defaultdict(lambda: 0)
  441. expected_case_perms = co.defaultdict(lambda: 0)
  442. expected_perms = 0
  443. total_perms = 0
  444. pattern = re.compile(
  445. '^(?P<id>(?P<case>(?P<suite>[^#]+)#[^\s#]+)[^\s]*)\s+'
  446. '[^\s]+\s+(?P<filtered>\d+)/(?P<perms>\d+)')
  447. # skip the first line
  448. for line in it.islice(proc.stdout, 1, None):
  449. m = pattern.match(line)
  450. if m:
  451. filtered = int(m.group('filtered'))
  452. expected_suite_perms[m.group('suite')] += filtered
  453. expected_case_perms[m.group('id')] += filtered
  454. expected_perms += filtered
  455. total_perms += int(m.group('perms'))
  456. proc.wait()
  457. if proc.returncode != 0:
  458. if not args.get('verbose'):
  459. for line in proc.stderr:
  460. sys.stdout.write(line)
  461. sys.exit(-1)
  462. return (
  463. expected_suite_perms,
  464. expected_case_perms,
  465. expected_perms,
  466. total_perms)
  467. def find_paths(runner_, **args):
  468. # query from runner
  469. cmd = runner_ + ['--list-paths']
  470. if args.get('verbose'):
  471. print(' '.join(shlex.quote(c) for c in cmd))
  472. proc = sp.Popen(cmd,
  473. stdout=sp.PIPE,
  474. stderr=sp.PIPE if not args.get('verbose') else None,
  475. universal_newlines=True,
  476. errors='replace')
  477. paths = co.OrderedDict()
  478. pattern = re.compile(
  479. '^(?P<id>(?P<case>(?P<suite>[^#]+)#[^\s#]+)[^\s]*)\s+'
  480. '(?P<path>[^:]+):(?P<lineno>\d+)')
  481. for line in proc.stdout:
  482. m = pattern.match(line)
  483. if m:
  484. paths[m.group('id')] = (m.group('path'), int(m.group('lineno')))
  485. proc.wait()
  486. if proc.returncode != 0:
  487. if not args.get('verbose'):
  488. for line in proc.stderr:
  489. sys.stdout.write(line)
  490. sys.exit(-1)
  491. return paths
  492. def find_defines(runner_, **args):
  493. # query from runner
  494. cmd = runner_ + ['--list-defines']
  495. if args.get('verbose'):
  496. print(' '.join(shlex.quote(c) for c in cmd))
  497. proc = sp.Popen(cmd,
  498. stdout=sp.PIPE,
  499. stderr=sp.PIPE if not args.get('verbose') else None,
  500. universal_newlines=True,
  501. errors='replace')
  502. defines = co.OrderedDict()
  503. pattern = re.compile(
  504. '^(?P<id>(?P<case>(?P<suite>[^#]+)#[^\s#]+)[^\s]*)\s+'
  505. '(?P<defines>(?:\w+=\w+\s*)+)')
  506. for line in proc.stdout:
  507. m = pattern.match(line)
  508. if m:
  509. defines[m.group('id')] = {k: v
  510. for k, v in re.findall('(\w+)=(\w+)', m.group('defines'))}
  511. proc.wait()
  512. if proc.returncode != 0:
  513. if not args.get('verbose'):
  514. for line in proc.stderr:
  515. sys.stdout.write(line)
  516. sys.exit(-1)
  517. return defines
  518. class TestFailure(Exception):
  519. def __init__(self, id, returncode, output, assert_=None):
  520. self.id = id
  521. self.returncode = returncode
  522. self.output = output
  523. self.assert_ = assert_
  524. def run_stage(name, runner_, **args):
  525. # get expected suite/case/perm counts
  526. expected_suite_perms, expected_case_perms, expected_perms, total_perms = (
  527. find_cases(runner_, **args))
  528. passed_suite_perms = co.defaultdict(lambda: 0)
  529. passed_case_perms = co.defaultdict(lambda: 0)
  530. passed_perms = 0
  531. failures = []
  532. killed = False
  533. pattern = re.compile('^(?:'
  534. '(?P<op>running|finished|skipped) '
  535. '(?P<id>(?P<case>(?P<suite>[^#]+)#[^\s#]+)[^\s]*)'
  536. '|' '(?P<path>[^:]+):(?P<lineno>\d+):(?P<op_>assert):'
  537. ' *(?P<message>.*)' ')$')
  538. locals = th.local()
  539. children = set()
  540. def run_runner(runner_):
  541. nonlocal passed_suite_perms
  542. nonlocal passed_case_perms
  543. nonlocal passed_perms
  544. nonlocal locals
  545. # run the tests!
  546. cmd = runner_.copy()
  547. if args.get('disk'):
  548. cmd.append('--disk=%s' % args['disk'])
  549. if args.get('trace'):
  550. cmd.append('--trace=%s' % args['trace'])
  551. if args.get('verbose'):
  552. print(' '.join(shlex.quote(c) for c in cmd))
  553. mpty, spty = pty.openpty()
  554. proc = sp.Popen(cmd, stdout=spty, stderr=spty)
  555. os.close(spty)
  556. children.add(proc)
  557. mpty = os.fdopen(mpty, 'r', 1)
  558. if args.get('output'):
  559. output = openio(args['output'], 'w')
  560. last_id = None
  561. last_output = []
  562. last_assert = None
  563. try:
  564. while True:
  565. # parse a line for state changes
  566. try:
  567. line = mpty.readline()
  568. except OSError as e:
  569. if e.errno == errno.EIO:
  570. break
  571. raise
  572. if not line:
  573. break
  574. last_output.append(line)
  575. if args.get('output'):
  576. output.write(line)
  577. elif args.get('verbose'):
  578. sys.stdout.write(line)
  579. m = pattern.match(line)
  580. if m:
  581. op = m.group('op') or m.group('op_')
  582. if op == 'running':
  583. locals.seen_perms += 1
  584. last_id = m.group('id')
  585. last_output = []
  586. last_assert = None
  587. elif op == 'finished':
  588. passed_suite_perms[m.group('suite')] += 1
  589. passed_case_perms[m.group('case')] += 1
  590. passed_perms += 1
  591. elif op == 'skipped':
  592. locals.seen_perms += 1
  593. elif op == 'assert':
  594. last_assert = (
  595. m.group('path'),
  596. int(m.group('lineno')),
  597. m.group('message'))
  598. # go ahead and kill the process, aborting takes a while
  599. if args.get('keep_going'):
  600. proc.kill()
  601. except KeyboardInterrupt:
  602. raise TestFailure(last_id, 1, last_output)
  603. finally:
  604. children.remove(proc)
  605. mpty.close()
  606. if args.get('output'):
  607. output.close()
  608. proc.wait()
  609. if proc.returncode != 0:
  610. raise TestFailure(
  611. last_id,
  612. proc.returncode,
  613. last_output,
  614. last_assert)
  615. def run_job(runner, start=None, step=None):
  616. nonlocal failures
  617. nonlocal locals
  618. start = start or 0
  619. step = step or 1
  620. while start < total_perms:
  621. runner_ = runner.copy()
  622. if start is not None:
  623. runner_.append('--start=%d' % start)
  624. if step is not None:
  625. runner_.append('--step=%d' % step)
  626. if args.get('isolate') or args.get('valgrind'):
  627. runner_.append('--stop=%d' % (start+step))
  628. try:
  629. # run the tests
  630. locals.seen_perms = 0
  631. run_runner(runner_)
  632. assert locals.seen_perms > 0
  633. start += locals.seen_perms*step
  634. except TestFailure as failure:
  635. # race condition for multiple failures?
  636. if failures and not args.get('keep_going'):
  637. break
  638. failures.append(failure)
  639. if args.get('keep_going') and not killed:
  640. # resume after failed test
  641. assert locals.seen_perms > 0
  642. start += locals.seen_perms*step
  643. continue
  644. else:
  645. # stop other tests
  646. for child in children.copy():
  647. child.kill()
  648. break
  649. # parallel jobs?
  650. runners = []
  651. if 'jobs' in args:
  652. for job in range(args['jobs']):
  653. runners.append(th.Thread(
  654. target=run_job, args=(runner_, job, args['jobs'])))
  655. else:
  656. runners.append(th.Thread(
  657. target=run_job, args=(runner_, None, None)))
  658. for r in runners:
  659. r.start()
  660. needs_newline = False
  661. try:
  662. while any(r.is_alive() for r in runners):
  663. time.sleep(0.01)
  664. if not args.get('verbose'):
  665. sys.stdout.write('\r\x1b[K'
  666. 'running \x1b[%dm%s:\x1b[m %s '
  667. % (32 if not failures else 31,
  668. name,
  669. ', '.join(filter(None, [
  670. '%d/%d suites' % (
  671. sum(passed_suite_perms[k] == v
  672. for k, v in expected_suite_perms.items()),
  673. len(expected_suite_perms))
  674. if (not args.get('by_suites')
  675. and not args.get('by_cases')) else None,
  676. '%d/%d cases' % (
  677. sum(passed_case_perms[k] == v
  678. for k, v in expected_case_perms.items()),
  679. len(expected_case_perms))
  680. if not args.get('by_cases') else None,
  681. '%d/%d perms' % (passed_perms, expected_perms),
  682. '\x1b[31m%d/%d failures\x1b[m'
  683. % (len(failures), expected_perms)
  684. if failures else None]))))
  685. sys.stdout.flush()
  686. needs_newline = True
  687. except KeyboardInterrupt:
  688. # this is handled by the runner threads, we just
  689. # need to not abort here
  690. killed = True
  691. finally:
  692. if needs_newline:
  693. print()
  694. for r in runners:
  695. r.join()
  696. return (
  697. expected_perms,
  698. passed_perms,
  699. failures,
  700. killed)
  701. def run(**args):
  702. start = time.time()
  703. runner_ = runner(**args)
  704. print('using runner: %s'
  705. % ' '.join(shlex.quote(c) for c in runner_))
  706. expected_suite_perms, expected_case_perms, expected_perms, total_perms = (
  707. find_cases(runner_, **args))
  708. print('found %d suites, %d cases, %d/%d permutations'
  709. % (len(expected_suite_perms),
  710. len(expected_case_perms),
  711. expected_perms,
  712. total_perms))
  713. print()
  714. expected = 0
  715. passed = 0
  716. failures = []
  717. for type, by in it.product(
  718. ['normal', 'reentrant'],
  719. expected_case_perms.keys() if args.get('by_cases')
  720. else expected_suite_perms.keys() if args.get('by_suites')
  721. else [None]):
  722. # rebuild runner for each stage to override test identifier if needed
  723. stage_runner = runner(**args | {
  724. 'test_ids': [by] if by is not None else args.get('test_ids', []),
  725. 'normal': type == 'normal',
  726. 'reentrant': type == 'reentrant'})
  727. # spawn jobs for stage
  728. expected_, passed_, failures_, killed = run_stage(
  729. '%s %s' % (type, by or 'tests'), stage_runner, **args)
  730. expected += expected_
  731. passed += passed_
  732. failures.extend(failures_)
  733. if (failures and not args.get('keep_going')) or killed:
  734. break
  735. # show summary
  736. print()
  737. print('\x1b[%dmdone:\x1b[m %d/%d passed, %d/%d failed, in %.2fs'
  738. % (32 if not failures else 31,
  739. passed, expected, len(failures), expected,
  740. time.time()-start))
  741. print()
  742. # print each failure
  743. if failures:
  744. # get some extra info from runner
  745. runner_paths = find_paths(runner_, **args)
  746. runner_defines = find_defines(runner_, **args)
  747. for failure in failures:
  748. # show summary of failure
  749. path, lineno = runner_paths[testcase(failure.id)]
  750. defines = runner_defines[failure.id]
  751. print('\x1b[01m%s:%d:\x1b[01;31mfailure:\x1b[m %s%s failed'
  752. % (path, lineno, failure.id,
  753. ' (%s)' % ', '.join(
  754. '%s=%s' % (k, v) for k, v in defines.items())
  755. if defines else ''))
  756. if failure.output:
  757. output = failure.output
  758. if failure.assert_ is not None:
  759. output = output[:-1]
  760. for line in output[-5:]:
  761. sys.stdout.write(line)
  762. if failure.assert_ is not None:
  763. path, lineno, message = failure.assert_
  764. print('\x1b[01m%s:%d:\x1b[01;31massert:\x1b[m %s'
  765. % (path, lineno, message))
  766. with open(path) as f:
  767. line = next(it.islice(f, lineno-1, None)).strip('\n')
  768. print(line)
  769. print()
  770. # drop into gdb?
  771. if failures and (args.get('gdb')
  772. or args.get('gdb_case')
  773. or args.get('gdb_main')):
  774. failure = failures[0]
  775. runner_ = runner(**args | {'test_ids': [failure.id]})
  776. if args.get('gdb_main'):
  777. cmd = ['gdb',
  778. '-ex', 'break main',
  779. '-ex', 'run',
  780. '--args'] + runner_
  781. elif args.get('gdb_case'):
  782. path, lineno = runner_paths[testcase(failure.id)]
  783. cmd = ['gdb',
  784. '-ex', 'break %s:%d' % (path, lineno),
  785. '-ex', 'run',
  786. '--args'] + runner_
  787. elif failure.assert_ is not None:
  788. cmd = ['gdb',
  789. '-ex', 'run',
  790. '-ex', 'frame function raise',
  791. '-ex', 'up 2',
  792. '--args'] + runner_
  793. else:
  794. cmd = ['gdb',
  795. '-ex', 'run',
  796. '--args'] + runner_
  797. # exec gdb interactively
  798. if args.get('verbose'):
  799. print(' '.join(shlex.quote(c) for c in cmd))
  800. os.execvp(cmd[0], cmd)
  801. return 1 if failures else 0
  802. def main(**args):
  803. if args.get('compile'):
  804. compile(**args)
  805. elif (args.get('summary')
  806. or args.get('list_suites')
  807. or args.get('list_cases')
  808. or args.get('list_paths')
  809. or args.get('list_defines')
  810. or args.get('list_geometries')
  811. or args.get('list_defaults')):
  812. list_(**args)
  813. else:
  814. run(**args)
  815. if __name__ == "__main__":
  816. import argparse
  817. import sys
  818. parser = argparse.ArgumentParser(
  819. description="Build and run tests.",
  820. conflict_handler='resolve')
  821. parser.add_argument('test_ids', nargs='*',
  822. help="Description of testis to run. May be a directory, path, or \
  823. test identifier. Test identifiers are of the form \
  824. <suite_name>#<case_name>#<permutation>, but suffixes can be \
  825. dropped to run any matching tests. Defaults to %r." % TEST_PATHS)
  826. parser.add_argument('-v', '--verbose', action='store_true',
  827. help="Output commands that run behind the scenes.")
  828. # test flags
  829. test_parser = parser.add_argument_group('test options')
  830. test_parser.add_argument('-Y', '--summary', action='store_true',
  831. help="Show quick summary.")
  832. test_parser.add_argument('-l', '--list-suites', action='store_true',
  833. help="List test suites.")
  834. test_parser.add_argument('-L', '--list-cases', action='store_true',
  835. help="List test cases.")
  836. test_parser.add_argument('--list-paths', action='store_true',
  837. help="List the path for each test case.")
  838. test_parser.add_argument('--list-defines', action='store_true',
  839. help="List the defines for each test permutation.")
  840. test_parser.add_argument('--list-geometries', action='store_true',
  841. help="List the disk geometries used for testing.")
  842. test_parser.add_argument('--list-defaults', action='store_true',
  843. help="List the default defines in this test-runner.")
  844. test_parser.add_argument('-D', '--define', action='append',
  845. help="Override a test define.")
  846. test_parser.add_argument('-G', '--geometry',
  847. help="Filter by geometry.")
  848. test_parser.add_argument('-n', '--normal', action='store_true',
  849. help="Filter for normal tests. Can be combined.")
  850. test_parser.add_argument('-r', '--reentrant', action='store_true',
  851. help="Filter for reentrant tests. Can be combined.")
  852. test_parser.add_argument('-d', '--disk',
  853. help="Use this file as the disk.")
  854. test_parser.add_argument('-t', '--trace',
  855. help="Redirect trace output to this file.")
  856. test_parser.add_argument('-o', '--output',
  857. help="Redirect stdout and stderr to this file.")
  858. test_parser.add_argument('--runner', default=[RUNNER_PATH],
  859. type=lambda x: x.split(),
  860. help="Path to runner, defaults to %r" % RUNNER_PATH)
  861. test_parser.add_argument('-j', '--jobs', nargs='?', type=int,
  862. const=len(os.sched_getaffinity(0)),
  863. help="Number of parallel runners to run.")
  864. test_parser.add_argument('-k', '--keep-going', action='store_true',
  865. help="Don't stop on first error.")
  866. test_parser.add_argument('-i', '--isolate', action='store_true',
  867. help="Run each test permutation in a separate process.")
  868. test_parser.add_argument('-b', '--by-suites', action='store_true',
  869. help="Step through tests by suite.")
  870. test_parser.add_argument('-B', '--by-cases', action='store_true',
  871. help="Step through tests by case.")
  872. test_parser.add_argument('--gdb', action='store_true',
  873. help="Drop into gdb on test failure.")
  874. test_parser.add_argument('--gdb-case', action='store_true',
  875. help="Drop into gdb on test failure but stop at the beginning \
  876. of the failing test case.")
  877. test_parser.add_argument('--gdb-main', action='store_true',
  878. help="Drop into gdb on test failure but stop at the beginning \
  879. of main.")
  880. test_parser.add_argument('--exec', default=[], type=lambda e: e.split(),
  881. help="Run under another executable.")
  882. test_parser.add_argument('--valgrind', action='store_true',
  883. help="Run under Valgrind to find memory errors. Implicitly sets \
  884. --isolate.")
  885. # compilation flags
  886. comp_parser = parser.add_argument_group('compilation options')
  887. comp_parser.add_argument('-c', '--compile', action='store_true',
  888. help="Compile a test suite or source file.")
  889. comp_parser.add_argument('-s', '--source',
  890. help="Source file to compile, possibly injecting internal tests.")
  891. comp_parser.add_argument('-o', '--output',
  892. help="Output file.")
  893. sys.exit(main(**{k: v
  894. for k, v in vars(parser.parse_args()).items()
  895. if v is not None}))