test.py 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2022 The MMGen Project <mmgen@tuta.io>
  5. #
  6. # This program is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. """
  19. test/test.py: Test suite for the MMGen wallet system
  20. """
  21. def check_segwit_opts():
  22. for k,m in (('segwit','S'),('segwit_random','S'),('bech32','B')):
  23. if getattr(opt,k) and m not in proto.mmtypes:
  24. die(1,f'--{k.replace("_","-")} option incompatible with {proto.cls_name}')
  25. def create_shm_dir(data_dir,trash_dir):
  26. # Laggy flash media can cause pexpect to fail, so create a temporary directory
  27. # under '/dev/shm' and put datadir and tmpdirs here.
  28. import shutil
  29. from subprocess import run
  30. if g.platform == 'win':
  31. for tdir in (data_dir,trash_dir):
  32. try: os.listdir(tdir)
  33. except: pass
  34. else:
  35. try: shutil.rmtree(tdir)
  36. except: # we couldn't remove data dir - perhaps regtest daemon is running
  37. try:
  38. run(['python3',os.path.join('cmds','mmgen-regtest'),'stop'],check=True)
  39. except:
  40. die(4,f'Unable to remove {tdir!r}!')
  41. else:
  42. time.sleep(2)
  43. shutil.rmtree(tdir)
  44. os.mkdir(tdir,0o755)
  45. shm_dir = 'test'
  46. else:
  47. tdir,pfx = '/dev/shm','mmgen-test-'
  48. try:
  49. run(f'rm -rf {tdir}/{pfx}*',shell=True,check=True)
  50. except Exception as e:
  51. die(2,f'Unable to delete directory tree {tdir}/{pfx}* ({e.args[0]})')
  52. try:
  53. import tempfile
  54. shm_dir = str(tempfile.mkdtemp('',pfx,tdir))
  55. except Exception as e:
  56. die(2,f'Unable to create temporary directory in {tdir} ({e.args[0]})')
  57. dest = os.path.join(shm_dir,os.path.basename(trash_dir))
  58. os.mkdir(dest,0o755)
  59. run(f'rm -rf {trash_dir}',shell=True,check=True)
  60. os.symlink(dest,trash_dir)
  61. dest = os.path.join(shm_dir,os.path.basename(data_dir))
  62. shutil.move(data_dir,dest) # data_dir was created by opts.init()
  63. os.symlink(dest,data_dir)
  64. return shm_dir
  65. import sys,os,time
  66. from include.tests_header import repo_root
  67. from test.overlay import get_overlay_dir,overlay_setup
  68. overlay_dir = get_overlay_dir(repo_root)
  69. sys.path.insert(0,overlay_dir)
  70. if not (len(sys.argv) == 2 and sys.argv[1] == 'clean'):
  71. 'hack: overlay must be set up before mmgen mods are imported'
  72. overlay_setup(repo_root)
  73. from mmgen.common import *
  74. try:
  75. os.unlink(os.path.join(repo_root,'test.py.err'))
  76. except:
  77. pass
  78. g.quiet = False # if 'quiet' was set in config file, disable here
  79. os.environ['MMGEN_QUIET'] = '0' # for this script and spawned scripts
  80. opts_data = {
  81. 'sets': [('list_current_cmd_groups',True,'list_cmd_groups',True)],
  82. 'text': {
  83. 'desc': 'Test suite for the MMGen suite',
  84. 'usage':'[options] [command(s) or metacommand(s)]',
  85. 'options': """
  86. -h, --help Print this help message
  87. --, --longhelp Print help message for long options (common options)
  88. -a, --no-altcoin Skip altcoin tests (WIP)
  89. -A, --no-daemon-autostart Don't start and stop daemons automatically
  90. -B, --bech32 Generate and use Bech32 addresses
  91. -b, --buf-keypress Use buffered keypresses as with real human input
  92. (often required on slow systems, or under emulation)
  93. -c, --print-cmdline Print the command line of each spawned command
  94. -C, --coverage Produce code coverage info using trace module
  95. -x, --debug-pexpect Produce debugging output for pexpect calls
  96. -D, --no-daemon-stop Don't stop auto-started daemons after running tests
  97. -E, --direct-exec Bypass pexpect and execute a command directly (for
  98. debugging only)
  99. -e, --exact-output Show the exact output of the MMGen script(s) being run
  100. -G, --exclude-groups=G Exclude the specified command groups (comma-separated)
  101. -l, --list-cmds List and describe the commands in the test suite
  102. -L, --list-cmd-groups Output a list of command groups with descriptions
  103. -g, --list-current-cmd-groups List command groups for current configuration
  104. -n, --names Display command names instead of descriptions
  105. -N, --no-timings Suppress display of timing information
  106. -o, --log Log commands to file {lf!r}
  107. -O, --pexpect-spawn Use pexpect.spawn instead of popen_spawn (much slower,
  108. kut does real terminal emulation)
  109. -p, --pause Pause between tests, resuming on keypress
  110. -P, --profile Record the execution time of each script
  111. -q, --quiet Produce minimal output. Suppress dependency info
  112. -r, --resume=c Resume at command 'c' after interrupted run
  113. -R, --resume-after=c Same, but resume at command following 'c'
  114. -t, --step After resuming, execute one command and stop
  115. -s, --system Test scripts and modules installed on system rather
  116. than those in the repo root
  117. -S, --skip-deps Skip dependency checking for command
  118. -u, --usr-random Get random data interactively from user
  119. -T, --pexpect-timeout=T Set the timeout for pexpect
  120. -v, --verbose Produce more verbose output
  121. -W, --no-dw-delete Don't remove default wallet from data dir after dw tests are done
  122. -X, --exit-after=C Exit after command 'C'
  123. -y, --segwit Generate and use Segwit addresses
  124. -Y, --segwit-random Generate and use a random mix of Segwit and Legacy addrs
  125. """,
  126. 'notes': """
  127. If no command is given, the whole test suite is run.
  128. """
  129. },
  130. 'code': {
  131. 'options': lambda proto,help_notes,s: s.format(
  132. lf = help_notes('test_py_log_file')
  133. )
  134. }
  135. }
  136. # we need some opt values before running opts.init, so parse without initializing:
  137. po = opts.init(opts_data,parse_only=True)
  138. from test.include.common import *
  139. from test.test_py_d.common import *
  140. data_dir = get_data_dir() # include/common.py
  141. # step 1: delete data_dir symlink in ./test;
  142. resuming = any(k in po.user_opts for k in ('resume','resume_after'))
  143. skipping_deps = resuming or 'skip_deps' in po.user_opts
  144. if not skipping_deps:
  145. try: os.unlink(data_dir)
  146. except: pass
  147. opts.UserOpts._reset_ok += ('no_daemon_autostart','names','no_timings','exit_after')
  148. # step 2: opts.init will create new data_dir in ./test (if not skipping_deps)
  149. usr_args = opts.init(opts_data)
  150. network_id = g.coin.lower() + ('_tn' if opt.testnet else '')
  151. from mmgen.protocol import init_proto_from_opts
  152. proto = init_proto_from_opts()
  153. # step 3: move data_dir to /dev/shm and symlink it back to ./test:
  154. trash_dir = os.path.join('test','trash')
  155. if not skipping_deps:
  156. shm_dir = create_shm_dir(data_dir,trash_dir)
  157. check_segwit_opts()
  158. testing_segwit = opt.segwit or opt.segwit_random or opt.bech32
  159. if g.test_suite_deterministic:
  160. opt.no_timings = True
  161. init_color(num_colors=0)
  162. os.environ['MMGEN_DISABLE_COLOR'] = '1'
  163. if opt.profile:
  164. opt.names = True
  165. if opt.exact_output:
  166. def msg(s): pass
  167. qmsg = qmsg_r = vmsg = vmsg_r = msg_r = msg
  168. if skipping_deps:
  169. opt.no_daemon_autostart = True
  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' },
  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. '29': {}, # xmrwallet
  329. '31': {},
  330. '32': {},
  331. '33': {},
  332. '34': {},
  333. '40': {},
  334. '41': {},
  335. '99': {}, # dummy
  336. }
  337. def fixup_cfgs():
  338. for k in ('6','7','8'):
  339. cfgs['2'+k] = {}
  340. cfgs['2'+k].update(cfgs[k])
  341. for k in cfgs:
  342. cfgs[k]['tmpdir'] = os.path.join('test',f'tmp{k}')
  343. cfgs[k]['segwit'] = randbool() if opt.segwit_random else bool(opt.segwit or opt.bech32)
  344. from copy import deepcopy
  345. for a,b in (('6','11'),('7','12'),('8','13')):
  346. cfgs[b] = deepcopy(cfgs[a])
  347. cfgs[b]['tmpdir'] = os.path.join('test','tmp'+b)
  348. if g.debug_utf8:
  349. for k in cfgs: cfgs[k]['tmpdir'] += '-α'
  350. fixup_cfgs()
  351. utils = {
  352. # 'check_deps': 'check dependencies for specified command (WIP)', # TODO
  353. 'clean': 'clean specified tmp dir(s) (specify by integer, no arg = all dirs)',
  354. }
  355. def list_cmds():
  356. gm = CmdGroupMgr()
  357. cw,d = 0,[]
  358. Msg(green('AVAILABLE COMMANDS:'))
  359. for gname in gm.cmd_groups:
  360. ts = gm.gm_init_group(None,gname,None)
  361. desc = ts.__doc__.strip() if ts.__doc__ else type(ts).__name__
  362. d.append( (gname,desc,gm.cmd_list,gm.dpy_data) )
  363. cw = max(max(len(k) for k in gm.dpy_data),cw)
  364. for gname,gdesc,clist,dpdata in d:
  365. Msg('\n'+green(f'{gname!r} - {gdesc}:'))
  366. for cmd in clist:
  367. data = dpdata[cmd]
  368. Msg(' {:{w}} - {}'.format(
  369. cmd,
  370. (data if type(data) == str else data[1]),
  371. w = cw ))
  372. w = max(map(len,utils))
  373. Msg('\n'+green('AVAILABLE UTILITIES:'))
  374. for cmd in sorted(utils):
  375. Msg(' {:{w}} - {}'.format( cmd, utils[cmd], w=w ))
  376. sys.exit(0)
  377. def do_between():
  378. if opt.pause:
  379. confirm_continue()
  380. elif (opt.verbose or opt.exact_output) and not skipping_deps:
  381. sys.stderr.write('\n')
  382. def list_tmpdirs():
  383. return {k:cfgs[k]['tmpdir'] for k in cfgs}
  384. def clean(usr_dirs=None,clean_overlay=True):
  385. if skipping_deps:
  386. return
  387. all_dirs = list_tmpdirs()
  388. dirnums = map(int,(usr_dirs if usr_dirs is not None else all_dirs))
  389. dirlist = list(map(str,sorted(dirnums)))
  390. for d in dirlist:
  391. if d in all_dirs:
  392. cleandir(all_dirs[d])
  393. else:
  394. die(1,f'{d}: invalid directory number')
  395. if dirlist:
  396. iqmsg(green('Cleaned tmp director{} {}'.format(
  397. suf(dirlist,'ies'),
  398. ' '.join(dirlist))
  399. ))
  400. cleandir(data_dir)
  401. cleandir(trash_dir)
  402. iqmsg(green(f'Cleaned directories {data_dir!r} {trash_dir!r}'))
  403. if clean_overlay:
  404. cleandir(overlay_dir)
  405. iqmsg(green(f'Cleaned directory {os.path.relpath(overlay_dir)!r}'))
  406. def create_tmp_dirs(shm_dir):
  407. if g.platform == 'win':
  408. for cfg in sorted(cfgs):
  409. mk_tmpdir(cfgs[cfg]['tmpdir'])
  410. else:
  411. for cfg in sorted(cfgs):
  412. src = os.path.join(shm_dir,cfgs[cfg]['tmpdir'].split('/')[-1])
  413. mk_tmpdir(src)
  414. try:
  415. os.unlink(cfgs[cfg]['tmpdir'])
  416. except OSError as e:
  417. if e.errno != 2:
  418. raise
  419. finally:
  420. os.symlink(src,cfgs[cfg]['tmpdir'])
  421. def set_environ_for_spawned_scripts():
  422. from mmgen.term import get_terminal_size
  423. os.environ['MMGEN_TERMINAL_WIDTH'] = str(get_terminal_size().width)
  424. if os.getenv('MMGEN_DEBUG_ALL'):
  425. for name in g.env_opts:
  426. if name[:11] == 'MMGEN_DEBUG':
  427. os.environ[name] = '1'
  428. if not opt.pexpect_spawn:
  429. os.environ['MMGEN_TEST_SUITE_POPEN_SPAWN'] = '1'
  430. if not opt.system:
  431. os.environ['PYTHONPATH'] = repo_root
  432. if not opt.buf_keypress:
  433. os.environ['MMGEN_DISABLE_HOLD_PROTECT'] = '1'
  434. os.environ['MMGEN_NO_LICENSE'] = '1'
  435. os.environ['MMGEN_MIN_URANDCHARS'] = '3'
  436. os.environ['MMGEN_BOGUS_SEND'] = '1'
  437. os.environ['MMGEN_TEST_SUITE_PEXPECT'] = '1'
  438. def set_restore_term_at_exit():
  439. import termios,atexit
  440. fd = sys.stdin.fileno()
  441. old = termios.tcgetattr(fd)
  442. def at_exit():
  443. termios.tcsetattr(fd, termios.TCSADRAIN, old)
  444. atexit.register(at_exit)
  445. class CmdGroupMgr(object):
  446. cmd_groups_dfl = {
  447. 'misc': ('TestSuiteMisc',{}),
  448. 'opts': ('TestSuiteOpts',{'full_data':True}),
  449. 'cfg': ('TestSuiteCfg',{'full_data':True}),
  450. 'helpscreens': ('TestSuiteHelp',{'modname':'misc','full_data':True}),
  451. 'main': ('TestSuiteMain',{'full_data':True}),
  452. 'conv': ('TestSuiteWalletConv',{'is3seed':True,'modname':'wallet'}),
  453. 'ref': ('TestSuiteRef',{}),
  454. 'ref3': ('TestSuiteRef3Seed',{'is3seed':True,'modname':'ref_3seed'}),
  455. 'ref3_addr': ('TestSuiteRef3Addr',{'is3seed':True,'modname':'ref_3seed'}),
  456. 'ref_altcoin': ('TestSuiteRefAltcoin',{}),
  457. 'seedsplit': ('TestSuiteSeedSplit',{}),
  458. 'tool': ('TestSuiteTool',{'full_data':True}),
  459. 'input': ('TestSuiteInput',{'full_data':True}),
  460. 'output': ('TestSuiteOutput',{'modname':'misc','full_data':True}),
  461. 'autosign': ('TestSuiteAutosign',{}),
  462. 'regtest': ('TestSuiteRegtest',{}),
  463. # 'chainsplit': ('TestSuiteChainsplit',{}),
  464. 'ethdev': ('TestSuiteEthdev',{}),
  465. 'xmrwallet': ('TestSuiteXMRWallet',{}),
  466. }
  467. cmd_groups_extra = {
  468. 'autosign_btc': ('TestSuiteAutosignBTC',{'modname':'autosign'}),
  469. 'autosign_live': ('TestSuiteAutosignLive',{'modname':'autosign'}),
  470. 'autosign_live_simulate': ('TestSuiteAutosignLiveSimulate',{'modname':'autosign'}),
  471. 'create_ref_tx': ('TestSuiteRefTX',{'modname':'misc','full_data':True}),
  472. }
  473. cmd_groups = cmd_groups_dfl.copy()
  474. cmd_groups.update(cmd_groups_extra)
  475. def load_mod(self,gname,modname=None):
  476. clsname,kwargs = self.cmd_groups[gname]
  477. if modname == None and 'modname' in kwargs:
  478. modname = kwargs['modname']
  479. import importlib
  480. modpath = f'test.test_py_d.ts_{modname or gname}'
  481. return getattr(importlib.import_module(modpath),clsname)
  482. def create_group(self,gname,full_data=False,modname=None,is3seed=False,add_dpy=False):
  483. """
  484. Initializes the list 'cmd_list' and dict 'dpy_data' from module's cmd_group data.
  485. Alternatively, if called with 'add_dpy=True', updates 'dpy_data' from module data
  486. without touching 'cmd_list'
  487. """
  488. cls = self.load_mod(gname,modname)
  489. cdata = []
  490. def get_shared_deps(cmdname,tmpdir_idx):
  491. """
  492. shared_deps are "implied" dependencies for all cmds in cmd_group that don't appear in
  493. the cmd_group data or cmds' argument lists. Supported only for 3seed tests at present.
  494. """
  495. if not hasattr(cls,'shared_deps'):
  496. return []
  497. return [k for k,v in cfgs[str(tmpdir_idx)]['dep_generators'].items()
  498. if k in cls.shared_deps and v != cmdname]
  499. for a,b in cls.cmd_group:
  500. if is3seed:
  501. for n,(i,j) in enumerate(zip(cls.tmpdir_nums,(128,192,256))):
  502. k = f'{a}_{n+1}'
  503. if hasattr(cls,'skip_cmds') and k in cls.skip_cmds:
  504. continue
  505. sdeps = get_shared_deps(k,i)
  506. if type(b) == str:
  507. cdata.append( (k, (i,f'{b} ({j}-bit)',[[[]+sdeps,i]])) )
  508. else:
  509. cdata.append( (k, (i,f'{b[1]} ({j}-bit)',[[b[0]+sdeps,i]])) )
  510. else:
  511. cdata.append( (a, b if full_data else (cls.tmpdir_nums[0],b,[[[],cls.tmpdir_nums[0]]])) )
  512. if add_dpy:
  513. self.dpy_data.update(dict(cdata))
  514. else:
  515. self.cmd_list = tuple(e[0] for e in cdata)
  516. self.dpy_data = dict(cdata)
  517. return cls
  518. def gm_init_group(self,trunner,gname,spawn_prog):
  519. kwargs = self.cmd_groups[gname][1]
  520. cls = self.create_group(gname,**kwargs)
  521. cls.group_name = gname
  522. return cls(trunner,cfgs,spawn_prog)
  523. def list_cmd_groups(self):
  524. ginfo = []
  525. for gname in self.cmd_groups:
  526. clsname,kwargs = self.cmd_groups[gname]
  527. cls = self.load_mod(gname,kwargs['modname'] if 'modname' in kwargs else None)
  528. ginfo.append((gname,cls))
  529. if opt.list_current_cmd_groups:
  530. exclude = (opt.exclude_groups or '').split(',')
  531. ginfo = [g for g in ginfo
  532. if network_id in g[1].networks
  533. and not g[0] in exclude
  534. and g[0] in tuple(self.cmd_groups_dfl) + tuple(usr_args) ]
  535. for name,cls in ginfo:
  536. msg('{:17} - {}'.format(
  537. name,
  538. cls.__doc__.strip() if cls.__doc__ else cls.__name__
  539. ))
  540. Msg( '\n' + ' '.join(e[0] for e in ginfo) )
  541. sys.exit(0)
  542. def find_cmd_in_groups(self,cmd,group=None):
  543. """
  544. Search for a test command in specified group or all configured command groups
  545. and return it as a string. Loads modules but alters no global variables.
  546. """
  547. if group:
  548. if not group in [e[0] for e in self.cmd_groups]:
  549. die(1,f'{group!r}: unrecognized group')
  550. groups = [self.cmd_groups[group]]
  551. else:
  552. groups = self.cmd_groups
  553. for gname in groups:
  554. clsname,kwargs = self.cmd_groups[gname]
  555. cls = self.load_mod(gname,kwargs['modname'] if 'modname' in kwargs else None)
  556. if cmd in cls.cmd_group: # first search the class
  557. return gname
  558. if cmd in dir(cls(None,None,None)): # then a throwaway instance
  559. return gname # cmd might exist in more than one group - we'll go with the first
  560. return None
  561. class TestSuiteRunner(object):
  562. 'test suite runner'
  563. def __del__(self):
  564. if opt.log:
  565. self.log_fd.close()
  566. def __init__(self,data_dir,trash_dir):
  567. self.data_dir = data_dir
  568. self.trash_dir = trash_dir
  569. self.cmd_total = 0
  570. self.rebuild_list = {}
  571. self.gm = CmdGroupMgr()
  572. self.repo_root = repo_root
  573. self.skipped_warnings = []
  574. self.resume_cmd = None
  575. if opt.log:
  576. self.log_fd = open(log_file,'a')
  577. self.log_fd.write(f'\nLog started: {make_timestr()} UTC\n')
  578. omsg(f'INFO → Logging to file {log_file!r}')
  579. else:
  580. self.log_fd = None
  581. if opt.coverage:
  582. coverdir,accfile = init_coverage()
  583. omsg(f'INFO → Writing coverage files to {coverdir!r}')
  584. self.pre_args = ['python3','-m','trace','--count','--coverdir='+coverdir,'--file='+accfile]
  585. else:
  586. self.pre_args = ['python3'] if g.platform == 'win' else []
  587. if opt.pexpect_spawn:
  588. omsg(f'INFO → Using pexpect.spawn() for real terminal emulation')
  589. def spawn_wrapper(self,cmd,
  590. args = [],
  591. extra_desc = '',
  592. no_output = False,
  593. msg_only = False,
  594. no_msg = False,
  595. cmd_dir = 'cmds',
  596. no_exec_wrapper = False ):
  597. desc = self.ts.test_name if opt.names else self.gm.dpy_data[self.ts.test_name][1]
  598. if extra_desc:
  599. desc += ' ' + extra_desc
  600. cmd_path = (
  601. cmd if opt.system # opt.system is broken for main test group with overlay tree
  602. else os.path.relpath(os.path.join(repo_root,cmd_dir,cmd)) )
  603. args = (
  604. self.pre_args +
  605. ([] if no_exec_wrapper else ['scripts/exec_wrapper.py']) +
  606. [cmd_path] +
  607. self.passthru_opts +
  608. self.ts.extra_spawn_args +
  609. args )
  610. for i in args:
  611. if not isinstance(i,str):
  612. die(2,'Error: missing input files in cmd line?:\nName: {}\nCmdline: {!r}'.format(
  613. self.ts.test_name,
  614. args ))
  615. qargs = ['{q}{}{q}'.format( a, q = "'" if ' ' in a else '' ) for a in args]
  616. cmd_disp = ' '.join(qargs).replace('\\','/') # for mingw
  617. if not no_msg:
  618. t_pfx = '' if opt.no_timings else f'[{time.time() - self.start_time:08.2f}] '
  619. if opt.verbose or opt.print_cmdline or opt.exact_output:
  620. omsg(green(f'{t_pfx}Testing: {desc}'))
  621. if not msg_only:
  622. clr1,clr2 = (nocolor,nocolor) if opt.print_cmdline else (green,cyan)
  623. omsg(
  624. clr1('Executing: ') +
  625. clr2(repr(cmd_disp) if g.platform == 'win' else cmd_disp)
  626. )
  627. else:
  628. omsg_r(f'{t_pfx}Testing {desc}: ')
  629. if msg_only:
  630. return
  631. if opt.log:
  632. self.log_fd.write('[{}][{}:{}] {}\n'.format(
  633. proto.coin.lower(),
  634. self.ts.group_name,
  635. self.ts.test_name,
  636. cmd_disp))
  637. os.environ['MMGEN_FORCE_COLOR'] = '1' if self.ts.color else ''
  638. env = { 'EXEC_WRAPPER_SPAWN':'1' }
  639. if 'exec_wrapper_init' in globals():
  640. # test.py itself is running under exec_wrapper, so disable traceback file writing for spawned script
  641. env.update({ 'EXEC_WRAPPER_NO_TRACEBACK':'1' }) # Python 3.9: OR the dicts
  642. env.update(os.environ)
  643. from test.include.pexpect import MMGenPexpect
  644. return MMGenPexpect( args, no_output=no_output, env=env )
  645. def end_msg(self):
  646. t = int(time.time() - self.start_time)
  647. sys.stderr.write(green(
  648. f'{self.cmd_total} test{suf(self.cmd_total)} performed' +
  649. ('\n' if opt.no_timings else f'. Elapsed time: {t//60:02d}:{t%60:02d}\n')
  650. ))
  651. def init_group(self,gname,cmd=None,quiet=False,do_clean=True):
  652. ts_cls = CmdGroupMgr().load_mod(gname)
  653. for k in ('segwit','segwit_random','bech32'):
  654. if getattr(opt,k):
  655. segwit_opt = k
  656. break
  657. else:
  658. segwit_opt = None
  659. def gen_msg():
  660. yield ('{g}:{c}' if cmd else 'test group {g!r}').format(g=gname,c=cmd)
  661. if len(ts_cls.networks) != 1:
  662. yield f' for {proto.coin} {proto.network}'
  663. if segwit_opt:
  664. yield ' (--{})'.format( segwit_opt.replace('_','-') )
  665. m = ''.join(gen_msg())
  666. if segwit_opt and not ts_cls.segwit_opts_ok:
  667. iqmsg('INFO → skipping ' + m)
  668. return False
  669. # 'networks = ()' means all networks allowed
  670. nws = [(e.split('_')[0],'testnet') if '_' in e else (e,'mainnet') for e in ts_cls.networks]
  671. if nws:
  672. coin = proto.coin.lower()
  673. nw = ('mainnet','testnet')[proto.testnet]
  674. for a,b in nws:
  675. if a == coin and b == nw:
  676. break
  677. else:
  678. iqmsg('INFO → skipping ' + m)
  679. return False
  680. if do_clean:
  681. clean(ts_cls.tmpdir_nums,clean_overlay=False)
  682. if not quiet:
  683. bmsg('Executing ' + m)
  684. if not self.daemons_started and network_id not in ('eth','etc','xmr'):
  685. start_test_daemons(network_id,remove_datadir=True)
  686. self.daemons_started = True
  687. os.environ['MMGEN_BOGUS_WALLET_DATA'] = '' # zero this here, so test groups don't have to
  688. self.ts = self.gm.gm_init_group(self,gname,self.spawn_wrapper)
  689. self.ts_clsname = type(self.ts).__name__
  690. self.passthru_opts = ['--{}{}'.format(
  691. k.replace('_','-'),
  692. '=' + getattr(opt,k) if getattr(opt,k) != True else ''
  693. ) for k in self.ts.base_passthru_opts + self.ts.passthru_opts if getattr(opt,k)]
  694. if resuming:
  695. rc = opt.resume or opt.resume_after
  696. offset = 1 if opt.resume_after else 0
  697. self.resume_cmd = self.gm.cmd_list[self.gm.cmd_list.index(rc)+offset]
  698. omsg(f'INFO → Resuming at command {self.resume_cmd!r}')
  699. if opt.step:
  700. opt.exit_after = self.resume_cmd
  701. if opt.exit_after and opt.exit_after not in self.gm.cmd_list:
  702. die(1,f'{opt.exit_after!r}: command not recognized')
  703. return True
  704. def run_tests(self,usr_args):
  705. self.start_time = time.time()
  706. self.daemons_started = False
  707. gname_save = None
  708. if usr_args:
  709. for arg in usr_args:
  710. if arg in self.gm.cmd_groups:
  711. if not self.init_group(arg):
  712. continue
  713. for cmd in self.gm.cmd_list:
  714. self.check_needs_rerun(cmd,build=True)
  715. do_between()
  716. else:
  717. if ':' in arg:
  718. gname,arg = arg.split(':')
  719. else:
  720. gname = self.gm.find_cmd_in_groups(arg)
  721. if gname:
  722. same_grp = gname == gname_save # same group as previous cmd: don't clean, suppress blue msg
  723. if not self.init_group(gname,arg,quiet=same_grp,do_clean=not same_grp):
  724. continue
  725. try:
  726. self.check_needs_rerun(arg,build=True)
  727. except Exception as e: # allow calling of functions not in cmd_group
  728. if isinstance(e,KeyError) and e.args[0] == arg:
  729. ret = getattr(self.ts,arg)()
  730. if type(ret).__name__ == 'coroutine':
  731. run_session(ret)
  732. else:
  733. raise
  734. do_between()
  735. gname_save = gname
  736. else:
  737. die(1,f'{arg!r}: command not recognized')
  738. else:
  739. if opt.exclude_groups:
  740. exclude = opt.exclude_groups.split(',')
  741. for e in exclude:
  742. if e not in self.gm.cmd_groups_dfl:
  743. die(1,f'{e!r}: group not recognized')
  744. for gname in self.gm.cmd_groups_dfl:
  745. if opt.exclude_groups and gname in exclude:
  746. continue
  747. if not self.init_group(gname):
  748. continue
  749. for cmd in self.gm.cmd_list:
  750. self.check_needs_rerun(cmd,build=True)
  751. do_between()
  752. self.end_msg()
  753. def check_needs_rerun(self,cmd,
  754. build = False,
  755. root = True,
  756. force_delete = False,
  757. dpy = False ):
  758. self.ts.test_name = cmd
  759. if self.ts_clsname == 'TestSuiteMain' and testing_segwit and cmd not in self.ts.segwit_do:
  760. return False
  761. rerun = root # force_delete is not passed to recursive call
  762. fns = []
  763. if force_delete or not root:
  764. # does cmd produce a needed dependency(ies)?
  765. ret = self.get_num_exts_for_cmd(cmd,dpy)
  766. if ret:
  767. for ext in ret[1]:
  768. fn = get_file_with_ext(cfgs[ret[0]]['tmpdir'],ext,delete=build)
  769. if fn:
  770. if force_delete: os.unlink(fn)
  771. else: fns.append(fn)
  772. else: rerun = True
  773. fdeps = self.generate_file_deps(cmd)
  774. cdeps = self.generate_cmd_deps(fdeps)
  775. for fn in fns:
  776. my_age = os.stat(fn).st_mtime
  777. for num,ext in fdeps:
  778. f = get_file_with_ext(cfgs[num]['tmpdir'],ext,delete=build)
  779. if f and os.stat(f).st_mtime > my_age:
  780. rerun = True
  781. for cdep in cdeps:
  782. if self.check_needs_rerun(cdep,build=build,root=False,dpy=cmd):
  783. rerun = True
  784. if build:
  785. if rerun:
  786. for fn in fns:
  787. if not root:
  788. os.unlink(fn)
  789. if not (dpy and skipping_deps):
  790. self.run_test(cmd)
  791. if not root:
  792. do_between()
  793. else:
  794. # If prog produces multiple files:
  795. if cmd not in self.rebuild_list or rerun == True:
  796. self.rebuild_list[cmd] = (rerun,fns[0] if fns else '') # FIX
  797. return rerun
  798. def run_test(self,cmd):
  799. d = [(str(num),ext) for exts,num in self.gm.dpy_data[cmd][2] for ext in exts]
  800. # delete files depended on by this cmd
  801. arg_list = [get_file_with_ext(cfgs[num]['tmpdir'],ext) for num,ext in d]
  802. # remove shared_deps from arg list
  803. if hasattr(self.ts,'shared_deps'):
  804. arg_list = arg_list[:-len(self.ts.shared_deps)]
  805. if self.resume_cmd:
  806. if cmd != self.resume_cmd:
  807. return
  808. bmsg(f'Resuming at {self.resume_cmd!r}')
  809. self.resume_cmd = None
  810. global skipping_deps,resuming
  811. skipping_deps = False
  812. resuming = False
  813. if opt.profile:
  814. start = time.time()
  815. self.ts.test_name = cmd # NB: Do not remove, this needs to be set twice
  816. cdata = self.gm.dpy_data[cmd]
  817. # self.ts.test_dpydata = cdata
  818. self.ts.tmpdir_num = cdata[0]
  819. # self.ts.cfg = cfgs[str(cdata[0])] # will remove this eventually
  820. cfg = cfgs[str(cdata[0])]
  821. for k in ( 'seed_len', 'seed_id',
  822. 'wpasswd', 'kapasswd',
  823. 'segwit', 'hash_preset',
  824. 'bw_filename', 'bw_params', 'ref_bw_seed_id',
  825. 'addr_idx_list', 'pass_idx_list' ):
  826. if k in cfg:
  827. setattr(self.ts,k,cfg[k])
  828. ret = getattr(self.ts,cmd)(*arg_list) # run the test
  829. if type(ret).__name__ == 'coroutine':
  830. ret = run_session(ret)
  831. self.process_retval(cmd,ret)
  832. if opt.profile:
  833. omsg('\r\033[50C{:.4f}'.format( time.time() - start ))
  834. if cmd == opt.exit_after:
  835. sys.exit(0)
  836. def warn_skipped(self):
  837. if self.skipped_warnings:
  838. print(yellow('The following tests were skipped and may require attention:'))
  839. r = '-' * 72 + '\n'
  840. print(r+('\n'+r).join(self.skipped_warnings))
  841. def process_retval(self,cmd,ret):
  842. if type(ret).__name__ == 'MMGenPexpect':
  843. ret.ok()
  844. self.cmd_total += 1
  845. elif ret == 'ok':
  846. ok()
  847. self.cmd_total += 1
  848. elif ret == 'skip':
  849. pass
  850. elif type(ret) == tuple and ret[0] == 'skip_warn':
  851. self.skipped_warnings.append(
  852. 'Test {!r} was skipped:\n {}'.format(cmd,'\n '.join(ret[1].split('\n'))))
  853. else:
  854. die(2,f'{cmd!r} returned {ret}')
  855. def check_deps(self,cmds): # TODO: broken
  856. if len(cmds) != 1:
  857. die(1,f'Usage: {g.prog_name} check_deps <command>')
  858. cmd = cmds[0]
  859. if cmd not in self.gm.cmd_list:
  860. die(1,f'{cmd!r}: unrecognized command')
  861. if not opt.quiet:
  862. omsg(f'Checking dependencies for {cmd!r}')
  863. self.check_needs_rerun(self.ts,cmd,build=False)
  864. w = max(map(len,self.rebuild_list)) + 1
  865. for cmd in self.rebuild_list:
  866. c = self.rebuild_list[cmd]
  867. m = 'Rebuild' if (c[0] and c[1]) else 'Build' if c[0] else 'OK'
  868. omsg('cmd {:<{w}} {}'.format( cmd+':', m, w=w ))
  869. def generate_file_deps(self,cmd):
  870. return [(str(n),e) for exts,n in self.gm.dpy_data[cmd][2] for e in exts]
  871. def generate_cmd_deps(self,fdeps):
  872. return [cfgs[str(n)]['dep_generators'][ext] for n,ext in fdeps]
  873. def get_num_exts_for_cmd(self,cmd,dpy=False): # dpy ignored here
  874. try:
  875. num = str(self.gm.dpy_data[cmd][0])
  876. except KeyError:
  877. qmsg_r(f'Missing dependency {cmd!r}')
  878. gname = self.gm.find_cmd_in_groups(cmd)
  879. if gname:
  880. kwargs = self.gm.cmd_groups[gname][1]
  881. kwargs.update({'add_dpy':True})
  882. self.gm.create_group(gname,**kwargs)
  883. num = str(self.gm.dpy_data[cmd][0])
  884. qmsg(f' found in group {gname!r}')
  885. else:
  886. qmsg(' not found in any command group!')
  887. raise
  888. dgl = cfgs[num]['dep_generators']
  889. if cmd in dgl.values():
  890. exts = [k for k in dgl if dgl[k] == cmd]
  891. return (num,exts)
  892. else:
  893. return None
  894. # main()
  895. if not skipping_deps: # do this before list cmds exit, so we stay in sync with shm_dir
  896. create_tmp_dirs(shm_dir)
  897. if opt.list_cmd_groups:
  898. CmdGroupMgr().list_cmd_groups()
  899. elif opt.list_cmds:
  900. list_cmds()
  901. elif usr_args and usr_args[0] in utils:
  902. globals()[usr_args[0]](*usr_args[1:])
  903. sys.exit(0)
  904. if opt.pause:
  905. set_restore_term_at_exit()
  906. set_environ_for_spawned_scripts()
  907. from mmgen.exception import TestSuiteException,TestSuiteFatalException
  908. try:
  909. tr = TestSuiteRunner(data_dir,trash_dir)
  910. tr.run_tests(usr_args)
  911. tr.warn_skipped()
  912. if network_id not in ('eth','etc','xmr'):
  913. stop_test_daemons(network_id)
  914. except KeyboardInterrupt:
  915. if network_id not in ('eth','etc','xmr'):
  916. stop_test_daemons(network_id)
  917. tr.warn_skipped()
  918. die(1,'\ntest.py exiting at user request')
  919. except TestSuiteException as e:
  920. die(2,e.args[0])
  921. except TestSuiteFatalException as e:
  922. die(4,e.args[0])
  923. except Exception:
  924. if 'exec_wrapper_init' in globals(): # test.py itself is running under exec_wrapper
  925. import traceback
  926. print(''.join(traceback.format_exception(*sys.exc_info())))
  927. msg(blue('Test script exited with error'))
  928. else:
  929. msg(blue('Spawned script exited with error'))
  930. raise
  931. except:
  932. raise