objtest.py 5.5 KB

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