test.py 32 KB

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