def test_replace():
"""Replaced methods replace the original one, but are restored after the with."""
class SomethingElse(object):
def foo(self, n, y=None):
assert None, 'This should never be reached in this test'
# Case: bound method
s = SomethingElse()
def replacement(n, y=None):
return y
original_method = six.get_method_function(s.foo)
with replaced(s.foo, replacement):
assert s.foo(1, y='a') == 'a'
assert s.foo(2) == None
assert six.get_method_function(s.foo) is original_method
# Case: unbound method
"""Python 3 does not support the concept of unbound methods, they are
just plain functions without an im_class pointing back to their class.
See https://docs.python.org/3/whatsnew/3.0.html#operators-and-special-methods,
and https://mail.python.org/pipermail/python-dev/2005-January/050625.html
for the rationale.
To be able to support them under Python3, on= is mandatory.
"""
s = SomethingElse()
def replacement(self, n, y=None):
return y
original_method = six.get_unbound_function(SomethingElse.foo)
with replaced(SomethingElse.foo, replacement, on=SomethingElse):
assert s.foo(1, y='a') == 'a'
assert s.foo(2) == None
restored_method = six.get_unbound_function(SomethingElse.foo)
assert restored_method is original_method
# Case: unbound method (no on= given)
s = SomethingElse()
def replacement(self, n, y=None):
return y
with pytest.raises(ValueError, message='You have to supply a on= when stubbing an unbound method'):
with replaced(SomethingElse.foo, replacement):
pass
评论列表
文章目录