testing_refleaks.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. # Protocol Buffers - Google's data interchange format
  2. # Copyright 2008 Google Inc. All rights reserved.
  3. #
  4. # Use of this source code is governed by a BSD-style
  5. # license that can be found in the LICENSE file or at
  6. # https://developers.google.com/open-source/licenses/bsd
  7. """A subclass of unittest.TestCase which checks for reference leaks.
  8. To use:
  9. - Use testing_refleak.BaseTestCase instead of unittest.TestCase
  10. - Configure and compile Python with --with-pydebug
  11. If sys.gettotalrefcount() is not available (because Python was built without
  12. the Py_DEBUG option), then this module is a no-op and tests will run normally.
  13. """
  14. import copyreg
  15. import gc
  16. import sys
  17. import unittest
  18. class LocalTestResult(unittest.TestResult):
  19. """A TestResult which forwards events to a parent object, except for Skips."""
  20. def __init__(self, parent_result):
  21. unittest.TestResult.__init__(self)
  22. self.parent_result = parent_result
  23. def addError(self, test, error):
  24. self.parent_result.addError(test, error)
  25. def addFailure(self, test, error):
  26. self.parent_result.addFailure(test, error)
  27. def addSkip(self, test, reason):
  28. pass
  29. class ReferenceLeakCheckerMixin(object):
  30. """A mixin class for TestCase, which checks reference counts."""
  31. NB_RUNS = 3
  32. def run(self, result=None):
  33. testMethod = getattr(self, self._testMethodName)
  34. expecting_failure_method = getattr(testMethod, "__unittest_expecting_failure__", False)
  35. expecting_failure_class = getattr(self, "__unittest_expecting_failure__", False)
  36. if expecting_failure_class or expecting_failure_method:
  37. return
  38. # python_message.py registers all Message classes to some pickle global
  39. # registry, which makes the classes immortal.
  40. # We save a copy of this registry, and reset it before we could references.
  41. self._saved_pickle_registry = copyreg.dispatch_table.copy()
  42. # Run the test twice, to warm up the instance attributes.
  43. super(ReferenceLeakCheckerMixin, self).run(result=result)
  44. super(ReferenceLeakCheckerMixin, self).run(result=result)
  45. oldrefcount = 0
  46. local_result = LocalTestResult(result)
  47. num_flakes = 0
  48. refcount_deltas = []
  49. while len(refcount_deltas) < self.NB_RUNS:
  50. oldrefcount = self._getRefcounts()
  51. super(ReferenceLeakCheckerMixin, self).run(result=local_result)
  52. newrefcount = self._getRefcounts()
  53. # If the GC was able to collect some objects after the call to run() that
  54. # it could not collect before the call, then the counts won't match.
  55. if newrefcount < oldrefcount and num_flakes < 2:
  56. # This result is (probably) a flake -- garbage collectors aren't very
  57. # predictable, but a lower ending refcount is the opposite of the
  58. # failure we are testing for. If the result is repeatable, then we will
  59. # eventually report it, but not after trying to eliminate it.
  60. num_flakes += 1
  61. continue
  62. num_flakes = 0
  63. refcount_deltas.append(newrefcount - oldrefcount)
  64. print(refcount_deltas, self)
  65. try:
  66. self.assertEqual(refcount_deltas, [0] * self.NB_RUNS)
  67. except Exception: # pylint: disable=broad-except
  68. result.addError(self, sys.exc_info())
  69. def _getRefcounts(self):
  70. copyreg.dispatch_table.clear()
  71. copyreg.dispatch_table.update(self._saved_pickle_registry)
  72. # It is sometimes necessary to gc.collect() multiple times, to ensure
  73. # that all objects can be collected.
  74. gc.collect()
  75. gc.collect()
  76. gc.collect()
  77. return sys.gettotalrefcount()
  78. if hasattr(sys, 'gettotalrefcount'):
  79. def TestCase(test_class):
  80. new_bases = (ReferenceLeakCheckerMixin,) + test_class.__bases__
  81. new_class = type(test_class)(
  82. test_class.__name__, new_bases, dict(test_class.__dict__))
  83. return new_class
  84. SkipReferenceLeakChecker = unittest.skip
  85. else:
  86. # When PyDEBUG is not enabled, run the tests normally.
  87. def TestCase(test_class):
  88. return test_class
  89. def SkipReferenceLeakChecker(reason):
  90. del reason # Don't skip, so don't need a reason.
  91. def Same(func):
  92. return func
  93. return Same