test.py 48 KB

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