1
patch.object
を使用してメソッドをモックすると、特定のパラメータ値に対してメソッドがまったく侮られていないことを指定する方法があります。 「本当の」return_valueを返し、他のパラメータの値は特定のreturn_valueを設定しますか?Python Mock - return_value - "実際の"戻り値を取得する
ありがとうございました。
patch.object
を使用してメソッドをモックすると、特定のパラメータ値に対してメソッドがまったく侮られていないことを指定する方法があります。 「本当の」return_valueを返し、他のパラメータの値は特定のreturn_valueを設定しますか?Python Mock - return_value - "実際の"戻り値を取得する
ありがとうございました。
ここでは、それが合理的にうまく動作する解決策(私が使ったところから修正)です。これには、パッチのside_effect
を関数に設定する必要があります。 https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock.side_effect
import os.path
from unittest import mock
def different_return_values(dct):
def f(*args):
return dct[args]
return f
with mock.patch.object(
os.path,
'exists',
side_effect=different_return_values({
# The "generic" version above makes the arguments in order
# the keys to this map, you could write a specialized version
# which has a single argument or *whatever* key combination you
# like
('myfile',): True,
('wat',): 'not a real return value but hey, monkeypatch!',
('otherfile',): False,
}),
):
print(os.path.exists('myfile'))
print(os.path.exists('wat'))
print(os.path.exists('otherfile'))
OUTPUT = """\
True
not a real return value but hey, monkeypatch!
False
"""
ここでお持ち帰りはあなたがside_effect
としてパッチを適用する機能の賢く実装を提供することができています