If you'd like to package typer apps then you should also think about
writing some unit tests for them. Thankfully, typer makes this easy
for you by adding a TestClient
to the framework.
Simple Test File
Here's an example of a test_cli.py
tests file.
from typer.testing import CliRunner
from demopkg.__main__ import app
runner = CliRunner()
def test_app():
result = runner.invoke(app, ["hello-world", "Vincent"])
assert result.exit_code == 0
assert "Vincent" in result.stdout
def test_db_create1():
# Note that we need to confirm here, hence the extra input!
result = runner.invoke(app, ["db", "create-db"], input="foobar\nfoobar\n")
assert result.exit_code == 0
assert "foobar" in result.stdout
def test_db_create2():
# Note that we need to confirm here, hence the extra input!
result = runner.invoke(app, ["db", "create-db", "--table", "foobar"], input="foobar\n")
assert result.exit_code == 0
print(result.stdout)
assert "foobar" in result.stdout
These tests are just meant as an example but it's hopefully clear
how these can be expanded. Note that we're using the input
parameter in
the running.invoke
command in the latter two tests.
These tests can all be run by using pytest
.
pytest
Again, if you want to see all the files you can get them from github.