test.py 30 KB

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