test_.py 26 KB

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