test.py 29 KB

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