objtest.py 5.8 KB

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