auto_stub.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. # Copyright (c) 2011 The Chromium Authors. All rights reserved.
  2. # Use of this source code is governed by a BSD-style license that can be
  3. # found in the LICENSE file.
  4. __version__ = '1.0'
  5. import collections
  6. import inspect
  7. import unittest
  8. class AutoStubMixIn(object):
  9. """Automatically restores stubbed functions on unit test teardDown.
  10. It's an extremely lightweight mocking class that doesn't require bookeeping.
  11. """
  12. _saved = None
  13. def mock(self, obj, member, mock):
  14. self._saved = self._saved or collections.OrderedDict()
  15. old_value = self._saved.setdefault(
  16. obj, collections.OrderedDict()).setdefault(member, getattr(obj, member))
  17. setattr(obj, member, mock)
  18. return old_value
  19. def tearDown(self):
  20. """Restore all the mocked members."""
  21. if self._saved:
  22. for obj, items in self._saved.items():
  23. for member, previous_value in items.items():
  24. setattr(obj, member, previous_value)
  25. class SimpleMock(object):
  26. """Really simple manual class mock."""
  27. def __init__(self, unit_test):
  28. """Do not call __init__ if you want to use the global call list to detect
  29. ordering across different instances.
  30. """
  31. self.calls = []
  32. self.unit_test = unit_test
  33. self.assertEqual = unit_test.assertEqual
  34. def pop_calls(self):
  35. """Returns the list of calls up to date.
  36. Good to do self.assertEqual(expected, mock.pop_calls()).
  37. """
  38. calls = self.calls
  39. self.calls = []
  40. return calls
  41. def check_calls(self, expected):
  42. self.assertEqual(expected, self.pop_calls())
  43. def _register_call(self, *args, **kwargs):
  44. """Registers the name of the caller function."""
  45. caller_name = kwargs.pop('caller_name', None) or inspect.stack()[1][3]
  46. str_args = ', '.join(repr(arg) for arg in args)
  47. str_kwargs = ', '.join('%s=%r' % (k, v) for k, v in kwargs.items())
  48. self.calls.append('%s(%s)' % (
  49. caller_name, ', '.join(filter(None, [str_args, str_kwargs]))))
  50. class TestCase(unittest.TestCase, AutoStubMixIn):
  51. """Adds self.mock() and self.has_failed() to a TestCase."""
  52. def tearDown(self):
  53. AutoStubMixIn.tearDown(self)
  54. unittest.TestCase.tearDown(self)
  55. def has_failed(self):
  56. """Returns True if the test has failed."""
  57. if not self._resultForDoCleanups:
  58. # Maybe skipped.
  59. return False
  60. return not self._resultForDoCleanups.wasSuccessful()