4

click我正在使用库为 python 中的命令行应用程序编写单元测试用例。

我试过下面的例子,这工作正常:

def test_hello_world():
    @click.command()
    @click.argument('name')
    def hello(name):
        click.echo('Hello %s!' % name)

    runner = CliRunner()
    result = runner.invoke(hello, ['Yash'])
    assert result.exit_code == 0
    assert result.output == 'Hello Yash!\n'

但现在我想从我的函数中输入提示。

像这样:

def test_name_prompt(self):
    @click.command()
    @click.option('-name', default=False)
    def username():
        fname = click.prompt("What's your first name?")
        lname = click.prompt("what's your last name?")
        click.echo("%s %s" % (fname, lname))

    runner = CliRunner()
    result = runner.invoke(username, ['-name'])
    assert result.exit_code == 0      
    assert result.output == 'Yash Lodha'
4

1 回答 1

2

Click 为此目的公开了“输入”参数(http://click.pocoo.org/5/testing/),您可以使用该参数向标准输入提供输入数据以满足提示。

import click
from click.testing import CliRunner

def test_prompts():
    @click.command()
    @click.option('--foo', prompt=True)
    def test(foo):
        click.echo('foo=%s' % foo)

    runner = CliRunner()
    result = runner.invoke(test, input='wau wau\n')
    assert not result.exception
    assert result.output == 'Foo: wau wau\nfoo=wau wau\n'
于 2017-03-09T05:20:26.233 回答