ct_cfgfile.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2024 The MMGen Project <mmgen@tuta.io>
  5. #
  6. # Project source code repository: https://github.com/mmgen/mmgen-wallet
  7. # Licensed according to the terms of GPL Version 3. See LICENSE for details.
  8. """
  9. test.cmdtest_py_d.ct_cfgfile: CfgFile tests for the MMGen cmdtest.py test suite
  10. """
  11. import sys,os,time,shutil
  12. from mmgen.color import yellow
  13. from mmgen.cfgfile import CfgFileSampleSys,CfgFileSampleUsr,cfg_file_sample
  14. from ..include.common import cfg,read_from_file,write_to_file,imsg
  15. from .ct_base import CmdTestBase
  16. class CmdTestCfgFile(CmdTestBase):
  17. 'CfgFile API'
  18. networks = ('btc',)
  19. tmpdir_nums = [40]
  20. base_passthru_opts = ()
  21. color = True
  22. cmd_group = (
  23. ('sysfile', (40,'init with system cfg sample file in place', [])),
  24. ('no_metadata_sample', (40,'init with unversioned cfg sample file', [])),
  25. ('altered_sample', (40,'init with user-modified cfg sample file', [])),
  26. ('old_sample', (40,'init with old v2 cfg sample file', [])),
  27. ('old_sample_bad_var', (40,'init with old v2 cfg sample file and bad variable in mmgen.cfg', [])),
  28. ('autoset_opts', (40,'setting autoset opts', [])),
  29. ('autoset_opts_cmdline', (40,'setting autoset opts (override on cmdline)', [])),
  30. ('autoset_opts_bad', (40,'setting autoset opts (bad value in cfg file)', [])),
  31. ('autoset_opts_bad_cmdline', (40,'setting autoset opts (bad param on cmdline)', [])),
  32. ('coin_specific_vars', (40,'setting coin-specific vars', [])),
  33. ('chain_names', (40,'setting chain names', [])),
  34. ('mnemonic_entry_modes', (40,'setting mnemonic entry modes', [])),
  35. )
  36. def __init__(self,trunner,cfgs,spawn):
  37. CmdTestBase.__init__(self,trunner,cfgs,spawn)
  38. self.spawn_env['MMGEN_TEST_SUITE_CFGTEST'] = '1'
  39. def spawn_test(self,args=[],extra_desc='',pexpect_spawn=None, exit_val=None):
  40. return self.spawn(
  41. 'test/misc/cfg.py',
  42. [f'--data-dir={self.path("data_dir")}'] + args,
  43. cmd_dir = '.',
  44. extra_desc = extra_desc,
  45. pexpect_spawn = pexpect_spawn,
  46. exit_val = exit_val)
  47. def path(self,id_str):
  48. return {
  49. 'ref': 'test/ref/mmgen.cfg',
  50. 'data_dir': '{}/data_dir'.format(self.tmpdir),
  51. 'shared_data': '{}/data_dir/{}'.format(self.tmpdir,CfgFileSampleSys.test_fn_subdir),
  52. 'usr': '{}/data_dir/mmgen.cfg'.format(self.tmpdir),
  53. 'sys': '{}/data_dir/{}/mmgen.cfg'.format(self.tmpdir,CfgFileSampleSys.test_fn_subdir),
  54. 'sample': '{}/data_dir/mmgen.cfg.sample'.format(os.path.abspath(self.tmpdir)),
  55. }[id_str]
  56. def copy_sys_sample(self):
  57. os.makedirs(self.path('shared_data'),exist_ok=True)
  58. shutil.copy2(self.path('ref'),self.path('sys'))
  59. def sysfile(self):
  60. self.copy_sys_sample()
  61. t = self.spawn_test()
  62. t.read()
  63. u = read_from_file(self.path('usr'))
  64. S = read_from_file(self.path('sys'))
  65. assert u[-1] == '\n', u
  66. assert u.replace('\r\n','\n') == S, 'u != S'
  67. self.check_replaced_sample()
  68. return t
  69. def check_replaced_sample(self):
  70. S = read_from_file(self.path('sys'))
  71. s = read_from_file(self.path('sample'))
  72. assert s[-1] == '\n', s
  73. assert S.splitlines() == s.splitlines()[:-1], 'sys != sample[:-1]'
  74. def bad_sample(self,s,e):
  75. write_to_file(self.path('sample'),s)
  76. t = self.spawn_test()
  77. t.expect(e)
  78. t.read()
  79. self.check_replaced_sample()
  80. return t
  81. def no_metadata_sample(self):
  82. self.copy_sys_sample()
  83. s = read_from_file(self.path('sys'))
  84. e = CfgFileSampleUsr.out_of_date_fs.format(self.path('sample'))
  85. return self.bad_sample(s,e)
  86. def altered_sample(self):
  87. s = '\n'.join(read_from_file(self.path('sample')).splitlines()[1:]) + '\n'
  88. e = CfgFileSampleUsr.altered_by_user_fs.format(self.path('sample'))
  89. return self.bad_sample(s,e)
  90. def old_sample_common(self,old_set=False,args=[],pexpect_spawn=False):
  91. s = read_from_file(self.path('sys'))
  92. d = s.replace('monero_','zcash_').splitlines()
  93. a1 = ['','# Uncomment to make foo true:','# foo true']
  94. a2 = ['','# Uncomment to make bar false:','# bar false']
  95. d = d + a1 + a2
  96. chk = cfg_file_sample.cls_make_metadata(d)
  97. write_to_file(self.path('sample'),'\n'.join(d+chk) + '\n')
  98. t = self.spawn_test(args=args, pexpect_spawn=pexpect_spawn, exit_val=1 if old_set else None)
  99. t.expect('options have changed')
  100. for s in ('have been added','monero_','have been removed','zcash_','foo','bar'):
  101. t.expect(s)
  102. if old_set:
  103. for s in ('must be deleted','bar','foo'):
  104. t.expect(s)
  105. cp = CfgFileSampleUsr.details_confirm_prompt + ' (y/N): '
  106. t.expect(cp,'y')
  107. for s in ('CHANGES','Removed','# zcash_','# foo','# bar','Added','# monero_'):
  108. t.expect(s)
  109. if t.pexpect_spawn: # view and exit pager
  110. time.sleep(1 if cfg.exact_output else t.send_delay)
  111. t.send('q')
  112. t.expect(cp,'n')
  113. if old_set:
  114. t.expect('unrecognized option')
  115. if args == ['parse_test']:
  116. t.expect('parsed chunks: 29')
  117. t.expect('usr cfg: testnet=true rpc_password=passwOrd')
  118. if not old_set:
  119. self.check_replaced_sample()
  120. return t
  121. def old_sample(self):
  122. d = ['testnet true','rpc_password passwOrd']
  123. write_to_file(self.path('usr'),'\n'.join(d) + '\n')
  124. return self.old_sample_common(args=['parse_test'])
  125. def old_sample_bad_var(self):
  126. d = ['foo true','bar false']
  127. write_to_file(self.path('usr'),'\n'.join(d) + '\n')
  128. t = self.old_sample_common(
  129. old_set = True,
  130. pexpect_spawn = not sys.platform == 'win32')
  131. t.expect('unrecognized option')
  132. return t
  133. def _autoset_opts(self, args=[], text='rpc_backend aiohttp\n', exit_val=None):
  134. write_to_file( self.path('usr'), text )
  135. imsg(yellow(f'Wrote cfg file:\n {text}'))
  136. return self.spawn_test(args=args, exit_val=exit_val)
  137. def autoset_opts(self):
  138. return self._autoset_opts(args=['autoset_opts'])
  139. def autoset_opts_cmdline(self):
  140. return self._autoset_opts(args=['--rpc-backend=curl','autoset_opts_cmdline'])
  141. def _autoset_opts_bad(self, expect, kwargs):
  142. t = self._autoset_opts(exit_val=1, **kwargs)
  143. t.expect(expect)
  144. return t
  145. def autoset_opts_bad(self):
  146. return self._autoset_opts_bad('not unique substring', {'text':'rpc_backend foo\n'})
  147. def autoset_opts_bad_cmdline(self):
  148. return self._autoset_opts_bad('not unique substring', {'args':['--rpc-backend=foo']})
  149. def coin_specific_vars(self):
  150. """
  151. ensure that derived classes explicitly set these variables
  152. """
  153. d = [
  154. 'btc_max_tx_fee 1.2345',
  155. 'eth_max_tx_fee 5.4321',
  156. 'btc_ignore_daemon_version true',
  157. 'eth_ignore_daemon_version true'
  158. ]
  159. write_to_file(self.path('usr'),'\n'.join(d) + '\n')
  160. imsg(yellow('Wrote cfg file:\n {}'.format('\n '.join(d))))
  161. for coin,res1_chk,res2_chk,res2_chk_eq in (
  162. ('BTC','True', '1.2345',True),
  163. ('LTC','False','1.2345',False),
  164. ('BCH','False','1.2345',False),
  165. ('ETH','True', '5.4321',True),
  166. ('ETC','False','5.4321',False)
  167. ):
  168. if cfg.no_altcoin and coin != 'BTC':
  169. continue
  170. t = self.spawn_test(
  171. args = [
  172. f'--coin={coin}',
  173. 'coin_specific_vars',
  174. 'ignore_daemon_version',
  175. 'max_tx_fee'
  176. ],
  177. extra_desc=f'({coin})' )
  178. res1 = t.expect_getend('ignore_daemon_version: ')
  179. res2 = t.expect_getend('max_tx_fee: ')
  180. assert res1 == res1_chk, f'{res1} != {res1_chk}'
  181. if res2_chk_eq:
  182. assert res2 == res2_chk, f'{res2} != {res2_chk}'
  183. else:
  184. assert res2 != res2_chk, f'{res2} == {res2_chk}'
  185. t.read()
  186. t.ok()
  187. t.skip_ok = True
  188. return t
  189. def mnemonic_entry_modes(self):
  190. def run(modes_chk):
  191. t = self.spawn_test(args=['mnemonic_entry_modes'])
  192. modes = t.expect_getend('mnemonic_entry_modes: ')
  193. assert modes_chk == modes, f'{modes_chk} != {modes}'
  194. return t
  195. txt = 'mnemonic_entry_modes mmgen:full bip39:short'
  196. write_to_file(self.path('usr'),txt+'\n')
  197. imsg(yellow(f'Wrote cfg file: {txt!r}'))
  198. t = run("{'mmgen': 'full', 'bip39': 'short'}")
  199. # check that set_dfl_entry_mode() set the mode correctly:
  200. t.expect('mmgen: full')
  201. t.expect('bip39: short')
  202. return t
  203. def chain_names(self):
  204. if cfg.no_altcoin:
  205. return 'skip'
  206. def run(chk,testnet):
  207. for coin,chain_chk in (('ETH',chk),('ETC',None)):
  208. t = self.spawn_test(
  209. args = [f'--coin={coin}',f'--testnet={(0,1)[testnet]}','coin_specific_vars','chain_names'],
  210. extra_desc = f'({coin} testnet={testnet!r:5} chain_names={chain_chk})' )
  211. chain = t.expect_getend('chain_names: ')
  212. if chain_chk:
  213. assert chain == chain_chk, f'{chain} != {chain_chk}'
  214. else:
  215. assert chain != chain_chk, f'{chain} == {chain_chk}'
  216. t.read()
  217. t.ok()
  218. return t
  219. txt = 'eth_mainnet_chain_names istanbul constantinople'
  220. write_to_file(self.path('usr'),txt+'\n')
  221. imsg(yellow(f'Wrote cfg file: {txt!r}'))
  222. t = run("['istanbul', 'constantinople']",False)
  223. t = run(None,True)
  224. txt = 'eth_testnet_chain_names rinkeby'
  225. write_to_file(self.path('usr'),txt+'\n')
  226. imsg(yellow(f'Wrote cfg file: {txt!r}'))
  227. t = run(None,False)
  228. t = run("['rinkeby']",True)
  229. t.skip_ok = True
  230. return t