Skip to content

Instantly share code, notes, and snippets.

@lbillingham
Created September 13, 2016 11:52
Show Gist options
  • Save lbillingham/6412cdc19f9a44901b03841e0443fbf7 to your computer and use it in GitHub Desktop.
Save lbillingham/6412cdc19f9a44901b03841e0443fbf7 to your computer and use it in GitHub Desktop.
python click + pytest example
# hello.py
import click
@click.command()
@click.option(
'--name', default='world',
prompt='greet whom?',
help='who should i greet?'
)
def main(name):
click.echo('Hello {}!'.format(name))
# test_hello.py
from click.testing import CliRunner
import pytest
from hello import hello as hll
@pytest.fixture(scope="module")
def runner():
return CliRunner()
def test_named_hello(runner):
result = runner.invoke(hll.main, ['--name','Amy'])
assert result.exit_code == 0
assert result.output == 'Hello Amy!\n'
def test_default_hello(runner):
result = runner.invoke(hll.main, input='\n')
assert result.exit_code == 0
print(result.output)
expected = 'greet whom? [world]: \nHello world!\n'
assert result.output == expected
@dtranhuusm
Copy link

Note: it would be better to add the following code after result = runner.invoke(...

if result.exception:
    traceback.print_exception(*result.exc_info)

It took me a while to figure out the exception was "trapped" by clirunner.

@clintmod
Copy link

clintmod commented Feb 7, 2021

@dtranhuusm you're a life saver :) Thank You!!

@bekzat-shayakhmet
Copy link

bekzat-shayakhmet commented Apr 11, 2022

There is now a flag, which says to trap catch or not exceptions

  result = cli_runner.invoke(
      cli,
      catch_exceptions=False,
      args=[],
  )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment