runner.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. #!/usr/bin/env python3
  2. #
  3. # MMGen Wallet, a terminal-based cryptocurrency wallet
  4. # Copyright (C)2013-2025 The MMGen Project <mmgen@tuta.io>
  5. # Licensed under the GNU General Public License, Version 3:
  6. # https://www.gnu.org/licenses
  7. # Public project repositories:
  8. # https://github.com/mmgen/mmgen-wallet
  9. # https://gitlab.com/mmgen/mmgen-wallet
  10. """
  11. test.include.runner: test runner for the MMGen Wallet cmdtest suite
  12. """
  13. import sys, os, time, asyncio
  14. from mmgen.cfg import gc
  15. from mmgen.color import red, yellow, green, blue, cyan, gray, nocolor
  16. from mmgen.util import msg, Msg, rmsg, bmsg, die, suf, make_timestr
  17. from test.include.common import (
  18. cmdtest_py_log_fn,
  19. iqmsg,
  20. omsg,
  21. omsg_r,
  22. ok,
  23. start_test_daemons,
  24. init_coverage,
  25. clean
  26. )
  27. from .common import get_file_with_ext, confirm_continue
  28. from .cfg import cfgs, cmd_groups_dfl
  29. from .group_mgr import CmdGroupMgr
  30. def format_args(args):
  31. try:
  32. return ' '.join((f"'{a}'" if ' ' in a else a) for a in args).replace('\\', '/') # for MSYS2
  33. except Exception as e:
  34. print(type(e), e)
  35. print('cmdline:', args)
  36. class CmdTestRunner:
  37. 'cmdtest.py test runner'
  38. def __del__(self):
  39. if self.logging:
  40. self.log_fd.close()
  41. def __init__(self, cfg, repo_root, data_dir, trash_dir, trash_dir2):
  42. self.cfg = cfg
  43. self.proto = cfg._proto
  44. self.data_dir = data_dir
  45. self.trash_dir = trash_dir
  46. self.trash_dir2 = trash_dir2
  47. self.cmd_total = 0
  48. self.rebuild_list = {}
  49. self.gm = CmdGroupMgr(cfg)
  50. self.repo_root = repo_root
  51. self.skipped_warnings = []
  52. self.resume_cmd = None
  53. self.deps_only = None
  54. self.logging = self.cfg.log or os.getenv('MMGEN_EXEC_WRAPPER')
  55. self.testing_segwit = cfg.segwit or cfg.segwit_random or cfg.bech32
  56. self.network_id = self.proto.coin.lower() + ('_tn' if self.proto.testnet else '')
  57. self.daemon_started = False
  58. global qmsg, qmsg_r
  59. if cfg.exact_output:
  60. qmsg = qmsg_r = lambda s: None
  61. else:
  62. qmsg = cfg._util.qmsg
  63. qmsg_r = cfg._util.qmsg_r
  64. if self.logging:
  65. self.log_fd = open(cmdtest_py_log_fn, 'a')
  66. self.log_fd.write(f'\nLog started: {make_timestr()} UTC\n')
  67. omsg(f'INFO → Logging to file {cmdtest_py_log_fn!r}')
  68. else:
  69. self.log_fd = None
  70. if self.cfg.coverage:
  71. coverdir, accfile = init_coverage()
  72. omsg(f'INFO → Writing coverage files to {coverdir!r}')
  73. self.pre_args = ['python3', '-m', 'trace', '--count', '--coverdir='+coverdir, '--file='+accfile]
  74. else:
  75. self.pre_args = ['python3'] if sys.platform == 'win32' else []
  76. if self.cfg.pexpect_spawn:
  77. omsg('INFO → Using pexpect.spawn() for real terminal emulation')
  78. self.set_spawn_env()
  79. self.start_time = time.time()
  80. def do_between(self):
  81. if self.cfg.pause:
  82. confirm_continue()
  83. elif (self.cfg.verbose or self.cfg.exact_output) and not self.cfg.skipping_deps:
  84. sys.stderr.write('\n')
  85. def set_spawn_env(self):
  86. self.spawn_env = dict(os.environ)
  87. self.spawn_env.update({
  88. 'MMGEN_NO_LICENSE': '1',
  89. 'MMGEN_BOGUS_SEND': '1',
  90. 'MMGEN_TEST_SUITE_PEXPECT': '1',
  91. 'EXEC_WRAPPER_DO_RUNTIME_MSG':'1',
  92. # if cmdtest.py itself is running under exec_wrapper, disable writing of traceback file for spawned script
  93. 'EXEC_WRAPPER_TRACEBACK': '' if os.getenv('MMGEN_EXEC_WRAPPER') else '1',
  94. })
  95. if self.cfg.exact_output:
  96. from mmgen.term import get_terminal_size
  97. self.spawn_env['MMGEN_COLUMNS'] = str(get_terminal_size().width)
  98. else:
  99. self.spawn_env['MMGEN_COLUMNS'] = '120'
  100. def spawn_wrapper(
  101. self,
  102. cmd = '',
  103. args = [],
  104. extra_desc = '',
  105. no_output = False,
  106. msg_only = False,
  107. no_msg = False,
  108. cmd_dir = 'cmds',
  109. no_exec_wrapper = False,
  110. timeout = None,
  111. pexpect_spawn = None,
  112. direct_exec = False,
  113. no_passthru_opts = False,
  114. spawn_env_override = None,
  115. exit_val = None,
  116. env = {}):
  117. self.exit_val = exit_val
  118. desc = self.tg.test_name if self.cfg.names else self.gm.dpy_data[self.tg.test_name][1]
  119. if extra_desc:
  120. desc += ' ' + extra_desc
  121. cmd_path = (
  122. cmd if self.cfg.system # self.cfg.system is broken for main test group with overlay tree
  123. else os.path.relpath(os.path.join(self.repo_root, cmd_dir, cmd)))
  124. passthru_opts = (
  125. self.passthru_opts if not no_passthru_opts else
  126. [] if no_passthru_opts is True else
  127. [o for o in self.passthru_opts if o[2:].split('=')[0] not in no_passthru_opts])
  128. args = (
  129. self.pre_args +
  130. ([] if no_exec_wrapper else ['scripts/exec_wrapper.py']) +
  131. [cmd_path] +
  132. passthru_opts +
  133. args)
  134. cmd_disp = format_args(args)
  135. if self.logging:
  136. self.log_fd.write('[{}][{}:{}] {}\n'.format(
  137. (self.proto.coin.lower() if 'coin' in self.tg.passthru_opts else 'NONE'),
  138. self.tg.group_name,
  139. self.tg.test_name,
  140. cmd_disp))
  141. for i in args: # die only after writing log entry
  142. if not isinstance(i, str):
  143. die(2, 'Error: missing input files in cmd line?:\nName: {}\nCmdline: {!r}'.format(
  144. self.tg.test_name,
  145. args))
  146. if not no_msg:
  147. t_pfx = '' if self.cfg.no_timings else f'[{time.time() - self.start_time:08.2f}] '
  148. if self.cfg.verbose or self.cfg.print_cmdline or self.cfg.exact_output:
  149. omsg(green(f'{t_pfx}Testing: {desc}'))
  150. if not msg_only:
  151. clr1, clr2 = (nocolor, nocolor) if self.cfg.print_cmdline else (green, cyan)
  152. omsg(
  153. clr1('Executing: ') +
  154. clr2(repr(cmd_disp) if sys.platform == 'win32' else cmd_disp)
  155. )
  156. else:
  157. omsg_r('{a}Testing {b}: {c}'.format(
  158. a = t_pfx,
  159. b = desc,
  160. c = 'OK\n' if direct_exec or self.cfg.direct_exec else ''))
  161. if msg_only:
  162. return
  163. # NB: the `pexpect_spawn` arg enables hold_protect and send_delay while the corresponding cmdline
  164. # option does not. For performance reasons, this is the desired behavior. For full emulation of
  165. # the user experience with hold protect enabled, specify --buf-keypress or --demo.
  166. send_delay = 0.4 if pexpect_spawn is True or self.cfg.buf_keypress else None
  167. pexpect_spawn = pexpect_spawn if pexpect_spawn is not None else bool(self.cfg.pexpect_spawn)
  168. spawn_env = dict(spawn_env_override or self.tg.spawn_env)
  169. spawn_env.update({
  170. 'MMGEN_HOLD_PROTECT_DISABLE': '' if send_delay else '1',
  171. 'MMGEN_TEST_SUITE_POPEN_SPAWN': '' if pexpect_spawn else '1',
  172. 'EXEC_WRAPPER_EXIT_VAL': '' if exit_val is None else str(exit_val),
  173. })
  174. spawn_env.update(env)
  175. from test.include.pexpect import MMGenPexpect
  176. return MMGenPexpect(
  177. args = args,
  178. no_output = no_output,
  179. spawn_env = spawn_env,
  180. pexpect_spawn = pexpect_spawn,
  181. timeout = timeout,
  182. send_delay = send_delay,
  183. direct_exec = direct_exec)
  184. def end_msg(self):
  185. t = int(time.time() - self.start_time)
  186. sys.stderr.write(green(
  187. f'{self.cmd_total} test{suf(self.cmd_total)} performed' +
  188. ('\n' if self.cfg.no_timings else f'. Elapsed time: {t//60:02d}:{t%60:02d}\n')
  189. ))
  190. def init_group(self, gname, sg_name=None, cmd=None, quiet=False, do_clean=True):
  191. from test.cmdtest_d.cfg import cmd_groups_altcoin
  192. if self.cfg.no_altcoin and gname in cmd_groups_altcoin:
  193. omsg(gray(f'INFO → skipping test group {gname!r} (--no-altcoin)'))
  194. return None
  195. ct_cls = self.gm.load_mod(gname)
  196. if sys.platform in ct_cls.platform_skip:
  197. omsg(gray(f'INFO → skipping test {gname!r} for platform {sys.platform!r}'))
  198. return None
  199. for k in ('segwit', 'segwit_random', 'bech32'):
  200. if getattr(self.cfg, k):
  201. segwit_opt = k
  202. break
  203. else:
  204. segwit_opt = None
  205. def gen_msg():
  206. yield ('{g}:{c}' if cmd else 'test group {g!r}').format(g=gname, c=cmd)
  207. if len(ct_cls.networks) != 1:
  208. yield f' for {self.proto.coin} {self.proto.network}'
  209. if segwit_opt:
  210. yield ' (--{})'.format(segwit_opt.replace('_', '-'))
  211. m = ''.join(gen_msg())
  212. if segwit_opt and not ct_cls.segwit_opts_ok:
  213. iqmsg(gray(f'INFO → skipping {m}'))
  214. return None
  215. # 'networks = ()' means all networks allowed
  216. nws = [(e.split('_')[0], 'testnet') if '_' in e else (e, 'mainnet') for e in ct_cls.networks]
  217. if nws:
  218. coin = self.proto.coin.lower()
  219. for a, b in nws:
  220. if a == coin and b == self.proto.network:
  221. break
  222. else:
  223. iqmsg(gray(f'INFO → skipping {m} for {self.proto.coin} {self.proto.network}'))
  224. return None
  225. if do_clean and not self.cfg.skipping_deps:
  226. clean(
  227. cfgs,
  228. tmpdir_ids = ct_cls.tmpdir_nums,
  229. extra_dirs = [self.data_dir, self.trash_dir, self.trash_dir2])
  230. if not quiet:
  231. bmsg('Executing ' + m)
  232. if (not self.daemon_started) and self.gm.get_cls_by_gname(gname).need_daemon:
  233. start_test_daemons(self.network_id, remove_datadir=True)
  234. self.daemon_started = True
  235. if hasattr(self, 'tg'):
  236. del self.tg
  237. self.tg = self.gm.gm_init_group(self.cfg, self, gname, sg_name, self.spawn_wrapper)
  238. self.ct_clsname = type(self.tg).__name__
  239. # pass through opts from cmdline (po.user_opts)
  240. self.passthru_opts = ['--{}{}'.format(
  241. k.replace('_', '-'),
  242. '' if self.cfg._uopts[k] is True else '=' + self.cfg._uopts[k]
  243. ) for k in self.cfg._uopts if k in self.tg.base_passthru_opts + self.tg.passthru_opts]
  244. if self.cfg.resuming:
  245. rc = self.cfg.resume or self.cfg.resume_after
  246. offset = 1 if self.cfg.resume_after else 0
  247. self.resume_cmd = self.gm.cmd_list[self.gm.cmd_list.index(rc)+offset]
  248. omsg(f'INFO → Resuming at command {self.resume_cmd!r}')
  249. if self.cfg.step:
  250. self.cfg.exit_after = self.resume_cmd
  251. if self.cfg.exit_after and self.cfg.exit_after not in self.gm.cmd_list:
  252. die(1, f'{self.cfg.exit_after!r}: command not recognized')
  253. return self.tg
  254. def run_tests(self, cmd_args):
  255. gname_save = None
  256. def parse_arg(arg):
  257. if '.' in arg:
  258. a, b = arg.split('.')
  259. return [a] + b.split(':') if ':' in b else [a, b, None]
  260. elif ':' in arg:
  261. a, b = arg.split(':')
  262. return [a, None, b]
  263. else:
  264. return [self.gm.find_cmd_in_groups(arg), None, arg]
  265. if cmd_args:
  266. for arg in cmd_args:
  267. if arg in self.gm.cmd_groups:
  268. if self.init_group(arg):
  269. for cmd in self.gm.cmd_list:
  270. self.check_needs_rerun(cmd, build=True)
  271. self.do_between()
  272. else:
  273. gname, sg_name, cmdname = parse_arg(arg)
  274. if gname:
  275. same_grp = gname == gname_save # same group as previous cmd: don't clean, suppress blue msg
  276. if self.init_group(gname, sg_name, cmdname, quiet=same_grp, do_clean=not same_grp):
  277. if cmdname:
  278. if self.cfg.deps_only:
  279. self.deps_only = cmdname
  280. try:
  281. self.check_needs_rerun(cmdname, build=True)
  282. except Exception as e: # allow calling of functions not in cmd_group
  283. if isinstance(e, KeyError) and e.args[0] == cmdname:
  284. ret = getattr(self.tg, cmdname)()
  285. if type(ret).__name__ == 'coroutine':
  286. ret = asyncio.run(ret)
  287. self.process_retval(cmdname, ret)
  288. else:
  289. raise
  290. self.do_between()
  291. else:
  292. for cmd in self.gm.cmd_list:
  293. self.check_needs_rerun(cmd, build=True)
  294. self.do_between()
  295. gname_save = gname
  296. else:
  297. die(1, f'{arg!r}: command not recognized')
  298. else:
  299. if self.cfg.exclude_groups:
  300. exclude = self.cfg.exclude_groups.split(',')
  301. for e in exclude:
  302. if e not in cmd_groups_dfl:
  303. die(1, f'{e!r}: group not recognized')
  304. for gname in cmd_groups_dfl:
  305. if self.cfg.exclude_groups and gname in exclude:
  306. continue
  307. if self.init_group(gname):
  308. for cmd in self.gm.cmd_list:
  309. self.check_needs_rerun(cmd, build=True)
  310. self.do_between()
  311. self.end_msg()
  312. def check_needs_rerun(
  313. self,
  314. cmd,
  315. build = False,
  316. root = True,
  317. force_delete = False,
  318. dpy = False):
  319. self.tg.test_name = cmd
  320. if self.ct_clsname == 'CmdTestMain' and self.testing_segwit and cmd not in self.tg.segwit_do:
  321. return False
  322. rerun = root # force_delete is not passed to recursive call
  323. fns = []
  324. if force_delete or not root:
  325. # does cmd produce a needed dependency(ies)?
  326. ret = self.get_num_exts_for_cmd(cmd)
  327. if ret:
  328. for ext in ret[1]:
  329. fn = get_file_with_ext(cfgs[ret[0]]['tmpdir'], ext, delete=build)
  330. if fn:
  331. if force_delete:
  332. os.unlink(fn)
  333. else: fns.append(fn)
  334. else: rerun = True
  335. fdeps = self.generate_file_deps(cmd)
  336. cdeps = self.generate_cmd_deps(fdeps)
  337. for fn in fns:
  338. my_age = os.stat(fn).st_mtime
  339. for num, ext in fdeps:
  340. f = get_file_with_ext(cfgs[num]['tmpdir'], ext, delete=build)
  341. if f and os.stat(f).st_mtime > my_age:
  342. rerun = True
  343. for cdep in cdeps:
  344. if self.check_needs_rerun(cdep, build=build, root=False, dpy=cmd):
  345. rerun = True
  346. if build:
  347. if rerun:
  348. for fn in fns:
  349. if not root:
  350. os.unlink(fn)
  351. if not (dpy and self.cfg.skipping_deps):
  352. self.run_test(cmd)
  353. if not root:
  354. self.do_between()
  355. else:
  356. # If prog produces multiple files:
  357. if cmd not in self.rebuild_list or rerun is True:
  358. self.rebuild_list[cmd] = (rerun, fns[0] if fns else '') # FIX
  359. return rerun
  360. def run_test(self, cmd):
  361. if self.deps_only and cmd == self.deps_only:
  362. sys.exit(0)
  363. if self.tg.full_data:
  364. d = [(str(num), ext) for exts, num in self.gm.dpy_data[cmd][2] for ext in exts]
  365. # delete files depended on by this cmd
  366. arg_list = [get_file_with_ext(cfgs[num]['tmpdir'], ext) for num, ext in d]
  367. # remove shared_deps from arg list
  368. if hasattr(self.tg, 'shared_deps'):
  369. arg_list = arg_list[:-len(self.tg.shared_deps)]
  370. else:
  371. arg_list = []
  372. if self.resume_cmd:
  373. if cmd != self.resume_cmd:
  374. return
  375. bmsg(f'Resuming at {self.resume_cmd!r}')
  376. self.resume_cmd = None
  377. self.cfg.skipping_deps = False
  378. self.cfg.resuming = False
  379. if self.cfg.profile:
  380. start = time.time()
  381. self.tg.test_name = cmd # NB: Do not remove, this needs to be set twice
  382. if self.tg.full_data:
  383. tmpdir_num = self.gm.dpy_data[cmd][0]
  384. self.tg.tmpdir_num = tmpdir_num
  385. for k in (test_cfg := cfgs[str(tmpdir_num)]):
  386. if k in self.gm.cfg_attrs:
  387. setattr(self.tg, k, test_cfg[k])
  388. ret = getattr(self.tg, cmd)(*arg_list) # run the test
  389. if type(ret).__name__ == 'coroutine':
  390. ret = asyncio.run(ret)
  391. self.process_retval(cmd, ret)
  392. if self.cfg.profile:
  393. omsg('\r\033[50C{:.4f}'.format(time.time() - start))
  394. if cmd == self.cfg.exit_after:
  395. sys.exit(0)
  396. def warn_skipped(self):
  397. if self.skipped_warnings:
  398. print(yellow('The following tests were skipped and may require attention:'))
  399. r = '-' * 72 + '\n'
  400. print(r+('\n'+r).join(self.skipped_warnings))
  401. def process_retval(self, cmd, ret):
  402. if type(ret).__name__ == 'MMGenPexpect':
  403. ret.ok(exit_val=self.exit_val)
  404. self.cmd_total += 1
  405. elif ret == 'ok':
  406. ok()
  407. self.cmd_total += 1
  408. elif ret in ('skip', 'skip_msg', 'silent'):
  409. if ret == 'silent':
  410. self.cmd_total += 1
  411. elif ret == 'skip_msg':
  412. ok('SKIP')
  413. elif ret == 'error':
  414. die(2, red(f'\nTest {self.tg.test_name!r} failed'))
  415. elif isinstance(ret, tuple) and ret[0] == 'skip_warn':
  416. self.skipped_warnings.append(
  417. 'Test {!r} was skipped:\n {}'.format(cmd, '\n '.join(ret[1].split('\n'))))
  418. else:
  419. die(2, f'{cmd!r} returned {ret}')
  420. def check_deps(self, cmds): # TODO: broken, unused
  421. if len(cmds) != 1:
  422. die(1, f'Usage: {gc.prog_name} check_deps <command>')
  423. cmd = cmds[0]
  424. if cmd not in self.gm.cmd_list:
  425. die(1, f'{cmd!r}: unrecognized command')
  426. if not self.cfg.quiet:
  427. omsg(f'Checking dependencies for {cmd!r}')
  428. self.check_needs_rerun(cmd)
  429. w = max(map(len, self.rebuild_list)) + 1
  430. for cmd in self.rebuild_list:
  431. c = self.rebuild_list[cmd]
  432. m = 'Rebuild' if (c[0] and c[1]) else 'Build' if c[0] else 'OK'
  433. omsg('cmd {:<{w}} {}'.format(cmd+':', m, w=w))
  434. def generate_file_deps(self, cmd):
  435. return [(str(n), e) for exts, n in self.gm.dpy_data[cmd][2] for e in exts]
  436. def generate_cmd_deps(self, fdeps):
  437. return [cfgs[str(n)]['dep_generators'][ext] for n, ext in fdeps]
  438. def get_num_exts_for_cmd(self, cmd):
  439. try:
  440. num = str(self.gm.dpy_data[cmd][0])
  441. except KeyError:
  442. qmsg_r(f'Missing dependency {cmd!r}')
  443. gname = self.gm.find_cmd_in_groups(cmd)
  444. if gname:
  445. kwargs = self.gm.cmd_groups[gname][1]
  446. kwargs.update({'add_dpy':True})
  447. self.gm.create_group(gname, None, **kwargs)
  448. num = str(self.gm.dpy_data[cmd][0])
  449. qmsg(f' found in group {gname!r}')
  450. else:
  451. qmsg(' not found in any command group!')
  452. raise
  453. dgl = cfgs[num]['dep_generators']
  454. if cmd in dgl.values():
  455. exts = [k for k in dgl if dgl[k] == cmd]
  456. return (num, exts)
  457. else:
  458. return None