cmdtest.py 31 KB

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