[英]Get patch'd object with use of unittest.mock's patch decorator and new
我有以下Python==3.8
代碼,其中我:
unittest.mock.patch
作為裝飾器patch(..., new=...)
:from unittest.mock import patch
class Foo:
pass
class Bar:
pass
@patch(__name__ + f".Foo", new=Bar)
def test_foo(patched_Bar) -> None:
_ = 0 # Do stuff
目前,這不會運行,因為沒有提供patched_Bar
參數。 如何讓patched_Bar
arg 傳入?
我知道存在以下解決方法,使用with
,但我不想這樣做,因為在我看來它不太干凈。
def test_foo2() -> None:
with patch(__name__ + f".Foo", new=Bar) as patched_Bar:
_ = 0 # Do stuff
這不是必需的,因為您已經有了修補類,例如Bar
在您的情況下。 如果您使用上下文管理器,您會得到相同的結果,如您所見:
def test_foo() -> None:
with patch(f"{__name__}.Foo", new=Bar) as patched_Bar:
assert patched_bar == Bar
可能您正在考慮獲取Bar
的實例,但這行不通,因為該實例只會在測試中創建。
與默認模擬的不同之處在於您可以將return_value
設置為模擬類,並且該類的每個實例化都會為您提供相同的實例:
@patch(f"{__name__}.Foo")
def test_foo(patched_foo) -> None:
foo1 = Foo()
foo2 = Foo()
assert patched_foo.return_value == foo1 == foo2
assert isinstance(foo1, MagicMock)
雖然使用不是模擬的替換類,這將不起作用:
@patch(f"{__name__}.Foo", Bar)
def test_foo() -> None:
foo1 = Foo()
foo2 = Foo()
assert foo1 != foo2
assert isinstance(foo1, Bar)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.