runner.py 16 KB

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