objattrtest.py 5.4 KB

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