我正在嘗試測驗一個簡單的 python 函式的例外塊,如下所示
函式串列.py
def option_check():
"""
Function to pick and return an option
"""
try:
# DELETE_FILES_ON_SUCCESS is a config value from constants class. Valid values True/False (boolean)
flag = Constants.DELETE_FILES_ON_SUCCESS
if flag:
return "remove_source_file"
else:
return "keep_source_file"
except Exception as error:
error_message = F"task option_check failed with below error {str(error)}"
raise Exception(f"Error occured: {error}") from error
如何強制和例外對例外塊進行單元測驗?請注意,我在例外塊中的內容是我實際擁有的內容的簡化版本。我正在尋找的是一種使用單元測驗來測驗例外場景來強制例外的方法。Python 版本是 3.6
uj5u.com熱心網友回復:
您可以修補Constants該類并洗掉您從模擬中訪問的屬性。
from unittest import mock
# replace __main__ with the package Constants is from
with mock.patch("__main__.Constants") as mock_constants:
del mock_constants.DELETE_FILES_ON_SUCCESS
option_check()
當option_check()嘗試訪問時Constants.DELETE_FILES_ON_SUCCESS,它會引發一個AttributeError,允許您到達該except塊。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/379799.html
上一篇:Angular如何測驗組件方法?
