2017-07-21 98 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' 

這是爲寫入在線測試中的微小你好世界函數來完成。 我的佇立是:

如何對不同文件中的腳本執行相同的測試?腳本的

示例使用點擊:

(從 click documentation)編輯
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() 

如果我嘗試運行它在丹的回答表明,後一對夫婦小時顯示此錯誤:

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

請參閱編輯 –