test.py 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2021 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. rdie(1,"Unable to remove {!r}!".format(tdir))
  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('rm -rf {}/{}*'.format(tdir,pfx),shell=True,check=True)
  50. except Exception as e:
  51. die(2,'Unable to delete directory tree {}/{}* ({})'.format(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,'Unable to create temporary directory in {} ({})'.format(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. try: os.unlink(os.path.join(repo_root,'my.err'))
  68. except: pass
  69. from mmgen.common import *
  70. from mmgen.daemon import CoinDaemon
  71. from test.include.common import *
  72. from test.test_py_d.common import *
  73. g.quiet = False # if 'quiet' was set in config file, disable here
  74. os.environ['MMGEN_QUIET'] = '0' # for this script and spawned scripts
  75. opts_data = {
  76. 'sets': [('list_current_cmd_groups',True,'list_cmd_groups',True)],
  77. 'text': {
  78. 'desc': 'Test suite for the MMGen suite',
  79. 'usage':'[options] [command(s) or metacommand(s)]',
  80. 'options': """
  81. -h, --help Print this help message
  82. --, --longhelp Print help message for long options (common options)
  83. -A, --no-daemon-autostart Don't start and stop daemons automatically
  84. -B, --bech32 Generate and use Bech32 addresses
  85. -b, --buf-keypress Use buffered keypresses as with real human input
  86. (often required on slow systems, or under emulation)
  87. -c, --print-cmdline Print the command line of each spawned command
  88. -C, --coverage Produce code coverage info using trace module
  89. -x, --debug-pexpect Produce debugging output for pexpect calls
  90. -D, --no-daemon-stop Don't stop auto-started daemons after running tests
  91. -E, --direct-exec Bypass pexpect and execute a command directly (for
  92. debugging only)
  93. -e, --exact-output Show the exact output of the MMGen script(s) being run
  94. -G, --exclude-groups=G Exclude the specified command groups (comma-separated)
  95. -l, --list-cmds List and describe the commands in the test suite
  96. -L, --list-cmd-groups Output a list of command groups with descriptions
  97. -g, --list-current-cmd-groups List command groups for current configuration
  98. -n, --names Display command names instead of descriptions
  99. -o, --log Log commands to file {lf}
  100. -O, --pexpect-spawn Use pexpect.spawn instead of popen_spawn (much slower,
  101. kut does real terminal emulation)
  102. -p, --pause Pause between tests, resuming on keypress
  103. -P, --profile Record the execution time of each script
  104. -q, --quiet Produce minimal output. Suppress dependency info
  105. -r, --resume=c Resume at command 'c' after interrupted run
  106. -R, --resume-after=c Same, but resume at command following 'c'
  107. -s, --system Test scripts and modules installed on system rather
  108. than those in the repo root
  109. -S, --skip-deps Skip dependency checking for command
  110. -u, --usr-random Get random data interactively from user
  111. -t, --traceback Run the command inside the '{tbc}' script
  112. -T, --pexpect-timeout=T Set the timeout for pexpect
  113. -v, --verbose Produce more verbose output
  114. -W, --no-dw-delete Don't remove default wallet from data dir after dw tests are done
  115. -X, --exit-after=C Exit after command 'C'
  116. -y, --segwit Generate and use Segwit addresses
  117. -Y, --segwit-random Generate and use a random mix of Segwit and Legacy addrs
  118. """,
  119. 'notes': """
  120. If no command is given, the whole test suite is run.
  121. """
  122. },
  123. 'code': {
  124. 'options': lambda s: s.format(
  125. tbc='scripts/traceback_run.py',
  126. lf=log_file),
  127. }
  128. }
  129. data_dir = get_data_dir() # include/common.py
  130. # we need some opt values before running opts.init, so parse without initializing:
  131. _uopts = opts.init(opts_data,parse_only=True).user_opts
  132. # step 1: delete data_dir symlink in ./test;
  133. if not ('resume' in _uopts or 'skip_deps' in _uopts):
  134. try: os.unlink(data_dir)
  135. except: pass
  136. def add_cmdline_opts():
  137. """
  138. These are set automatically now when g.test_suite == True:
  139. --data-dir in opts.init()
  140. --daemon-data-dir and --rpc-port by CoinDaemon()
  141. """
  142. def get_coin():
  143. return (_uopts.get('coin') or 'btc').lower()
  144. network_id = get_coin().lower() + ('_tn' if _uopts.get('testnet') else '')
  145. sys.argv.insert(1,'--data-dir=' + data_dir)
  146. sys.argv.insert(1,'--daemon-data-dir=test/daemons/' + get_coin())
  147. sys.argv.insert(1,'--rpc-port={}'.format(CoinDaemon(network_id,test_suite=True).rpc_port))
  148. # add_cmdline_opts()
  149. opts.UserOpts._reset_ok += ('skip_deps',)
  150. # step 2: opts.init will create new data_dir in ./test (if not 'resume' or 'skip_deps'):
  151. usr_args = opts.init(opts_data)
  152. network_id = g.coin.lower() + ('_tn' if opt.testnet else '')
  153. from mmgen.protocol import init_proto_from_opts
  154. proto = init_proto_from_opts()
  155. # step 3: move data_dir to /dev/shm and symlink it back to ./test:
  156. trash_dir = os.path.join('test','trash')
  157. if not (opt.resume or opt.skip_deps):
  158. shm_dir = create_shm_dir(data_dir,trash_dir)
  159. check_segwit_opts()
  160. if opt.profile:
  161. opt.names = True
  162. if opt.exact_output:
  163. def msg(s): pass
  164. qmsg = qmsg_r = vmsg = vmsg_r = msg_r = msg
  165. if opt.resume or opt.resume_after:
  166. opt.skip_deps = True
  167. resume = opt.resume or opt.resume_after
  168. else:
  169. resume = False
  170. cfgs = { # addr_idx_lists (except 31,32,33,34) must contain exactly 8 addresses
  171. '1': { 'wpasswd': 'Dorian-α',
  172. 'kapasswd': 'Grok the blockchain',
  173. 'addr_idx_list': '12,99,5-10,5,12',
  174. 'dep_generators': {
  175. pwfile: 'walletgen',
  176. 'mmdat': 'walletgen',
  177. 'addrs': 'addrgen',
  178. 'rawtx': 'txcreate',
  179. 'txbump': 'txbump',
  180. 'sigtx': 'txsign',
  181. 'mmwords': 'export_mnemonic',
  182. 'mmseed': 'export_seed',
  183. 'mmhex': 'export_hex',
  184. 'mmincog': 'export_incog',
  185. 'mmincox': 'export_incog_hex',
  186. hincog_fn: 'export_incog_hidden',
  187. incog_id_fn: 'export_incog_hidden',
  188. 'akeys.mmenc': 'keyaddrgen'
  189. },
  190. },
  191. '2': { 'wpasswd': 'Hodling away',
  192. 'addr_idx_list': '37,45,3-6,22-23',
  193. 'seed_len': 128,
  194. 'dep_generators': {
  195. 'mmdat': 'walletgen2',
  196. 'addrs': 'addrgen2',
  197. 'rawtx': 'txcreate2',
  198. 'sigtx': 'txsign2',
  199. 'mmwords': 'export_mnemonic2',
  200. },
  201. },
  202. '3': { 'wpasswd': 'Major miner',
  203. 'addr_idx_list': '73,54,1022-1023,2-5',
  204. 'dep_generators': {
  205. 'mmdat': 'walletgen3',
  206. 'addrs': 'addrgen3',
  207. 'rawtx': 'txcreate3',
  208. 'sigtx': 'txsign3'
  209. },
  210. },
  211. '4': { 'wpasswd': 'Hashrate good',
  212. 'addr_idx_list': '63,1004,542-544,7-9',
  213. 'seed_len': 192,
  214. 'dep_generators': {
  215. 'mmdat': 'walletgen4',
  216. 'mmbrain': 'walletgen4',
  217. 'addrs': 'addrgen4',
  218. 'rawtx': 'txcreate4',
  219. 'sigtx': 'txsign4',
  220. 'txdo': 'txdo4',
  221. },
  222. 'bw_filename': 'brainwallet.mmbrain',
  223. 'bw_params': '192,1',
  224. },
  225. '5': { 'wpasswd': 'My changed password-α',
  226. 'hash_preset': '2',
  227. 'dep_generators': {
  228. 'mmdat': 'passchg',
  229. pwfile: 'passchg',
  230. },
  231. },
  232. '6': { 'seed_len': 128,
  233. 'seed_id': 'FE3C6545',
  234. 'ref_bw_seed_id': '33F10310',
  235. 'wpasswd': 'reference password',
  236. 'kapasswd': '',
  237. 'dep_generators': {
  238. 'mmdat': 'ref_walletgen_brain_1',
  239. pwfile: 'ref_walletgen_brain_1',
  240. 'addrs': 'refaddrgen_1',
  241. 'akeys.mmenc': 'refkeyaddrgen_1'
  242. },
  243. },
  244. '7': { 'seed_len': 192,
  245. 'seed_id': '1378FC64',
  246. 'ref_bw_seed_id': 'CE918388',
  247. 'wpasswd': 'reference password',
  248. 'kapasswd': '',
  249. 'dep_generators': {
  250. 'mmdat': 'ref_walletgen_brain_2',
  251. pwfile: 'ref_walletgen_brain_2',
  252. 'addrs': 'refaddrgen_2',
  253. 'akeys.mmenc': 'refkeyaddrgen_2'
  254. },
  255. },
  256. '8': { 'seed_len': 256,
  257. 'seed_id': '98831F3A',
  258. 'ref_bw_seed_id': 'B48CD7FC',
  259. 'wpasswd': 'reference password',
  260. 'kapasswd': '',
  261. 'dep_generators': {
  262. 'mmdat': 'ref_walletgen_brain_3',
  263. pwfile: 'ref_walletgen_brain_3',
  264. 'addrs': 'refaddrgen_3',
  265. 'akeys.mmenc': 'refkeyaddrgen_3'
  266. },
  267. },
  268. '9': { 'tool_enc_infn': 'tool_encrypt.in',
  269. 'dep_generators': {
  270. 'tool_encrypt.in': 'tool_encrypt',
  271. 'tool_encrypt.in.mmenc': 'tool_encrypt',
  272. },
  273. },
  274. '14': { 'kapasswd': 'Maxwell',
  275. 'wpasswd': 'The Halving',
  276. 'addr_idx_list': '61,998,502-504,7-9',
  277. 'seed_len': 256,
  278. 'dep_generators': {
  279. 'mmdat': 'walletgen14',
  280. 'addrs': 'addrgen14',
  281. 'akeys.mmenc': 'keyaddrgen14',
  282. },
  283. },
  284. '15': { 'wpasswd': 'Dorian-α',
  285. 'kapasswd': 'Grok the blockchain',
  286. 'addr_idx_list': '12,99,5-10,5,12',
  287. 'dep_generators': {
  288. pwfile: 'walletgen_dfl_wallet',
  289. 'addrs': 'addrgen_dfl_wallet',
  290. 'rawtx': 'txcreate_dfl_wallet',
  291. 'sigtx': 'txsign_dfl_wallet',
  292. 'mmseed': 'export_seed_dfl_wallet',
  293. 'del_dw_run': 'delete_dfl_wallet',
  294. },
  295. },
  296. '16': { 'wpasswd': 'My changed password',
  297. 'hash_preset': '2',
  298. 'dep_generators': {
  299. pwfile: 'passchg_dfl_wallet',
  300. },
  301. },
  302. '17': {},
  303. '18': {},
  304. '19': { 'wpasswd':'abc' }, # B2X
  305. '20': { 'wpasswd': 'Vsize it',
  306. 'addr_idx_list': '1-8',
  307. 'seed_len': 256,
  308. 'dep_generators': {
  309. 'mmdat': 'walletgen5',
  310. 'addrs': 'addrgen5',
  311. 'rawtx': 'txcreate5',
  312. 'sigtx': 'txsign5',
  313. },
  314. },
  315. '21': { 'wpasswd': 'Vsize it',
  316. 'addr_idx_list': '1-8',
  317. 'seed_len': 256,
  318. 'dep_generators': {
  319. 'mmdat': 'walletgen6',
  320. 'addrs': 'addrgen6',
  321. 'rawtx': 'txcreate6',
  322. 'sigtx': 'txsign6',
  323. },
  324. },
  325. '22': {},
  326. '23': {},
  327. # 26,27,28 are taken
  328. '31': {},
  329. '32': {},
  330. '33': {},
  331. '34': {},
  332. '40': {},
  333. '41': {},
  334. '99': {}, # dummy
  335. }
  336. def fixup_cfgs():
  337. for k in ('6','7','8'):
  338. cfgs['2'+k] = {}
  339. cfgs['2'+k].update(cfgs[k])
  340. for k in cfgs:
  341. cfgs[k]['tmpdir'] = os.path.join('test','tmp{}'.format(k))
  342. cfgs[k]['segwit'] = randbool() if opt.segwit_random else bool(opt.segwit or opt.bech32)
  343. from copy import deepcopy
  344. for a,b in (('6','11'),('7','12'),('8','13')):
  345. cfgs[b] = deepcopy(cfgs[a])
  346. cfgs[b]['tmpdir'] = os.path.join('test','tmp'+b)
  347. if g.debug_utf8:
  348. for k in cfgs: cfgs[k]['tmpdir'] += '-α'
  349. fixup_cfgs()
  350. utils = {
  351. # 'check_deps': 'check dependencies for specified command (WIP)', # TODO
  352. 'clean': 'clean specified tmp dir(s) (specify by integer, no arg = all dirs)',
  353. }
  354. def list_cmds():
  355. gm = CmdGroupMgr()
  356. cw,d = 0,[]
  357. Msg(green('AVAILABLE COMMANDS:'))
  358. for gname in gm.cmd_groups:
  359. ts = gm.gm_init_group(None,gname,None)
  360. d.append((gname,ts.__doc__.strip(),gm.cmd_list,gm.dpy_data))
  361. cw = max(max(len(k) for k in gm.dpy_data),cw)
  362. for gname,gdesc,clist,dpdata in d:
  363. Msg('\n'+green('{!r} - {}:'.format(gname,gdesc)))
  364. for cmd in clist:
  365. data = dpdata[cmd]
  366. Msg(' {:{w}} - {}'.format(cmd,data if type(data) == str else data[1],w=cw))
  367. w = max(map(len,utils))
  368. Msg('\n'+green('AVAILABLE UTILITIES:'))
  369. for cmd in sorted(utils):
  370. Msg(' {:{w}} - {}'.format(cmd,utils[cmd],w=w))
  371. sys.exit(0)
  372. def do_between():
  373. if opt.pause:
  374. confirm_continue()
  375. elif (opt.verbose or opt.exact_output) and not opt.skip_deps:
  376. sys.stderr.write('\n')
  377. def list_tmpdirs():
  378. return {k:cfgs[k]['tmpdir'] for k in cfgs}
  379. def clean(usr_dirs=None):
  380. if opt.skip_deps:
  381. return
  382. all_dirs = list_tmpdirs()
  383. dirnums = map(int,(usr_dirs if usr_dirs is not None else all_dirs))
  384. dirlist = list(map(str,sorted(dirnums)))
  385. for d in dirlist:
  386. if d in all_dirs:
  387. cleandir(all_dirs[d])
  388. else:
  389. die(1,'{}: invalid directory number'.format(d))
  390. if dirlist:
  391. iqmsg(green('Cleaned tmp director{} {}'.format(suf(dirlist,'ies'),' '.join(dirlist))))
  392. cleandir(data_dir)
  393. cleandir(trash_dir)
  394. iqmsg(green("Cleaned directories '{}'".format("' '".join([data_dir,trash_dir]))))
  395. def create_tmp_dirs(shm_dir):
  396. if g.platform == 'win':
  397. for cfg in sorted(cfgs):
  398. mk_tmpdir(cfgs[cfg]['tmpdir'])
  399. else:
  400. for cfg in sorted(cfgs):
  401. src = os.path.join(shm_dir,cfgs[cfg]['tmpdir'].split('/')[-1])
  402. mk_tmpdir(src)
  403. try:
  404. os.unlink(cfgs[cfg]['tmpdir'])
  405. except OSError as e:
  406. if e.errno != 2: raise
  407. finally:
  408. os.symlink(src,cfgs[cfg]['tmpdir'])
  409. def set_environ_for_spawned_scripts():
  410. from mmgen.term import get_terminal_size
  411. os.environ['MMGEN_TERMINAL_WIDTH'] = str(get_terminal_size().width)
  412. if os.getenv('MMGEN_DEBUG_ALL'):
  413. for name in g.env_opts:
  414. if name[:11] == 'MMGEN_DEBUG':
  415. os.environ[name] = '1'
  416. if not opt.pexpect_spawn:
  417. os.environ['MMGEN_TEST_SUITE_POPEN_SPAWN'] = '1'
  418. if not opt.system:
  419. os.environ['PYTHONPATH'] = repo_root
  420. if not opt.buf_keypress:
  421. os.environ['MMGEN_DISABLE_HOLD_PROTECT'] = '1'
  422. # If test.py itself is running under traceback, the spawned script shouldn't be, so disable this:
  423. if os.getenv('MMGEN_TRACEBACK') and not opt.traceback:
  424. os.environ['MMGEN_TRACEBACK'] = ''
  425. os.environ['MMGEN_NO_LICENSE'] = '1'
  426. os.environ['MMGEN_MIN_URANDCHARS'] = '3'
  427. os.environ['MMGEN_BOGUS_SEND'] = '1'
  428. os.environ['MMGEN_TEST_SUITE_PEXPECT'] = '1'
  429. def set_restore_term_at_exit():
  430. import termios,atexit
  431. fd = sys.stdin.fileno()
  432. old = termios.tcgetattr(fd)
  433. def at_exit():
  434. termios.tcsetattr(fd, termios.TCSADRAIN, old)
  435. atexit.register(at_exit)
  436. class CmdGroupMgr(object):
  437. cmd_groups_dfl = {
  438. 'misc': ('TestSuiteMisc',{}),
  439. 'opts': ('TestSuiteOpts',{'full_data':True}),
  440. 'cfg': ('TestSuiteCfg',{'full_data':True}),
  441. 'helpscreens': ('TestSuiteHelp',{'modname':'misc','full_data':True}),
  442. 'main': ('TestSuiteMain',{'full_data':True}),
  443. 'conv': ('TestSuiteWalletConv',{'is3seed':True,'modname':'wallet'}),
  444. 'ref': ('TestSuiteRef',{}),
  445. 'ref3': ('TestSuiteRef3Seed',{'is3seed':True,'modname':'ref_3seed'}),
  446. 'ref3_addr': ('TestSuiteRef3Addr',{'is3seed':True,'modname':'ref_3seed'}),
  447. 'ref_altcoin': ('TestSuiteRefAltcoin',{}),
  448. 'seedsplit': ('TestSuiteSeedSplit',{}),
  449. 'tool': ('TestSuiteTool',{'full_data':True}),
  450. 'input': ('TestSuiteInput',{'full_data':True}),
  451. 'output': ('TestSuiteOutput',{'modname':'misc','full_data':True}),
  452. 'autosign': ('TestSuiteAutosign',{}),
  453. 'regtest': ('TestSuiteRegtest',{}),
  454. # 'chainsplit': ('TestSuiteChainsplit',{}),
  455. 'ethdev': ('TestSuiteEthdev',{}),
  456. }
  457. cmd_groups_extra = {
  458. 'autosign_btc': ('TestSuiteAutosignBTC',{'modname':'autosign'}),
  459. 'autosign_live': ('TestSuiteAutosignLive',{'modname':'autosign'}),
  460. 'autosign_live_simulate': ('TestSuiteAutosignLiveSimulate',{'modname':'autosign'}),
  461. 'create_ref_tx': ('TestSuiteRefTX',{'modname':'misc','full_data':True}),
  462. }
  463. cmd_groups = cmd_groups_dfl.copy()
  464. cmd_groups.update(cmd_groups_extra)
  465. def load_mod(self,gname,modname=None):
  466. clsname,kwargs = self.cmd_groups[gname]
  467. if modname == None and 'modname' in kwargs:
  468. modname = kwargs['modname']
  469. import importlib
  470. modpath = 'test.test_py_d.ts_{}'.format(modname or gname)
  471. return getattr(importlib.import_module(modpath),clsname)
  472. def create_group(self,gname,full_data=False,modname=None,is3seed=False,add_dpy=False):
  473. """
  474. Initializes the list 'cmd_list' and dict 'dpy_data' from module's cmd_group data.
  475. Alternatively, if called with 'add_dpy=True', updates 'dpy_data' from module data
  476. without touching 'cmd_list'
  477. """
  478. cls = self.load_mod(gname,modname)
  479. cdata = []
  480. def get_shared_deps(cmdname,tmpdir_idx):
  481. """
  482. shared_deps are "implied" dependencies for all cmds in cmd_group that don't appear in
  483. the cmd_group data or cmds' argument lists. Supported only for 3seed tests at present.
  484. """
  485. if not hasattr(cls,'shared_deps'):
  486. return []
  487. return [k for k,v in cfgs[str(tmpdir_idx)]['dep_generators'].items()
  488. if k in cls.shared_deps and v != cmdname]
  489. for a,b in cls.cmd_group:
  490. if is3seed:
  491. for n,(i,j) in enumerate(zip(cls.tmpdir_nums,(128,192,256))):
  492. k = '{}_{}'.format(a,n+1)
  493. if hasattr(cls,'skip_cmds') and k in cls.skip_cmds:
  494. continue
  495. sdeps = get_shared_deps(k,i)
  496. if type(b) == str:
  497. cdata.append( (k, (i,'{} ({}-bit)'.format(b,j),[[[]+sdeps,i]])) )
  498. else:
  499. cdata.append( (k, (i,'{} ({}-bit)'.format(b[1],j),[[b[0]+sdeps,i]])) )
  500. else:
  501. cdata.append( (a, b if full_data else (cls.tmpdir_nums[0],b,[[[],cls.tmpdir_nums[0]]])) )
  502. if add_dpy:
  503. self.dpy_data.update(dict(cdata))
  504. else:
  505. self.cmd_list = tuple(e[0] for e in cdata)
  506. self.dpy_data = dict(cdata)
  507. return cls
  508. def gm_init_group(self,trunner,gname,spawn_prog):
  509. kwargs = self.cmd_groups[gname][1]
  510. cls = self.create_group(gname,**kwargs)
  511. cls.group_name = gname
  512. return cls(trunner,cfgs,spawn_prog)
  513. def list_cmd_groups(self):
  514. ginfo = []
  515. for gname in self.cmd_groups:
  516. clsname,kwargs = self.cmd_groups[gname]
  517. cls = self.load_mod(gname,kwargs['modname'] if 'modname' in kwargs else None)
  518. ginfo.append((gname,cls))
  519. if opt.list_current_cmd_groups:
  520. exclude = (opt.exclude_groups or '').split(',')
  521. ginfo = [g for g in ginfo
  522. if network_id in g[1].networks
  523. and not g[0] in exclude
  524. and g[0] in tuple(self.cmd_groups_dfl) + tuple(usr_args) ]
  525. for name,cls in ginfo:
  526. msg('{:17} - {}'.format(name,cls.__doc__))
  527. Die(0,'\n'+' '.join(e[0] for e in ginfo))
  528. def find_cmd_in_groups(self,cmd,group=None):
  529. """
  530. Search for a test command in specified group or all configured command groups
  531. and return it as a string. Loads modules but alters no global variables.
  532. """
  533. if group:
  534. if not group in [e[0] for e in self.cmd_groups]:
  535. die(1,'{!r}: unrecognized group'.format(group))
  536. groups = [self.cmd_groups[group]]
  537. else:
  538. groups = self.cmd_groups
  539. for gname in groups:
  540. clsname,kwargs = self.cmd_groups[gname]
  541. cls = self.load_mod(gname,kwargs['modname'] if 'modname' in kwargs else None)
  542. if cmd in cls.cmd_group: # first search the class
  543. return gname
  544. if cmd in dir(cls(None,None,None)): # then a throwaway instance
  545. return gname # cmd might exist in more than one group - we'll go with the first
  546. return None
  547. class TestSuiteRunner(object):
  548. 'test suite runner'
  549. def __init__(self,data_dir,trash_dir):
  550. self.data_dir = data_dir
  551. self.trash_dir = trash_dir
  552. self.cmd_total = 0
  553. self.rebuild_list = {}
  554. self.gm = CmdGroupMgr()
  555. self.repo_root = repo_root
  556. self.skipped_warnings = []
  557. if opt.log:
  558. self.log_fd = open(log_file,'a')
  559. self.log_fd.write('\nLog started: {} UTC\n'.format(make_timestr()))
  560. omsg('INFO → Logging to file {!r}'.format(log_file))
  561. else:
  562. self.log_fd = None
  563. if opt.coverage:
  564. self.coverdir,self.accfile = init_coverage()
  565. omsg('INFO → Writing coverage files to {!r}'.format(self.coverdir))
  566. def spawn_wrapper( self, cmd,
  567. args = [],
  568. extra_desc = '',
  569. no_output = False,
  570. msg_only = False,
  571. no_msg = False,
  572. cmd_dir = 'cmds' ):
  573. desc = self.ts.test_name if opt.names else self.gm.dpy_data[self.ts.test_name][1]
  574. if extra_desc: desc += ' ' + extra_desc
  575. if not opt.system:
  576. cmd = os.path.relpath(os.path.join(repo_root,cmd_dir,cmd))
  577. elif g.platform == 'win':
  578. cmd = os.path.join('/mingw64','opt','bin',cmd)
  579. passthru_opts = ['--{}{}'.format(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 getattr(opt,k)]
  582. args = [cmd] + passthru_opts + self.ts.extra_spawn_args + args
  583. if opt.traceback:
  584. args = ['scripts/traceback_run.py'] + args
  585. if g.platform == 'win':
  586. args = ['python3'] + args
  587. for i in args:
  588. if type(i) != str:
  589. m = 'Error: missing input files in cmd line?:\nName: {}\nCmdline: {!r}'
  590. die(2,m.format(self.ts.test_name,args))
  591. if opt.coverage:
  592. args = ['python3','-m','trace','--count','--coverdir='+self.coverdir,'--file='+self.accfile] + args
  593. qargs = ['{q}{}{q}'.format(a,q=('',"'")[' ' in a]) for a in args]
  594. cmd_disp = ' '.join(qargs).replace('\\','/') # for mingw
  595. if not no_msg:
  596. if opt.verbose or opt.print_cmdline or opt.exact_output:
  597. clr1,clr2 = ((green,cyan),(nocolor,nocolor))[bool(opt.print_cmdline)]
  598. omsg(green('Testing: {}'.format(desc)))
  599. if not msg_only:
  600. s = repr(cmd_disp) if g.platform == 'win' else cmd_disp
  601. omsg(clr1('Executing: ') + clr2(s))
  602. else:
  603. omsg_r('Testing {}: '.format(desc))
  604. if msg_only:
  605. return
  606. if opt.log:
  607. self.log_fd.write('[{}][{}:{}] {}\n'.format(
  608. proto.coin.lower(),
  609. self.ts.group_name,
  610. self.ts.test_name,
  611. cmd_disp))
  612. os.environ['MMGEN_FORCE_COLOR'] = ('1' if self.ts.color and g.platform == 'linux' else '')
  613. from test.include.pexpect import MMGenPexpect
  614. return MMGenPexpect(args,no_output=no_output)
  615. def end_msg(self):
  616. t = int(time.time()) - self.start_time
  617. m = '{} test{} performed. Elapsed time: {:02d}:{:02d}\n'
  618. sys.stderr.write(green(m.format(self.cmd_total,suf(self.cmd_total),t//60,t%60)))
  619. def init_group(self,gname,cmd=None,quiet=False):
  620. ts_cls = CmdGroupMgr().load_mod(gname)
  621. for k in ('segwit','segwit_random','bech32'):
  622. if getattr(opt,k):
  623. segwit_opt = k
  624. break
  625. else:
  626. segwit_opt = None
  627. def gen_msg():
  628. yield ('{g}:{c}' if cmd else 'test group {g!r}').format(g=gname,c=cmd)
  629. if len(ts_cls.networks) != 1:
  630. yield ' for {} {}'.format(proto.coin,proto.network)
  631. if segwit_opt:
  632. yield ' (--{})'.format(segwit_opt.replace('_','-'))
  633. m = ''.join(gen_msg())
  634. if segwit_opt and not ts_cls.segwit_opts_ok:
  635. iqmsg('INFO → skipping ' + m)
  636. return False
  637. # 'networks = ()' means all networks allowed
  638. nws = [(e.split('_')[0],'testnet') if '_' in e else (e,'mainnet') for e in ts_cls.networks]
  639. if nws:
  640. coin = proto.coin.lower()
  641. nw = ('mainnet','testnet')[proto.testnet]
  642. for a,b in nws:
  643. if a == coin and b == nw:
  644. break
  645. else:
  646. iqmsg('INFO → skipping ' + m)
  647. return False
  648. if not quiet:
  649. bmsg('Executing ' + m)
  650. os.environ['MMGEN_BOGUS_WALLET_DATA'] = '' # zero this here, so test group doesn't have to
  651. self.ts = self.gm.gm_init_group(self,gname,self.spawn_wrapper)
  652. if opt.resume_after:
  653. global resume
  654. resume = self.gm.cmd_list[self.gm.cmd_list.index(resume)+1]
  655. omsg(f'INFO → Resuming at command {resume!r}')
  656. if opt.exit_after and opt.exit_after not in self.gm.cmd_list:
  657. die(1,'{!r}: command not recognized'.format(opt.exit_after))
  658. return True
  659. def run_tests(self,usr_args):
  660. self.start_time = int(time.time())
  661. gname_save = None
  662. if usr_args:
  663. for arg in usr_args:
  664. if arg in self.gm.cmd_groups:
  665. if not self.init_group(arg):
  666. continue
  667. clean(self.ts.tmpdir_nums)
  668. for cmd in self.gm.cmd_list:
  669. self.check_needs_rerun(cmd,build=True)
  670. do_between()
  671. elif arg in utils:
  672. params = usr_args[usr_args.index(arg)+1:]
  673. globals()[arg](*params)
  674. sys.exit(0)
  675. else:
  676. if ':' in arg:
  677. gname,arg = arg.split(':')
  678. direct_call_ok = True # allow calling of functions not in cmd_group
  679. else:
  680. gname = self.gm.find_cmd_in_groups(arg)
  681. direct_call_ok = False
  682. if gname:
  683. same_grp = gname == gname_save # same group as previous cmd: don't clean, suppress blue msg
  684. if not self.init_group(gname,arg,quiet=same_grp):
  685. continue
  686. if not same_grp:
  687. clean(self.ts.tmpdir_nums)
  688. try:
  689. self.check_needs_rerun(arg,build=True)
  690. except:
  691. if direct_call_ok:
  692. ret = getattr(self.ts,arg)()
  693. if type(ret).__name__ == 'coroutine':
  694. run_session(ret)
  695. else:
  696. raise
  697. do_between()
  698. gname_save = gname
  699. else:
  700. die(1,'{!r}: command not recognized'.format(arg))
  701. else:
  702. if opt.exclude_groups:
  703. exclude = opt.exclude_groups.split(',')
  704. for e in exclude:
  705. if e not in self.gm.cmd_groups_dfl:
  706. die(1,'{!r}: group not recognized'.format(e))
  707. for gname in self.gm.cmd_groups_dfl:
  708. if opt.exclude_groups and gname in exclude:
  709. continue
  710. if not self.init_group(gname):
  711. continue
  712. clean(self.ts.tmpdir_nums)
  713. for cmd in self.gm.cmd_list:
  714. self.check_needs_rerun(cmd,build=True)
  715. do_between()
  716. self.end_msg()
  717. def check_needs_rerun(self,
  718. cmd,
  719. build=False,
  720. root=True,
  721. force_delete=False,
  722. dpy=False
  723. ):
  724. rerun = root # force_delete is not passed to recursive call
  725. fns = []
  726. if force_delete or not root:
  727. # does cmd produce a needed dependency(ies)?
  728. ret = self.get_num_exts_for_cmd(cmd,dpy)
  729. if ret:
  730. for ext in ret[1]:
  731. fn = get_file_with_ext(cfgs[ret[0]]['tmpdir'],ext,delete=build)
  732. if fn:
  733. if force_delete: os.unlink(fn)
  734. else: fns.append(fn)
  735. else: rerun = True
  736. fdeps = self.generate_file_deps(cmd)
  737. cdeps = self.generate_cmd_deps(fdeps)
  738. for fn in fns:
  739. my_age = os.stat(fn).st_mtime
  740. for num,ext in fdeps:
  741. f = get_file_with_ext(cfgs[num]['tmpdir'],ext,delete=build)
  742. if f and os.stat(f).st_mtime > my_age:
  743. rerun = True
  744. for cdep in cdeps:
  745. if self.check_needs_rerun(cdep,build=build,root=False,dpy=cmd):
  746. rerun = True
  747. if build:
  748. if rerun:
  749. for fn in fns:
  750. if not root: os.unlink(fn)
  751. if not (dpy and opt.skip_deps):
  752. self.run_test(cmd)
  753. if not root: do_between()
  754. else:
  755. # If prog produces multiple files:
  756. if cmd not in self.rebuild_list or rerun == True:
  757. self.rebuild_list[cmd] = (rerun,fns[0] if fns else '') # FIX
  758. return rerun
  759. def run_test(self,cmd):
  760. d = [(str(num),ext) for exts,num in self.gm.dpy_data[cmd][2] for ext in exts]
  761. # delete files depended on by this cmd
  762. arg_list = [get_file_with_ext(cfgs[num]['tmpdir'],ext) for num,ext in d]
  763. # remove shared_deps from arg list
  764. if hasattr(self.ts,'shared_deps'):
  765. arg_list = arg_list[:-len(self.ts.shared_deps)]
  766. global resume
  767. if resume:
  768. if cmd != resume:
  769. return
  770. bmsg('Resuming at {!r}'.format(cmd))
  771. resume = False
  772. opt.skip_deps = False
  773. if opt.profile: start = time.time()
  774. cdata = self.gm.dpy_data[cmd]
  775. self.ts.test_name = cmd
  776. # self.ts.test_dpydata = cdata
  777. self.ts.tmpdir_num = cdata[0]
  778. # self.ts.cfg = cfgs[str(cdata[0])] # will remove this eventually
  779. cfg = cfgs[str(cdata[0])]
  780. for k in ( 'seed_len', 'seed_id',
  781. 'wpasswd', 'kapasswd',
  782. 'segwit', 'hash_preset',
  783. 'bw_filename', 'bw_params', 'ref_bw_seed_id',
  784. 'addr_idx_list', 'pass_idx_list' ):
  785. if k in cfg:
  786. setattr(self.ts,k,cfg[k])
  787. ret = getattr(self.ts,cmd)(*arg_list) # run the test
  788. if type(ret).__name__ == 'coroutine':
  789. ret = run_session(ret)
  790. self.process_retval(cmd,ret)
  791. if opt.profile:
  792. omsg('\r\033[50C{:.4f}'.format(time.time() - start))
  793. if cmd == opt.exit_after:
  794. sys.exit(0)
  795. def warn_skipped(self):
  796. if self.skipped_warnings:
  797. print(yellow('The following tests were skipped and may require attention:'))
  798. r = '-' * 72 + '\n'
  799. print(r+('\n'+r).join(self.skipped_warnings))
  800. def process_retval(self,cmd,ret):
  801. if type(ret).__name__ == 'MMGenPexpect':
  802. ret.ok()
  803. self.cmd_total += 1
  804. elif ret == 'ok':
  805. ok()
  806. self.cmd_total += 1
  807. elif ret == 'skip':
  808. pass
  809. elif type(ret) == tuple and ret[0] == 'skip_warn':
  810. self.skipped_warnings.append(
  811. 'Test {!r} was skipped:\n {}'.format(cmd,'\n '.join(ret[1].split('\n'))))
  812. else:
  813. rdie(1,'{!r} returned {}'.format(cmd,ret))
  814. def check_deps(self,cmds): # TODO: broken
  815. if len(cmds) != 1:
  816. die(1,'Usage: {} check_deps <command>'.format(g.prog_name))
  817. cmd = cmds[0]
  818. if cmd not in self.gm.cmd_list:
  819. die(1,'{!r}: unrecognized command'.format(cmd))
  820. if not opt.quiet:
  821. omsg('Checking dependencies for {!r}'.format(cmd))
  822. self.check_needs_rerun(self.ts,cmd,build=False)
  823. w = max(map(len,self.rebuild_list)) + 1
  824. for cmd in self.rebuild_list:
  825. c = self.rebuild_list[cmd]
  826. m = 'Rebuild' if (c[0] and c[1]) else 'Build' if c[0] else 'OK'
  827. omsg('cmd {:<{w}} {}'.format(cmd+':', m, w=w))
  828. def generate_file_deps(self,cmd):
  829. return [(str(n),e) for exts,n in self.gm.dpy_data[cmd][2] for e in exts]
  830. def generate_cmd_deps(self,fdeps):
  831. return [cfgs[str(n)]['dep_generators'][ext] for n,ext in fdeps]
  832. def get_num_exts_for_cmd(self,cmd,dpy=False): # dpy ignored here
  833. try:
  834. num = str(self.gm.dpy_data[cmd][0])
  835. except KeyError:
  836. qmsg_r('Missing dependency {!r}'.format(cmd))
  837. gname = self.gm.find_cmd_in_groups(cmd)
  838. if gname:
  839. kwargs = self.gm.cmd_groups[gname][1]
  840. kwargs.update({'add_dpy':True})
  841. self.gm.create_group(gname,**kwargs)
  842. num = str(self.gm.dpy_data[cmd][0])
  843. qmsg(' found in group {!r}'.format(gname))
  844. else:
  845. qmsg(' not found in any command group!')
  846. raise
  847. dgl = cfgs[num]['dep_generators']
  848. if cmd in dgl.values():
  849. exts = [k for k in dgl if dgl[k] == cmd]
  850. return (num,exts)
  851. else:
  852. return None
  853. # main()
  854. if not opt.skip_deps: # do this before list cmds exit, so we stay in sync with shm_dir
  855. create_tmp_dirs(shm_dir)
  856. if opt.list_cmd_groups:
  857. CmdGroupMgr().list_cmd_groups()
  858. elif opt.list_cmds:
  859. list_cmds()
  860. if opt.pause:
  861. set_restore_term_at_exit()
  862. set_environ_for_spawned_scripts()
  863. if network_id not in ('eth','etc'):
  864. start_test_daemons(network_id,remove_datadir=True)
  865. try:
  866. tr = TestSuiteRunner(data_dir,trash_dir)
  867. tr.run_tests(usr_args)
  868. tr.warn_skipped()
  869. if network_id not in ('eth','etc'):
  870. stop_test_daemons(network_id)
  871. except KeyboardInterrupt:
  872. if network_id not in ('eth','etc'):
  873. stop_test_daemons(network_id)
  874. tr.warn_skipped()
  875. die(1,'\ntest.py exiting at user request')
  876. except TestSuiteException as e:
  877. ydie(1,e.args[0])
  878. except TestSuiteFatalException as e:
  879. rdie(1,e.args[0])
  880. except Exception:
  881. if opt.traceback:
  882. msg(blue('Spawned script exited with error'))
  883. else:
  884. import traceback
  885. print(''.join(traceback.format_exception(*sys.exc_info())))
  886. msg(blue('Test script exited with error'))
  887. raise
  888. except:
  889. raise