objtest.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. #!/usr/bin/env python3
  2. #
  3. # MMGen Wallet, a terminal-based cryptocurrency wallet
  4. # Copyright (C)2013-2025 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/objtest.py: Test MMGen data objects
  20. """
  21. import os, re
  22. try:
  23. from include import test_init
  24. except ImportError:
  25. from test.include import test_init
  26. # for objtest, violate MMGen Project best practices and allow use of the dev tools
  27. # in production code:
  28. from mmgen.devtools import pmsg
  29. if not os.getenv('MMGEN_DEVTOOLS'):
  30. from mmgen.devinit import init_dev
  31. init_dev()
  32. from mmgen.cfg import Config
  33. from mmgen.util import msg, msg_r, gmsg, capfirst, die
  34. from mmgen.color import red, yellow, blue, green, orange, purple, gray, nocolor
  35. from mmgen.obj import get_obj
  36. opts_data = {
  37. 'sets': [('super_silent', True, 'silent', True)],
  38. 'text': {
  39. 'desc': 'Test MMGen data objects',
  40. 'usage':'[options] [object]',
  41. 'options': """
  42. -h, --help Print this help message
  43. --, --longhelp Print help message for long (global) options
  44. -g, --getobj Instantiate objects with get_obj() wrapper
  45. -q, --quiet Produce quieter output
  46. -s, --silent Silence output of tested objects
  47. -S, --super-silent Silence all output except for errors
  48. -v, --verbose Produce more verbose output
  49. """
  50. }
  51. }
  52. cfg = Config(opts_data=opts_data)
  53. if cfg.verbose:
  54. from mmgen.objmethods import MMGenObject
  55. from test.include.common import set_globals
  56. set_globals(cfg)
  57. def run_test(mod, test, arg, input_data, arg1, exc_name):
  58. arg_copy, ret_chk, ret_idx, kwargs = (arg, arg, None, {})
  59. if input_data == 'good' and isinstance(arg, tuple):
  60. arg, ret_chk = arg
  61. if isinstance(arg, dict): # pass one arg + kwargs to constructor
  62. arg_copy = arg.copy()
  63. if 'arg' in arg:
  64. args = [arg['arg']]
  65. ret_chk = args[0]
  66. del arg['arg']
  67. else:
  68. args = []
  69. ret_chk = list(arg.values())[0] # assume only one key present
  70. if 'ret' in arg:
  71. ret_chk = arg['ret']
  72. del arg['ret']
  73. del arg_copy['ret']
  74. if 'exc_name' in arg:
  75. exc_name = arg['exc_name']
  76. del arg['exc_name']
  77. del arg_copy['exc_name']
  78. if 'ret_idx' in arg:
  79. ret_idx = arg['ret_idx']
  80. del arg['ret_idx']
  81. del arg_copy['ret_idx']
  82. kwargs.update(arg)
  83. elif isinstance(arg, tuple):
  84. args = arg
  85. else:
  86. args = [arg]
  87. if cfg.getobj:
  88. if args:
  89. assert len(args) == 1, 'objtest_chk1: only one positional arg is allowed'
  90. kwargs.update( { arg1: args[0] } )
  91. if cfg.silent:
  92. kwargs.update( { 'silent': True } )
  93. try:
  94. if not cfg.super_silent:
  95. arg_disp = repr(arg_copy[0] if isinstance(arg_copy, tuple) else arg_copy)
  96. if cfg.test_suite_deterministic and isinstance(arg_copy, dict):
  97. arg_disp = re.sub(r'object at 0x[0-9a-f]+', 'object at [SCRUBBED]', arg_disp)
  98. msg_r((green if input_data=='good' else orange)(f'{arg_disp+":":<22}'))
  99. cls = getattr(mod, test)
  100. if cfg.getobj:
  101. ret = get_obj(getattr(mod, test), **kwargs)
  102. else:
  103. ret = cls(*args, **kwargs)
  104. bad_ret = [] if issubclass(cls, list) else None
  105. if isinstance(ret_chk, str):
  106. ret_chk = ret_chk.encode()
  107. if isinstance(ret, str):
  108. ret = ret.encode()
  109. if cfg.getobj:
  110. if input_data == 'bad':
  111. assert ret is False, 'non-False return on bad input data'
  112. else:
  113. if (cfg.silent and input_data=='bad' and ret!=bad_ret) or (not cfg.silent and input_data=='bad'):
  114. raise UserWarning(f"Non-'None' return value {ret!r} with bad input data")
  115. if cfg.silent and input_data=='good' and ret==bad_ret:
  116. raise UserWarning("'None' returned with good input data")
  117. if input_data=='good':
  118. if ret_idx:
  119. ret_chk = arg[list(arg.keys())[ret_idx]].encode()
  120. if ret != ret_chk and repr(ret) != repr(ret_chk):
  121. raise UserWarning(f"Return value ({ret!r}) doesn't match expected value ({ret_chk!r})")
  122. if cfg.super_silent:
  123. return
  124. if cfg.getobj and (not cfg.silent and input_data == 'bad'):
  125. pass
  126. else:
  127. try:
  128. ret_disp = ret.decode()
  129. except:
  130. ret_disp = ret
  131. msg(f'==> {ret_disp!r}')
  132. if cfg.verbose and issubclass(cls, MMGenObject):
  133. ret.pmsg() if hasattr(ret, 'pmsg') else pmsg(ret)
  134. except UserWarning as e:
  135. msg(f'==> {ret!r}')
  136. die(2, red(str(e)))
  137. except Exception as e:
  138. if input_data == 'good':
  139. raise ValueError(f'Error on good input data: {e}') from e
  140. if not type(e).__name__ == exc_name:
  141. msg(f'Incorrect exception: expected {exc_name} but got {type(e).__name__}')
  142. raise
  143. if cfg.super_silent:
  144. pass
  145. elif cfg.silent:
  146. msg(f'==> {exc_name}')
  147. else:
  148. msg( yellow(f' {exc_name}:') + str(e) )
  149. except SystemExit as e:
  150. if input_data == 'good':
  151. raise ValueError('Error on good input data') from e
  152. if cfg.verbose:
  153. msg(f'exitval: {e.code}')
  154. def do_loop():
  155. import importlib
  156. modname = f'test.objtest_d.{proto.coin.lower()}_{proto.network}'
  157. mod = importlib.import_module(modname)
  158. test_data = getattr(mod, 'tests')
  159. gmsg(f'Running data object tests for {proto.coin} {proto.network}')
  160. clr = None
  161. utests = cfg._args
  162. for test in test_data:
  163. arg1 = test_data[test].get('arg1')
  164. if utests and test not in utests:
  165. continue
  166. nl = ('\n', '')[bool(cfg.super_silent) or clr is None]
  167. clr = (blue, nocolor)[bool(cfg.super_silent)]
  168. if cfg.getobj and arg1 is None:
  169. msg(gray(f'{nl}Skipping {test}'))
  170. continue
  171. msg(clr(f'{nl}Testing {test}'))
  172. for k in ('bad', 'good'):
  173. if not cfg.super_silent:
  174. msg(purple(capfirst(k)+' input:'))
  175. for arg in test_data[test][k]:
  176. run_test(
  177. mod,
  178. test,
  179. arg,
  180. input_data = k,
  181. arg1 = arg1,
  182. exc_name = test_data[test].get('exc_name') or ('ObjectInitError', 'None')[k=='good'])
  183. proto = cfg._proto
  184. if __name__ == '__main__':
  185. do_loop()