test.py 30 KB

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