objtest.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2020 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. -q, --quiet Produce quieter output
  40. -s, --silent Silence output of tested objects
  41. -S, --super-silent Silence all output except for errors
  42. -v, --verbose Produce more verbose output
  43. """
  44. }
  45. }
  46. cmd_args = opts.init(opts_data)
  47. def run_test(test,arg,input_data):
  48. arg_copy = arg
  49. kwargs = {'on_fail':'silent'} if opt.silent else {'on_fail':'die'}
  50. ret_chk = arg
  51. exc_type = None
  52. if input_data == 'good' and type(arg) == tuple: arg,ret_chk = arg
  53. if type(arg) == dict: # pass one arg + kwargs to constructor
  54. arg_copy = arg.copy()
  55. if 'arg' in arg:
  56. args = [arg['arg']]
  57. ret_chk = args[0]
  58. del arg['arg']
  59. else:
  60. args = []
  61. ret_chk = list(arg.values())[0] # assume only one key present
  62. if 'ret' in arg:
  63. ret_chk = arg['ret']
  64. del arg['ret']
  65. del arg_copy['ret']
  66. if 'ExcType' in arg:
  67. exc_type = arg['ExcType']
  68. del arg['ExcType']
  69. del arg_copy['ExcType']
  70. kwargs.update(arg)
  71. elif type(arg) == tuple:
  72. args = arg
  73. else:
  74. args = [arg]
  75. try:
  76. if not opt.super_silent:
  77. arg_disp = repr(arg_copy[0] if type(arg_copy) == tuple else arg_copy)
  78. msg_r((orange,green)[input_data=='good']('{:<22}'.format(arg_disp+':')))
  79. cls = globals()[test]
  80. ret = cls(*args,**kwargs)
  81. bad_ret = list() if issubclass(cls,list) else None
  82. if isinstance(ret_chk,str): ret_chk = ret_chk.encode()
  83. if isinstance(ret,str): ret = ret.encode()
  84. if (opt.silent and input_data=='bad' and ret!=bad_ret) or (not opt.silent and input_data=='bad'):
  85. raise UserWarning("Non-'None' return value {} with bad input data".format(repr(ret)))
  86. if opt.silent and input_data=='good' and ret==bad_ret:
  87. raise UserWarning("'None' returned with good input data")
  88. if input_data=='good' and ret != ret_chk and repr(ret) != repr(ret_chk):
  89. raise UserWarning("Return value ({!r}) doesn't match expected value ({!r})".format(ret,ret_chk))
  90. if not opt.super_silent:
  91. try: ret_disp = ret.decode()
  92. except: ret_disp = ret
  93. msg('==> {!r}'.format(ret_disp))
  94. if opt.verbose and issubclass(cls,MMGenObject):
  95. ret.pmsg() if hasattr(ret,'pmsg') else pmsg(ret)
  96. except Exception as e:
  97. if not type(e).__name__ == exc_type:
  98. raise
  99. if not opt.super_silent:
  100. msg_r(' {}'.format(yellow(exc_type+':')))
  101. msg(e.args[0])
  102. except SystemExit as e:
  103. if input_data == 'good':
  104. raise ValueError('Error on good input data')
  105. if opt.verbose:
  106. msg('exitval: {}'.format(e.code))
  107. except UserWarning as e:
  108. msg('==> {!r}'.format(ret))
  109. die(2,red('{}'.format(e.args[0])))
  110. def do_loop():
  111. import importlib
  112. modname = 'test.objtest_py_d.ot_{}_{}'.format(g.coin.lower(),g.network)
  113. test_data = importlib.import_module(modname).tests
  114. gmsg('Running data object tests for {} {}'.format(g.coin,g.network))
  115. clr = None
  116. utests = cmd_args
  117. for test in test_data:
  118. if utests and test not in utests: continue
  119. nl = ('\n','')[bool(opt.super_silent) or clr == None]
  120. clr = (blue,nocolor)[bool(opt.super_silent)]
  121. msg(clr('{}Testing {}'.format(nl,test)))
  122. for k in ('bad','good'):
  123. if not opt.silent:
  124. msg(purple(capfirst(k)+' input:'))
  125. for arg in test_data[test][k]:
  126. run_test(test,arg,input_data=k)
  127. do_loop()