Click: Is it possible to pass multiple inputs to CliRunner.invoke?
Asked Answered
E

1

6

I have a click command called download which prompts the user for a username and password before downloading a series of files:

$ python download.py
Username: jkarimi91
Password: 1234
Download complete!

To test this command, I need to be able to pass both a username and a password, separately, to stdin. The CliRunner.invoke() method has an input argument but it does not accept lists. Is it possible to pass multiple inputs to CliRunner.invoke()?

Ethylene answered 4/6, 2017 at 3:2 Comment(2)
@StephenRauch, an input argument, not an input method. See Input Streams in click documentation.Tenuis
My mistake, i made a typo but have since corrected it; input is an argument for the invoke method of clirunnerEthylene
T
6

You can pass multiple inputs by passing string joined by newline (\n):

import click
from click.testing import CliRunner


def test_prompts():
    @click.command()
    @click.option('--username', prompt=True)
    @click.option('--password', prompt=True)
    def test(username, password):
        # download ..
        click.echo('Download complete!')

    # OR
    #
    # @click.command()
    # def test():
    #     username = click.prompt('Username')
    #     password = click.prompt('Password', hide_input=True)
    #     # download ..
    #     click.echo('Download complete!')


    runner = CliRunner()
    result = runner.invoke(test, input='username\npassword\n') # <---
    assert not result.exception
    assert result.output.endswith('Download complete!\n')


if __name__ == '__main__':
    test_prompts()
Tenuis answered 4/6, 2017 at 3:30 Comment(3)
would it be possible if we didn't add username and password as arguments but retrieved them inside of test() using raw_input() and getpass.getpass() instead?Ethylene
@jkarimi, If you use click.prompt(), it's possible. I didn't test with raw_input() or getpass.getpass().Tenuis
@jkarimi, I tested with raw_input, getpass.getpass. It works with raw_input, but not with getpass.getpass. You'd better to use click.prompt('Username') and click.prompt('Password', hide_input=True) for password input which works very well with runner.invoke(..., input=..)Tenuis

© 2022 - 2024 — McMap. All rights reserved.