objattrtest.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  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 collections import namedtuple
  24. import include.test_init
  25. from mmgen.cfg import Config
  26. from mmgen.util import msg,msg_r,gmsg,die
  27. from mmgen.color import red,yellow,green,blue,purple,nocolor
  28. from mmgen.obj import ImmutableAttr,ListItemAttr
  29. opts_data = {
  30. 'sets': [
  31. ('show_descriptor_type', True, 'verbose', True),
  32. ],
  33. 'text': {
  34. 'desc': 'Test immutable attributes of 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. -d, --show-descriptor-type Display the attribute's descriptor type
  40. -v, --verbose Produce more verbose output
  41. """
  42. }
  43. }
  44. cfg = Config(opts_data=opts_data)
  45. from test.include.common import set_globals
  46. set_globals(cfg)
  47. from test.objattrtest_py_d.oat_common import sample_objs
  48. pd = namedtuple('attr_bits', ['read_ok','delete_ok','reassign_ok','typeconv','set_none_ok'])
  49. perm_bits = ('read_ok','delete_ok','reassign_ok')
  50. attr_dfls = {
  51. 'reassign_ok': False,
  52. 'delete_ok': False,
  53. 'typeconv': True,
  54. 'set_none_ok': False,
  55. }
  56. def parse_attrbits(bits):
  57. return pd(
  58. bool(0b00001 & bits), # read
  59. bool(0b00010 & bits), # delete
  60. bool(0b00100 & bits), # reassign
  61. bool(0b01000 & bits), # typeconv
  62. bool(0b10000 & bits), # set_none
  63. )
  64. def get_descriptor_obj(objclass,attrname):
  65. for o in (objclass,objclass.__bases__[0]): # assume there's only one base class
  66. if attrname in o.__dict__:
  67. return o.__dict__[attrname]
  68. die(4,f'unable to find descriptor {objclass.__name__}.{attrname}')
  69. def test_attr_perm(obj,attrname,perm_name,perm_value,dobj,attrval_type):
  70. class SampleObjError(Exception):
  71. pass
  72. pname = perm_name.replace('_ok','')
  73. pstem = pname.rstrip('e')
  74. try:
  75. if perm_name == 'read_ok': # non-existent perm
  76. getattr(obj,attrname)
  77. elif perm_name == 'reassign_ok':
  78. try:
  79. so = sample_objs[attrval_type.__name__]
  80. except:
  81. raise SampleObjError(f'unable to find sample object of type {attrval_type.__name__!r}')
  82. # ListItemAttr allows setting an attribute if its value is None
  83. if type(dobj) == ListItemAttr and getattr(obj,attrname) == None:
  84. setattr(obj,attrname,so)
  85. setattr(obj,attrname,so)
  86. elif perm_name == 'delete_ok':
  87. delattr(obj,attrname)
  88. except SampleObjError as e:
  89. die(4,f'Test script error ({e})')
  90. except Exception as e:
  91. if perm_value == True:
  92. fs = '{!r}: unable to {} attribute {!r}, though {}ing is allowed ({})'
  93. die(4,fs.format(type(obj).__name__,pname,attrname,pstem,e))
  94. else:
  95. if perm_value == False:
  96. fs = '{!r}: attribute {!r} is {n}able, though {n}ing is forbidden'
  97. die(4,fs.format(type(obj).__name__,attrname,n=pstem))
  98. def test_attr(data,obj,attrname,dobj,bits,attrval_type):
  99. if hasattr(obj,attrname): # TODO
  100. td_attrval_type = data.attrs[attrname][1]
  101. if attrval_type not in (td_attrval_type,type(None)):
  102. fs = '\nattribute {!r} of {!r} instance has incorrect type {!r} (should be {!r})'
  103. die(4,fs.format(attrname,type(obj).__name__,attrval_type.__name__,td_attrval_type.__name__))
  104. if hasattr(dobj,'__dict__'):
  105. d = dobj.__dict__
  106. bits = bits._asdict()
  107. colors = {
  108. 'reassign_ok': purple,
  109. 'delete_ok': red,
  110. 'typeconv': green,
  111. 'set_none_ok': yellow,
  112. }
  113. for k in bits:
  114. if k in d:
  115. if d[k] != bits[k]:
  116. fs = 'init value {iv}={a} for attr {n!r} does not match test data ({iv}={b})'
  117. die(4,fs.format(iv=k,n=attrname,a=d[k],b=bits[k]))
  118. if cfg.verbose and d[k] != attr_dfls[k]:
  119. msg_r(colors[k](f' {k}={d[k]!r}'))
  120. def test_object(mod,test_data,objname):
  121. if '.' in objname:
  122. on1,on2 = objname.split('.')
  123. cls = getattr(getattr(mod,on1),on2)
  124. else:
  125. cls = getattr(mod,objname)
  126. fs = 'Testing attribute ' + ('{!r:<15}{dt:13}' if cfg.show_descriptor_type else '{!r}')
  127. data = test_data[objname]
  128. obj = cls(*data.args,**data.kwargs)
  129. for attrname,adata in data.attrs.items():
  130. dobj = get_descriptor_obj(type(obj),attrname)
  131. if cfg.verbose:
  132. msg_r(fs.format(attrname,dt=type(dobj).__name__.replace('MMGen','')))
  133. bits = parse_attrbits(adata[0])
  134. test_attr(data,obj,attrname,dobj,bits,adata[1])
  135. for bit_name,bit_value in bits._asdict().items():
  136. if bit_name in perm_bits:
  137. test_attr_perm(obj,attrname,bit_name,bit_value,dobj,adata[1])
  138. cfg._util.vmsg('')
  139. def do_loop():
  140. import importlib
  141. modname = f'test.objattrtest_py_d.oat_{proto.coin.lower()}_{proto.network}'
  142. mod = importlib.import_module(modname)
  143. test_data = getattr(mod,'tests')
  144. gmsg(f'Running immutable attribute tests for {proto.coin} {proto.network}')
  145. utests = cfg._args
  146. for obj in test_data:
  147. if utests and obj not in utests:
  148. continue
  149. msg((blue if cfg.verbose else nocolor)(f'Testing {obj}'))
  150. test_object(mod,test_data,obj)
  151. proto = cfg._proto
  152. do_loop()