cmdtest.py 32 KB

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