testing click python applications
Asked Answered
C

2

15

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?

Circumvent answered 5/11, 2014 at 21:5 Comment(4)
So put tests inside toroman.py and run it? I have tried but it does not work.Circumvent
From the Testing chapter in the docs, it looks like you can write tests as separate scripts that use click.testing.CliRunner, and then you run the tests just by running those scripts the same as any other Python script. What part of that is confusing? Where are you stuck?Raddi
Yes, but when I run the python file that contains the tests I don't get any output to tell me if they passed or failed.Circumvent
OK, then show us a simple example of a click app and CliRunner tests, and how you're running them, don't make us guess at what you did and what parts you may or may not understsand.Raddi
C
18

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
Circumvent answered 5/11, 2014 at 22:19 Comment(2)
This example function works as expected if embedded in testing framework like nose or pytest see example in clickEmporium
This is just an example of a tiny in-line function how do I test a script that uses click??Dove
D
3

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'
Docia answered 8/2, 2018 at 3:48 Comment(1)
Would you consider adding source for 'click_app.py' to complete the example?Linnealinnean

© 2022 - 2024 — McMap. All rights reserved.