cmdtest.py 31 KB

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