verify.py 7.2 KB

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