模拟用户输入()

Mock user input()

我正在尝试为我要使用 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

它确实捕获了适当的标准输出调用 "You are too young"。

ask 不会 return 在第一个太小的年龄之后;它循环直到输入适当的年龄。如所写,您需要提供 所有 它可能读取的字符串,然后在 ask returns.

之后执行所有断言
@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!"