testing click python applications

orthodoxpirate picture orthodoxpirate · Nov 5, 2014 · Viewed 7.9k times · Source

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?

Answer

orthodoxpirate picture orthodoxpirate · Nov 5, 2014

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