test.py 31 KB

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