Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

verify.py 7.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. ##############################################################################
  2. #
  3. # Copyright (c) 2001, 2002 Zope Foundation and Contributors.
  4. # All Rights Reserved.
  5. #
  6. # This software is subject to the provisions of the Zope Public License,
  7. # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
  8. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
  9. # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  10. # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
  11. # FOR A PARTICULAR PURPOSE.
  12. #
  13. ##############################################################################
  14. """Verify interface implementations
  15. """
  16. import inspect
  17. import sys
  18. from types import FunctionType
  19. from types import MethodType
  20. from zope.interface.exceptions import BrokenImplementation
  21. from zope.interface.exceptions import BrokenMethodImplementation
  22. from zope.interface.exceptions import DoesNotImplement
  23. from zope.interface.exceptions import Invalid
  24. from zope.interface.exceptions import MultipleInvalid
  25. from zope.interface.interface import fromMethod, fromFunction, Method
  26. __all__ = [
  27. 'verifyObject',
  28. 'verifyClass',
  29. ]
  30. # This will be monkey-patched when running under Zope 2, so leave this
  31. # here:
  32. MethodTypes = (MethodType, )
  33. def _verify(iface, candidate, tentative=False, vtype=None):
  34. """
  35. Verify that *candidate* might correctly provide *iface*.
  36. This involves:
  37. - Making sure the candidate claims that it provides the
  38. interface using ``iface.providedBy`` (unless *tentative* is `True`,
  39. in which case this step is skipped). This means that the candidate's class
  40. declares that it `implements <zope.interface.implementer>` the interface,
  41. or the candidate itself declares that it `provides <zope.interface.provider>`
  42. the interface
  43. - Making sure the candidate defines all the necessary methods
  44. - Making sure the methods have the correct signature (to the
  45. extent possible)
  46. - Making sure the candidate defines all the necessary attributes
  47. :return bool: Returns a true value if everything that could be
  48. checked passed.
  49. :raises zope.interface.Invalid: If any of the previous
  50. conditions does not hold.
  51. .. versionchanged:: 5.0
  52. If multiple methods or attributes are invalid, all such errors
  53. are collected and reported. Previously, only the first error was reported.
  54. As a special case, if only one such error is present, it is raised
  55. alone, like before.
  56. """
  57. if vtype == 'c':
  58. tester = iface.implementedBy
  59. else:
  60. tester = iface.providedBy
  61. excs = []
  62. if not tentative and not tester(candidate):
  63. excs.append(DoesNotImplement(iface, candidate))
  64. for name, desc in iface.namesAndDescriptions(all=True):
  65. try:
  66. _verify_element(iface, name, desc, candidate, vtype)
  67. except Invalid as e:
  68. excs.append(e)
  69. if excs:
  70. if len(excs) == 1:
  71. raise excs[0]
  72. raise MultipleInvalid(iface, candidate, excs)
  73. return True
  74. def _verify_element(iface, name, desc, candidate, vtype):
  75. # Here the `desc` is either an `Attribute` or `Method` instance
  76. try:
  77. attr = getattr(candidate, name)
  78. except AttributeError:
  79. if (not isinstance(desc, Method)) and vtype == 'c':
  80. # We can't verify non-methods on classes, since the
  81. # class may provide attrs in it's __init__.
  82. return
  83. # TODO: This should use ``raise...from``
  84. raise BrokenImplementation(iface, desc, candidate)
  85. if not isinstance(desc, Method):
  86. # If it's not a method, there's nothing else we can test
  87. return
  88. if inspect.ismethoddescriptor(attr) or inspect.isbuiltin(attr):
  89. # The first case is what you get for things like ``dict.pop``
  90. # on CPython (e.g., ``verifyClass(IFullMapping, dict))``). The
  91. # second case is what you get for things like ``dict().pop`` on
  92. # CPython (e.g., ``verifyObject(IFullMapping, dict()))``.
  93. # In neither case can we get a signature, so there's nothing
  94. # to verify. Even the inspect module gives up and raises
  95. # ValueError: no signature found. The ``__text_signature__`` attribute
  96. # isn't typically populated either.
  97. #
  98. # Note that on PyPy 2 or 3 (up through 7.3 at least), these are
  99. # not true for things like ``dict.pop`` (but might be true for C extensions?)
  100. return
  101. if isinstance(attr, FunctionType):
  102. if isinstance(candidate, type) and vtype == 'c':
  103. # This is an "unbound method".
  104. # Only unwrap this if we're verifying implementedBy;
  105. # otherwise we can unwrap @staticmethod on classes that directly
  106. # provide an interface.
  107. meth = fromFunction(attr, iface, name=name, imlevel=1)
  108. else:
  109. # Nope, just a normal function
  110. meth = fromFunction(attr, iface, name=name)
  111. elif (isinstance(attr, MethodTypes)
  112. and type(attr.__func__) is FunctionType):
  113. meth = fromMethod(attr, iface, name)
  114. elif isinstance(attr, property) and vtype == 'c':
  115. # Without an instance we cannot be sure it's not a
  116. # callable.
  117. # TODO: This should probably check inspect.isdatadescriptor(),
  118. # a more general form than ``property``
  119. return
  120. else:
  121. if not callable(attr):
  122. raise BrokenMethodImplementation(desc, "implementation is not a method",
  123. attr, iface, candidate)
  124. # sigh, it's callable, but we don't know how to introspect it, so
  125. # we have to give it a pass.
  126. return
  127. # Make sure that the required and implemented method signatures are
  128. # the same.
  129. mess = _incompat(desc.getSignatureInfo(), meth.getSignatureInfo())
  130. if mess:
  131. raise BrokenMethodImplementation(desc, mess, attr, iface, candidate)
  132. def verifyClass(iface, candidate, tentative=False):
  133. """
  134. Verify that the *candidate* might correctly provide *iface*.
  135. """
  136. return _verify(iface, candidate, tentative, vtype='c')
  137. def verifyObject(iface, candidate, tentative=False):
  138. return _verify(iface, candidate, tentative, vtype='o')
  139. verifyObject.__doc__ = _verify.__doc__
  140. _MSG_TOO_MANY = 'implementation requires too many arguments'
  141. def _incompat(required, implemented):
  142. #if (required['positional'] !=
  143. # implemented['positional'][:len(required['positional'])]
  144. # and implemented['kwargs'] is None):
  145. # return 'imlementation has different argument names'
  146. if len(implemented['required']) > len(required['required']):
  147. return _MSG_TOO_MANY
  148. if ((len(implemented['positional']) < len(required['positional']))
  149. and not implemented['varargs']):
  150. return "implementation doesn't allow enough arguments"
  151. if required['kwargs'] and not implemented['kwargs']:
  152. return "implementation doesn't support keyword arguments"
  153. if required['varargs'] and not implemented['varargs']:
  154. return "implementation doesn't support variable arguments"