ct_cfgfile.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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):
  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. def path(self,id_str):
  47. return {
  48. 'ref': 'test/ref/mmgen.cfg',
  49. 'data_dir': '{}/data_dir'.format(self.tmpdir),
  50. 'shared_data': '{}/data_dir/{}'.format(self.tmpdir,CfgFileSampleSys.test_fn_subdir),
  51. 'usr': '{}/data_dir/mmgen.cfg'.format(self.tmpdir),
  52. 'sys': '{}/data_dir/{}/mmgen.cfg'.format(self.tmpdir,CfgFileSampleSys.test_fn_subdir),
  53. 'sample': '{}/data_dir/mmgen.cfg.sample'.format(os.path.abspath(self.tmpdir)),
  54. }[id_str]
  55. def copy_sys_sample(self):
  56. os.makedirs(self.path('shared_data'),exist_ok=True)
  57. shutil.copy2(self.path('ref'),self.path('sys'))
  58. def sysfile(self):
  59. self.copy_sys_sample()
  60. t = self.spawn_test()
  61. t.read()
  62. u = read_from_file(self.path('usr'))
  63. S = read_from_file(self.path('sys'))
  64. assert u[-1] == '\n', u
  65. assert u.replace('\r\n','\n') == S, 'u != S'
  66. self.check_replaced_sample()
  67. return t
  68. def check_replaced_sample(self):
  69. S = read_from_file(self.path('sys'))
  70. s = read_from_file(self.path('sample'))
  71. assert s[-1] == '\n', s
  72. assert S.splitlines() == s.splitlines()[:-1], 'sys != sample[:-1]'
  73. def bad_sample(self,s,e):
  74. write_to_file(self.path('sample'),s)
  75. t = self.spawn_test()
  76. t.expect(e)
  77. t.read()
  78. self.check_replaced_sample()
  79. return t
  80. def no_metadata_sample(self):
  81. self.copy_sys_sample()
  82. s = read_from_file(self.path('sys'))
  83. e = CfgFileSampleUsr.out_of_date_fs.format(self.path('sample'))
  84. return self.bad_sample(s,e)
  85. def altered_sample(self):
  86. s = '\n'.join(read_from_file(self.path('sample')).splitlines()[1:]) + '\n'
  87. e = CfgFileSampleUsr.altered_by_user_fs.format(self.path('sample'))
  88. return self.bad_sample(s,e)
  89. def old_sample_common(self,old_set=False,args=[],pexpect_spawn=False):
  90. s = read_from_file(self.path('sys'))
  91. d = s.replace('monero_','zcash_').splitlines()
  92. a1 = ['','# Uncomment to make foo true:','# foo true']
  93. a2 = ['','# Uncomment to make bar false:','# bar false']
  94. d = d + a1 + a2
  95. chk = cfg_file_sample.cls_make_metadata(d)
  96. write_to_file(self.path('sample'),'\n'.join(d+chk) + '\n')
  97. t = self.spawn_test(args=args,pexpect_spawn=pexpect_spawn)
  98. t.expect('options have changed')
  99. for s in ('have been added','monero_','have been removed','zcash_','foo','bar'):
  100. t.expect(s)
  101. if old_set:
  102. for s in ('must be deleted','bar','foo'):
  103. t.expect(s)
  104. cp = CfgFileSampleUsr.details_confirm_prompt + ' (y/N): '
  105. t.expect(cp,'y')
  106. for s in ('CHANGES','Removed','# zcash_','# foo','# bar','Added','# monero_'):
  107. t.expect(s)
  108. if t.pexpect_spawn: # view and exit pager
  109. time.sleep(1 if cfg.exact_output else t.send_delay)
  110. t.send('q')
  111. t.expect(cp,'n')
  112. if old_set:
  113. t.expect('unrecognized option')
  114. t.req_exit_val = 1
  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. return self.old_sample_common(
  129. old_set = True,
  130. pexpect_spawn = not sys.platform == 'win32')
  131. def _autoset_opts(self,args=[],text='rpc_backend aiohttp\n'):
  132. write_to_file( self.path('usr'), text )
  133. imsg(yellow(f'Wrote cfg file:\n {text}'))
  134. return self.spawn_test(args=args)
  135. def autoset_opts(self):
  136. return self._autoset_opts(args=['autoset_opts'])
  137. def autoset_opts_cmdline(self):
  138. return self._autoset_opts(args=['--rpc-backend=curl','autoset_opts_cmdline'])
  139. def _autoset_opts_bad(self,kwargs):
  140. t = self._autoset_opts(**kwargs)
  141. t.req_exit_val = 1
  142. return t
  143. def autoset_opts_bad(self):
  144. return self._autoset_opts_bad({'text':'rpc_backend foo\n'})
  145. def autoset_opts_bad_cmdline(self):
  146. return self._autoset_opts_bad({'args':['--rpc-backend=foo']})
  147. def coin_specific_vars(self):
  148. """
  149. ensure that derived classes explicitly set these variables
  150. """
  151. d = [
  152. 'btc_max_tx_fee 1.2345',
  153. 'eth_max_tx_fee 5.4321',
  154. 'btc_ignore_daemon_version true',
  155. 'eth_ignore_daemon_version true'
  156. ]
  157. write_to_file(self.path('usr'),'\n'.join(d) + '\n')
  158. imsg(yellow('Wrote cfg file:\n {}'.format('\n '.join(d))))
  159. for coin,res1_chk,res2_chk,res2_chk_eq in (
  160. ('BTC','True', '1.2345',True),
  161. ('LTC','False','1.2345',False),
  162. ('BCH','False','1.2345',False),
  163. ('ETH','True', '5.4321',True),
  164. ('ETC','False','5.4321',False)
  165. ):
  166. if cfg.no_altcoin and coin != 'BTC':
  167. continue
  168. t = self.spawn_test(
  169. args = [
  170. f'--coin={coin}',
  171. 'coin_specific_vars',
  172. 'ignore_daemon_version',
  173. 'max_tx_fee'
  174. ],
  175. extra_desc=f'({coin})' )
  176. res1 = t.expect_getend('ignore_daemon_version: ')
  177. res2 = t.expect_getend('max_tx_fee: ')
  178. assert res1 == res1_chk, f'{res1} != {res1_chk}'
  179. if res2_chk_eq:
  180. assert res2 == res2_chk, f'{res2} != {res2_chk}'
  181. else:
  182. assert res2 != res2_chk, f'{res2} == {res2_chk}'
  183. t.read()
  184. t.ok()
  185. t.skip_ok = True
  186. return t
  187. def mnemonic_entry_modes(self):
  188. def run(modes_chk):
  189. t = self.spawn_test(args=['mnemonic_entry_modes'])
  190. modes = t.expect_getend('mnemonic_entry_modes: ')
  191. assert modes_chk == modes, f'{modes_chk} != {modes}'
  192. return t
  193. txt = 'mnemonic_entry_modes mmgen:full bip39:short'
  194. write_to_file(self.path('usr'),txt+'\n')
  195. imsg(yellow(f'Wrote cfg file: {txt!r}'))
  196. t = run("{'mmgen': 'full', 'bip39': 'short'}")
  197. # check that set_dfl_entry_mode() set the mode correctly:
  198. t.expect('mmgen: full')
  199. t.expect('bip39: short')
  200. return t
  201. def chain_names(self):
  202. if cfg.no_altcoin:
  203. return 'skip'
  204. def run(chk,testnet):
  205. for coin,chain_chk in (('ETH',chk),('ETC',None)):
  206. t = self.spawn_test(
  207. args = [f'--coin={coin}',f'--testnet={(0,1)[testnet]}','coin_specific_vars','chain_names'],
  208. extra_desc = f'({coin} testnet={testnet!r:5} chain_names={chain_chk})' )
  209. chain = t.expect_getend('chain_names: ')
  210. if chain_chk:
  211. assert chain == chain_chk, f'{chain} != {chain_chk}'
  212. else:
  213. assert chain != chain_chk, f'{chain} == {chain_chk}'
  214. t.read()
  215. t.ok()
  216. return t
  217. txt = 'eth_mainnet_chain_names istanbul constantinople'
  218. write_to_file(self.path('usr'),txt+'\n')
  219. imsg(yellow(f'Wrote cfg file: {txt!r}'))
  220. t = run("['istanbul', 'constantinople']",False)
  221. t = run(None,True)
  222. txt = 'eth_testnet_chain_names rinkeby'
  223. write_to_file(self.path('usr'),txt+'\n')
  224. imsg(yellow(f'Wrote cfg file: {txt!r}'))
  225. t = run(None,False)
  226. t = run("['rinkeby']",True)
  227. t.skip_ok = True
  228. return t