objattrtest.py 5.4 KB

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