test.py 29 KB

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