test.py 30 KB

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