test.py 26 KB

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