test.py 31 KB

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