test.py 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004
  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. # TODO move this out in other files
  44. def openio(path, mode='r'):
  45. if path == '-':
  46. if 'r' in mode:
  47. return os.fdopen(os.dup(sys.stdin.fileno()), 'r')
  48. else:
  49. return os.fdopen(os.dup(sys.stdout.fileno()), 'w')
  50. else:
  51. return open(path, mode)
  52. class TestCase:
  53. # create a TestCase object from a config
  54. def __init__(self, config, args={}):
  55. self.name = config.pop('name')
  56. self.path = config.pop('path')
  57. self.suite = config.pop('suite')
  58. self.lineno = config.pop('lineno', None)
  59. self.if_ = config.pop('if', None)
  60. if isinstance(self.if_, bool):
  61. self.if_ = 'true' if self.if_ else 'false'
  62. self.code = config.pop('code')
  63. self.code_lineno = config.pop('code_lineno', None)
  64. self.in_ = config.pop('in',
  65. config.pop('suite_in', None))
  66. self.normal = config.pop('normal',
  67. config.pop('suite_normal', True))
  68. self.reentrant = config.pop('reentrant',
  69. config.pop('suite_reentrant', False))
  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. code_linenos = []
  107. for i, line in enumerate(f):
  108. match = re.match(
  109. '(?P<case>\[\s*cases\s*\.\s*(?P<name>\w+)\s*\])'
  110. '|' '(?P<code>code\s*=)',
  111. line)
  112. if match and match.group('case'):
  113. case_linenos.append((i+1, match.group('name')))
  114. elif match and match.group('code'):
  115. code_linenos.append(i+2)
  116. # sort in case toml parsing did not retain order
  117. case_linenos.sort()
  118. cases = config.pop('cases')
  119. for (lineno, name), (nlineno, _) in it.zip_longest(
  120. case_linenos, case_linenos[1:],
  121. fillvalue=(float('inf'), None)):
  122. code_lineno = min(
  123. (l for l in code_linenos if l >= lineno and l < nlineno),
  124. default=None)
  125. cases[name]['lineno'] = lineno
  126. cases[name]['code_lineno'] = code_lineno
  127. self.if_ = config.pop('if', None)
  128. if isinstance(self.if_, bool):
  129. self.if_ = 'true' if self.if_ else 'false'
  130. self.code = config.pop('code', None)
  131. self.code_lineno = min(
  132. (l for l in code_linenos
  133. if not case_linenos or l < case_linenos[0][0]),
  134. default=None)
  135. # a couple of these we just forward to all cases
  136. defines = config.pop('defines', {})
  137. in_ = config.pop('in', None)
  138. normal = config.pop('normal', True)
  139. reentrant = config.pop('reentrant', False)
  140. self.cases = []
  141. for name, case in sorted(cases.items(),
  142. key=lambda c: c[1].get('lineno')):
  143. self.cases.append(TestCase(config={
  144. 'name': name,
  145. 'path': path + (':%d' % case['lineno']
  146. if 'lineno' in case else ''),
  147. 'suite': self.name,
  148. 'suite_defines': defines,
  149. 'suite_in': in_,
  150. 'suite_normal': normal,
  151. 'suite_reentrant': reentrant,
  152. **case}))
  153. # combine per-case defines
  154. self.defines = set.union(*(
  155. set(case.defines) for case in self.cases))
  156. # combine other per-case things
  157. self.normal = any(case.normal for case in self.cases)
  158. self.reentrant = any(case.reentrant for case in self.cases)
  159. for k in config.keys():
  160. print('\x1b[01;33mwarning:\x1b[m in %s, found unused key %r'
  161. % (self.id(), k),
  162. file=sys.stderr)
  163. def id(self):
  164. return self.name
  165. def compile(**args):
  166. # find .toml files
  167. paths = []
  168. for path in args.get('test_ids', TEST_PATHS):
  169. if os.path.isdir(path):
  170. path = path + '/*.toml'
  171. for path in glob.glob(path):
  172. paths.append(path)
  173. if not paths:
  174. print('no test suites found in %r?' % args['test_ids'])
  175. sys.exit(-1)
  176. if not args.get('source'):
  177. if len(paths) > 1:
  178. print('more than one test suite for compilation? (%r)'
  179. % args['test_ids'])
  180. sys.exit(-1)
  181. # load our suite
  182. suite = TestSuite(paths[0])
  183. else:
  184. # load all suites
  185. suites = [TestSuite(path) for path in paths]
  186. suites.sort(key=lambda s: s.name)
  187. # write generated test source
  188. if 'output' in args:
  189. with openio(args['output'], 'w') as f:
  190. _write = f.write
  191. def write(s):
  192. f.lineno += s.count('\n')
  193. _write(s)
  194. def writeln(s=''):
  195. f.lineno += s.count('\n') + 1
  196. _write(s)
  197. _write('\n')
  198. f.lineno = 1
  199. f.write = write
  200. f.writeln = writeln
  201. # redirect littlefs tracing
  202. f.writeln('#define LFS_TRACE_(fmt, ...) do { \\')
  203. f.writeln(8*' '+'extern FILE *test_trace; \\')
  204. f.writeln(8*' '+'if (test_trace) { \\')
  205. f.writeln(12*' '+'fprintf(test_trace, '
  206. '"%s:%d:trace: " fmt "%s\\n", \\')
  207. f.writeln(20*' '+'__FILE__, __LINE__, __VA_ARGS__); \\')
  208. f.writeln(8*' '+'} \\')
  209. f.writeln(4*' '+'} while (0)')
  210. f.writeln('#define LFS_TRACE(...) LFS_TRACE_(__VA_ARGS__, "")')
  211. f.writeln('#define LFS_TESTBD_TRACE(...) '
  212. 'LFS_TRACE_(__VA_ARGS__, "")')
  213. f.writeln()
  214. # write out generated functions, this can end up in different
  215. # files depending on the "in" attribute
  216. #
  217. # note it's up to the specific generated file to declare
  218. # the test defines
  219. def write_case_functions(f, suite, case):
  220. # create case define functions
  221. if case.defines:
  222. # deduplicate defines by value to try to reduce the
  223. # number of functions we generate
  224. define_cbs = {}
  225. for i, defines in enumerate(case.permutations):
  226. for k, v in sorted(defines.items()):
  227. if v not in define_cbs:
  228. name = ('__test__%s__%s__%s__%d'
  229. % (suite.name, case.name, k, i))
  230. define_cbs[v] = name
  231. f.writeln('intmax_t %s(void) {' % name)
  232. f.writeln(4*' '+'return %s;' % v)
  233. f.writeln('}')
  234. f.writeln()
  235. f.writeln('intmax_t (*const *const '
  236. '__test__%s__%s__defines[])(void) = {'
  237. % (suite.name, case.name))
  238. for defines in case.permutations:
  239. f.writeln(4*' '+'(intmax_t (*const[])(void)){')
  240. for define in sorted(suite.defines):
  241. f.writeln(8*' '+'%s,' % (
  242. define_cbs[defines[define]]
  243. if define in defines
  244. else 'NULL'))
  245. f.writeln(4*' '+'},')
  246. f.writeln('};')
  247. f.writeln()
  248. # create case filter function
  249. if suite.if_ is not None or case.if_ is not None:
  250. f.writeln('bool __test__%s__%s__filter(void) {'
  251. % (suite.name, case.name))
  252. f.writeln(4*' '+'return %s;'
  253. % ' && '.join('(%s)' % if_
  254. for if_ in [suite.if_, case.if_]
  255. if if_ is not None))
  256. f.writeln('}')
  257. f.writeln()
  258. # create case run function
  259. f.writeln('void __test__%s__%s__run('
  260. '__attribute__((unused)) struct lfs_config *cfg) {'
  261. % (suite.name, case.name))
  262. if CASE_PROLOGUE.strip():
  263. f.writeln(4*' '+'%s'
  264. % CASE_PROLOGUE.strip().replace('\n', '\n'+4*' '))
  265. f.writeln()
  266. f.writeln(4*' '+'// test case %s' % case.id())
  267. if case.code_lineno is not None:
  268. f.writeln(4*' '+'#line %d "%s"'
  269. % (case.code_lineno, suite.path))
  270. f.write(case.code)
  271. if case.code_lineno is not None:
  272. f.writeln(4*' '+'#line %d "%s"'
  273. % (f.lineno+1, args['output']))
  274. if CASE_EPILOGUE.strip():
  275. f.writeln()
  276. f.writeln(4*' '+'%s'
  277. % CASE_EPILOGUE.strip().replace('\n', '\n'+4*' '))
  278. f.writeln('}')
  279. f.writeln()
  280. if not args.get('source'):
  281. # write test suite prologue
  282. f.writeln('%s' % SUITE_PROLOGUE.strip())
  283. f.writeln()
  284. if suite.code is not None:
  285. if suite.code_lineno is not None:
  286. f.writeln('#line %d "%s"'
  287. % (suite.code_lineno, suite.path))
  288. f.write(suite.code)
  289. if suite.code_lineno is not None:
  290. f.writeln('#line %d "%s"'
  291. % (f.lineno+1, args['output']))
  292. f.writeln()
  293. if suite.defines:
  294. for i, define in enumerate(sorted(suite.defines)):
  295. f.writeln('#ifndef %s' % define)
  296. f.writeln('#define %-24s test_define(%d)'
  297. % (define, i))
  298. f.writeln('#endif')
  299. f.writeln()
  300. # create case functions
  301. for case in suite.cases:
  302. if case.in_ is None:
  303. write_case_functions(f, suite, case)
  304. else:
  305. if case.defines:
  306. f.writeln('extern intmax_t (*const *const '
  307. '__test__%s__%s__defines[])(void);'
  308. % (suite.name, case.name))
  309. if suite.if_ is not None or case.if_ is not None:
  310. f.writeln('extern bool __test__%s__%s__filter('
  311. 'void);'
  312. % (suite.name, case.name))
  313. f.writeln('extern void __test__%s__%s__run('
  314. 'struct lfs_config *cfg);'
  315. % (suite.name, case.name))
  316. f.writeln()
  317. # create suite struct
  318. f.writeln('__attribute__((section("_test_suites")))')
  319. f.writeln('const struct test_suite __test__%s__suite = {'
  320. % suite.name)
  321. f.writeln(4*' '+'.id = "%s",' % suite.id())
  322. f.writeln(4*' '+'.name = "%s",' % suite.name)
  323. f.writeln(4*' '+'.path = "%s",' % suite.path)
  324. f.writeln(4*' '+'.types = %s,'
  325. % ' | '.join(filter(None, [
  326. 'TEST_NORMAL' if suite.normal else None,
  327. 'TEST_REENTRANT' if suite.reentrant else None])))
  328. if suite.defines:
  329. # create suite define names
  330. f.writeln(4*' '+'.define_names = (const char *const[]){')
  331. for k in sorted(suite.defines):
  332. f.writeln(8*' '+'"%s",' % k)
  333. f.writeln(4*' '+'},')
  334. f.writeln(4*' '+'.define_count = %d,' % len(suite.defines))
  335. f.writeln(4*' '+'.cases = (const struct test_case[]){')
  336. for case in suite.cases:
  337. # create case structs
  338. f.writeln(8*' '+'{')
  339. f.writeln(12*' '+'.id = "%s",' % case.id())
  340. f.writeln(12*' '+'.name = "%s",' % case.name)
  341. f.writeln(12*' '+'.path = "%s",' % case.path)
  342. f.writeln(12*' '+'.types = %s,'
  343. % ' | '.join(filter(None, [
  344. 'TEST_NORMAL' if case.normal else None,
  345. 'TEST_REENTRANT' if case.reentrant else None])))
  346. f.writeln(12*' '+'.permutations = %d,'
  347. % len(case.permutations))
  348. if case.defines:
  349. f.writeln(12*' '+'.defines = __test__%s__%s__defines,'
  350. % (suite.name, case.name))
  351. if suite.if_ is not None or case.if_ is not None:
  352. f.writeln(12*' '+'.filter = __test__%s__%s__filter,'
  353. % (suite.name, case.name))
  354. f.writeln(12*' '+'.run = __test__%s__%s__run,'
  355. % (suite.name, case.name))
  356. f.writeln(8*' '+'},')
  357. f.writeln(4*' '+'},')
  358. f.writeln(4*' '+'.case_count = %d,' % len(suite.cases))
  359. f.writeln('};')
  360. f.writeln()
  361. else:
  362. # copy source
  363. f.writeln('#line 1 "%s"' % args['source'])
  364. with open(args['source']) as sf:
  365. shutil.copyfileobj(sf, f)
  366. f.writeln()
  367. f.write(SUITE_PROLOGUE)
  368. f.writeln()
  369. # write any internal tests
  370. for suite in suites:
  371. for case in suite.cases:
  372. if (case.in_ is not None
  373. and os.path.normpath(case.in_)
  374. == os.path.normpath(args['source'])):
  375. # write defines, but note we need to undef any
  376. # new defines since we're in someone else's file
  377. if suite.defines:
  378. for i, define in enumerate(
  379. sorted(suite.defines)):
  380. f.writeln('#ifndef %s' % define)
  381. f.writeln('#define %-24s test_define(%d)'
  382. % (define, i))
  383. f.writeln('#define __TEST__%s__NEEDS_UNDEF'
  384. % define)
  385. f.writeln('#endif')
  386. f.writeln()
  387. write_case_functions(f, suite, case)
  388. if suite.defines:
  389. for define in sorted(suite.defines):
  390. f.writeln('#ifdef __TEST__%s__NEEDS_UNDEF'
  391. % define)
  392. f.writeln('#undef __TEST__%s__NEEDS_UNDEF'
  393. % define)
  394. f.writeln('#undef %s' % define)
  395. f.writeln('#endif')
  396. f.writeln()
  397. def runner(**args):
  398. cmd = args['runner'].copy()
  399. cmd.extend(args.get('test_ids'))
  400. # run under some external command?
  401. cmd[:0] = args.get('exec', [])
  402. # run under valgrind?
  403. if args.get('valgrind'):
  404. cmd[:0] = filter(None, [
  405. 'valgrind',
  406. '--leak-check=full',
  407. '--track-origins=yes',
  408. '--error-exitcode=4',
  409. '-q'])
  410. # filter tests?
  411. if args.get('normal'): cmd.append('-n')
  412. if args.get('reentrant'): cmd.append('-r')
  413. if args.get('geometry'):
  414. cmd.append('-G%s' % args.get('geometry'))
  415. # defines?
  416. if args.get('define'):
  417. for define in args.get('define'):
  418. cmd.append('-D%s' % define)
  419. return cmd
  420. def list_(**args):
  421. cmd = runner(**args)
  422. if args.get('summary'): cmd.append('--summary')
  423. if args.get('list_suites'): cmd.append('--list-suites')
  424. if args.get('list_cases'): cmd.append('--list-cases')
  425. if args.get('list_paths'): cmd.append('--list-paths')
  426. if args.get('list_defines'): cmd.append('--list-defines')
  427. if args.get('list_geometries'): cmd.append('--list-geometries')
  428. if args.get('verbose'):
  429. print(' '.join(shlex.quote(c) for c in cmd))
  430. sys.exit(sp.call(cmd))
  431. def find_cases(runner_, **args):
  432. # query from runner
  433. cmd = runner_ + ['--list-cases']
  434. if args.get('verbose'):
  435. print(' '.join(shlex.quote(c) for c in cmd))
  436. proc = sp.Popen(cmd,
  437. stdout=sp.PIPE,
  438. stderr=sp.PIPE if not args.get('verbose') else None,
  439. universal_newlines=True,
  440. errors='replace')
  441. expected_suite_perms = co.defaultdict(lambda: 0)
  442. expected_case_perms = co.defaultdict(lambda: 0)
  443. expected_perms = 0
  444. total_perms = 0
  445. pattern = re.compile(
  446. '^(?P<id>(?P<case>(?P<suite>[^#]+)#[^\s#]+)[^\s]*)\s+'
  447. '[^\s]+\s+(?P<filtered>\d+)/(?P<perms>\d+)')
  448. # skip the first line
  449. for line in it.islice(proc.stdout, 1, None):
  450. m = pattern.match(line)
  451. if m:
  452. filtered = int(m.group('filtered'))
  453. expected_suite_perms[m.group('suite')] += filtered
  454. expected_case_perms[m.group('id')] += filtered
  455. expected_perms += filtered
  456. total_perms += int(m.group('perms'))
  457. proc.wait()
  458. if proc.returncode != 0:
  459. if not args.get('verbose'):
  460. for line in proc.stderr:
  461. sys.stdout.write(line)
  462. sys.exit(-1)
  463. return (
  464. expected_suite_perms,
  465. expected_case_perms,
  466. expected_perms,
  467. total_perms)
  468. def find_paths(runner_, **args):
  469. # query from runner
  470. cmd = runner_ + ['--list-paths']
  471. if args.get('verbose'):
  472. print(' '.join(shlex.quote(c) for c in cmd))
  473. proc = sp.Popen(cmd,
  474. stdout=sp.PIPE,
  475. stderr=sp.PIPE if not args.get('verbose') else None,
  476. universal_newlines=True,
  477. errors='replace')
  478. paths = co.OrderedDict()
  479. pattern = re.compile(
  480. '^(?P<id>(?P<case>(?P<suite>[^#]+)#[^\s#]+)[^\s]*)\s+'
  481. '(?P<path>[^:]+):(?P<lineno>\d+)')
  482. for line in proc.stdout:
  483. m = pattern.match(line)
  484. if m:
  485. paths[m.group('id')] = (m.group('path'), int(m.group('lineno')))
  486. proc.wait()
  487. if proc.returncode != 0:
  488. if not args.get('verbose'):
  489. for line in proc.stderr:
  490. sys.stdout.write(line)
  491. sys.exit(-1)
  492. return paths
  493. def find_defines(runner_, **args):
  494. # query from runner
  495. cmd = runner_ + ['--list-defines']
  496. if args.get('verbose'):
  497. print(' '.join(shlex.quote(c) for c in cmd))
  498. proc = sp.Popen(cmd,
  499. stdout=sp.PIPE,
  500. stderr=sp.PIPE if not args.get('verbose') else None,
  501. universal_newlines=True,
  502. errors='replace')
  503. defines = co.OrderedDict()
  504. pattern = re.compile(
  505. '^(?P<id>(?P<case>(?P<suite>[^#]+)#[^\s#]+)[^\s]*)\s+'
  506. '(?P<defines>(?:\w+=\w+\s*)+)')
  507. for line in proc.stdout:
  508. m = pattern.match(line)
  509. if m:
  510. defines[m.group('id')] = {k: v
  511. for k, v in re.findall('(\w+)=(\w+)', m.group('defines'))}
  512. proc.wait()
  513. if proc.returncode != 0:
  514. if not args.get('verbose'):
  515. for line in proc.stderr:
  516. sys.stdout.write(line)
  517. sys.exit(-1)
  518. return defines
  519. class TestFailure(Exception):
  520. def __init__(self, id, returncode, output, assert_=None):
  521. self.id = id
  522. self.returncode = returncode
  523. self.output = output
  524. self.assert_ = assert_
  525. def run_stage(name, runner_, **args):
  526. # get expected suite/case/perm counts
  527. expected_suite_perms, expected_case_perms, expected_perms, total_perms = (
  528. find_cases(runner_, **args))
  529. passed_suite_perms = co.defaultdict(lambda: 0)
  530. passed_case_perms = co.defaultdict(lambda: 0)
  531. passed_perms = 0
  532. failures = []
  533. killed = False
  534. pattern = re.compile('^(?:'
  535. '(?P<op>running|finished|skipped) '
  536. '(?P<id>(?P<case>(?P<suite>[^#]+)#[^\s#]+)[^\s]*)'
  537. '|' '(?P<path>[^:]+):(?P<lineno>\d+):(?P<op_>assert):'
  538. ' *(?P<message>.*)' ')$')
  539. locals = th.local()
  540. children = set()
  541. def run_runner(runner_):
  542. nonlocal passed_suite_perms
  543. nonlocal passed_case_perms
  544. nonlocal passed_perms
  545. nonlocal locals
  546. # run the tests!
  547. cmd = runner_.copy()
  548. if args.get('disk'):
  549. cmd.append('--disk=%s' % args['disk'])
  550. if args.get('trace'):
  551. cmd.append('--trace=%s' % args['trace'])
  552. if args.get('verbose'):
  553. print(' '.join(shlex.quote(c) for c in cmd))
  554. mpty, spty = pty.openpty()
  555. proc = sp.Popen(cmd, stdout=spty, stderr=spty)
  556. os.close(spty)
  557. children.add(proc)
  558. mpty = os.fdopen(mpty, 'r', 1)
  559. if args.get('output'):
  560. output = openio(args['output'], 'w')
  561. last_id = None
  562. last_output = []
  563. last_assert = None
  564. try:
  565. while True:
  566. # parse a line for state changes
  567. try:
  568. line = mpty.readline()
  569. except OSError as e:
  570. if e.errno == errno.EIO:
  571. break
  572. raise
  573. if not line:
  574. break
  575. last_output.append(line)
  576. if args.get('output'):
  577. output.write(line)
  578. elif args.get('verbose'):
  579. sys.stdout.write(line)
  580. m = pattern.match(line)
  581. if m:
  582. op = m.group('op') or m.group('op_')
  583. if op == 'running':
  584. locals.seen_perms += 1
  585. last_id = m.group('id')
  586. last_output = []
  587. last_assert = None
  588. elif op == 'finished':
  589. passed_suite_perms[m.group('suite')] += 1
  590. passed_case_perms[m.group('case')] += 1
  591. passed_perms += 1
  592. elif op == 'skipped':
  593. locals.seen_perms += 1
  594. elif op == 'assert':
  595. last_assert = (
  596. m.group('path'),
  597. int(m.group('lineno')),
  598. m.group('message'))
  599. # go ahead and kill the process, aborting takes a while
  600. if args.get('keep_going'):
  601. proc.kill()
  602. except KeyboardInterrupt:
  603. raise TestFailure(last_id, 1, last_output)
  604. finally:
  605. children.remove(proc)
  606. mpty.close()
  607. if args.get('output'):
  608. output.close()
  609. proc.wait()
  610. if proc.returncode != 0:
  611. raise TestFailure(
  612. last_id,
  613. proc.returncode,
  614. last_output,
  615. last_assert)
  616. def run_job(runner, start=None, step=None):
  617. nonlocal failures
  618. nonlocal locals
  619. start = start or 0
  620. step = step or 1
  621. while start < total_perms:
  622. runner_ = runner.copy()
  623. if start is not None:
  624. runner_.append('--start=%d' % start)
  625. if step is not None:
  626. runner_.append('--step=%d' % step)
  627. if args.get('isolate') or args.get('valgrind'):
  628. runner_.append('--stop=%d' % (start+step))
  629. try:
  630. # run the tests
  631. locals.seen_perms = 0
  632. run_runner(runner_)
  633. assert locals.seen_perms > 0
  634. start += locals.seen_perms*step
  635. except TestFailure as failure:
  636. # race condition for multiple failures?
  637. if failures and not args.get('keep_going'):
  638. break
  639. failures.append(failure)
  640. if args.get('keep_going') and not killed:
  641. # resume after failed test
  642. assert locals.seen_perms > 0
  643. start += locals.seen_perms*step
  644. continue
  645. else:
  646. # stop other tests
  647. for child in children.copy():
  648. child.kill()
  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('--valgrind', action='store_true',
  881. help="Run under Valgrind to find memory errors. Implicitly sets \
  882. --isolate.")
  883. test_parser.add_argument('--exec', default=[], type=lambda e: e.split(),
  884. help="Run under another executable.")
  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. # TODO apply this to other scripts?
  894. sys.exit(main(**{k: v
  895. for k, v in vars(parser.parse_args()).items()
  896. if v is not None}))