test.py 30 KB

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