ct_cfgfile.py 9.4 KB

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