cmdtest.py 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022
  1. #!/usr/bin/env python3
  2. #
  3. # MMGen Wallet, a terminal-based cryptocurrency wallet
  4. # Copyright (C)2013-2024 The MMGen Project <mmgen@tuta.io>
  5. #
  6. # This program is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. """
  19. test/cmdtest.py: Command test runner for the MMGen wallet system
  20. """
  21. def check_segwit_opts():
  22. for k, m in (('segwit', 'S'), ('segwit_random', 'S'), ('bech32', 'B')):
  23. if getattr(cfg, k) and m not in proto.mmtypes:
  24. die(1, f'--{k.replace("_", "-")} option incompatible with {proto.cls_name}')
  25. def create_shm_dir(data_dir, trash_dir):
  26. # Laggy flash media can cause pexpect to fail, so create a temporary directory
  27. # under '/dev/shm' and put datadir and tmpdirs here.
  28. import shutil
  29. from subprocess import run
  30. if sys.platform in ('win32', 'darwin'):
  31. for tdir in (data_dir, trash_dir):
  32. try:
  33. os.listdir(tdir)
  34. except:
  35. pass
  36. else:
  37. try:
  38. shutil.rmtree(tdir)
  39. except: # we couldn't remove data dir - perhaps regtest daemon is running
  40. try:
  41. run(['python3', os.path.join('cmds', 'mmgen-regtest'), 'stop'], check=True)
  42. except:
  43. die(4, f'Unable to remove {tdir!r}!')
  44. else:
  45. time.sleep(2)
  46. shutil.rmtree(tdir)
  47. os.mkdir(tdir, 0o755)
  48. shm_dir = 'test'
  49. else:
  50. tdir, pfx = '/dev/shm', 'mmgen-test-'
  51. try:
  52. run(f'rm -rf {tdir}/{pfx}*', shell=True, check=True)
  53. except Exception as e:
  54. die(2, f'Unable to delete directory tree {tdir}/{pfx}* ({e.args[0]})')
  55. try:
  56. import tempfile
  57. shm_dir = str(tempfile.mkdtemp('', pfx, tdir))
  58. except Exception as e:
  59. die(2, f'Unable to create temporary directory in {tdir} ({e.args[0]})')
  60. dest = os.path.join(shm_dir, os.path.basename(trash_dir))
  61. os.mkdir(dest, 0o755)
  62. run(f'rm -rf {trash_dir}', shell=True, check=True)
  63. os.symlink(dest, trash_dir)
  64. dest = os.path.join(shm_dir, os.path.basename(data_dir))
  65. shutil.move(data_dir, dest) # data_dir was created by Config()
  66. os.symlink(dest, data_dir)
  67. return shm_dir
  68. import sys, os, time, asyncio
  69. # overlay must be set up before importing mmgen mods!
  70. try:
  71. from include.test_init import repo_root
  72. except ImportError:
  73. from test.include.test_init import repo_root
  74. from mmgen.cfg import Config, gc
  75. from mmgen.color import red, yellow, green, blue, cyan, gray, nocolor, init_color
  76. from mmgen.util import msg, Msg, rmsg, bmsg, die, suf, make_timestr
  77. from test.include.common import (
  78. set_globals,
  79. cmdtest_py_log_fn,
  80. cmdtest_py_error_fn,
  81. mk_tmpdir,
  82. iqmsg,
  83. omsg,
  84. omsg_r,
  85. ok,
  86. start_test_daemons,
  87. stop_test_daemons,
  88. init_coverage,
  89. clean,
  90. )
  91. try:
  92. os.unlink(os.path.join(repo_root, cmdtest_py_error_fn))
  93. except:
  94. pass
  95. os.environ['MMGEN_QUIET'] = '0' # for this script and spawned scripts
  96. opts_data = {
  97. 'sets': [
  98. ('list_current_cmd_groups', True, 'list_cmd_groups', True),
  99. ('demo', True, 'exact_output', True),
  100. ('demo', True, 'buf_keypress', True),
  101. ('demo', True, 'pexpect_spawn', True),
  102. ],
  103. 'text': {
  104. 'desc': 'High-level tests for the MMGen Wallet suite',
  105. 'usage':'[options] [command [..command]] | [command_group[.command_subgroup][:command]]',
  106. 'options': """
  107. -h, --help Print this help message
  108. --, --longhelp Print help message for long (global) options
  109. -a, --no-altcoin Skip altcoin tests (WIP)
  110. -A, --no-daemon-autostart Don't start and stop daemons automatically
  111. -B, --bech32 Generate and use Bech32 addresses
  112. -b, --buf-keypress Use buffered keypresses as with real human input
  113. (often required on slow systems, or under emulation)
  114. -c, --print-cmdline Print the command line of each spawned command
  115. -C, --coverage Produce code coverage info using trace module
  116. -x, --debug-pexpect Produce debugging output for pexpect calls
  117. --, --demo Add extra delay after each send to make input visible.
  118. Implies --exact-output --pexpect-spawn --buf-keypress
  119. -d, --deps-only Run a command or command subgroup’s dependencies without
  120. running the command or command group itself.
  121. -D, --no-daemon-stop Don't stop auto-started daemons after running tests
  122. -E, --direct-exec Bypass pexpect and execute a command directly (for
  123. debugging only)
  124. -e, --exact-output Show the exact output of the MMGen script(s) being run
  125. -G, --exclude-groups=G Exclude the specified command groups (comma-separated)
  126. -l, --list-cmds List the test script’s available commands
  127. -L, --list-cmd-groups List the test script’s command groups and subgroups
  128. -g, --list-current-cmd-groups List command groups for current configuration
  129. -n, --names Display command names instead of descriptions
  130. -N, --no-timings Suppress display of timing information
  131. -o, --log Log commands to file {lf!r}
  132. -O, --pexpect-spawn Use pexpect.spawn instead of popen_spawn (much slower,
  133. kut does real terminal emulation)
  134. -p, --pause Pause between tests, resuming on keypress
  135. -P, --profile Record the execution time of each script
  136. -q, --quiet Produce minimal output. Suppress dependency info
  137. -r, --resume=c Resume at command 'c' after interrupted run
  138. -R, --resume-after=c Same, but resume at command following 'c'
  139. -t, --step After resuming, execute one command and stop
  140. -S, --skip-deps Skip dependency checking for command
  141. -u, --usr-random Get random data interactively from user
  142. -T, --pexpect-timeout=T Set the timeout for pexpect
  143. -v, --verbose Produce more verbose output
  144. -W, --no-dw-delete Don't remove default wallet from data dir after dw tests
  145. are done
  146. -X, --exit-after=C Exit after command 'C'
  147. -y, --segwit Generate and use Segwit addresses
  148. -Y, --segwit-random Generate and use a random mix of Segwit and Legacy addrs
  149. """,
  150. 'notes': """
  151. If no command is given, the whole test suite is run for the currently
  152. specified coin (default BTC).
  153. For traceback output and error file support, set the EXEC_WRAPPER_TRACEBACK
  154. environment var
  155. """
  156. },
  157. 'code': {
  158. 'options': lambda proto, help_notes, s: s.format(
  159. lf = cmdtest_py_log_fn
  160. )
  161. }
  162. }
  163. # we need some opt values before running opts.init, so parse without initializing:
  164. po = Config(opts_data=opts_data, parse_only=True)._parsed_opts
  165. data_dir = Config.test_datadir
  166. # step 1: delete data_dir symlink in ./test;
  167. if not po.user_opts.get('skip_deps'):
  168. try:
  169. os.unlink(data_dir)
  170. except:
  171. pass
  172. # step 2: opts.init will create new data_dir in ./test (if not po.user_opts['skip_deps'])
  173. cfg = Config(opts_data=opts_data)
  174. if cfg.no_altcoin and cfg.coin != 'BTC':
  175. die(1, f'--no-altcoin incompatible with --coin={cfg.coin}')
  176. set_globals(cfg)
  177. from test.cmdtest_d.common import ( # this must be loaded after set_globals()
  178. get_file_with_ext,
  179. confirm_continue
  180. )
  181. type(cfg)._reset_ok += (
  182. 'no_daemon_autostart',
  183. 'names',
  184. 'no_timings',
  185. 'exit_after',
  186. 'resuming',
  187. 'skipping_deps')
  188. logging = cfg.log or os.getenv('MMGEN_EXEC_WRAPPER')
  189. cfg.resuming = any(k in po.user_opts for k in ('resume', 'resume_after'))
  190. cfg.skipping_deps = cfg.resuming or 'skip_deps' in po.user_opts
  191. cmd_args = cfg._args
  192. if cfg.pexpect_spawn and sys.platform == 'win32':
  193. die(1, '--pexpect-spawn option not supported on Windows platform, exiting')
  194. if cfg.daemon_id and cfg.daemon_id in cfg.blacklisted_daemons.split():
  195. die(1, f'cmdtest.py: daemon {cfg.daemon_id!r} blacklisted, exiting')
  196. network_id = cfg.coin.lower() + ('_tn' if cfg.testnet else '')
  197. proto = cfg._proto
  198. # step 3: move data_dir to /dev/shm and symlink it back to ./test:
  199. trash_dir = os.path.join('test', 'trash')
  200. trash_dir2 = os.path.join('test', 'trash2')
  201. if not cfg.skipping_deps:
  202. shm_dir = create_shm_dir(data_dir, trash_dir)
  203. check_segwit_opts()
  204. testing_segwit = cfg.segwit or cfg.segwit_random or cfg.bech32
  205. if cfg.test_suite_deterministic:
  206. cfg.no_timings = True
  207. init_color(num_colors=0)
  208. os.environ['MMGEN_DISABLE_COLOR'] = '1' # for this script and spawned scripts
  209. if cfg.profile:
  210. cfg.names = True
  211. if cfg.exact_output:
  212. qmsg = qmsg_r = lambda s: None
  213. else:
  214. qmsg = cfg._util.qmsg
  215. qmsg_r = cfg._util.qmsg_r
  216. if cfg.skipping_deps:
  217. cfg.no_daemon_autostart = True
  218. from test.cmdtest_d.cfg import cfgs
  219. def list_cmds():
  220. def gen_output():
  221. gm = CmdGroupMgr()
  222. cw, d = 0, []
  223. yield green('AVAILABLE COMMANDS:')
  224. for gname in gm.cmd_groups:
  225. tg = gm.gm_init_group(None, gname, None, None)
  226. desc = tg.__doc__.strip() if tg.__doc__ else type(tg).__name__
  227. d.append((gname, desc, gm.cmd_list, gm.dpy_data))
  228. cw = max(max(len(k) for k in gm.dpy_data), cw)
  229. for gname, gdesc, clist, dpdata in d:
  230. yield '\n'+green(f'{gname!r} - {gdesc}:')
  231. for cmd in clist:
  232. data = dpdata[cmd]
  233. yield ' {:{w}} - {}'.format(
  234. cmd,
  235. (data if isinstance(data, str) else data[1]),
  236. w = cw)
  237. from mmgen.ui import do_pager
  238. do_pager('\n'.join(gen_output()))
  239. sys.exit(0)
  240. def do_between():
  241. if cfg.pause:
  242. confirm_continue()
  243. elif (cfg.verbose or cfg.exact_output) and not cfg.skipping_deps:
  244. sys.stderr.write('\n')
  245. def create_tmp_dirs(shm_dir):
  246. if sys.platform in ('win32', 'darwin'):
  247. for cfg in sorted(cfgs):
  248. mk_tmpdir(cfgs[cfg]['tmpdir'])
  249. else:
  250. os.makedirs(os.path.join('test', 'tmp'), mode=0o755, exist_ok=True)
  251. for cfg in sorted(cfgs):
  252. src = os.path.join(shm_dir, cfgs[cfg]['tmpdir'].split('/')[-1])
  253. mk_tmpdir(src)
  254. try:
  255. os.unlink(cfgs[cfg]['tmpdir'])
  256. except OSError as e:
  257. if e.errno != 2:
  258. raise
  259. finally:
  260. os.symlink(src, cfgs[cfg]['tmpdir'])
  261. def set_restore_term_at_exit():
  262. import termios, atexit
  263. fd = sys.stdin.fileno()
  264. old = termios.tcgetattr(fd)
  265. def at_exit():
  266. termios.tcsetattr(fd, termios.TCSADRAIN, old)
  267. atexit.register(at_exit)
  268. class CmdGroupMgr:
  269. dpy_data = None
  270. from test.cmdtest_d.cfg import cmd_groups_dfl, cmd_groups_extra
  271. cmd_groups = cmd_groups_dfl.copy()
  272. cmd_groups.update(cmd_groups_extra)
  273. @staticmethod
  274. def create_cmd_group(cls, sg_name=None):
  275. cmd_group_in = dict(cls.cmd_group_in)
  276. if sg_name and 'subgroup.' + sg_name not in cmd_group_in:
  277. die(1, f'{sg_name!r}: no such subgroup in test group {cls.__name__}')
  278. def add_entries(key, add_deps=True, added_subgroups=[]):
  279. if add_deps:
  280. for dep in cmd_group_in['subgroup.'+key]:
  281. yield from add_entries(dep)
  282. assert isinstance(cls.cmd_subgroups[key][0], str), f'header for subgroup {key!r} missing!'
  283. if not key in added_subgroups:
  284. yield from cls.cmd_subgroups[key][1:]
  285. added_subgroups.append(key)
  286. def gen():
  287. for name, data in cls.cmd_group_in:
  288. if name.startswith('subgroup.'):
  289. sg_key = name.removeprefix('subgroup.')
  290. if sg_name in (None, sg_key):
  291. yield from add_entries(
  292. sg_key,
  293. add_deps = sg_name and not cfg.skipping_deps,
  294. added_subgroups = [sg_name] if cfg.deps_only else [])
  295. if cfg.deps_only and sg_key == sg_name:
  296. return
  297. elif not cfg.skipping_deps:
  298. yield (name, data)
  299. return tuple(gen())
  300. def load_mod(self, gname, modname=None):
  301. clsname, kwargs = self.cmd_groups[gname]
  302. if modname is None and 'modname' in kwargs:
  303. modname = kwargs['modname']
  304. import importlib
  305. modpath = f'test.cmdtest_d.ct_{modname or gname}'
  306. return getattr(importlib.import_module(modpath), clsname)
  307. def create_group(self, gname, sg_name, full_data=False, modname=None, is3seed=False, add_dpy=False):
  308. """
  309. Initializes the list 'cmd_list' and dict 'dpy_data' from module's cmd_group data.
  310. Alternatively, if called with 'add_dpy=True', updates 'dpy_data' from module data
  311. without touching 'cmd_list'
  312. """
  313. cls = self.load_mod(gname, modname)
  314. cdata = []
  315. def get_shared_deps(cmdname, tmpdir_idx):
  316. """
  317. shared_deps are "implied" dependencies for all cmds in cmd_group that don't appear in
  318. the cmd_group data or cmds' argument lists. Supported only for 3seed tests at present.
  319. """
  320. if not hasattr(cls, 'shared_deps'):
  321. return []
  322. return [k for k, v in cfgs[str(tmpdir_idx)]['dep_generators'].items()
  323. if k in cls.shared_deps and v != cmdname]
  324. if not hasattr(cls, 'cmd_group'):
  325. cls.cmd_group = self.create_cmd_group(cls, sg_name)
  326. for a, b in cls.cmd_group:
  327. if is3seed:
  328. for n, (i, j) in enumerate(zip(cls.tmpdir_nums, (128, 192, 256))):
  329. k = f'{a}_{n+1}'
  330. if hasattr(cls, 'skip_cmds') and k in cls.skip_cmds:
  331. continue
  332. sdeps = get_shared_deps(k, i)
  333. if isinstance(b, str):
  334. cdata.append((k, (i, f'{b} ({j}-bit)', [[[]+sdeps, i]])))
  335. else:
  336. cdata.append((k, (i, f'{b[1]} ({j}-bit)', [[b[0]+sdeps, i]])))
  337. else:
  338. cdata.append((a, b if full_data else (cls.tmpdir_nums[0], b, [[[], cls.tmpdir_nums[0]]])))
  339. if add_dpy:
  340. self.dpy_data.update(dict(cdata))
  341. else:
  342. self.cmd_list = tuple(e[0] for e in cdata)
  343. self.dpy_data = dict(cdata)
  344. return cls
  345. def gm_init_group(self, trunner, gname, sg_name, spawn_prog):
  346. kwargs = self.cmd_groups[gname][1]
  347. cls = self.create_group(gname, sg_name, **kwargs)
  348. cls.group_name = gname
  349. return cls(trunner, cfgs, spawn_prog)
  350. def get_cls_by_gname(self, gname):
  351. return self.load_mod(gname, self.cmd_groups[gname][1].get('modname'))
  352. def list_cmd_groups(self):
  353. ginfo = []
  354. for gname in self.cmd_groups:
  355. ginfo.append((gname, self.get_cls_by_gname(gname)))
  356. if cfg.list_current_cmd_groups:
  357. exclude = (cfg.exclude_groups or '').split(',')
  358. ginfo = [g for g in ginfo
  359. if network_id in g[1].networks
  360. and not g[0] in exclude
  361. and g[0] in tuple(self.cmd_groups_dfl) + tuple(cmd_args)]
  362. desc = 'CONFIGURED'
  363. else:
  364. desc = 'AVAILABLE'
  365. def gen_output():
  366. yield green(f'{desc} COMMAND GROUPS AND SUBGROUPS:')
  367. yield ''
  368. for name, cls in ginfo:
  369. yield ' {} - {}'.format(
  370. yellow(name.ljust(13)),
  371. (cls.__doc__.strip() if cls.__doc__ else cls.__name__))
  372. if hasattr(cls, 'cmd_subgroups'):
  373. subgroups = {k:v for k, v in cls.cmd_subgroups.items() if not k.startswith('_')}
  374. max_w = max(len(k) for k in subgroups)
  375. for k, v in subgroups.items():
  376. yield ' + {} · {}'.format(cyan(k.ljust(max_w+1)), v[0])
  377. from mmgen.ui import do_pager
  378. do_pager('\n'.join(gen_output()))
  379. Msg('\n' + ' '.join(e[0] for e in ginfo))
  380. sys.exit(0)
  381. def find_cmd_in_groups(self, cmd, group=None):
  382. """
  383. Search for a test command in specified group or all configured command groups
  384. and return it as a string. Loads modules but alters no global variables.
  385. """
  386. if group:
  387. if not group in [e[0] for e in self.cmd_groups]:
  388. die(1, f'{group!r}: unrecognized group')
  389. groups = [self.cmd_groups[group]]
  390. else:
  391. groups = self.cmd_groups
  392. for gname in groups:
  393. cls = self.get_cls_by_gname(gname)
  394. if not hasattr(cls, 'cmd_group'):
  395. cls.cmd_group = self.create_cmd_group(cls)
  396. if cmd in cls.cmd_group: # first search the class
  397. return gname
  398. if cmd in dir(cls(None, None, None)): # then a throwaway instance
  399. return gname # cmd might exist in more than one group - we'll go with the first
  400. return None
  401. class CmdTestRunner:
  402. 'cmdtest.py test runner'
  403. def __del__(self):
  404. if logging:
  405. self.log_fd.close()
  406. def __init__(self, data_dir, trash_dir):
  407. self.data_dir = data_dir
  408. self.trash_dir = trash_dir
  409. self.cmd_total = 0
  410. self.rebuild_list = {}
  411. self.gm = CmdGroupMgr()
  412. self.repo_root = repo_root
  413. self.skipped_warnings = []
  414. self.resume_cmd = None
  415. self.deps_only = None
  416. if logging:
  417. self.log_fd = open(cmdtest_py_log_fn, 'a')
  418. self.log_fd.write(f'\nLog started: {make_timestr()} UTC\n')
  419. omsg(f'INFO → Logging to file {cmdtest_py_log_fn!r}')
  420. else:
  421. self.log_fd = None
  422. if cfg.coverage:
  423. coverdir, accfile = init_coverage()
  424. omsg(f'INFO → Writing coverage files to {coverdir!r}')
  425. self.pre_args = ['python3', '-m', 'trace', '--count', '--coverdir='+coverdir, '--file='+accfile]
  426. else:
  427. self.pre_args = ['python3'] if sys.platform == 'win32' else []
  428. if cfg.pexpect_spawn:
  429. omsg('INFO → Using pexpect.spawn() for real terminal emulation')
  430. self.set_spawn_env()
  431. def set_spawn_env(self):
  432. self.spawn_env = dict(os.environ)
  433. self.spawn_env.update({
  434. 'MMGEN_NO_LICENSE': '1',
  435. 'MMGEN_BOGUS_SEND': '1',
  436. 'MMGEN_TEST_SUITE_PEXPECT': '1',
  437. 'EXEC_WRAPPER_DO_RUNTIME_MSG':'1',
  438. # if cmdtest.py itself is running under exec_wrapper, disable writing of traceback file for spawned script
  439. 'EXEC_WRAPPER_TRACEBACK': '' if os.getenv('MMGEN_EXEC_WRAPPER') else '1',
  440. })
  441. if cfg.exact_output:
  442. from mmgen.term import get_terminal_size
  443. self.spawn_env['MMGEN_COLUMNS'] = str(get_terminal_size().width)
  444. else:
  445. self.spawn_env['MMGEN_COLUMNS'] = '120'
  446. def spawn_wrapper(
  447. self,
  448. cmd,
  449. args = [],
  450. extra_desc = '',
  451. no_output = False,
  452. msg_only = False,
  453. no_msg = False,
  454. cmd_dir = 'cmds',
  455. no_exec_wrapper = False,
  456. timeout = None,
  457. pexpect_spawn = None,
  458. direct_exec = False,
  459. no_passthru_opts = False,
  460. spawn_env_override = None,
  461. exit_val = None,
  462. env = {}):
  463. self.exit_val = exit_val
  464. desc = self.tg.test_name if cfg.names else self.gm.dpy_data[self.tg.test_name][1]
  465. if extra_desc:
  466. desc += ' ' + extra_desc
  467. cmd_path = (
  468. cmd if cfg.system # cfg.system is broken for main test group with overlay tree
  469. else os.path.relpath(os.path.join(repo_root, cmd_dir, cmd)))
  470. args = (
  471. self.pre_args +
  472. ([] if no_exec_wrapper else ['scripts/exec_wrapper.py']) +
  473. [cmd_path] +
  474. ([] if no_passthru_opts else self.passthru_opts) +
  475. args)
  476. try:
  477. qargs = ['{q}{}{q}'.format(a, q = "'" if ' ' in a else '') for a in args]
  478. except:
  479. msg(f'args: {args}')
  480. raise
  481. cmd_disp = ' '.join(qargs).replace('\\', '/') # for mingw
  482. if logging:
  483. self.log_fd.write('[{}][{}:{}] {}\n'.format(
  484. proto.coin.lower(),
  485. self.tg.group_name,
  486. self.tg.test_name,
  487. cmd_disp))
  488. for i in args: # die only after writing log entry
  489. if not isinstance(i, str):
  490. die(2, 'Error: missing input files in cmd line?:\nName: {}\nCmdline: {!r}'.format(
  491. self.tg.test_name,
  492. args))
  493. if not no_msg:
  494. t_pfx = '' if cfg.no_timings else f'[{time.time() - self.start_time:08.2f}] '
  495. if cfg.verbose or cfg.print_cmdline or cfg.exact_output:
  496. omsg(green(f'{t_pfx}Testing: {desc}'))
  497. if not msg_only:
  498. clr1, clr2 = (nocolor, nocolor) if cfg.print_cmdline else (green, cyan)
  499. omsg(
  500. clr1('Executing: ') +
  501. clr2(repr(cmd_disp) if sys.platform == 'win32' else cmd_disp)
  502. )
  503. else:
  504. omsg_r('{a}Testing {b}: {c}'.format(
  505. a = t_pfx,
  506. b = desc,
  507. c = 'OK\n' if direct_exec or cfg.direct_exec else ''))
  508. if msg_only:
  509. return
  510. # NB: the `pexpect_spawn` arg enables hold_protect and send_delay while the corresponding cmdline
  511. # option does not. For performance reasons, this is the desired behavior. For full emulation of
  512. # the user experience with hold protect enabled, specify --buf-keypress or --demo.
  513. send_delay = 0.4 if pexpect_spawn is True or cfg.buf_keypress else None
  514. pexpect_spawn = pexpect_spawn if pexpect_spawn is not None else bool(cfg.pexpect_spawn)
  515. spawn_env = dict(spawn_env_override or self.tg.spawn_env)
  516. spawn_env.update({
  517. 'MMGEN_HOLD_PROTECT_DISABLE': '' if send_delay else '1',
  518. 'MMGEN_TEST_SUITE_POPEN_SPAWN': '' if pexpect_spawn else '1',
  519. 'EXEC_WRAPPER_EXIT_VAL': '' if exit_val is None else str(exit_val),
  520. })
  521. spawn_env.update(env)
  522. from test.include.pexpect import MMGenPexpect
  523. return MMGenPexpect(
  524. args = args,
  525. no_output = no_output,
  526. spawn_env = spawn_env,
  527. pexpect_spawn = pexpect_spawn,
  528. timeout = timeout,
  529. send_delay = send_delay,
  530. direct_exec = direct_exec)
  531. def end_msg(self):
  532. t = int(time.time() - self.start_time)
  533. sys.stderr.write(green(
  534. f'{self.cmd_total} test{suf(self.cmd_total)} performed' +
  535. ('\n' if cfg.no_timings else f'. Elapsed time: {t//60:02d}:{t%60:02d}\n')
  536. ))
  537. def init_group(self, gname, sg_name=None, cmd=None, quiet=False, do_clean=True):
  538. from test.cmdtest_d.cfg import cmd_groups_altcoin
  539. if cfg.no_altcoin and gname in cmd_groups_altcoin:
  540. omsg(gray(f'INFO → skipping test group {gname!r} (--no-altcoin)'))
  541. return None
  542. ct_cls = CmdGroupMgr().load_mod(gname)
  543. if sys.platform in ct_cls.platform_skip:
  544. omsg(gray(f'INFO → skipping test {gname!r} for platform {sys.platform!r}'))
  545. return None
  546. for k in ('segwit', 'segwit_random', 'bech32'):
  547. if getattr(cfg, k):
  548. segwit_opt = k
  549. break
  550. else:
  551. segwit_opt = None
  552. def gen_msg():
  553. yield ('{g}:{c}' if cmd else 'test group {g!r}').format(g=gname, c=cmd)
  554. if len(ct_cls.networks) != 1:
  555. yield f' for {proto.coin} {proto.network}'
  556. if segwit_opt:
  557. yield ' (--{})'.format(segwit_opt.replace('_', '-'))
  558. m = ''.join(gen_msg())
  559. if segwit_opt and not ct_cls.segwit_opts_ok:
  560. iqmsg(gray(f'INFO → skipping {m}'))
  561. return None
  562. # 'networks = ()' means all networks allowed
  563. nws = [(e.split('_')[0], 'testnet') if '_' in e else (e, 'mainnet') for e in ct_cls.networks]
  564. if nws:
  565. coin = proto.coin.lower()
  566. for a, b in nws:
  567. if a == coin and b == proto.network:
  568. break
  569. else:
  570. iqmsg(gray(f'INFO → skipping {m} for {proto.coin} {proto.network}'))
  571. return None
  572. if do_clean and not cfg.skipping_deps:
  573. clean(cfgs, tmpdir_ids=ct_cls.tmpdir_nums, extra_dirs=[data_dir, trash_dir, trash_dir2])
  574. if not quiet:
  575. bmsg('Executing ' + m)
  576. if (not self.daemon_started) and self.gm.get_cls_by_gname(gname).need_daemon:
  577. start_test_daemons(network_id, remove_datadir=True)
  578. self.daemon_started = True
  579. if hasattr(self, 'tg'):
  580. del self.tg
  581. self.tg = self.gm.gm_init_group(self, gname, sg_name, self.spawn_wrapper)
  582. self.ct_clsname = type(self.tg).__name__
  583. # pass through opts from cmdline (po.user_opts)
  584. self.passthru_opts = ['--{}{}'.format(
  585. k.replace('_', '-'),
  586. '' if cfg._uopts[k] is True else '=' + cfg._uopts[k]
  587. ) for k in cfg._uopts if k in self.tg.base_passthru_opts + self.tg.passthru_opts]
  588. if cfg.resuming:
  589. rc = cfg.resume or cfg.resume_after
  590. offset = 1 if cfg.resume_after else 0
  591. self.resume_cmd = self.gm.cmd_list[self.gm.cmd_list.index(rc)+offset]
  592. omsg(f'INFO → Resuming at command {self.resume_cmd!r}')
  593. if cfg.step:
  594. cfg.exit_after = self.resume_cmd
  595. if cfg.exit_after and cfg.exit_after not in self.gm.cmd_list:
  596. die(1, f'{cfg.exit_after!r}: command not recognized')
  597. return self.tg
  598. def run_tests(self, cmd_args):
  599. self.start_time = time.time()
  600. self.daemon_started = False
  601. gname_save = None
  602. def parse_arg(arg):
  603. if '.' in arg:
  604. a, b = arg.split('.')
  605. return [a] + b.split(':') if ':' in b else [a, b, None]
  606. elif ':' in arg:
  607. a, b = arg.split(':')
  608. return [a, None, b]
  609. else:
  610. return [self.gm.find_cmd_in_groups(arg), None, arg]
  611. if cmd_args:
  612. for arg in cmd_args:
  613. if arg in self.gm.cmd_groups:
  614. if self.init_group(arg):
  615. for cmd in self.gm.cmd_list:
  616. self.check_needs_rerun(cmd, build=True)
  617. do_between()
  618. else:
  619. gname, sg_name, cmdname = parse_arg(arg)
  620. if gname:
  621. same_grp = gname == gname_save # same group as previous cmd: don't clean, suppress blue msg
  622. if self.init_group(gname, sg_name, cmdname, quiet=same_grp, do_clean=not same_grp):
  623. if cmdname:
  624. if cfg.deps_only:
  625. self.deps_only = cmdname
  626. try:
  627. self.check_needs_rerun(cmdname, build=True)
  628. except Exception as e: # allow calling of functions not in cmd_group
  629. if isinstance(e, KeyError) and e.args[0] == cmdname:
  630. ret = getattr(self.tg, cmdname)()
  631. if type(ret).__name__ == 'coroutine':
  632. asyncio.run(ret)
  633. else:
  634. raise
  635. do_between()
  636. else:
  637. for cmd in self.gm.cmd_list:
  638. self.check_needs_rerun(cmd, build=True)
  639. do_between()
  640. gname_save = gname
  641. else:
  642. die(1, f'{arg!r}: command not recognized')
  643. else:
  644. if cfg.exclude_groups:
  645. exclude = cfg.exclude_groups.split(',')
  646. for e in exclude:
  647. if e not in self.gm.cmd_groups_dfl:
  648. die(1, f'{e!r}: group not recognized')
  649. for gname in self.gm.cmd_groups_dfl:
  650. if cfg.exclude_groups and gname in exclude:
  651. continue
  652. if self.init_group(gname):
  653. for cmd in self.gm.cmd_list:
  654. self.check_needs_rerun(cmd, build=True)
  655. do_between()
  656. self.end_msg()
  657. def check_needs_rerun(
  658. self,
  659. cmd,
  660. build = False,
  661. root = True,
  662. force_delete = False,
  663. dpy = False):
  664. self.tg.test_name = cmd
  665. if self.ct_clsname == 'CmdTestMain' and testing_segwit and cmd not in self.tg.segwit_do:
  666. return False
  667. rerun = root # force_delete is not passed to recursive call
  668. fns = []
  669. if force_delete or not root:
  670. # does cmd produce a needed dependency(ies)?
  671. ret = self.get_num_exts_for_cmd(cmd)
  672. if ret:
  673. for ext in ret[1]:
  674. fn = get_file_with_ext(cfgs[ret[0]]['tmpdir'], ext, delete=build)
  675. if fn:
  676. if force_delete:
  677. os.unlink(fn)
  678. else: fns.append(fn)
  679. else: rerun = True
  680. fdeps = self.generate_file_deps(cmd)
  681. cdeps = self.generate_cmd_deps(fdeps)
  682. for fn in fns:
  683. my_age = os.stat(fn).st_mtime
  684. for num, ext in fdeps:
  685. f = get_file_with_ext(cfgs[num]['tmpdir'], ext, delete=build)
  686. if f and os.stat(f).st_mtime > my_age:
  687. rerun = True
  688. for cdep in cdeps:
  689. if self.check_needs_rerun(cdep, build=build, root=False, dpy=cmd):
  690. rerun = True
  691. if build:
  692. if rerun:
  693. for fn in fns:
  694. if not root:
  695. os.unlink(fn)
  696. if not (dpy and cfg.skipping_deps):
  697. self.run_test(cmd)
  698. if not root:
  699. do_between()
  700. else:
  701. # If prog produces multiple files:
  702. if cmd not in self.rebuild_list or rerun is True:
  703. self.rebuild_list[cmd] = (rerun, fns[0] if fns else '') # FIX
  704. return rerun
  705. def run_test(self, cmd):
  706. if self.deps_only and cmd == self.deps_only:
  707. sys.exit(0)
  708. d = [(str(num), ext) for exts, num in self.gm.dpy_data[cmd][2] for ext in exts]
  709. # delete files depended on by this cmd
  710. arg_list = [get_file_with_ext(cfgs[num]['tmpdir'], ext) for num, ext in d]
  711. # remove shared_deps from arg list
  712. if hasattr(self.tg, 'shared_deps'):
  713. arg_list = arg_list[:-len(self.tg.shared_deps)]
  714. if self.resume_cmd:
  715. if cmd != self.resume_cmd:
  716. return
  717. bmsg(f'Resuming at {self.resume_cmd!r}')
  718. self.resume_cmd = None
  719. cfg.skipping_deps = False
  720. cfg.resuming = False
  721. if cfg.profile:
  722. start = time.time()
  723. self.tg.test_name = cmd # NB: Do not remove, this needs to be set twice
  724. cdata = self.gm.dpy_data[cmd]
  725. # self.tg.test_dpydata = cdata
  726. self.tg.tmpdir_num = cdata[0]
  727. # self.tg.cfg = cfgs[str(cdata[0])] # will remove this eventually
  728. test_cfg = cfgs[str(cdata[0])]
  729. for k in (
  730. 'seed_len', 'seed_id', 'wpasswd', 'kapasswd', 'segwit', 'hash_preset', 'bw_filename',
  731. 'bw_params', 'ref_bw_seed_id', 'addr_idx_list', 'pass_idx_list'):
  732. if k in test_cfg:
  733. setattr(self.tg, k, test_cfg[k])
  734. ret = getattr(self.tg, cmd)(*arg_list) # run the test
  735. if type(ret).__name__ == 'coroutine':
  736. ret = asyncio.run(ret)
  737. self.process_retval(cmd, ret)
  738. if cfg.profile:
  739. omsg('\r\033[50C{:.4f}'.format(time.time() - start))
  740. if cmd == cfg.exit_after:
  741. sys.exit(0)
  742. def warn_skipped(self):
  743. if self.skipped_warnings:
  744. print(yellow('The following tests were skipped and may require attention:'))
  745. r = '-' * 72 + '\n'
  746. print(r+('\n'+r).join(self.skipped_warnings))
  747. def process_retval(self, cmd, ret):
  748. if type(ret).__name__ == 'MMGenPexpect':
  749. ret.ok(exit_val=self.exit_val)
  750. self.cmd_total += 1
  751. elif ret == 'ok':
  752. ok()
  753. self.cmd_total += 1
  754. elif ret == 'error':
  755. die(2, red(f'\nTest {self.tg.test_name!r} failed'))
  756. elif ret in ('skip', 'skip_msg', 'silent'):
  757. if ret == 'silent':
  758. self.cmd_total += 1
  759. elif ret == 'skip_msg':
  760. ok('SKIP')
  761. elif isinstance(ret, tuple) and ret[0] == 'skip_warn':
  762. self.skipped_warnings.append(
  763. 'Test {!r} was skipped:\n {}'.format(cmd, '\n '.join(ret[1].split('\n'))))
  764. else:
  765. die(2, f'{cmd!r} returned {ret}')
  766. def check_deps(self, cmds): # TODO: broken
  767. if len(cmds) != 1:
  768. die(1, f'Usage: {gc.prog_name} check_deps <command>')
  769. cmd = cmds[0]
  770. if cmd not in self.gm.cmd_list:
  771. die(1, f'{cmd!r}: unrecognized command')
  772. if not cfg.quiet:
  773. omsg(f'Checking dependencies for {cmd!r}')
  774. self.check_needs_rerun(self.tg, cmd)
  775. w = max(map(len, self.rebuild_list)) + 1
  776. for cmd in self.rebuild_list:
  777. c = self.rebuild_list[cmd]
  778. m = 'Rebuild' if (c[0] and c[1]) else 'Build' if c[0] else 'OK'
  779. omsg('cmd {:<{w}} {}'.format(cmd+':', m, w=w))
  780. def generate_file_deps(self, cmd):
  781. return [(str(n), e) for exts, n in self.gm.dpy_data[cmd][2] for e in exts]
  782. def generate_cmd_deps(self, fdeps):
  783. return [cfgs[str(n)]['dep_generators'][ext] for n, ext in fdeps]
  784. def get_num_exts_for_cmd(self, cmd):
  785. try:
  786. num = str(self.gm.dpy_data[cmd][0])
  787. except KeyError:
  788. qmsg_r(f'Missing dependency {cmd!r}')
  789. gname = self.gm.find_cmd_in_groups(cmd)
  790. if gname:
  791. kwargs = self.gm.cmd_groups[gname][1]
  792. kwargs.update({'add_dpy':True})
  793. self.gm.create_group(gname, None, **kwargs)
  794. num = str(self.gm.dpy_data[cmd][0])
  795. qmsg(f' found in group {gname!r}')
  796. else:
  797. qmsg(' not found in any command group!')
  798. raise
  799. dgl = cfgs[num]['dep_generators']
  800. if cmd in dgl.values():
  801. exts = [k for k in dgl if dgl[k] == cmd]
  802. return (num, exts)
  803. else:
  804. return None
  805. if __name__ == '__main__':
  806. if not cfg.skipping_deps: # do this before list cmds exit, so we stay in sync with shm_dir
  807. create_tmp_dirs(shm_dir)
  808. if cfg.list_cmd_groups:
  809. CmdGroupMgr().list_cmd_groups()
  810. elif cfg.list_cmds:
  811. list_cmds()
  812. if cfg.pause:
  813. set_restore_term_at_exit()
  814. from mmgen.exception import TestSuiteSpawnedScriptException
  815. try:
  816. tr = CmdTestRunner(data_dir, trash_dir)
  817. tr.run_tests(cmd_args)
  818. tr.warn_skipped()
  819. if tr.daemon_started and not cfg.no_daemon_stop:
  820. stop_test_daemons(network_id, remove_datadir=True)
  821. if hasattr(tr, 'tg'):
  822. del tr.tg
  823. del tr
  824. except KeyboardInterrupt:
  825. if tr.daemon_started and not cfg.no_daemon_stop:
  826. stop_test_daemons(network_id, remove_datadir=True)
  827. tr.warn_skipped()
  828. if hasattr(tr, 'tg'):
  829. del tr.tg
  830. del tr
  831. die(1, yellow('\ntest.py exiting at user request'))
  832. except TestSuiteSpawnedScriptException as e:
  833. # if spawned script is not running under exec_wrapper, output brief error msg:
  834. if os.getenv('MMGEN_EXEC_WRAPPER'):
  835. Msg(red(str(e)))
  836. Msg(blue('cmdtest.py: spawned script exited with error'))
  837. if hasattr(tr, 'tg'):
  838. del tr.tg
  839. del tr
  840. raise
  841. except Exception as e:
  842. if type(e).__name__ == 'TestSuiteException':
  843. rmsg('TEST ERROR: ' + str(e))
  844. if hasattr(tr, 'tg'):
  845. del tr.tg
  846. del tr
  847. # if cmdtest.py itself is running under exec_wrapper, re-raise so exec_wrapper can handle exception:
  848. if os.getenv('MMGEN_EXEC_WRAPPER') or not os.getenv('MMGEN_IGNORE_TEST_PY_EXCEPTION'):
  849. raise
  850. die(1, red('Test script exited with error'))