stubout.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. #!/usr/bin/python2.4
  2. #
  3. # Copyright 2008 Google Inc.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. # This file is used for testing. The original is at:
  17. # http://code.google.com/p/pymox/
  18. import inspect
  19. class StubOutForTesting:
  20. """Sample Usage:
  21. You want os.path.exists() to always return true during testing.
  22. stubs = StubOutForTesting()
  23. stubs.Set(os.path, 'exists', lambda x: 1)
  24. ...
  25. stubs.UnsetAll()
  26. The above changes os.path.exists into a lambda that returns 1. Once
  27. the ... part of the code finishes, the UnsetAll() looks up the old value
  28. of os.path.exists and restores it.
  29. """
  30. def __init__(self):
  31. self.cache = []
  32. self.stubs = []
  33. def __del__(self):
  34. self.SmartUnsetAll()
  35. self.UnsetAll()
  36. def SmartSet(self, obj, attr_name, new_attr):
  37. """Replace obj.attr_name with new_attr. This method is smart and works
  38. at the module, class, and instance level while preserving proper
  39. inheritance. It will not stub out C types however unless that has been
  40. explicitly allowed by the type.
  41. This method supports the case where attr_name is a staticmethod or a
  42. classmethod of obj.
  43. Notes:
  44. - If obj is an instance, then it is its class that will actually be
  45. stubbed. Note that the method Set() does not do that: if obj is
  46. an instance, it (and not its class) will be stubbed.
  47. - The stubbing is using the builtin getattr and setattr. So, the __get__
  48. and __set__ will be called when stubbing (TODO: A better idea would
  49. probably be to manipulate obj.__dict__ instead of getattr() and
  50. setattr()).
  51. Raises AttributeError if the attribute cannot be found.
  52. """
  53. if (inspect.ismodule(obj) or
  54. (not inspect.isclass(obj) and obj.__dict__.has_key(attr_name))):
  55. orig_obj = obj
  56. orig_attr = getattr(obj, attr_name)
  57. else:
  58. if not inspect.isclass(obj):
  59. mro = list(inspect.getmro(obj.__class__))
  60. else:
  61. mro = list(inspect.getmro(obj))
  62. mro.reverse()
  63. orig_attr = None
  64. for cls in mro:
  65. try:
  66. orig_obj = cls
  67. orig_attr = getattr(obj, attr_name)
  68. except AttributeError:
  69. continue
  70. if orig_attr is None:
  71. raise AttributeError("Attribute not found.")
  72. # Calling getattr() on a staticmethod transforms it to a 'normal' function.
  73. # We need to ensure that we put it back as a staticmethod.
  74. old_attribute = obj.__dict__.get(attr_name)
  75. if old_attribute is not None and isinstance(old_attribute, staticmethod):
  76. orig_attr = staticmethod(orig_attr)
  77. self.stubs.append((orig_obj, attr_name, orig_attr))
  78. setattr(orig_obj, attr_name, new_attr)
  79. def SmartUnsetAll(self):
  80. """Reverses all the SmartSet() calls, restoring things to their original
  81. definition. Its okay to call SmartUnsetAll() repeatedly, as later calls
  82. have no effect if no SmartSet() calls have been made.
  83. """
  84. self.stubs.reverse()
  85. for args in self.stubs:
  86. setattr(*args)
  87. self.stubs = []
  88. def Set(self, parent, child_name, new_child):
  89. """Replace child_name's old definition with new_child, in the context
  90. of the given parent. The parent could be a module when the child is a
  91. function at module scope. Or the parent could be a class when a class'
  92. method is being replaced. The named child is set to new_child, while
  93. the prior definition is saved away for later, when UnsetAll() is called.
  94. This method supports the case where child_name is a staticmethod or a
  95. classmethod of parent.
  96. """
  97. old_child = getattr(parent, child_name)
  98. old_attribute = parent.__dict__.get(child_name)
  99. if old_attribute is not None and isinstance(old_attribute, staticmethod):
  100. old_child = staticmethod(old_child)
  101. self.cache.append((parent, old_child, child_name))
  102. setattr(parent, child_name, new_child)
  103. def UnsetAll(self):
  104. """Reverses all the Set() calls, restoring things to their original
  105. definition. Its okay to call UnsetAll() repeatedly, as later calls have
  106. no effect if no Set() calls have been made.
  107. """
  108. # Undo calls to Set() in reverse order, in case Set() was called on the
  109. # same arguments repeatedly (want the original call to be last one undone)
  110. self.cache.reverse()
  111. for (parent, old_child, child_name) in self.cache:
  112. setattr(parent, child_name, old_child)
  113. self.cache = []