test_.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747
  1. #!/usr/bin/env python3
  2. # This script manages littlefs tests, which are configured with
  3. # .toml files stored in the tests directory.
  4. #
  5. # TODO
  6. # x nargs > 1?
  7. # x show perm config on failure
  8. # x filtering
  9. # n show perm config on verbose?
  10. # x better lineno tracking for cases?
  11. # n non-int perms?
  12. # x different path format?
  13. # - suite.prologue, suite.epilogue
  14. # x in
  15. # x change BLOCK_CYCLES to -1 by default
  16. # x change persist behaviour
  17. # x config chaining correct
  18. # - why can't gdb see my defines?
  19. # - say no to internal?
  20. # x buffering stdout issues?
  21. import toml
  22. import glob
  23. import re
  24. import os
  25. import io
  26. import itertools as it
  27. import collections.abc as abc
  28. import subprocess as sp
  29. import base64
  30. import sys
  31. import copy
  32. import shlex
  33. import pty
  34. import errno
  35. import signal
  36. TESTDIR = 'tests_'
  37. RULES = """
  38. define FLATTEN
  39. tests_/%$(subst /,.,$(target)): $(target)
  40. ./scripts/explode_asserts.py $$< -o $$@
  41. endef
  42. $(foreach target,$(SRC),$(eval $(FLATTEN)))
  43. -include tests_/*.d
  44. .SECONDARY:
  45. %.test: override CFLAGS += -gdwarf-2
  46. %.test: override CFLAGS += -ggdb3
  47. %.test: override CFLAGS += -g3
  48. %.test: %.test.o $(foreach f,$(subst /,.,$(SRC:.c=.o)),%.$f)
  49. $(CC) $(CFLAGS) $^ $(LFLAGS) -o $@
  50. """
  51. GLOBALS = """
  52. //////////////// AUTOGENERATED TEST ////////////////
  53. #include "lfs.h"
  54. #include "testbd/lfs_testbd.h"
  55. #include <stdio.h>
  56. extern const char *lfs_testbd_path;
  57. extern uint32_t lfs_testbd_cycles;
  58. """
  59. DEFINES = {
  60. 'LFS_READ_SIZE': 16,
  61. 'LFS_PROG_SIZE': 'LFS_READ_SIZE',
  62. 'LFS_BLOCK_SIZE': 512,
  63. 'LFS_BLOCK_COUNT': 1024,
  64. 'LFS_BLOCK_CYCLES': -1,
  65. 'LFS_CACHE_SIZE': '(64 % LFS_PROG_SIZE == 0 ? 64 : LFS_PROG_SIZE)',
  66. 'LFS_LOOKAHEAD_SIZE': 16,
  67. 'LFS_ERASE_VALUE': 0xff,
  68. 'LFS_ERASE_CYCLES': 0,
  69. 'LFS_BADBLOCK_BEHAVIOR': 'LFS_TESTBD_BADBLOCK_NOPROG',
  70. }
  71. PROLOGUE = """
  72. // prologue
  73. __attribute__((unused)) lfs_t lfs;
  74. __attribute__((unused)) lfs_testbd_t bd;
  75. __attribute__((unused)) lfs_file_t file;
  76. __attribute__((unused)) lfs_dir_t dir;
  77. __attribute__((unused)) struct lfs_info info;
  78. __attribute__((unused)) char path[1024];
  79. __attribute__((unused)) uint8_t buffer[1024];
  80. __attribute__((unused)) lfs_size_t size;
  81. __attribute__((unused)) int err;
  82. __attribute__((unused)) const struct lfs_config cfg = {
  83. .context = &bd,
  84. .read = lfs_testbd_read,
  85. .prog = lfs_testbd_prog,
  86. .erase = lfs_testbd_erase,
  87. .sync = lfs_testbd_sync,
  88. .read_size = LFS_READ_SIZE,
  89. .prog_size = LFS_PROG_SIZE,
  90. .block_size = LFS_BLOCK_SIZE,
  91. .block_count = LFS_BLOCK_COUNT,
  92. .block_cycles = LFS_BLOCK_CYCLES,
  93. .cache_size = LFS_CACHE_SIZE,
  94. .lookahead_size = LFS_LOOKAHEAD_SIZE,
  95. };
  96. __attribute__((unused)) const struct lfs_testbd_config bdcfg = {
  97. .erase_value = LFS_ERASE_VALUE,
  98. .erase_cycles = LFS_ERASE_CYCLES,
  99. .badblock_behavior = LFS_BADBLOCK_BEHAVIOR,
  100. .power_cycles = lfs_testbd_cycles,
  101. };
  102. lfs_testbd_createcfg(&cfg, lfs_testbd_path, &bdcfg) => 0;
  103. """
  104. EPILOGUE = """
  105. // epilogue
  106. lfs_testbd_destroy(&cfg) => 0;
  107. """
  108. PASS = '\033[32m✓\033[0m'
  109. FAIL = '\033[31m✗\033[0m'
  110. class TestFailure(Exception):
  111. def __init__(self, case, returncode=None, stdout=None, assert_=None):
  112. self.case = case
  113. self.returncode = returncode
  114. self.stdout = stdout
  115. self.assert_ = assert_
  116. class TestCase:
  117. def __init__(self, config, filter=filter,
  118. suite=None, caseno=None, lineno=None, **_):
  119. self.filter = filter
  120. self.suite = suite
  121. self.caseno = caseno
  122. self.lineno = lineno
  123. self.code = config['code']
  124. self.code_lineno = config['code_lineno']
  125. self.defines = config.get('define', {})
  126. self.if_ = config.get('if', None)
  127. self.in_ = config.get('in', None)
  128. def __str__(self):
  129. if hasattr(self, 'permno'):
  130. if any(k not in self.case.defines for k in self.defines):
  131. return '%s#%d#%d (%s)' % (
  132. self.suite.name, self.caseno, self.permno, ', '.join(
  133. '%s=%s' % (k, v) for k, v in self.defines.items()
  134. if k not in self.case.defines))
  135. else:
  136. return '%s#%d#%d' % (
  137. self.suite.name, self.caseno, self.permno)
  138. else:
  139. return '%s#%d' % (
  140. self.suite.name, self.caseno)
  141. def permute(self, defines, permno=None, **_):
  142. ncase = copy.copy(self)
  143. ncase.case = self
  144. ncase.perms = [ncase]
  145. ncase.permno = permno
  146. ncase.defines = defines
  147. return ncase
  148. def build(self, f, **_):
  149. # prologue
  150. for k, v in sorted(self.defines.items()):
  151. if k not in self.suite.defines:
  152. f.write('#define %s %s\n' % (k, v))
  153. f.write('void test_case%d(%s) {' % (self.caseno, ','.join(
  154. '\n'+8*' '+'__attribute__((unused)) intmax_t %s' % k
  155. for k in sorted(self.perms[0].defines)
  156. if k not in self.defines)))
  157. f.write(PROLOGUE)
  158. f.write('\n')
  159. f.write(4*' '+'// test case %d\n' % self.caseno)
  160. f.write(4*' '+'#line %d "%s"\n' % (self.code_lineno, self.suite.path))
  161. # test case goes here
  162. f.write(self.code)
  163. # epilogue
  164. f.write(EPILOGUE)
  165. f.write('}\n')
  166. for k, v in sorted(self.defines.items()):
  167. if k not in self.suite.defines:
  168. f.write('#undef %s\n' % k)
  169. def shouldtest(self, **args):
  170. if (self.filter is not None and
  171. len(self.filter) >= 1 and
  172. self.filter[0] != self.caseno):
  173. return False
  174. elif (self.filter is not None and
  175. len(self.filter) >= 2 and
  176. self.filter[1] != self.permno):
  177. return False
  178. elif self.if_ is not None:
  179. return eval(self.if_, None, self.defines.copy())
  180. else:
  181. return True
  182. def test(self, exec=[], persist=False, cycles=None,
  183. gdb=False, failure=None, **args):
  184. # build command
  185. cmd = exec + ['./%s.test' % self.suite.path,
  186. repr(self.caseno), repr(self.permno)]
  187. # persist disk or keep in RAM for speed?
  188. if persist:
  189. if persist != 'noerase':
  190. try:
  191. os.remove(self.suite.path + '.disk')
  192. except FileNotFoundError:
  193. pass
  194. cmd.append(self.suite.path + '.disk')
  195. # simulate power-loss after n cycles?
  196. if cycles:
  197. cmd.append(str(cycles))
  198. # failed? drop into debugger?
  199. if gdb and failure:
  200. ncmd = ['gdb']
  201. if gdb == 'assert':
  202. ncmd.extend(['-ex', 'r'])
  203. if failure.assert_:
  204. ncmd.extend(['-ex', 'up'])
  205. elif gdb == 'start':
  206. ncmd.extend([
  207. '-ex', 'b %s:%d' % (self.suite.path, self.code_lineno),
  208. '-ex', 'r'])
  209. ncmd.extend(['--args'] + cmd)
  210. if args.get('verbose', False):
  211. print(' '.join(shlex.quote(c) for c in ncmd))
  212. signal.signal(signal.SIGINT, signal.SIG_IGN)
  213. sys.exit(sp.call(ncmd))
  214. # run test case!
  215. mpty, spty = pty.openpty()
  216. if args.get('verbose', False):
  217. print(' '.join(shlex.quote(c) for c in cmd))
  218. proc = sp.Popen(cmd, stdout=spty, stderr=spty)
  219. os.close(spty)
  220. mpty = os.fdopen(mpty, 'r', 1)
  221. stdout = []
  222. assert_ = None
  223. while True:
  224. try:
  225. line = mpty.readline()
  226. except OSError as e:
  227. if e.errno == errno.EIO:
  228. break
  229. raise
  230. stdout.append(line)
  231. if args.get('verbose', False):
  232. sys.stdout.write(line)
  233. # intercept asserts
  234. m = re.match(
  235. '^{0}([^:]+):(\d+):(?:\d+:)?{0}{1}:{0}(.*)$'
  236. .format('(?:\033\[[\d;]*.| )*', 'assert'),
  237. line)
  238. if m and assert_ is None:
  239. try:
  240. with open(m.group(1)) as f:
  241. lineno = int(m.group(2))
  242. line = next(it.islice(f, lineno-1, None)).strip('\n')
  243. assert_ = {
  244. 'path': m.group(1),
  245. 'line': line,
  246. 'lineno': lineno,
  247. 'message': m.group(3)}
  248. except:
  249. pass
  250. proc.wait()
  251. # did we pass?
  252. if proc.returncode != 0:
  253. raise TestFailure(self, proc.returncode, stdout, assert_)
  254. else:
  255. return PASS
  256. class ValgrindTestCase(TestCase):
  257. def __init__(self, config, **args):
  258. self.leaky = config.get('leaky', False)
  259. super().__init__(config, **args)
  260. def shouldtest(self, **args):
  261. return not self.leaky and super().shouldtest(**args)
  262. def test(self, exec=[], **args):
  263. exec = exec + [
  264. 'valgrind',
  265. '--leak-check=full',
  266. '--error-exitcode=4',
  267. '-q']
  268. return super().test(exec=exec, **args)
  269. class ReentrantTestCase(TestCase):
  270. def __init__(self, config, **args):
  271. self.reentrant = config.get('reentrant', False)
  272. super().__init__(config, **args)
  273. def shouldtest(self, **args):
  274. return self.reentrant and super().shouldtest(**args)
  275. def test(self, exec=[], persist=False, gdb=False, failure=None, **args):
  276. for cycles in it.count(1):
  277. # clear disk first?
  278. if cycles == 1 and persist != 'noerase':
  279. persist = 'erase'
  280. else:
  281. persist = 'noerase'
  282. # exact cycle we should drop into debugger?
  283. if gdb and failure and failure.cycleno == cycles:
  284. return super().test(gdb=gdb,
  285. persist=persist, failure=failure, **args)
  286. # run tests, but kill the program after prog/erase has
  287. # been hit n cycles. We exit with a special return code if the
  288. # program has not finished, since this isn't a test failure.
  289. try:
  290. return super().test(persist=persist, cycles=cycles, **args)
  291. except TestFailure as nfailure:
  292. if nfailure.returncode == 33:
  293. continue
  294. else:
  295. nfailure.cycleno = cycles
  296. raise
  297. class TestSuite:
  298. def __init__(self, path, filter=None, TestCase=TestCase, **args):
  299. self.name = os.path.basename(path)
  300. if self.name.endswith('.toml'):
  301. self.name = self.name[:-len('.toml')]
  302. self.path = path
  303. self.filter = filter
  304. self.TestCase = TestCase
  305. with open(path) as f:
  306. # load tests
  307. config = toml.load(f)
  308. # find line numbers
  309. f.seek(0)
  310. linenos = []
  311. code_linenos = []
  312. for i, line in enumerate(f):
  313. if re.match(r'\[\[\s*case\s*\]\]', line):
  314. linenos.append(i+1)
  315. if re.match(r'code\s*=\s*(\'\'\'|""")', line):
  316. code_linenos.append(i+2)
  317. code_linenos.reverse()
  318. # grab global config
  319. self.defines = config.get('define', {})
  320. self.code = config.get('code', None)
  321. if self.code is not None:
  322. self.code_lineno = code_linenos.pop()
  323. # create initial test cases
  324. self.cases = []
  325. for i, (case, lineno) in enumerate(zip(config['case'], linenos)):
  326. # code lineno?
  327. if 'code' in case:
  328. case['code_lineno'] = code_linenos.pop()
  329. # give our case's config a copy of our "global" config
  330. for k, v in config.items():
  331. if k not in case:
  332. case[k] = v
  333. # initialize test case
  334. self.cases.append(self.TestCase(case, filter=filter,
  335. suite=self, caseno=i, lineno=lineno, **args))
  336. def __str__(self):
  337. return self.name
  338. def __lt__(self, other):
  339. return self.name < other.name
  340. def permute(self, defines={}, **args):
  341. for case in self.cases:
  342. # lets find all parameterized definitions, in one of [args.D,
  343. # suite.defines, case.defines, DEFINES]. Note that each of these
  344. # can be either a dict of defines, or a list of dicts, expressing
  345. # an initial set of permutations.
  346. pending = [{}]
  347. for inits in [defines, self.defines, case.defines, DEFINES]:
  348. if not isinstance(inits, list):
  349. inits = [inits]
  350. npending = []
  351. for init, pinit in it.product(inits, pending):
  352. ninit = pinit.copy()
  353. for k, v in init.items():
  354. if k not in ninit:
  355. try:
  356. ninit[k] = eval(v)
  357. except:
  358. ninit[k] = v
  359. npending.append(ninit)
  360. pending = npending
  361. # expand permutations
  362. pending = list(reversed(pending))
  363. expanded = []
  364. while pending:
  365. perm = pending.pop()
  366. for k, v in sorted(perm.items()):
  367. if not isinstance(v, str) and isinstance(v, abc.Iterable):
  368. for nv in reversed(v):
  369. nperm = perm.copy()
  370. nperm[k] = nv
  371. pending.append(nperm)
  372. break
  373. else:
  374. expanded.append(perm)
  375. # generate permutations
  376. case.perms = []
  377. for i, perm in enumerate(expanded):
  378. case.perms.append(case.permute(perm, permno=i, **args))
  379. # also track non-unique defines
  380. case.defines = {}
  381. for k, v in case.perms[0].defines.items():
  382. if all(perm.defines[k] == v for perm in case.perms):
  383. case.defines[k] = v
  384. # track all perms and non-unique defines
  385. self.perms = []
  386. for case in self.cases:
  387. self.perms.extend(case.perms)
  388. self.defines = {}
  389. for k, v in self.perms[0].defines.items():
  390. if all(perm.defines.get(k, None) == v for perm in self.perms):
  391. self.defines[k] = v
  392. return self.perms
  393. def build(self, **args):
  394. # build test files
  395. tf = open(self.path + '.test.c.t', 'w')
  396. tf.write(GLOBALS)
  397. if self.code is not None:
  398. tf.write('#line %d "%s"\n' % (self.code_lineno, self.path))
  399. tf.write(self.code)
  400. tfs = {None: tf}
  401. for case in self.cases:
  402. if case.in_ not in tfs:
  403. tfs[case.in_] = open(self.path+'.'+
  404. case.in_.replace('/', '.')+'.t', 'w')
  405. tfs[case.in_].write('#line 1 "%s"\n' % case.in_)
  406. with open(case.in_) as f:
  407. for line in f:
  408. tfs[case.in_].write(line)
  409. tfs[case.in_].write('\n')
  410. tfs[case.in_].write(GLOBALS)
  411. tfs[case.in_].write('\n')
  412. case.build(tfs[case.in_], **args)
  413. tf.write('\n')
  414. tf.write('const char *lfs_testbd_path;\n')
  415. tf.write('uint32_t lfs_testbd_cycles;\n')
  416. tf.write('int main(int argc, char **argv) {\n')
  417. tf.write(4*' '+'int case_ = (argc > 1) ? atoi(argv[1]) : 0;\n')
  418. tf.write(4*' '+'int perm = (argc > 2) ? atoi(argv[2]) : 0;\n')
  419. tf.write(4*' '+'lfs_testbd_path = (argc > 3) ? argv[3] : NULL;\n')
  420. tf.write(4*' '+'lfs_testbd_cycles = (argc > 4) ? atoi(argv[4]) : 0;\n')
  421. for perm in self.perms:
  422. # test declaration
  423. tf.write(4*' '+'extern void test_case%d(%s);\n' % (
  424. perm.caseno, ', '.join(
  425. 'intmax_t %s' % k for k in sorted(perm.defines)
  426. if k not in perm.case.defines)))
  427. # test call
  428. tf.write(4*' '+
  429. 'if (argc < 3 || (case_ == %d && perm == %d)) {'
  430. ' test_case%d(%s); '
  431. '}\n' % (perm.caseno, perm.permno, perm.caseno, ', '.join(
  432. str(v) for k, v in sorted(perm.defines.items())
  433. if k not in perm.case.defines)))
  434. tf.write('}\n')
  435. for tf in tfs.values():
  436. tf.close()
  437. # write makefiles
  438. with open(self.path + '.mk', 'w') as mk:
  439. mk.write(RULES.replace(4*' ', '\t'))
  440. mk.write('\n')
  441. # add truely global defines globally
  442. for k, v in sorted(self.defines.items()):
  443. mk.write('%s: override CFLAGS += -D%s=%r\n' % (
  444. self.path+'.test', k, v))
  445. for path in tfs:
  446. if path is None:
  447. mk.write('%s: %s | %s\n' % (
  448. self.path+'.test.c',
  449. self.path,
  450. self.path+'.test.c.t'))
  451. else:
  452. mk.write('%s: %s %s | %s\n' % (
  453. self.path+'.'+path.replace('/', '.'),
  454. self.path, path,
  455. self.path+'.'+path.replace('/', '.')+'.t'))
  456. mk.write('\t./scripts/explode_asserts.py $| -o $@\n')
  457. self.makefile = self.path + '.mk'
  458. self.target = self.path + '.test'
  459. return self.makefile, self.target
  460. def test(self, caseno=None, permno=None, **args):
  461. # run test suite!
  462. if not args.get('verbose', True):
  463. sys.stdout.write(self.name + ' ')
  464. sys.stdout.flush()
  465. for perm in self.perms:
  466. if caseno is not None and perm.caseno != caseno:
  467. continue
  468. if permno is not None and perm.permno != permno:
  469. continue
  470. if not perm.shouldtest(**args):
  471. continue
  472. try:
  473. result = perm.test(**args)
  474. except TestFailure as failure:
  475. perm.result = failure
  476. if not args.get('verbose', True):
  477. sys.stdout.write(FAIL)
  478. sys.stdout.flush()
  479. if not args.get('keep_going', False):
  480. if not args.get('verbose', True):
  481. sys.stdout.write('\n')
  482. raise
  483. else:
  484. perm.result = PASS
  485. if not args.get('verbose', True):
  486. sys.stdout.write(PASS)
  487. sys.stdout.flush()
  488. if not args.get('verbose', True):
  489. sys.stdout.write('\n')
  490. def main(**args):
  491. suites = []
  492. for testpath in args['testpaths']:
  493. # optionally specified test case/perm
  494. testpath, *filter = testpath.split('#')
  495. filter = [int(f) for f in filter]
  496. # figure out the suite's toml file
  497. if os.path.isdir(testpath):
  498. testpath = testpath + '/test_*.toml'
  499. elif os.path.isfile(testpath):
  500. testpath = testpath
  501. elif testpath.endswith('.toml'):
  502. testpath = TESTDIR + '/' + testpath
  503. else:
  504. testpath = TESTDIR + '/' + testpath + '.toml'
  505. # find tests
  506. for path in glob.glob(testpath):
  507. if args.get('valgrind', False):
  508. TestCase_ = ValgrindTestCase
  509. elif args.get('reentrant', False):
  510. TestCase_ = ReentrantTestCase
  511. else:
  512. TestCase_ = TestCase
  513. suites.append(TestSuite(path,
  514. filter=filter, TestCase=TestCase_, **args))
  515. # sort for reproducability
  516. suites = sorted(suites)
  517. # generate permutations
  518. defines = {}
  519. for define in args['D']:
  520. k, v, *_ = define.split('=', 2) + ['']
  521. defines[k] = v
  522. for suite in suites:
  523. suite.permute(defines, **args)
  524. # build tests in parallel
  525. print('====== building ======')
  526. makefiles = []
  527. targets = []
  528. for suite in suites:
  529. makefile, target = suite.build(**args)
  530. makefiles.append(makefile)
  531. targets.append(target)
  532. cmd = (['make', '-f', 'Makefile'] +
  533. list(it.chain.from_iterable(['-f', m] for m in makefiles)) +
  534. [target for target in targets])
  535. mpty, spty = pty.openpty()
  536. if args.get('verbose', False):
  537. print(' '.join(shlex.quote(c) for c in cmd))
  538. proc = sp.Popen(cmd, stdout=spty, stderr=spty)
  539. os.close(spty)
  540. mpty = os.fdopen(mpty, 'r', 1)
  541. stdout = []
  542. while True:
  543. try:
  544. line = mpty.readline()
  545. except OSError as e:
  546. if e.errno == errno.EIO:
  547. break
  548. raise
  549. stdout.append(line)
  550. if args.get('verbose', False):
  551. sys.stdout.write(line)
  552. # intercept warnings
  553. m = re.match(
  554. '^{0}([^:]+):(\d+):(?:\d+:)?{0}{1}:{0}(.*)$'
  555. .format('(?:\033\[[\d;]*.| )*', 'warning'),
  556. line)
  557. if m and not args.get('verbose', False):
  558. try:
  559. with open(m.group(1)) as f:
  560. lineno = int(m.group(2))
  561. line = next(it.islice(f, lineno-1, None)).strip('\n')
  562. sys.stdout.write(
  563. "\033[01m{path}:{lineno}:\033[01;35mwarning:\033[m "
  564. "{message}\n{line}\n\n".format(
  565. path=m.group(1), line=line, lineno=lineno,
  566. message=m.group(3)))
  567. except:
  568. pass
  569. proc.wait()
  570. if proc.returncode != 0:
  571. if not args.get('verbose', False):
  572. for line in stdout:
  573. sys.stdout.write(line)
  574. sys.exit(-3)
  575. print('built %d test suites, %d test cases, %d permutations' % (
  576. len(suites),
  577. sum(len(suite.cases) for suite in suites),
  578. sum(len(suite.perms) for suite in suites)))
  579. filtered = 0
  580. for suite in suites:
  581. for perm in suite.perms:
  582. filtered += perm.shouldtest(**args)
  583. if filtered != sum(len(suite.perms) for suite in suites):
  584. print('filtered down to %d permutations' % filtered)
  585. print('====== testing ======')
  586. try:
  587. for suite in suites:
  588. suite.test(**args)
  589. except TestFailure:
  590. pass
  591. print('====== results ======')
  592. passed = 0
  593. failed = 0
  594. for suite in suites:
  595. for perm in suite.perms:
  596. if not hasattr(perm, 'result'):
  597. continue
  598. if perm.result == PASS:
  599. passed += 1
  600. else:
  601. sys.stdout.write(
  602. "\033[01m{path}:{lineno}:\033[01;31mfailure:\033[m "
  603. "{perm} failed with {returncode}\n".format(
  604. perm=perm, path=perm.suite.path, lineno=perm.lineno,
  605. returncode=perm.result.returncode or 0))
  606. if perm.result.stdout:
  607. for line in (perm.result.stdout
  608. if not perm.result.assert_
  609. else perm.result.stdout[:-1]):
  610. sys.stdout.write(line)
  611. if perm.result.assert_:
  612. sys.stdout.write(
  613. "\033[01m{path}:{lineno}:\033[01;31massert:\033[m "
  614. "{message}\n{line}\n".format(
  615. **perm.result.assert_))
  616. else:
  617. for line in perm.result.stdout:
  618. sys.stdout.write(line)
  619. sys.stdout.write('\n')
  620. failed += 1
  621. if args.get('gdb', False):
  622. failure = None
  623. for suite in suites:
  624. for perm in suite.perms:
  625. if getattr(perm, 'result', PASS) != PASS:
  626. failure = perm.result
  627. if failure is not None:
  628. print('======= gdb ======')
  629. # drop into gdb
  630. failure.case.test(failure=failure, **args)
  631. sys.exit(0)
  632. print('tests passed: %d' % passed)
  633. print('tests failed: %d' % failed)
  634. return 1 if failed > 0 else 0
  635. if __name__ == "__main__":
  636. import argparse
  637. parser = argparse.ArgumentParser(
  638. description="Run parameterized tests in various configurations.")
  639. parser.add_argument('testpaths', nargs='*', default=[TESTDIR],
  640. help="Description of test(s) to run. By default, this is all tests \
  641. found in the \"{0}\" directory. Here, you can specify a different \
  642. directory of tests, a specific file, a suite by name, and even a \
  643. specific test case by adding brackets. For example \
  644. \"test_dirs[0]\" or \"{0}/test_dirs.toml[0]\".".format(TESTDIR))
  645. parser.add_argument('-D', action='append', default=[],
  646. help="Overriding parameter definitions.")
  647. parser.add_argument('-v', '--verbose', action='store_true',
  648. help="Output everything that is happening.")
  649. parser.add_argument('-k', '--keep-going', action='store_true',
  650. help="Run all tests instead of stopping on first error. Useful for CI.")
  651. parser.add_argument('-p', '--persist', choices=['erase', 'noerase'],
  652. nargs='?', const='erase',
  653. help="Store disk image in a file.")
  654. parser.add_argument('-g', '--gdb', choices=['init', 'start', 'assert'],
  655. nargs='?', const='assert',
  656. help="Drop into gdb on test failure.")
  657. parser.add_argument('--valgrind', action='store_true',
  658. help="Run non-leaky tests under valgrind to check for memory leaks.")
  659. parser.add_argument('--reentrant', action='store_true',
  660. help="Run reentrant tests with simulated power-loss.")
  661. parser.add_argument('-e', '--exec', default=[], type=lambda e: e.split(' '),
  662. help="Run tests with another executable prefixed on the command line.")
  663. sys.exit(main(**vars(parser.parse_args())))