objattrtest.py 5.4 KB

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