objattrtest.py 5.4 KB

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