python - 模拟用户输入()

标签 python testing input mocking flexmock

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

相关文章:

python - 如何在 Python 中使用 matplotlib 创建子图

python - 使用谷歌应用程序引擎渲染动态图像

python - 对 0D 和 1D numpy 数组使用数组索引的统一方式

input - 从 stdin 读取数据而不阻塞?

javascript - 通过JS使用RGB输入框上色

python - 属性错误: 'str' object has no attribute 'TimeUD' | Variable Calling

java - @InjectMocks 注释。 java代码模拟

java - 在 Google App Engine 中使用 JDO 定义的集合中保留任意顺序

angular - 错误 : StaticInjectorError(DynamicTestModule)[CityService -> Http]: No provider for Http

javascript - 以编程方式更改输入类型文件的值?