模拟用户输入() [英] Mock user input()

查看:109
本文介绍了模拟用户输入()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试模拟要使用py.test进行的python脚本的用户输入.这是一些代表我要完成的基本代码:

I am trying to simulate user input for a python script that I have going using py.test. Here's some basic code that represents what I'm trying to accomplish:

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!")

我想模仿用户输入并读取输出.一个例子可能是这样的:

I would like to mimic user input and read the output. An example might be something like:

@mock.patch('builtins.input', side_effect=['11'])
def test_invalid_age():
    ask()
    assert stdout == "You are too young"

我还听说过flexmock可能是内置的unittest模拟系统的更好替代方案,但是在这一点上我将采取任何解决方案.

I've also heard that flexmock might be a better alternative to the built-in unittest mocking system, but I'll take any solution at this point.

更新:

我玩了一些,并做了一个测试:

I played around a bit more and have a test that is this:

@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时,我得到以下结果:

When I run py.test I get this result:

E StopIteration /usr/lib/python3.3/unittest/mock.py:904:
StopIteration

它确实捕获了适当的标准输出调用,例如您太年轻".

It did catch capture the appropriate standard output call as "You are too young".

推荐答案

ask在第一次过小就不再返回;它会循环播放,直到输入适当的年龄为止.按照书面规定,您需要提供 all 可能读取的字符串,然后在ask返回之后执行所有断言.

ask doesn't return after the first too-young age; it loops until an appropriate age is entered. As written, you'll need to supply all the strings it might read, then do all your assertions after 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!"

这篇关于模拟用户输入()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆