test.py 31 KB

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