test.py 27 KB

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