| 1 | from pathlib import Path |
| 2 | from textwrap import dedent |
| 3 | from typing import Annotated |
| 4 | |
| 5 | import pytest |
| 6 | |
| 7 | from cyclopts import Parameter |
| 8 | from cyclopts.exceptions import CoercionError |
| 9 | |
| 10 | |
| 11 | @pytest.mark.parametrize( |
| 12 | "cmd_str,expected", |
| 13 | [ |
| 14 | ("foo 1", 1), |
| 15 | ("foo --a=1", 1), |
| 16 | ("foo --a 1", 1), |
| 17 | ("foo bar", "bar"), |
| 18 | ("foo --a=bar", "bar"), |
| 19 | ("foo --a bar", "bar"), |
| 20 | ], |
| 21 | ) |
| 22 | @pytest.mark.parametrize("annotated", [False, True]) |
| 23 | def test_union_required_implicit_coercion(app, cmd_str, expected, annotated, assert_parse_args): |
| 24 | """ |
| 25 | For a union without an explicit coercion, the first non-None type annotation |
| 26 | should be used. In this case, it's ``int``. |
| 27 | """ |
| 28 | if annotated: |
| 29 | |
| 30 | @app.command |
| 31 | def foo(a: Annotated[None | int | str, Parameter(help="help for a")]): |
| 32 | pass |
| 33 | |
| 34 | else: |
| 35 | |
| 36 | @app.command |
| 37 | def foo(a: None | int | str): |
| 38 | pass |
| 39 | |
| 40 | assert_parse_args(foo, cmd_str, expected) |
| 41 | |
| 42 | |
| 43 | def test_union_coercion_cannot_coerce_error(app, console): |
| 44 | @app.default |
| 45 | def default(a: None | int | float): |
| 46 | pass |
| 47 | |
| 48 | with console.capture() as capture, pytest.raises(CoercionError): |
| 49 | app.parse_args("foo", error_console=console, exit_on_error=False) |
| 50 | |
| 51 | actual = capture.get() |
| 52 | |
| 53 | expected = dedent( |
| 54 | """\ |
| 55 | ╭─ Error ────────────────────────────────────────────────────────────╮ |
| 56 | │ Invalid value for A: unable to convert "foo" into int|float. │ |
| 57 | ╰────────────────────────────────────────────────────────────────────╯ |
| 58 | """ |
| 59 | ) |
| 60 | |
| 61 | assert actual == expected |
| 62 | |
| 63 | |
| 64 | @pytest.mark.parametrize( |
| 65 | "cmd_str,expected", |
| 66 | [ |
| 67 | ("bar", ["bar"]), |
| 68 | ("bar baz", ["bar", "baz"]), |
| 69 | ], |
| 70 | ) |
| 71 | def test_union_of_list_types(app, cmd_str, expected, assert_parse_args): |
| 72 | """list[str] | list[Path] should work as a union of list types (issue #780).""" |
| 73 | |
| 74 | @app.default |
| 75 | def foo(paths: list[str] | list[Path]): |
| 76 | pass |
| 77 | |
| 78 | assert_parse_args(foo, cmd_str, expected) |
| 79 | |
| 80 | |
| 81 | @pytest.mark.parametrize( |
| 82 | "cmd_str,expected", |
| 83 | [ |
| 84 | ("bar", ["bar"]), |
| 85 | ("bar baz", ["bar", "baz"]), |
| 86 | ], |
| 87 | ) |
| 88 | def test_union_of_list_types_optional(app, cmd_str, expected, assert_parse_args): |
| 89 | """list[str] | list[Path] | None should work as a union of list types.""" |
| 90 | |
| 91 | @app.default |
| 92 | def foo(paths: list[str] | list[Path] | None = None): |
| 93 | pass |
| 94 | |
| 95 | assert_parse_args(foo, cmd_str, expected) |