我正在向管道專案添加測驗,代碼已經撰寫并投入生產,因此無法更改以適應測驗。
簡單來說,如果我有這樣的功能:
def other_foo():
return 1
def foo():
res = other_foo()
return res
實際上,other_foo呼叫會回傳各種回應,但為了測驗,我想創建一個固定回應 test foo。
因此,在我的測驗中,我想創建一個other_foo對 2. 的固定回應,并且我的測驗評估類似于:
def test_foo():
# some mocking or nesting handle here for other_foo
res = foo()
assert res == 2
uj5u.com熱心網友回復:
使用patch裝飾器unitest.mock并修補您的模塊區域變數。
from your.module import foo
from unitest.mock import patch
@patch('your.module.other_foo')
def test_foo(mock_other_foo):
mock_other_foo.return_value = 3
assert foo() == 3
mock_other_foo.return_value = 42
assert foo() == 42
您可以在這里和那里找到更多資訊。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/478943.html
