test.py 31 KB

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