1 回答

TA貢獻1833條經(jīng)驗 獲得超4個贊
我假設(shè)您想為login_features(). 一般來說,我會這樣重構(gòu)函數(shù):
def execute_login_option(opt_str: str):
switcher = {...}
login = switcher.get(login_input, login_features)
login() # Executing the called function
def login_features():
print("Choose option to login")
print("1. BDO login")
print("2. GPM login")
print("3. Member login")
login_input = int(input())
execute_login_option(login_input)
這樣您就可以輕松地進行測試execute_login_option而無需修補input().
如果你需要產(chǎn)生一些輸入,你可以使用 Python 的unittest.mock.patch:
def my_function_with_input():
test = input("please enter a value")
return test
with mock.patch('%s.input' % __name__) as patched_input:
patched_input.return_value = "foo"
assert my_function_with_input() == "foo"
在上下文中,我將調(diào)用的返回值重新定義input()為 be "foo"。同樣,您可以在測試用例中將返回值設(shè)置為所需的用戶輸入login_features。
編輯(回答評論中關(guān)于如何測試不返回值的函數(shù)的問題):
如果您的函數(shù)沒有返回要斷言的值,它通常會將整個系統(tǒng)的狀態(tài)更改為副作用(在您的示例中,這樣的副作用可能是用戶已登錄)。請參閱下面有關(guān)如何在此類設(shè)置中進行測試的最小示例:
from unittest import mock
class ClassToTest:
def __init__(self):
self.state = "A"
def my_function_with_input(self):
test = input("please enter a value")
if test == "foo":
self.state = "B"
else:
self.state = "C"
def my_function_with_input():
test = input("please enter a value")
return test
with mock.patch('%s.input' % __name__) as patched_input:
patched_input.return_value = "foo"
test_obj = ClassToTest()
assert test_obj.state == "A"
test_obj.my_function_with_input()
assert test_obj.state == "B" # assert that the state changed to B
使用unittest.mock -framework可以利用更多的選項和可能性。
添加回答
舉報