test.py 27 KB

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