Search code examples
pythonpython-2.7command-line-interfacepython-click

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


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


Solution

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