2017-07-21 3 views
1

私はクリックを使って入力引数を取得するスクリプトを持っています。そのdocumentation CliRunnerによると、ユニットテストを行うために使用することができます。CliRunnerを使用してスクリプトをテストするにはどうすればよいですか?

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' 

これはテスト中にインラインで書かれている小さなこんにちは世界の機能のために行われます。 私の待ち時間:

別のファイルのスクリプトに対して同じテストを実行するにはどうすればよいですか?クリック使用するスクリプトの

例:

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() 

click documentationから)

EDIT:

私はダンの答えで提案されているようにカップルした後、それを実行しようとした場合このエラーが表示される時間数:

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) 

答えて

0

テストファイルで、このようなことをしてください。

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' 
+0

編集をご覧ください –

関連する問題