yash lodha
yash lodha

Reputation: 273

Python - Click command line unit test case for input prompt from command line function

I am working on writing unit test cases for a command line application in python using click library.

I tried below example and this is working fine:

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'

But now I want to input prompt from my function.

like this:

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'

Upvotes: 5

Views: 3881

Answers (1)

user3291073
user3291073

Reputation: 62

Click exposes the 'input' parameter for this purpose (http://click.pocoo.org/5/testing/) which you can use to provide input data to stdin to satisfy a prompt.

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'

Upvotes: 2

Related Questions