我想使用 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 回答
![?](http://img1.sycdn.imooc.com/5458477300014deb02200220-100-100.jpg)
哆啦的时光机
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
提交
取消