Skip to content
Myr

test_annotated.py

This file

Path

tests/test_annotated.py

59 lines · 1.6 KiB · Python

Last changed by

✨ Add support for PEP-593 `Annotated` for specifying options and arguments (#584)Ryan Miller Galambbefore adoption458a492

History of this file

Take it

1import typer2from typer.testing import CliRunner3from typing_extensions import Annotated45runner = CliRunner()678def test_annotated_argument_with_default():9    app = typer.Typer()1011    @app.command()12    def cmd(val: Annotated[int, typer.Argument()] = 0):13        print(f"hello {val}")1415    result = runner.invoke(app)16    assert result.exit_code == 0, result.output17    assert "hello 0" in result.output1819    result = runner.invoke(app, ["42"])20    assert result.exit_code == 0, result.output21    assert "hello 42" in result.output222324def test_annotated_argument_with_default_factory():25    app = typer.Typer()2627    def make_string():28        return "I made it"2930    @app.command()31    def cmd(val: Annotated[str, typer.Argument(default_factory=make_string)]):32        print(val)3334    result = runner.invoke(app)35    assert result.exit_code == 0, result.output36    assert "I made it" in result.output3738    result = runner.invoke(app, ["overridden"])39    assert result.exit_code == 0, result.output40    assert "overridden" in result.output414243def test_annotated_option_with_argname_doesnt_mutate_multiple_calls():44    app = typer.Typer()4546    @app.command()47    def cmd(force: Annotated[bool, typer.Option("--force")] = False):48        if force:49            print("Forcing operation")50        else:51            print("Not forcing")5253    result = runner.invoke(app)54    assert result.exit_code == 0, result.output55    assert "Not forcing" in result.output5657    result = runner.invoke(app, ["--force"])58    assert result.exit_code == 0, result.output59    assert "Forcing operation" in result.output