test.py 32 KB

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