test_.py 35 KB

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