慕的地8271018
2023-09-05 17:12:49
我想使用 Python 3.8 在單元測試中模擬用戶的輸入。我有一個函數,首先詢問用戶要執行哪個程序,然后詢問多個其他輸入以獲取所述應用程序所需的值。我想在單元測試中模擬這些輸入(input())。我無法從這篇文章中找到答案,因為該答案使用“輸入”文本,然后將其插入函數中,并且不能與input()無縫配合。我想要一個與input()無縫協作的解決方案,就好像人類正在運行程序一樣,并返回程序中函數輸出的值。使用單獨的函數非常繁瑣,并且意味著更新程序兩次,這并不理想。如果這是唯一的方法,我愿意處理它,但我寧愿不這樣做。這是一些需要測試的代碼。main.py:import numworksLibsdef page1(): if (prgrmchoice == "1"): numer = int(input("Enter the Numerator of the Fraction: ")) denom = int(input("Enter the Denominator of the Fraction: ")) numworksLibs.simplify_fraction(numer, denom)庫文件接受此輸入并輸出答案(numworksLibs.py)。
1 回答

哆啦的時光機
TA貢獻1779條經驗 獲得超6個贊
我不確定您到底想測試什么(也許是numworksLibs生成的輸出),但由于這是關于模擬輸入,因此我將展示一個不使用未知變量或函數的簡化示例:
main.py
def page1():
number = int(input("Enter the Numerator of the Fraction: "))
denom = int(input("Enter the Denominator of the Fraction: "))
return number, denom
test_main.py
from unittest import mock
from main import page1
@mock.patch("main.input")
def test_input(mocked_input):
mocked_input.side_effect = ['20', '10']
assert page1() == (20, 10)
side_effect您可以根據需要將任意數量的輸入值放入數組中- 這將模擬單獨調用的返回值input。當然,您必須使測試代碼適應實際代碼。
這假設pytest,因為unittest對于添加的參數來說它看起來是相同的接受self。
添加回答
舉報
0/150
提交
取消