test.py 29 KB

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