test.py 29 KB

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