5

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'

1 Answer 1

2

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'
Sign up to request clarification or add additional context in comments.

4 Comments

I'm curious about this because I come from Java and Javascript and so this feels unnatural because it appears as though the command test is nested within the test_prompts unit test. I would have expected to write my unit tests in a separate file or in a separate function, but nesting the definition of what you want to test within the test feels way off. I noticed the same pattern in the documentation here. Can you please explain this?
I believe the question was asked that way just for simplicity, to fit the whole example in one code snippet. For our real codebase we define all of the commands in separate files from the tests and then import them and call runner.invoke to test the imported function.
Ok, and then do you also need a test framework to run the test scripts or is Click self sufficient in this regard? How do you run the scripts? Is it as simple as python test_foo.py? What if there is more than one test script? How do I run them all in one go?
The question was about how to test click.prompt(), not click.echo().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.