test.py 27 KB

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