test_.py 27 KB

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