[英]How to patch or mock subsequent API calls in python unit testing?
我有關注 function
def test_dir_creation():
if not os.path.exists(root_dir_path):
raise Exception("Root dir don't exits")
if not os.path.exists(log_dir_path):
raise Exception("Log dir don't exits")
if not os.path.exists(subscription_handle_dir_path):
raise Exception("subscription_handle_dir_path dir don't exits")
我想測試三個條件,我的測試用例如下 -
@mock.patch("os.path.exists", return_value=False)
def test_args_parser_when_root_dir_dont_exists(*mocks):
with pytest.raises(Exception) as excinfo:
args_parser()
expected_message = "Root dir don't exits"
assert expected_message in str(excinfo)
這個測試用例有效,但我也想測試其他兩個條件,怎么做?
我如何修補 os.path.exists(log_dir_path) == False 之類的東西?
在您的示例中,您是 mocking對整個 function的調用。 如果您想要模擬更改行為,我建議您使用上下文管理器。
import os.path
def do_test():
with mock.patch('os.path.exists', return_value='hello'):
assert os.path.exists() == 'hello'
with mock.patch('os.path.exists', return_value=-5):
assert os.path.exists() == -5
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.