objattrtest.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2023 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/objattrtest.py: Test immutable attributes of MMGen data objects
  20. """
  21. # TODO: test 'typeconv' during instance creation
  22. import sys,os
  23. pn = os.path.dirname(sys.argv[0])
  24. os.chdir(os.path.join(pn,os.pardir))
  25. sys.path.__setitem__(0,os.path.abspath(os.curdir))
  26. os.environ['MMGEN_TEST_SUITE'] = '1'
  27. # Import these _after_ local path's been added to sys.path
  28. from mmgen.common import *
  29. from mmgen.addrlist import *
  30. from mmgen.passwdlist import *
  31. from mmgen.tx.base import Base
  32. from mmgen.proto.btc.tw.unspent import BitcoinTwUnspentOutputs
  33. opts_data = {
  34. 'sets': [
  35. ('show_nonstandard_init', True, 'verbose', True),
  36. ('show_descriptor_type', True, 'verbose', True),
  37. ],
  38. 'text': {
  39. 'desc': 'Test immutable attributes of MMGen data objects',
  40. 'usage':'[options] [object]',
  41. 'options': """
  42. -h, --help Print this help message
  43. --, --longhelp Print help message for long options (common options)
  44. -i, --show-nonstandard-init Display non-standard attribute initialization info
  45. -d, --show-descriptor-type Display the attribute's descriptor type
  46. -v, --verbose Produce more verbose output
  47. """
  48. }
  49. }
  50. cfg = Config(opts_data=opts_data)
  51. from test.include.common import set_globals
  52. set_globals(cfg)
  53. from test.objattrtest_py_d.oat_common import *
  54. pd = namedtuple('permission_bits', ['read_ok','delete_ok','reassign_ok'])
  55. def parse_permbits(bits):
  56. return pd(
  57. bool(0b001 & bits), # read
  58. bool(0b010 & bits), # delete
  59. bool(0b100 & bits), # reassign
  60. )
  61. def get_descriptor_obj(objclass,attrname):
  62. for o in (objclass,objclass.__bases__[0]): # assume there's only one base class
  63. if attrname in o.__dict__:
  64. return o.__dict__[attrname]
  65. die(4,f'unable to find descriptor {objclass.__name__}.{attrname}')
  66. def test_attr_perm(obj,attrname,perm_name,perm_value,dobj,attrval_type):
  67. class SampleObjError(Exception): pass
  68. pname = perm_name.replace('_ok','')
  69. pstem = pname.rstrip('e')
  70. try:
  71. if perm_name == 'read_ok':
  72. getattr(obj,attrname)
  73. elif perm_name == 'reassign_ok':
  74. try:
  75. so = sample_objs[attrval_type.__name__]
  76. except:
  77. die( 'SampleObjError', f'unable to find sample object of type {attrval_type.__name__!r}' )
  78. # ListItemAttr allows setting an attribute if its value is None
  79. if type(dobj) == ListItemAttr and getattr(obj,attrname) == None:
  80. setattr(obj,attrname,so)
  81. setattr(obj,attrname,so)
  82. elif perm_name == 'delete_ok':
  83. delattr(obj,attrname)
  84. except SampleObjError as e:
  85. die(4,f'Test script error ({e})')
  86. except Exception as e:
  87. if perm_value == True:
  88. fs = '{!r}: unable to {} attribute {!r}, though {}ing is allowed ({})'
  89. die(4,fs.format(type(obj).__name__,pname,attrname,pstem,e))
  90. else:
  91. if perm_value == False:
  92. fs = '{!r}: attribute {!r} is {n}able, though {n}ing is forbidden'
  93. die(4,fs.format(type(obj).__name__,attrname,n=pstem))
  94. def test_attr(data,obj,attrname,dobj,bits,attrval_type):
  95. if hasattr(obj,attrname): # TODO
  96. td_attrval_type = data.attrs[attrname][1]
  97. if attrval_type not in (td_attrval_type,type(None)):
  98. fs = '\nattribute {!r} of {!r} instance has incorrect type {!r} (should be {!r})'
  99. die(4,fs.format(attrname,type(obj).__name__,attrval_type.__name__,td_attrval_type.__name__))
  100. if hasattr(dobj,'__dict__'):
  101. d = dobj.__dict__
  102. bits = bits._asdict()
  103. for k in ('reassign_ok','delete_ok'):
  104. if k in d:
  105. if d[k] != bits[k]:
  106. fs = 'init value {iv}={a} for attr {n!r} does not match test data ({iv}={b})'
  107. die(4,fs.format(iv=k,n=attrname,a=d[k],b=bits[k]))
  108. if cfg.verbose and d[k] == True:
  109. msg_r(f' {k}={d[k]!r}')
  110. if cfg.show_nonstandard_init:
  111. for k,v in (('typeconv',False),('set_none_ok',True)):
  112. if d[k] == v:
  113. msg_r(f' {k}={v}')
  114. def test_object(test_data,objname):
  115. if '.' in objname:
  116. on1,on2 = objname.split('.')
  117. cls = getattr(globals()[on1],on2)
  118. else:
  119. cls = globals()[objname]
  120. fs = 'Testing attribute ' + ('{!r:<15}{dt:13}' if cfg.show_descriptor_type else '{!r}')
  121. data = test_data[objname]
  122. obj = cls(*data.args,**data.kwargs)
  123. for attrname,adata in data.attrs.items():
  124. dobj = get_descriptor_obj(type(obj),attrname)
  125. if cfg.verbose:
  126. msg_r(fs.format(attrname,dt=type(dobj).__name__.replace('MMGen','')))
  127. bits = parse_permbits(adata[0])
  128. test_attr(data,obj,attrname,dobj,bits,adata[1])
  129. for perm_name,perm_value in bits._asdict().items():
  130. test_attr_perm(obj,attrname,perm_name,perm_value,dobj,adata[1])
  131. cfg._util.vmsg('')
  132. def do_loop():
  133. import importlib
  134. modname = f'test.objattrtest_py_d.oat_{proto.coin.lower()}_{proto.network}'
  135. test_data = importlib.import_module(modname).tests
  136. gmsg(f'Running immutable attribute tests for {proto.coin} {proto.network}')
  137. utests = cfg._args
  138. for obj in test_data:
  139. if utests and obj not in utests: continue
  140. msg((blue if cfg.verbose else nocolor)(f'Testing {obj}'))
  141. test_object(test_data,obj)
  142. proto = cfg._proto
  143. do_loop()