test.py 32 KB

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