test.py 30 KB

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