test.py 27 KB

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