Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 752
orthodoxpirate Avatar asked Nov 05 '14 21:11

orthodoxpirate


People also ask

What is CLI testing?

The CLI tests are integration tests - they test the CLI as a standalone application. Originally an attempt was made to write tests with java and junit. But jline hangs when testing the CLI in the same JVM as Junit.


2 Answers

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
like image 61
orthodoxpirate Avatar answered Oct 11 '22 07:10

orthodoxpirate


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'
like image 41
Kit Plummer Avatar answered Oct 11 '22 06:10

Kit Plummer