test.py 29 KB

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