test.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767
  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_PROGERROR',
  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. if_ = self.if_
  166. while True:
  167. for k, v in self.defines.items():
  168. if k in if_:
  169. if_ = if_.replace(k, '(%s)' % v)
  170. break
  171. else:
  172. break
  173. if_ = (
  174. re.sub('(\&\&|\?)', ' and ',
  175. re.sub('(\|\||:)', ' or ',
  176. re.sub('!(?!=)', ' not ', if_))))
  177. return eval(if_)
  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. if args.get('verbose', False):
  191. print('rm', 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 2'])
  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. try:
  224. while True:
  225. try:
  226. line = mpty.readline()
  227. except OSError as e:
  228. if e.errno == errno.EIO:
  229. break
  230. raise
  231. stdout.append(line)
  232. if args.get('verbose', False):
  233. sys.stdout.write(line)
  234. # intercept asserts
  235. m = re.match(
  236. '^{0}([^:]+):(\d+):(?:\d+:)?{0}{1}:{0}(.*)$'
  237. .format('(?:\033\[[\d;]*.| )*', 'assert'),
  238. line)
  239. if m and assert_ is None:
  240. try:
  241. with open(m.group(1)) as f:
  242. lineno = int(m.group(2))
  243. line = (next(it.islice(f, lineno-1, None))
  244. .strip('\n'))
  245. assert_ = {
  246. 'path': m.group(1),
  247. 'line': line,
  248. 'lineno': lineno,
  249. 'message': m.group(3)}
  250. except:
  251. pass
  252. except KeyboardInterrupt:
  253. raise TestFailure(self, 1, stdout, None)
  254. proc.wait()
  255. # did we pass?
  256. if proc.returncode != 0:
  257. raise TestFailure(self, proc.returncode, stdout, assert_)
  258. else:
  259. return PASS
  260. class ValgrindTestCase(TestCase):
  261. def __init__(self, config, **args):
  262. self.leaky = config.get('leaky', False)
  263. super().__init__(config, **args)
  264. def shouldtest(self, **args):
  265. return not self.leaky and super().shouldtest(**args)
  266. def test(self, exec=[], **args):
  267. exec = exec + [
  268. 'valgrind',
  269. '--leak-check=full',
  270. '--error-exitcode=4',
  271. '-q']
  272. return super().test(exec=exec, **args)
  273. class ReentrantTestCase(TestCase):
  274. def __init__(self, config, **args):
  275. self.reentrant = config.get('reentrant', False)
  276. super().__init__(config, **args)
  277. def shouldtest(self, **args):
  278. return self.reentrant and super().shouldtest(**args)
  279. def test(self, exec=[], persist=False, gdb=False, failure=None, **args):
  280. for cycles in it.count(1):
  281. # clear disk first?
  282. if cycles == 1 and persist != 'noerase':
  283. persist = 'erase'
  284. else:
  285. persist = 'noerase'
  286. # exact cycle we should drop into debugger?
  287. if gdb and failure and failure.cycleno == cycles:
  288. return super().test(gdb=gdb, persist=persist, cycles=cycles,
  289. failure=failure, **args)
  290. # run tests, but kill the program after prog/erase has
  291. # been hit n cycles. We exit with a special return code if the
  292. # program has not finished, since this isn't a test failure.
  293. try:
  294. return super().test(persist=persist, cycles=cycles, **args)
  295. except TestFailure as nfailure:
  296. if nfailure.returncode == 33:
  297. continue
  298. else:
  299. nfailure.cycleno = cycles
  300. raise
  301. class TestSuite:
  302. def __init__(self, path, classes=[TestCase], defines={},
  303. filter=None, **args):
  304. self.name = os.path.basename(path)
  305. if self.name.endswith('.toml'):
  306. self.name = self.name[:-len('.toml')]
  307. self.path = path
  308. self.classes = classes
  309. self.defines = defines.copy()
  310. self.filter = filter
  311. with open(path) as f:
  312. # load tests
  313. config = toml.load(f)
  314. # find line numbers
  315. f.seek(0)
  316. linenos = []
  317. code_linenos = []
  318. for i, line in enumerate(f):
  319. if re.match(r'\[\[\s*case\s*\]\]', line):
  320. linenos.append(i+1)
  321. if re.match(r'code\s*=\s*(\'\'\'|""")', line):
  322. code_linenos.append(i+2)
  323. code_linenos.reverse()
  324. # grab global config
  325. for k, v in config.get('define', {}).items():
  326. if k not in self.defines:
  327. self.defines[k] = v
  328. self.code = config.get('code', None)
  329. if self.code is not None:
  330. self.code_lineno = code_linenos.pop()
  331. # create initial test cases
  332. self.cases = []
  333. for i, (case, lineno) in enumerate(zip(config['case'], linenos)):
  334. # code lineno?
  335. if 'code' in case:
  336. case['code_lineno'] = code_linenos.pop()
  337. # give our case's config a copy of our "global" config
  338. for k, v in config.items():
  339. if k not in case:
  340. case[k] = v
  341. # initialize test case
  342. self.cases.append(TestCase(case, filter=filter,
  343. suite=self, caseno=i+1, lineno=lineno, **args))
  344. def __str__(self):
  345. return self.name
  346. def __lt__(self, other):
  347. return self.name < other.name
  348. def permute(self, **args):
  349. for case in self.cases:
  350. # lets find all parameterized definitions, in one of [args.D,
  351. # suite.defines, case.defines, DEFINES]. Note that each of these
  352. # can be either a dict of defines, or a list of dicts, expressing
  353. # an initial set of permutations.
  354. pending = [{}]
  355. for inits in [self.defines, case.defines, DEFINES]:
  356. if not isinstance(inits, list):
  357. inits = [inits]
  358. npending = []
  359. for init, pinit in it.product(inits, pending):
  360. ninit = pinit.copy()
  361. for k, v in init.items():
  362. if k not in ninit:
  363. try:
  364. ninit[k] = eval(v)
  365. except:
  366. ninit[k] = v
  367. npending.append(ninit)
  368. pending = npending
  369. # expand permutations
  370. pending = list(reversed(pending))
  371. expanded = []
  372. while pending:
  373. perm = pending.pop()
  374. for k, v in sorted(perm.items()):
  375. if not isinstance(v, str) and isinstance(v, abc.Iterable):
  376. for nv in reversed(v):
  377. nperm = perm.copy()
  378. nperm[k] = nv
  379. pending.append(nperm)
  380. break
  381. else:
  382. expanded.append(perm)
  383. # generate permutations
  384. case.perms = []
  385. for i, (class_, defines) in enumerate(
  386. it.product(self.classes, expanded)):
  387. case.perms.append(case.permute(
  388. class_, defines, permno=i+1, **args))
  389. # also track non-unique defines
  390. case.defines = {}
  391. for k, v in case.perms[0].defines.items():
  392. if all(perm.defines[k] == v for perm in case.perms):
  393. case.defines[k] = v
  394. # track all perms and non-unique defines
  395. self.perms = []
  396. for case in self.cases:
  397. self.perms.extend(case.perms)
  398. self.defines = {}
  399. for k, v in self.perms[0].defines.items():
  400. if all(perm.defines.get(k, None) == v for perm in self.perms):
  401. self.defines[k] = v
  402. return self.perms
  403. def build(self, **args):
  404. # build test files
  405. tf = open(self.path + '.test.c.t', 'w')
  406. tf.write(GLOBALS)
  407. if self.code is not None:
  408. tf.write('#line %d "%s"\n' % (self.code_lineno, self.path))
  409. tf.write(self.code)
  410. tfs = {None: tf}
  411. for case in self.cases:
  412. if case.in_ not in tfs:
  413. tfs[case.in_] = open(self.path+'.'+
  414. case.in_.replace('/', '.')+'.t', 'w')
  415. tfs[case.in_].write('#line 1 "%s"\n' % case.in_)
  416. with open(case.in_) as f:
  417. for line in f:
  418. tfs[case.in_].write(line)
  419. tfs[case.in_].write('\n')
  420. tfs[case.in_].write(GLOBALS)
  421. tfs[case.in_].write('\n')
  422. case.build(tfs[case.in_], **args)
  423. tf.write('\n')
  424. tf.write('const char *lfs_testbd_path;\n')
  425. tf.write('uint32_t lfs_testbd_cycles;\n')
  426. tf.write('int main(int argc, char **argv) {\n')
  427. tf.write(4*' '+'int case_ = (argc > 1) ? atoi(argv[1]) : 0;\n')
  428. tf.write(4*' '+'int perm = (argc > 2) ? atoi(argv[2]) : 0;\n')
  429. tf.write(4*' '+'lfs_testbd_path = (argc > 3) ? argv[3] : NULL;\n')
  430. tf.write(4*' '+'lfs_testbd_cycles = (argc > 4) ? atoi(argv[4]) : 0;\n')
  431. for perm in self.perms:
  432. # test declaration
  433. tf.write(4*' '+'extern void test_case%d(%s);\n' % (
  434. perm.caseno, ', '.join(
  435. 'intmax_t %s' % k for k in sorted(perm.defines)
  436. if k not in perm.case.defines)))
  437. # test call
  438. tf.write(4*' '+
  439. 'if (argc < 3 || (case_ == %d && perm == %d)) {'
  440. ' test_case%d(%s); '
  441. '}\n' % (perm.caseno, perm.permno, perm.caseno, ', '.join(
  442. str(v) for k, v in sorted(perm.defines.items())
  443. if k not in perm.case.defines)))
  444. tf.write('}\n')
  445. for tf in tfs.values():
  446. tf.close()
  447. # write makefiles
  448. with open(self.path + '.mk', 'w') as mk:
  449. mk.write(RULES.replace(4*' ', '\t'))
  450. mk.write('\n')
  451. # add truely global defines globally
  452. for k, v in sorted(self.defines.items()):
  453. mk.write('%s: override CFLAGS += -D%s=%r\n' % (
  454. self.path+'.test', k, v))
  455. for path in tfs:
  456. if path is None:
  457. mk.write('%s: %s | %s\n' % (
  458. self.path+'.test.c',
  459. self.path,
  460. self.path+'.test.c.t'))
  461. else:
  462. mk.write('%s: %s %s | %s\n' % (
  463. self.path+'.'+path.replace('/', '.'),
  464. self.path, path,
  465. self.path+'.'+path.replace('/', '.')+'.t'))
  466. mk.write('\t./scripts/explode_asserts.py $| -o $@\n')
  467. self.makefile = self.path + '.mk'
  468. self.target = self.path + '.test'
  469. return self.makefile, self.target
  470. def test(self, **args):
  471. # run test suite!
  472. if not args.get('verbose', True):
  473. sys.stdout.write(self.name + ' ')
  474. sys.stdout.flush()
  475. for perm in self.perms:
  476. if not perm.shouldtest(**args):
  477. continue
  478. try:
  479. result = perm.test(**args)
  480. except TestFailure as failure:
  481. perm.result = failure
  482. if not args.get('verbose', True):
  483. sys.stdout.write(FAIL)
  484. sys.stdout.flush()
  485. if not args.get('keep_going', False):
  486. if not args.get('verbose', True):
  487. sys.stdout.write('\n')
  488. raise
  489. else:
  490. perm.result = PASS
  491. if not args.get('verbose', True):
  492. sys.stdout.write(PASS)
  493. sys.stdout.flush()
  494. if not args.get('verbose', True):
  495. sys.stdout.write('\n')
  496. def main(**args):
  497. # figure out explicit defines
  498. defines = {}
  499. for define in args['D']:
  500. k, v, *_ = define.split('=', 2) + ['']
  501. defines[k] = v
  502. # and what class of TestCase to run
  503. classes = []
  504. if args.get('normal', False):
  505. classes.append(TestCase)
  506. if args.get('reentrant', False):
  507. classes.append(ReentrantTestCase)
  508. if args.get('valgrind', False):
  509. classes.append(ValgrindTestCase)
  510. if not classes:
  511. classes = [TestCase]
  512. suites = []
  513. for testpath in args['testpaths']:
  514. # optionally specified test case/perm
  515. testpath, *filter = testpath.split('#')
  516. filter = [int(f) for f in filter]
  517. # figure out the suite's toml file
  518. if os.path.isdir(testpath):
  519. testpath = testpath + '/test_*.toml'
  520. elif os.path.isfile(testpath):
  521. testpath = testpath
  522. elif testpath.endswith('.toml'):
  523. testpath = TESTDIR + '/' + testpath
  524. else:
  525. testpath = TESTDIR + '/' + testpath + '.toml'
  526. # find tests
  527. for path in glob.glob(testpath):
  528. suites.append(TestSuite(path, classes, defines, filter, **args))
  529. # sort for reproducability
  530. suites = sorted(suites)
  531. # generate permutations
  532. for suite in suites:
  533. suite.permute(**args)
  534. # build tests in parallel
  535. print('====== building ======')
  536. makefiles = []
  537. targets = []
  538. for suite in suites:
  539. makefile, target = suite.build(**args)
  540. makefiles.append(makefile)
  541. targets.append(target)
  542. cmd = (['make', '-f', 'Makefile'] +
  543. list(it.chain.from_iterable(['-f', m] for m in makefiles)) +
  544. [target for target in targets])
  545. mpty, spty = pty.openpty()
  546. if args.get('verbose', False):
  547. print(' '.join(shlex.quote(c) for c in cmd))
  548. proc = sp.Popen(cmd, stdout=spty, stderr=spty)
  549. os.close(spty)
  550. mpty = os.fdopen(mpty, 'r', 1)
  551. stdout = []
  552. while True:
  553. try:
  554. line = mpty.readline()
  555. except OSError as e:
  556. if e.errno == errno.EIO:
  557. break
  558. raise
  559. stdout.append(line)
  560. if args.get('verbose', False):
  561. sys.stdout.write(line)
  562. # intercept warnings
  563. m = re.match(
  564. '^{0}([^:]+):(\d+):(?:\d+:)?{0}{1}:{0}(.*)$'
  565. .format('(?:\033\[[\d;]*.| )*', 'warning'),
  566. line)
  567. if m and not args.get('verbose', False):
  568. try:
  569. with open(m.group(1)) as f:
  570. lineno = int(m.group(2))
  571. line = next(it.islice(f, lineno-1, None)).strip('\n')
  572. sys.stdout.write(
  573. "\033[01m{path}:{lineno}:\033[01;35mwarning:\033[m "
  574. "{message}\n{line}\n\n".format(
  575. path=m.group(1), line=line, lineno=lineno,
  576. message=m.group(3)))
  577. except:
  578. pass
  579. proc.wait()
  580. if proc.returncode != 0:
  581. if not args.get('verbose', False):
  582. for line in stdout:
  583. sys.stdout.write(line)
  584. sys.exit(-3)
  585. print('built %d test suites, %d test cases, %d permutations' % (
  586. len(suites),
  587. sum(len(suite.cases) for suite in suites),
  588. sum(len(suite.perms) for suite in suites)))
  589. filtered = 0
  590. for suite in suites:
  591. for perm in suite.perms:
  592. filtered += perm.shouldtest(**args)
  593. if filtered != sum(len(suite.perms) for suite in suites):
  594. print('filtered down to %d permutations' % filtered)
  595. # only requested to build?
  596. if args.get('build', False):
  597. return 0
  598. print('====== testing ======')
  599. try:
  600. for suite in suites:
  601. suite.test(**args)
  602. except TestFailure:
  603. pass
  604. print('====== results ======')
  605. passed = 0
  606. failed = 0
  607. for suite in suites:
  608. for perm in suite.perms:
  609. if not hasattr(perm, 'result'):
  610. continue
  611. if perm.result == PASS:
  612. passed += 1
  613. else:
  614. sys.stdout.write(
  615. "\033[01m{path}:{lineno}:\033[01;31mfailure:\033[m "
  616. "{perm} failed with {returncode}\n".format(
  617. perm=perm, path=perm.suite.path, lineno=perm.lineno,
  618. returncode=perm.result.returncode or 0))
  619. if perm.result.stdout:
  620. if perm.result.assert_:
  621. stdout = perm.result.stdout[:-1]
  622. else:
  623. stdout = perm.result.stdout
  624. if (not args.get('verbose', False) and len(stdout) > 5):
  625. sys.stdout.write('...\n')
  626. for line in stdout[-5:]:
  627. sys.stdout.write(line)
  628. if perm.result.assert_:
  629. sys.stdout.write(
  630. "\033[01m{path}:{lineno}:\033[01;31massert:\033[m "
  631. "{message}\n{line}\n".format(
  632. **perm.result.assert_))
  633. sys.stdout.write('\n')
  634. failed += 1
  635. if args.get('gdb', False):
  636. failure = None
  637. for suite in suites:
  638. for perm in suite.perms:
  639. if getattr(perm, 'result', PASS) != PASS:
  640. failure = perm.result
  641. if failure is not None:
  642. print('======= gdb ======')
  643. # drop into gdb
  644. failure.case.test(failure=failure, **args)
  645. sys.exit(0)
  646. print('tests passed: %d' % passed)
  647. print('tests failed: %d' % failed)
  648. return 1 if failed > 0 else 0
  649. if __name__ == "__main__":
  650. import argparse
  651. parser = argparse.ArgumentParser(
  652. description="Run parameterized tests in various configurations.")
  653. parser.add_argument('testpaths', nargs='*', default=[TESTDIR],
  654. help="Description of test(s) to run. By default, this is all tests \
  655. found in the \"{0}\" directory. Here, you can specify a different \
  656. directory of tests, a specific file, a suite by name, and even a \
  657. specific test case by adding brackets. For example \
  658. \"test_dirs[0]\" or \"{0}/test_dirs.toml[0]\".".format(TESTDIR))
  659. parser.add_argument('-D', action='append', default=[],
  660. help="Overriding parameter definitions.")
  661. parser.add_argument('-v', '--verbose', action='store_true',
  662. help="Output everything that is happening.")
  663. parser.add_argument('-k', '--keep-going', action='store_true',
  664. help="Run all tests instead of stopping on first error. Useful for CI.")
  665. parser.add_argument('-p', '--persist', choices=['erase', 'noerase'],
  666. nargs='?', const='erase',
  667. help="Store disk image in a file.")
  668. parser.add_argument('-b', '--build', action='store_true',
  669. help="Only build the tests, do not execute.")
  670. parser.add_argument('-g', '--gdb', choices=['init', 'start', 'assert'],
  671. nargs='?', const='assert',
  672. help="Drop into gdb on test failure.")
  673. parser.add_argument('--no-internal', action='store_true',
  674. help="Don't run tests that require internal knowledge.")
  675. parser.add_argument('-n', '--normal', action='store_true',
  676. help="Run tests normally.")
  677. parser.add_argument('-r', '--reentrant', action='store_true',
  678. help="Run reentrant tests with simulated power-loss.")
  679. parser.add_argument('-V', '--valgrind', action='store_true',
  680. help="Run non-leaky tests under valgrind to check for memory leaks.")
  681. parser.add_argument('-e', '--exec', default=[], type=lambda e: e.split(' '),
  682. help="Run tests with another executable prefixed on the command line.")
  683. sys.exit(main(**vars(parser.parse_args())))