test.py 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087
  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. if opt.daemon_id and opt.daemon_id in g.blacklist_daemons.split():
  151. die(0,f'test.py: daemon {opt.daemon_id!r} blacklisted, exiting')
  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 skipping_deps:
  158. shm_dir = create_shm_dir(data_dir,trash_dir)
  159. check_segwit_opts()
  160. testing_segwit = opt.segwit or opt.segwit_random or opt.bech32
  161. if g.test_suite_deterministic:
  162. opt.no_timings = True
  163. init_color(num_colors=0)
  164. os.environ['MMGEN_DISABLE_COLOR'] = '1'
  165. if opt.profile:
  166. opt.names = True
  167. if opt.exact_output:
  168. def msg(s): pass
  169. qmsg = qmsg_r = vmsg = vmsg_r = msg_r = msg
  170. if skipping_deps:
  171. opt.no_daemon_autostart = True
  172. cfgs = { # addr_idx_lists (except 31,32,33,34) must contain exactly 8 addresses
  173. '1': { 'wpasswd': 'Dorian-α',
  174. 'kapasswd': 'Grok the blockchain',
  175. 'addr_idx_list': '12,99,5-10,5,12',
  176. 'dep_generators': {
  177. pwfile: 'walletgen',
  178. 'mmdat': 'walletgen',
  179. 'addrs': 'addrgen',
  180. 'rawtx': 'txcreate',
  181. 'txbump': 'txbump',
  182. 'sigtx': 'txsign',
  183. 'mmwords': 'export_mnemonic',
  184. 'mmseed': 'export_seed',
  185. 'mmhex': 'export_hex',
  186. 'mmincog': 'export_incog',
  187. 'mmincox': 'export_incog_hex',
  188. hincog_fn: 'export_incog_hidden',
  189. incog_id_fn: 'export_incog_hidden',
  190. 'akeys.mmenc': 'keyaddrgen'
  191. },
  192. },
  193. '2': { 'wpasswd': 'Hodling away',
  194. 'addr_idx_list': '37,45,3-6,22-23',
  195. 'seed_len': 128,
  196. 'dep_generators': {
  197. 'mmdat': 'walletgen2',
  198. 'addrs': 'addrgen2',
  199. 'rawtx': 'txcreate2',
  200. 'sigtx': 'txsign2',
  201. 'mmwords': 'export_mnemonic2',
  202. },
  203. },
  204. '3': { 'wpasswd': 'Major miner',
  205. 'addr_idx_list': '73,54,1022-1023,2-5',
  206. 'dep_generators': {
  207. 'mmdat': 'walletgen3',
  208. 'addrs': 'addrgen3',
  209. 'rawtx': 'txcreate3',
  210. 'sigtx': 'txsign3'
  211. },
  212. },
  213. '4': { 'wpasswd': 'Hashrate good',
  214. 'addr_idx_list': '63,1004,542-544,7-9',
  215. 'seed_len': 192,
  216. 'dep_generators': {
  217. 'mmdat': 'walletgen4',
  218. 'mmbrain': 'walletgen4',
  219. 'addrs': 'addrgen4',
  220. 'rawtx': 'txcreate4',
  221. 'sigtx': 'txsign4',
  222. 'txdo': 'txdo4',
  223. },
  224. 'bw_filename': 'brainwallet.mmbrain',
  225. 'bw_params': '192,1',
  226. },
  227. '5': { 'wpasswd': 'My changed password-α',
  228. 'hash_preset': '2',
  229. 'dep_generators': {
  230. 'mmdat': 'passchg',
  231. pwfile: 'passchg',
  232. },
  233. },
  234. '6': { 'seed_len': 128,
  235. 'seed_id': 'FE3C6545',
  236. 'ref_bw_seed_id': '33F10310',
  237. 'wpasswd': 'reference password',
  238. 'kapasswd': '',
  239. 'dep_generators': {
  240. 'mmdat': 'ref_walletgen_brain_1',
  241. pwfile: 'ref_walletgen_brain_1',
  242. 'addrs': 'refaddrgen_1',
  243. 'akeys.mmenc': 'refkeyaddrgen_1'
  244. },
  245. },
  246. '7': { 'seed_len': 192,
  247. 'seed_id': '1378FC64',
  248. 'ref_bw_seed_id': 'CE918388',
  249. 'wpasswd': 'reference password',
  250. 'kapasswd': '',
  251. 'dep_generators': {
  252. 'mmdat': 'ref_walletgen_brain_2',
  253. pwfile: 'ref_walletgen_brain_2',
  254. 'addrs': 'refaddrgen_2',
  255. 'akeys.mmenc': 'refkeyaddrgen_2'
  256. },
  257. },
  258. '8': { 'seed_len': 256,
  259. 'seed_id': '98831F3A',
  260. 'ref_bw_seed_id': 'B48CD7FC',
  261. 'wpasswd': 'reference password',
  262. 'kapasswd': '',
  263. 'dep_generators': {
  264. 'mmdat': 'ref_walletgen_brain_3',
  265. pwfile: 'ref_walletgen_brain_3',
  266. 'addrs': 'refaddrgen_3',
  267. 'akeys.mmenc': 'refkeyaddrgen_3'
  268. },
  269. },
  270. '9': { 'tool_enc_infn': 'tool_encrypt.in',
  271. 'dep_generators': {
  272. 'tool_encrypt.in': 'tool_encrypt',
  273. 'tool_encrypt.in.mmenc': 'tool_encrypt',
  274. },
  275. },
  276. '14': { 'kapasswd': 'Maxwell',
  277. 'wpasswd': 'The Halving',
  278. 'addr_idx_list': '61,998,502-504,7-9',
  279. 'seed_len': 256,
  280. 'dep_generators': {
  281. 'mmdat': 'walletgen14',
  282. 'addrs': 'addrgen14',
  283. 'akeys.mmenc': 'keyaddrgen14',
  284. },
  285. },
  286. '15': { 'wpasswd': 'Dorian-α',
  287. 'kapasswd': 'Grok the blockchain',
  288. 'addr_idx_list': '12,99,5-10,5,12',
  289. 'dep_generators': {
  290. pwfile: 'walletgen_dfl_wallet',
  291. 'addrs': 'addrgen_dfl_wallet',
  292. 'rawtx': 'txcreate_dfl_wallet',
  293. 'sigtx': 'txsign_dfl_wallet',
  294. 'mmseed': 'export_seed_dfl_wallet',
  295. 'del_dw_run': 'delete_dfl_wallet',
  296. },
  297. },
  298. '16': { 'wpasswd': 'My changed password',
  299. 'hash_preset': '2',
  300. 'dep_generators': {
  301. pwfile: 'passchg_dfl_wallet',
  302. },
  303. },
  304. '17': {},
  305. '18': {},
  306. '19': { 'wpasswd':'abc' },
  307. '20': { 'wpasswd': 'Vsize it',
  308. 'addr_idx_list': '1-8',
  309. 'seed_len': 256,
  310. 'dep_generators': {
  311. 'mmdat': 'walletgen5',
  312. 'addrs': 'addrgen5',
  313. 'rawtx': 'txcreate5',
  314. 'sigtx': 'txsign5',
  315. },
  316. },
  317. '21': { 'wpasswd': 'Vsize it',
  318. 'addr_idx_list': '1-8',
  319. 'seed_len': 256,
  320. 'dep_generators': {
  321. 'mmdat': 'walletgen6',
  322. 'addrs': 'addrgen6',
  323. 'rawtx': 'txcreate6',
  324. 'sigtx': 'txsign6',
  325. },
  326. },
  327. '22': {},
  328. '23': {},
  329. # 26,27,28 are taken
  330. '29': {}, # xmrwallet
  331. '31': {},
  332. '32': {},
  333. '33': {},
  334. '34': {},
  335. '40': {},
  336. '41': {},
  337. '99': {}, # dummy
  338. }
  339. def fixup_cfgs():
  340. for k in ('6','7','8'):
  341. cfgs['2'+k] = {}
  342. cfgs['2'+k].update(cfgs[k])
  343. for k in cfgs:
  344. cfgs[k]['tmpdir'] = os.path.join('test',f'tmp{k}')
  345. cfgs[k]['segwit'] = randbool() if opt.segwit_random else bool(opt.segwit or opt.bech32)
  346. from copy import deepcopy
  347. for a,b in (('6','11'),('7','12'),('8','13')):
  348. cfgs[b] = deepcopy(cfgs[a])
  349. cfgs[b]['tmpdir'] = os.path.join('test','tmp'+b)
  350. if g.debug_utf8:
  351. for k in cfgs: cfgs[k]['tmpdir'] += '-α'
  352. fixup_cfgs()
  353. utils = {
  354. # 'check_deps': 'check dependencies for specified command (WIP)', # TODO
  355. 'clean': 'clean specified tmp dir(s) (specify by integer, no arg = all dirs)',
  356. }
  357. def list_cmds():
  358. gm = CmdGroupMgr()
  359. cw,d = 0,[]
  360. Msg(green('AVAILABLE COMMANDS:'))
  361. for gname in gm.cmd_groups:
  362. ts = gm.gm_init_group(None,gname,None)
  363. desc = ts.__doc__.strip() if ts.__doc__ else type(ts).__name__
  364. d.append( (gname,desc,gm.cmd_list,gm.dpy_data) )
  365. cw = max(max(len(k) for k in gm.dpy_data),cw)
  366. for gname,gdesc,clist,dpdata in d:
  367. Msg('\n'+green(f'{gname!r} - {gdesc}:'))
  368. for cmd in clist:
  369. data = dpdata[cmd]
  370. Msg(' {:{w}} - {}'.format(
  371. cmd,
  372. (data if type(data) == str else data[1]),
  373. w = cw ))
  374. w = max(map(len,utils))
  375. Msg('\n'+green('AVAILABLE UTILITIES:'))
  376. for cmd in sorted(utils):
  377. Msg(' {:{w}} - {}'.format( cmd, utils[cmd], w=w ))
  378. sys.exit(0)
  379. def do_between():
  380. if opt.pause:
  381. confirm_continue()
  382. elif (opt.verbose or opt.exact_output) and not skipping_deps:
  383. sys.stderr.write('\n')
  384. def list_tmpdirs():
  385. return {k:cfgs[k]['tmpdir'] for k in cfgs}
  386. def clean(usr_dirs=None,clean_overlay=True):
  387. if skipping_deps:
  388. return
  389. all_dirs = list_tmpdirs()
  390. dirnums = map(int,(usr_dirs if usr_dirs is not None else all_dirs))
  391. dirlist = list(map(str,sorted(dirnums)))
  392. for d in dirlist:
  393. if d in all_dirs:
  394. cleandir(all_dirs[d])
  395. else:
  396. die(1,f'{d}: invalid directory number')
  397. if dirlist:
  398. iqmsg(green('Cleaned tmp director{} {}'.format(
  399. suf(dirlist,'ies'),
  400. ' '.join(dirlist))
  401. ))
  402. cleandir(data_dir)
  403. cleandir(trash_dir)
  404. iqmsg(green(f'Cleaned directories {data_dir!r} {trash_dir!r}'))
  405. if clean_overlay:
  406. cleandir(overlay_dir)
  407. iqmsg(green(f'Cleaned directory {os.path.relpath(overlay_dir)!r}'))
  408. def create_tmp_dirs(shm_dir):
  409. if g.platform == 'win':
  410. for cfg in sorted(cfgs):
  411. mk_tmpdir(cfgs[cfg]['tmpdir'])
  412. else:
  413. for cfg in sorted(cfgs):
  414. src = os.path.join(shm_dir,cfgs[cfg]['tmpdir'].split('/')[-1])
  415. mk_tmpdir(src)
  416. try:
  417. os.unlink(cfgs[cfg]['tmpdir'])
  418. except OSError as e:
  419. if e.errno != 2:
  420. raise
  421. finally:
  422. os.symlink(src,cfgs[cfg]['tmpdir'])
  423. def set_environ_for_spawned_scripts():
  424. from mmgen.term import get_terminal_size
  425. os.environ['MMGEN_COLUMNS'] = str(get_terminal_size().width)
  426. if os.getenv('MMGEN_DEBUG_ALL'):
  427. for name in g.env_opts:
  428. if name[:11] == 'MMGEN_DEBUG':
  429. os.environ[name] = '1'
  430. if not opt.pexpect_spawn:
  431. os.environ['MMGEN_TEST_SUITE_POPEN_SPAWN'] = '1'
  432. if not opt.system:
  433. os.environ['PYTHONPATH'] = repo_root
  434. if not opt.buf_keypress:
  435. os.environ['MMGEN_DISABLE_HOLD_PROTECT'] = '1'
  436. os.environ['MMGEN_NO_LICENSE'] = '1'
  437. os.environ['MMGEN_MIN_URANDCHARS'] = '3'
  438. os.environ['MMGEN_BOGUS_SEND'] = '1'
  439. os.environ['MMGEN_TEST_SUITE_PEXPECT'] = '1'
  440. def set_restore_term_at_exit():
  441. import termios,atexit
  442. fd = sys.stdin.fileno()
  443. old = termios.tcgetattr(fd)
  444. def at_exit():
  445. termios.tcsetattr(fd, termios.TCSADRAIN, old)
  446. atexit.register(at_exit)
  447. class CmdGroupMgr(object):
  448. cmd_groups_dfl = {
  449. 'misc': ('TestSuiteMisc',{}),
  450. 'opts': ('TestSuiteOpts',{'full_data':True}),
  451. 'cfg': ('TestSuiteCfg',{'full_data':True}),
  452. 'helpscreens': ('TestSuiteHelp',{'modname':'misc','full_data':True}),
  453. 'main': ('TestSuiteMain',{'full_data':True}),
  454. 'conv': ('TestSuiteWalletConv',{'is3seed':True,'modname':'wallet'}),
  455. 'ref': ('TestSuiteRef',{}),
  456. 'ref3': ('TestSuiteRef3Seed',{'is3seed':True,'modname':'ref_3seed'}),
  457. 'ref3_addr': ('TestSuiteRef3Addr',{'is3seed':True,'modname':'ref_3seed'}),
  458. 'ref_altcoin': ('TestSuiteRefAltcoin',{}),
  459. 'seedsplit': ('TestSuiteSeedSplit',{}),
  460. 'tool': ('TestSuiteTool',{'full_data':True}),
  461. 'input': ('TestSuiteInput',{'full_data':True}),
  462. 'output': ('TestSuiteOutput',{'modname':'misc','full_data':True}),
  463. 'autosign': ('TestSuiteAutosign',{}),
  464. 'regtest': ('TestSuiteRegtest',{}),
  465. # 'chainsplit': ('TestSuiteChainsplit',{}),
  466. 'ethdev': ('TestSuiteEthdev',{}),
  467. 'xmrwallet': ('TestSuiteXMRWallet',{}),
  468. }
  469. cmd_groups_extra = {
  470. 'autosign_btc': ('TestSuiteAutosignBTC',{'modname':'autosign'}),
  471. 'autosign_live': ('TestSuiteAutosignLive',{'modname':'autosign'}),
  472. 'autosign_live_simulate': ('TestSuiteAutosignLiveSimulate',{'modname':'autosign'}),
  473. 'create_ref_tx': ('TestSuiteRefTX',{'modname':'misc','full_data':True}),
  474. }
  475. cmd_groups = cmd_groups_dfl.copy()
  476. cmd_groups.update(cmd_groups_extra)
  477. def load_mod(self,gname,modname=None):
  478. clsname,kwargs = self.cmd_groups[gname]
  479. if modname == None and 'modname' in kwargs:
  480. modname = kwargs['modname']
  481. import importlib
  482. modpath = f'test.test_py_d.ts_{modname or gname}'
  483. return getattr(importlib.import_module(modpath),clsname)
  484. def create_group(self,gname,full_data=False,modname=None,is3seed=False,add_dpy=False):
  485. """
  486. Initializes the list 'cmd_list' and dict 'dpy_data' from module's cmd_group data.
  487. Alternatively, if called with 'add_dpy=True', updates 'dpy_data' from module data
  488. without touching 'cmd_list'
  489. """
  490. cls = self.load_mod(gname,modname)
  491. cdata = []
  492. def get_shared_deps(cmdname,tmpdir_idx):
  493. """
  494. shared_deps are "implied" dependencies for all cmds in cmd_group that don't appear in
  495. the cmd_group data or cmds' argument lists. Supported only for 3seed tests at present.
  496. """
  497. if not hasattr(cls,'shared_deps'):
  498. return []
  499. return [k for k,v in cfgs[str(tmpdir_idx)]['dep_generators'].items()
  500. if k in cls.shared_deps and v != cmdname]
  501. for a,b in cls.cmd_group:
  502. if is3seed:
  503. for n,(i,j) in enumerate(zip(cls.tmpdir_nums,(128,192,256))):
  504. k = f'{a}_{n+1}'
  505. if hasattr(cls,'skip_cmds') and k in cls.skip_cmds:
  506. continue
  507. sdeps = get_shared_deps(k,i)
  508. if type(b) == str:
  509. cdata.append( (k, (i,f'{b} ({j}-bit)',[[[]+sdeps,i]])) )
  510. else:
  511. cdata.append( (k, (i,f'{b[1]} ({j}-bit)',[[b[0]+sdeps,i]])) )
  512. else:
  513. cdata.append( (a, b if full_data else (cls.tmpdir_nums[0],b,[[[],cls.tmpdir_nums[0]]])) )
  514. if add_dpy:
  515. self.dpy_data.update(dict(cdata))
  516. else:
  517. self.cmd_list = tuple(e[0] for e in cdata)
  518. self.dpy_data = dict(cdata)
  519. return cls
  520. def gm_init_group(self,trunner,gname,spawn_prog):
  521. kwargs = self.cmd_groups[gname][1]
  522. cls = self.create_group(gname,**kwargs)
  523. cls.group_name = gname
  524. return cls(trunner,cfgs,spawn_prog)
  525. def list_cmd_groups(self):
  526. ginfo = []
  527. for gname in self.cmd_groups:
  528. clsname,kwargs = self.cmd_groups[gname]
  529. cls = self.load_mod(gname,kwargs['modname'] if 'modname' in kwargs else None)
  530. ginfo.append((gname,cls))
  531. if opt.list_current_cmd_groups:
  532. exclude = (opt.exclude_groups or '').split(',')
  533. ginfo = [g for g in ginfo
  534. if network_id in g[1].networks
  535. and not g[0] in exclude
  536. and g[0] in tuple(self.cmd_groups_dfl) + tuple(usr_args) ]
  537. for name,cls in ginfo:
  538. msg('{:17} - {}'.format(
  539. name,
  540. cls.__doc__.strip() if cls.__doc__ else cls.__name__
  541. ))
  542. Msg( '\n' + ' '.join(e[0] for e in ginfo) )
  543. sys.exit(0)
  544. def find_cmd_in_groups(self,cmd,group=None):
  545. """
  546. Search for a test command in specified group or all configured command groups
  547. and return it as a string. Loads modules but alters no global variables.
  548. """
  549. if group:
  550. if not group in [e[0] for e in self.cmd_groups]:
  551. die(1,f'{group!r}: unrecognized group')
  552. groups = [self.cmd_groups[group]]
  553. else:
  554. groups = self.cmd_groups
  555. for gname in groups:
  556. clsname,kwargs = self.cmd_groups[gname]
  557. cls = self.load_mod(gname,kwargs['modname'] if 'modname' in kwargs else None)
  558. if cmd in cls.cmd_group: # first search the class
  559. return gname
  560. if cmd in dir(cls(None,None,None)): # then a throwaway instance
  561. return gname # cmd might exist in more than one group - we'll go with the first
  562. return None
  563. class TestSuiteRunner(object):
  564. 'test suite runner'
  565. def __del__(self):
  566. if opt.log:
  567. self.log_fd.close()
  568. def __init__(self,data_dir,trash_dir):
  569. self.data_dir = data_dir
  570. self.trash_dir = trash_dir
  571. self.cmd_total = 0
  572. self.rebuild_list = {}
  573. self.gm = CmdGroupMgr()
  574. self.repo_root = repo_root
  575. self.skipped_warnings = []
  576. self.resume_cmd = None
  577. if opt.log:
  578. self.log_fd = open(log_file,'a')
  579. self.log_fd.write(f'\nLog started: {make_timestr()} UTC\n')
  580. omsg(f'INFO → Logging to file {log_file!r}')
  581. else:
  582. self.log_fd = None
  583. if opt.coverage:
  584. coverdir,accfile = init_coverage()
  585. omsg(f'INFO → Writing coverage files to {coverdir!r}')
  586. self.pre_args = ['python3','-m','trace','--count','--coverdir='+coverdir,'--file='+accfile]
  587. else:
  588. self.pre_args = ['python3'] if g.platform == 'win' else []
  589. if opt.pexpect_spawn:
  590. omsg(f'INFO → Using pexpect.spawn() for real terminal emulation')
  591. def spawn_wrapper(self,cmd,
  592. args = [],
  593. extra_desc = '',
  594. no_output = False,
  595. msg_only = False,
  596. no_msg = False,
  597. cmd_dir = 'cmds',
  598. no_exec_wrapper = False ):
  599. desc = self.ts.test_name if opt.names else self.gm.dpy_data[self.ts.test_name][1]
  600. if extra_desc:
  601. desc += ' ' + extra_desc
  602. cmd_path = (
  603. cmd if opt.system # opt.system is broken for main test group with overlay tree
  604. else os.path.relpath(os.path.join(repo_root,cmd_dir,cmd)) )
  605. args = (
  606. self.pre_args +
  607. ([] if no_exec_wrapper else ['scripts/exec_wrapper.py']) +
  608. [cmd_path] +
  609. self.passthru_opts +
  610. self.ts.extra_spawn_args +
  611. args )
  612. for i in args:
  613. if not isinstance(i,str):
  614. die(2,'Error: missing input files in cmd line?:\nName: {}\nCmdline: {!r}'.format(
  615. self.ts.test_name,
  616. args ))
  617. qargs = ['{q}{}{q}'.format( a, q = "'" if ' ' in a else '' ) for a in args]
  618. cmd_disp = ' '.join(qargs).replace('\\','/') # for mingw
  619. if not no_msg:
  620. t_pfx = '' if opt.no_timings else f'[{time.time() - self.start_time:08.2f}] '
  621. if opt.verbose or opt.print_cmdline or opt.exact_output:
  622. omsg(green(f'{t_pfx}Testing: {desc}'))
  623. if not msg_only:
  624. clr1,clr2 = (nocolor,nocolor) if opt.print_cmdline else (green,cyan)
  625. omsg(
  626. clr1('Executing: ') +
  627. clr2(repr(cmd_disp) if g.platform == 'win' else cmd_disp)
  628. )
  629. else:
  630. omsg_r(f'{t_pfx}Testing {desc}: ')
  631. if msg_only:
  632. return
  633. if opt.log:
  634. self.log_fd.write('[{}][{}:{}] {}\n'.format(
  635. proto.coin.lower(),
  636. self.ts.group_name,
  637. self.ts.test_name,
  638. cmd_disp))
  639. os.environ['MMGEN_FORCE_COLOR'] = '1' if self.ts.color else ''
  640. env = { 'EXEC_WRAPPER_SPAWN':'1' }
  641. if 'exec_wrapper_init' in globals():
  642. # test.py itself is running under exec_wrapper, so disable traceback file writing for spawned script
  643. env.update({ 'EXEC_WRAPPER_NO_TRACEBACK':'1' }) # Python 3.9: OR the dicts
  644. env.update(os.environ)
  645. from test.include.pexpect import MMGenPexpect
  646. return MMGenPexpect( args, no_output=no_output, env=env )
  647. def end_msg(self):
  648. t = int(time.time() - self.start_time)
  649. sys.stderr.write(green(
  650. f'{self.cmd_total} test{suf(self.cmd_total)} performed' +
  651. ('\n' if opt.no_timings else f'. Elapsed time: {t//60:02d}:{t%60:02d}\n')
  652. ))
  653. def init_group(self,gname,cmd=None,quiet=False,do_clean=True):
  654. ts_cls = CmdGroupMgr().load_mod(gname)
  655. for k in ('segwit','segwit_random','bech32'):
  656. if getattr(opt,k):
  657. segwit_opt = k
  658. break
  659. else:
  660. segwit_opt = None
  661. def gen_msg():
  662. yield ('{g}:{c}' if cmd else 'test group {g!r}').format(g=gname,c=cmd)
  663. if len(ts_cls.networks) != 1:
  664. yield f' for {proto.coin} {proto.network}'
  665. if segwit_opt:
  666. yield ' (--{})'.format( segwit_opt.replace('_','-') )
  667. m = ''.join(gen_msg())
  668. if segwit_opt and not ts_cls.segwit_opts_ok:
  669. iqmsg('INFO → skipping ' + m)
  670. return False
  671. # 'networks = ()' means all networks allowed
  672. nws = [(e.split('_')[0],'testnet') if '_' in e else (e,'mainnet') for e in ts_cls.networks]
  673. if nws:
  674. coin = proto.coin.lower()
  675. nw = ('mainnet','testnet')[proto.testnet]
  676. for a,b in nws:
  677. if a == coin and b == nw:
  678. break
  679. else:
  680. iqmsg('INFO → skipping ' + m)
  681. return False
  682. if do_clean:
  683. clean(ts_cls.tmpdir_nums,clean_overlay=False)
  684. if not quiet:
  685. bmsg('Executing ' + m)
  686. if not self.daemons_started and network_id not in ('eth','etc','xmr'):
  687. start_test_daemons(network_id,remove_datadir=True)
  688. self.daemons_started = True
  689. os.environ['MMGEN_BOGUS_UNSPENT_DATA'] = '' # zero this here, so test groups don't have to
  690. self.ts = self.gm.gm_init_group(self,gname,self.spawn_wrapper)
  691. self.ts_clsname = type(self.ts).__name__
  692. self.passthru_opts = ['--{}{}'.format(
  693. k.replace('_','-'),
  694. '=' + getattr(opt,k) if getattr(opt,k) != True else ''
  695. ) for k in self.ts.base_passthru_opts + self.ts.passthru_opts if getattr(opt,k)]
  696. if resuming:
  697. rc = opt.resume or opt.resume_after
  698. offset = 1 if opt.resume_after else 0
  699. self.resume_cmd = self.gm.cmd_list[self.gm.cmd_list.index(rc)+offset]
  700. omsg(f'INFO → Resuming at command {self.resume_cmd!r}')
  701. if opt.step:
  702. opt.exit_after = self.resume_cmd
  703. if opt.exit_after and opt.exit_after not in self.gm.cmd_list:
  704. die(1,f'{opt.exit_after!r}: command not recognized')
  705. return True
  706. def run_tests(self,usr_args):
  707. self.start_time = time.time()
  708. self.daemons_started = False
  709. gname_save = None
  710. if usr_args:
  711. for arg in usr_args:
  712. if arg in self.gm.cmd_groups:
  713. if not self.init_group(arg):
  714. continue
  715. for cmd in self.gm.cmd_list:
  716. self.check_needs_rerun(cmd,build=True)
  717. do_between()
  718. else:
  719. if ':' in arg:
  720. gname,arg = arg.split(':')
  721. else:
  722. gname = self.gm.find_cmd_in_groups(arg)
  723. if gname:
  724. same_grp = gname == gname_save # same group as previous cmd: don't clean, suppress blue msg
  725. if not self.init_group(gname,arg,quiet=same_grp,do_clean=not same_grp):
  726. continue
  727. try:
  728. self.check_needs_rerun(arg,build=True)
  729. except Exception as e: # allow calling of functions not in cmd_group
  730. if isinstance(e,KeyError) and e.args[0] == arg:
  731. ret = getattr(self.ts,arg)()
  732. if type(ret).__name__ == 'coroutine':
  733. run_session(ret)
  734. else:
  735. raise
  736. do_between()
  737. gname_save = gname
  738. else:
  739. die(1,f'{arg!r}: command not recognized')
  740. else:
  741. if opt.exclude_groups:
  742. exclude = opt.exclude_groups.split(',')
  743. for e in exclude:
  744. if e not in self.gm.cmd_groups_dfl:
  745. die(1,f'{e!r}: group not recognized')
  746. for gname in self.gm.cmd_groups_dfl:
  747. if opt.exclude_groups and gname in exclude:
  748. continue
  749. if not self.init_group(gname):
  750. continue
  751. for cmd in self.gm.cmd_list:
  752. self.check_needs_rerun(cmd,build=True)
  753. do_between()
  754. self.end_msg()
  755. def check_needs_rerun(self,cmd,
  756. build = False,
  757. root = True,
  758. force_delete = False,
  759. dpy = False ):
  760. self.ts.test_name = cmd
  761. if self.ts_clsname == 'TestSuiteMain' and testing_segwit and cmd not in self.ts.segwit_do:
  762. return False
  763. rerun = root # force_delete is not passed to recursive call
  764. fns = []
  765. if force_delete or not root:
  766. # does cmd produce a needed dependency(ies)?
  767. ret = self.get_num_exts_for_cmd(cmd,dpy)
  768. if ret:
  769. for ext in ret[1]:
  770. fn = get_file_with_ext(cfgs[ret[0]]['tmpdir'],ext,delete=build)
  771. if fn:
  772. if force_delete: os.unlink(fn)
  773. else: fns.append(fn)
  774. else: rerun = True
  775. fdeps = self.generate_file_deps(cmd)
  776. cdeps = self.generate_cmd_deps(fdeps)
  777. for fn in fns:
  778. my_age = os.stat(fn).st_mtime
  779. for num,ext in fdeps:
  780. f = get_file_with_ext(cfgs[num]['tmpdir'],ext,delete=build)
  781. if f and os.stat(f).st_mtime > my_age:
  782. rerun = True
  783. for cdep in cdeps:
  784. if self.check_needs_rerun(cdep,build=build,root=False,dpy=cmd):
  785. rerun = True
  786. if build:
  787. if rerun:
  788. for fn in fns:
  789. if not root:
  790. os.unlink(fn)
  791. if not (dpy and skipping_deps):
  792. self.run_test(cmd)
  793. if not root:
  794. do_between()
  795. else:
  796. # If prog produces multiple files:
  797. if cmd not in self.rebuild_list or rerun == True:
  798. self.rebuild_list[cmd] = (rerun,fns[0] if fns else '') # FIX
  799. return rerun
  800. def run_test(self,cmd):
  801. d = [(str(num),ext) for exts,num in self.gm.dpy_data[cmd][2] for ext in exts]
  802. # delete files depended on by this cmd
  803. arg_list = [get_file_with_ext(cfgs[num]['tmpdir'],ext) for num,ext in d]
  804. # remove shared_deps from arg list
  805. if hasattr(self.ts,'shared_deps'):
  806. arg_list = arg_list[:-len(self.ts.shared_deps)]
  807. if self.resume_cmd:
  808. if cmd != self.resume_cmd:
  809. return
  810. bmsg(f'Resuming at {self.resume_cmd!r}')
  811. self.resume_cmd = None
  812. global skipping_deps,resuming
  813. skipping_deps = False
  814. resuming = False
  815. if opt.profile:
  816. start = time.time()
  817. self.ts.test_name = cmd # NB: Do not remove, this needs to be set twice
  818. cdata = self.gm.dpy_data[cmd]
  819. # self.ts.test_dpydata = cdata
  820. self.ts.tmpdir_num = cdata[0]
  821. # self.ts.cfg = cfgs[str(cdata[0])] # will remove this eventually
  822. cfg = cfgs[str(cdata[0])]
  823. for k in ( 'seed_len', 'seed_id',
  824. 'wpasswd', 'kapasswd',
  825. 'segwit', 'hash_preset',
  826. 'bw_filename', 'bw_params', 'ref_bw_seed_id',
  827. 'addr_idx_list', 'pass_idx_list' ):
  828. if k in cfg:
  829. setattr(self.ts,k,cfg[k])
  830. ret = getattr(self.ts,cmd)(*arg_list) # run the test
  831. if type(ret).__name__ == 'coroutine':
  832. ret = run_session(ret)
  833. self.process_retval(cmd,ret)
  834. if opt.profile:
  835. omsg('\r\033[50C{:.4f}'.format( time.time() - start ))
  836. if cmd == opt.exit_after:
  837. sys.exit(0)
  838. def warn_skipped(self):
  839. if self.skipped_warnings:
  840. print(yellow('The following tests were skipped and may require attention:'))
  841. r = '-' * 72 + '\n'
  842. print(r+('\n'+r).join(self.skipped_warnings))
  843. def process_retval(self,cmd,ret):
  844. if type(ret).__name__ == 'MMGenPexpect':
  845. ret.ok()
  846. self.cmd_total += 1
  847. elif ret == 'ok':
  848. ok()
  849. self.cmd_total += 1
  850. elif ret in ('skip','silent'):
  851. pass
  852. elif type(ret) == tuple and ret[0] == 'skip_warn':
  853. self.skipped_warnings.append(
  854. 'Test {!r} was skipped:\n {}'.format(cmd,'\n '.join(ret[1].split('\n'))))
  855. else:
  856. die(2,f'{cmd!r} returned {ret}')
  857. def check_deps(self,cmds): # TODO: broken
  858. if len(cmds) != 1:
  859. die(1,f'Usage: {g.prog_name} check_deps <command>')
  860. cmd = cmds[0]
  861. if cmd not in self.gm.cmd_list:
  862. die(1,f'{cmd!r}: unrecognized command')
  863. if not opt.quiet:
  864. omsg(f'Checking dependencies for {cmd!r}')
  865. self.check_needs_rerun(self.ts,cmd,build=False)
  866. w = max(map(len,self.rebuild_list)) + 1
  867. for cmd in self.rebuild_list:
  868. c = self.rebuild_list[cmd]
  869. m = 'Rebuild' if (c[0] and c[1]) else 'Build' if c[0] else 'OK'
  870. omsg('cmd {:<{w}} {}'.format( cmd+':', m, w=w ))
  871. def generate_file_deps(self,cmd):
  872. return [(str(n),e) for exts,n in self.gm.dpy_data[cmd][2] for e in exts]
  873. def generate_cmd_deps(self,fdeps):
  874. return [cfgs[str(n)]['dep_generators'][ext] for n,ext in fdeps]
  875. def get_num_exts_for_cmd(self,cmd,dpy=False): # dpy ignored here
  876. try:
  877. num = str(self.gm.dpy_data[cmd][0])
  878. except KeyError:
  879. qmsg_r(f'Missing dependency {cmd!r}')
  880. gname = self.gm.find_cmd_in_groups(cmd)
  881. if gname:
  882. kwargs = self.gm.cmd_groups[gname][1]
  883. kwargs.update({'add_dpy':True})
  884. self.gm.create_group(gname,**kwargs)
  885. num = str(self.gm.dpy_data[cmd][0])
  886. qmsg(f' found in group {gname!r}')
  887. else:
  888. qmsg(' not found in any command group!')
  889. raise
  890. dgl = cfgs[num]['dep_generators']
  891. if cmd in dgl.values():
  892. exts = [k for k in dgl if dgl[k] == cmd]
  893. return (num,exts)
  894. else:
  895. return None
  896. # main()
  897. if not skipping_deps: # do this before list cmds exit, so we stay in sync with shm_dir
  898. create_tmp_dirs(shm_dir)
  899. if opt.list_cmd_groups:
  900. CmdGroupMgr().list_cmd_groups()
  901. elif opt.list_cmds:
  902. list_cmds()
  903. elif usr_args and usr_args[0] in utils:
  904. globals()[usr_args[0]](*usr_args[1:])
  905. sys.exit(0)
  906. if opt.pause:
  907. set_restore_term_at_exit()
  908. set_environ_for_spawned_scripts()
  909. from mmgen.exception import TestSuiteException,TestSuiteFatalException
  910. try:
  911. tr = TestSuiteRunner(data_dir,trash_dir)
  912. tr.run_tests(usr_args)
  913. tr.warn_skipped()
  914. if network_id not in ('eth','etc','xmr'):
  915. stop_test_daemons(network_id)
  916. except KeyboardInterrupt:
  917. if network_id not in ('eth','etc','xmr'):
  918. stop_test_daemons(network_id)
  919. tr.warn_skipped()
  920. die(1,'\ntest.py exiting at user request')
  921. except TestSuiteException as e:
  922. die(2,e.args[0])
  923. except TestSuiteFatalException as e:
  924. die(4,e.args[0])
  925. except Exception:
  926. if 'exec_wrapper_init' in globals(): # test.py itself is running under exec_wrapper
  927. import traceback
  928. print(''.join(traceback.format_exception(*sys.exc_info())))
  929. msg(blue('Test script exited with error'))
  930. else:
  931. msg(blue('Spawned script exited with error'))
  932. raise
  933. except:
  934. raise