__init__.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. from zope.interface._compat import _should_attempt_c_optimizations
  2. class OptimizationTestMixin(object):
  3. """
  4. Helper for testing that C optimizations are used
  5. when appropriate.
  6. """
  7. def _getTargetClass(self):
  8. """
  9. Define this to return the implementation in use,
  10. without the 'Py' or 'Fallback' suffix.
  11. """
  12. raise NotImplementedError
  13. def _getFallbackClass(self):
  14. """
  15. Define this to return the fallback Python implementation.
  16. """
  17. # Is there an algorithmic way to do this? The C
  18. # objects all come from the same module so I don't see how we can
  19. # get the Python object from that.
  20. raise NotImplementedError
  21. def _test_optimizations(self):
  22. used = self._getTargetClass()
  23. fallback = self._getFallbackClass()
  24. if _should_attempt_c_optimizations():
  25. self.assertIsNot(used, fallback)
  26. else:
  27. self.assertIs(used, fallback)
  28. class MissingSomeAttrs(object):
  29. """
  30. Helper for tests that raises a specific exception
  31. for attributes that are missing. This is usually not
  32. an AttributeError, and this object is used to test that
  33. those errors are not improperly caught and treated like
  34. an AttributeError.
  35. """
  36. def __init__(self, exc_kind, **other_attrs):
  37. self.__exc_kind = exc_kind
  38. d = object.__getattribute__(self, '__dict__')
  39. d.update(other_attrs)
  40. def __getattribute__(self, name):
  41. # Note that we ignore objects found in the class dictionary.
  42. d = object.__getattribute__(self, '__dict__')
  43. try:
  44. return d[name]
  45. except KeyError:
  46. raise d['_MissingSomeAttrs__exc_kind'](name)
  47. EXCEPTION_CLASSES = (
  48. TypeError,
  49. RuntimeError,
  50. BaseException,
  51. ValueError,
  52. )
  53. @classmethod
  54. def test_raises(cls, unittest, test_func, expected_missing, **other_attrs):
  55. """
  56. Loop through various exceptions, calling *test_func* inside a ``assertRaises`` block.
  57. :param test_func: A callable of one argument, the instance of this
  58. class.
  59. :param str expected_missing: The attribute that should fail with the exception.
  60. This is used to ensure that we're testing the path we think we are.
  61. :param other_attrs: Attributes that should be provided on the test object.
  62. Must not contain *expected_missing*.
  63. """
  64. assert isinstance(expected_missing, str)
  65. assert expected_missing not in other_attrs
  66. for exc in cls.EXCEPTION_CLASSES:
  67. ob = cls(exc, **other_attrs)
  68. with unittest.assertRaises(exc) as ex:
  69. test_func(ob)
  70. unittest.assertEqual(ex.exception.args[0], expected_missing)
  71. # Now test that the AttributeError for that expected_missing is *not* raised.
  72. ob = cls(AttributeError, **other_attrs)
  73. try:
  74. test_func(ob)
  75. except AttributeError as e:
  76. unittest.assertNotIn(expected_missing, str(e))
  77. except Exception: # pylint:disable=broad-except
  78. pass
  79. # Be sure cleanup functionality is available; classes that use the adapter hook
  80. # need to be sure to subclass ``CleanUp``.
  81. #
  82. # If zope.component is installed and imported when we run our tests
  83. # (import chain:
  84. # zope.testrunner->zope.security->zope.location->zope.component.api)
  85. # it adds an adapter hook that uses its global site manager. That can cause
  86. # leakage from one test to another unless its cleanup hooks are run. The symptoms can
  87. # be odd, especially if one test used C objects and the next used the Python
  88. # implementation. (For example, you can get strange TypeErrors or find inexplicable
  89. # comparisons being done.)
  90. try:
  91. from zope.testing import cleanup
  92. except ImportError:
  93. class CleanUp(object):
  94. def cleanUp(self):
  95. pass
  96. setUp = tearDown = cleanUp
  97. else:
  98. CleanUp = cleanup.CleanUp