我正在尝试使用 py.test
模拟用户对 python 脚本的输入。下面是一些基本代码,代表了我要完成的任务:
def ask():
while True:
age = input("Enter your age: ")
if int(age) < 13:
print("You are too young")
else:
name = input("Enter your name: ")
break
print("Welcome!")
我想模仿用户输入并读取输出。一个例子可能是这样的:
@mock.patch('builtins.input', side_effect=['11'])
def test_invalid_age():
ask()
assert stdout == "You are too young"
我还听说 flexmock
可能是内置 unittest
模拟系统的更好替代方案,但此时我会采用任何解决方案。
更新:
我又玩了一会儿,测试是这样的:
@mock.patch('builtins.input', side_effect=['11'])
def test_bad_params(self, input):
ask()
output = sys.stdout.getline().strip()
assert output == "You are too young"
当我运行 py.test 时,我得到了这个结果:
E StopIteration /usr/lib/python3.3/unittest/mock.py:904:
StopIteration
它确实捕获了适当的标准输出调用“你太年轻了”。
最佳答案
ask
在第一个太年轻的年龄后没有返回;它循环直到输入适当的年龄。如所写,您需要提供所有它可能读取的字符串,然后在ask
返回后执行所有断言。
@mock.patch('builtins.input', side_effect=['11', '13', 'Bob'])
def test_bad_params(self, input):
ask()
output = sys.stdout.getline().strip()
assert output == "You are too young"
# Check the output after "13" and "Bob" are entered as well!
assert sys.stdout.getline().strip() == "Welcome!"
关于python - 模拟用户输入(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30039503/