Tom Kealy
Tom Kealy

Reputation: 2669

Unit testing assertions in command line applications with Click

I need to unit test that an assertion is raised in a command line function.

click provides functionality to test command line applications, and unittest provides functionality to test that assertions are raised. My problem is combining the two.

What I'm testing is similar to the code below. There is a function with a command-line argument and an option that must be specified if that the argument is a certain value. It is similar in spirit to this example:

import unittest
import click
from click.testing import CliRunner

@click.command()
@click.argument('name')
@click.option('--age')
def hello(name, age):
    if name == 'Peter' and not age:
        raise ValueError('Please specify an age!')
    click.echo('Hello %s!' % name)


class TestClickAssertion(unittest.TestCase):
    def test_hello_world(self):
        with self.assertRaises(ValueError):
            runner = CliRunner()
            result = runner.invoke(hello, ['Peter'])
            print(result)

The issue I have, is that running with unittest in pycharm, I get an AssertionError: ValueError not raised but the print() command prints <Result ValueError('Please specify an age!',)>: which is what I want!

How do I get this test to pass?

Upvotes: 0

Views: 276

Answers (1)

BlackBear
BlackBear

Reputation: 22979

As you experienced, CliRunner will not raise exceptions, but will return them in the result object (documentation).

So instead of using assertRaises check that isinstance(result.exception, ValueError).

Upvotes: 2

Related Questions