test.py 27 KB

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