test.py 27 KB

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