Unit Testing CLI Python

Unit Testing CLI Applications built with Python CLICK

We have been building a lot of CLI apps with CLICK in python. In this tutorial we will learn how to test these applications to make it more production ready. It is a useful practice to test your programs and CLI apps you build.

CLICK comes with its own unit testing suite which makes it easier to test applications built with click. It provides a CLI runner that allows you to invoke the same commands you would have done when using the CLI you’ve built. Let us see an example of how to do so.

First let us build a simple CLI and then we will write a test for the CLI.

import click

@click.group()
def main():
    pass

@main.command()
@click.argument('text')
def say(text):
	click.echo('You said {}'.format(text.title()))

@main.command()
@click.argument('name')
def greet(name):
	click.echo('Hello {}'.format(name))
    

if __name__ == "__main__":
    main()

Our CLI works perfectly but we need to write some test for it.So let us see how to do so.
To begin with, we will need another file, where all our tests will be and then import our required
packages

We will import our main functions from our simple_cli.py  . The main refers to the function in which all the commands have been grouped under.

from click.testing import CliRunner
from simple_cli import main

# Unit Test

def test_say_in_cli():
	runner = CliRunner()
	result = runner.invoke(main,['say','Hello'])
	assert 'You said Hello' in result.output
	assert result.exit_code == 0


def test_greet_in_cli():
	runner = CliRunner()
	result = runner.invoke(main,['greet','John'])
	assert result.output == 'Hello John\n'
	assert result.exit_code == 0

Finally, to run our test we can use pytest as below to execute our test.

py.test

For more information you can add the verbose option to produce more info.

py.test -v

You can even test only a single function in our testing-script using the -k option

py.test -v -k test__say_in_cli

testing click app

It is quite easy to test our CLI using the CliRunner. You can check the video tutorial of the entire process below

Thanks For Your time
Jesus Saves
By Jesse E.Agbe(JCharis)

Leave a Comment

Your email address will not be published. Required fields are marked *