Python 如何使用CliRunner测试脚本?

Python 如何使用CliRunner测试脚本?,python,python-unittest,python-click,Python,Python Unittest,Python Click,我有一个使用单击获取输入参数的脚本。根据客户的要求,Runner可用于进行单元测试: import click from click.testing import CliRunner def test_hello_world(): @click.command() @click.argument('name') def hello(name): click.echo('Hello %s!' % name) runner = CliRunner(

我有一个使用单击获取输入参数的脚本。根据客户的要求,Runner可用于进行单元测试:

import click
from click.testing import CliRunner

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

    runner = CliRunner()
    result = runner.invoke(hello, ['Peter'])
    assert result.exit_code == 0
    assert result.output == 'Hello Peter!\n'
这是为在测试中在线编写的一个很小的helloworld函数完成的。 我的问题是:

如何对不同文件中的脚本执行相同的测试???

使用单击的脚本示例:

import click
@click.command()
@click.option('--count', default=1, help='Number of greetings.')
@click.option('--name', prompt='Your name', help='The person to greet.')
def hello(count, name):
    """Simple program that greets NAME for a total of COUNT times."""
    for x in range(count):
        click.echo('Hello %s!' % name)

if __name__ == '__main__':
    hello()
(来自)

编辑:

如果我尝试按照Dan的回答中的建议运行它,几个小时后会显示以下错误:

test_hello_world (__main__.TestRasterCalc) ... ERROR

======================================================================
ERROR: test_hello_world (__main__.TestRasterCalc)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/src/HelloClickUnitTest.py", line 35, in test_hello_world
    result = runner.invoke(hello, ['Peter'])
  File "/usr/local/lib/python2.7/dist-packages/click/testing.py", line 299, in invoke
    output = out.getvalue()
MemoryError

----------------------------------------------------------------------
Ran 1 test in 9385.931s

FAILED (errors=1)

在测试文件中,执行以下操作

import click
from click.testing import CliRunner
from hello_module import hello  # Import the function to test

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

您的测试有几个挑战

  • 您的程序希望通过
    --name
    名称指定为选项

    要修复测试,请将
    ['--name',Peter']
    传递到
    invoke()

  • 此外,如果未指定该选项,则会提示输入。
    MemoryError
    是由于不断单击试图提示不存在的用户

    要修复测试,请通过
    input='Peter\n'
    调用。这就像用户在提示下键入:
    Peter

  • 代码:
    我也为此奋斗了很久。结果证明答案比你想象的要简单。这一切都取决于runner.invoke()函数。就你而言:

    runner.invoke(hello, '--count 3 --name Peter')
    
    runner.invoke(hello, '--count 3 --name Peter')