test.py 27 KB

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