問題描述
是否有一種干凈的方法來修補對象,以便在測試用例中獲得 assert_call*
幫助程序,而無需實際刪除操作?
Is there a clean way to patch an object so that you get the assert_call*
helpers in your test case, without actually removing the action?
例如,如何修改 @patch
行以使以下測試通過:
For example, how can I modify the @patch
line to get the following test passing:
from unittest import TestCase
from mock import patch
class Potato(object):
def foo(self, n):
return self.bar(n)
def bar(self, n):
return n + 2
class PotatoTest(TestCase):
@patch.object(Potato, 'foo')
def test_something(self, mock):
spud = Potato()
forty_two = spud.foo(n=40)
mock.assert_called_once_with(n=40)
self.assertEqual(forty_two, 42)
我可能可以使用 side_effect
來破解它,但我希望有一種更好的方法可以在所有函數、類方法、靜態方法、未綁定方法等上以相同的方式工作.
I could probably hack this together using side_effect
, but I was hoping there would be a nicer way which works the same way on all of functions, classmethods, staticmethods, unbound methods, etc.
推薦答案
與你的解決方案類似,但使用 wraps
:
Similar solution with yours, but using wraps
:
def test_something(self):
spud = Potato()
with patch.object(Potato, 'foo', wraps=spud.foo) as mock:
forty_two = spud.foo(n=40)
mock.assert_called_once_with(n=40)
self.assertEqual(forty_two, 42)
根據文檔:
wraps:要包裝的模擬對象的項目.如果 wraps 不是 None 那么調用 Mock 會將調用傳遞給被包裝的對象(返回真實結果).模擬上的屬性訪問將返回一個 Mock 對象,包裝了被包裹的對應屬性對象(因此嘗試訪問不存在的屬性將引發 AttributeError).
wraps: Item for the mock object to wrap. If wraps is not None then calling the Mock will pass the call through to the wrapped object (returning the real result). Attribute access on the mock will return a Mock object that wraps the corresponding attribute of the wrapped object (so attempting to access an attribute that doesn’t exist will raise an AttributeError).
<小時>
class Potato(object):
def spam(self, n):
return self.foo(n=n)
def foo(self, n):
return self.bar(n)
def bar(self, n):
return n + 2
class PotatoTest(TestCase):
def test_something(self):
spud = Potato()
with patch.object(Potato, 'foo', wraps=spud.foo) as mock:
forty_two = spud.spam(n=40)
mock.assert_called_once_with(n=40)
self.assertEqual(forty_two, 42)
這篇關于python mock - 在不妨礙實現的情況下修補方法的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!