holybull
holybull

Reputation: 2016

testing click python applications

click is a python package for creating nice commandline interfaces for your applications. I have been playing with click a bit and today pushed this simple roman numeral converter on github.

What I want to do now is to test my click application. I am reading through the documentation, but don't know how to run the tests.

Does anyone have experience with testing click applications?

Upvotes: 15

Views: 14419

Answers (2)

Kit Plummer
Kit Plummer

Reputation: 902

pytest has the handlers for the asserts.

To run tests against an existing script, it must be 'imported'.

import click
from click.testing import CliRunner
from click_app import configure, cli

def test_command_configure():
    runner = CliRunner()
    result = runner.invoke(cli, ["configure"])
    assert result.exit_code == 0
    assert result.output == 'configure'

Upvotes: 3

holybull
holybull

Reputation: 2016

Putting the code below in test_greet.py:

import click
from click.testing import CliRunner

def test_greet():
    @click.command()
    @click.argument('name')
    def greet(name):
        click.echo('Hello %s' % name)

    runner = CliRunner()
    result = runner.invoke(greet, ['Sam'])
    assert result.output == 'Hello Sam\n'

if __name__ == '__main__':
    test_greet()

If simply called with python test_greet.py the tests pass and nothing is shown. When used in a testing framework, it performs as expected. For example nosetests test_greet.py returns

.
----------------------------------------------------------------------
Ran 1 test in 0.002s

OK

Upvotes: 18

Related Questions