【问题标题】:Mock user input()模拟用户输入()
【发布时间】:2015-05-04 20:36:13
【问题描述】:

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

它确实捕获了适当的标准输出调用为“你太年轻了”。

【问题讨论】:

  • 您的问题到底是什么?您是否尝试过实现这一点?你运行了这个例子吗?发生了什么?看看例如stackoverflow.com/q/2617057/3001761
  • 请编辑问题。

标签: python testing input mocking flexmock


【解决方案1】:

ask 在第一个太年轻后不会返回;它循环直到输入适当的年龄。如所写,您需要提供 all 它可能读取的字符串,然后在 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!"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-27
    • 2016-10-05
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 2011-10-09
    • 2010-11-22
    相关资源
    最近更新 更多