ct_cfgfile.py 8.8 KB

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