1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
|
import inspect
import sys
from datetime import datetime, timedelta
from enum import Enum, auto
from pathlib import Path
from typing import Annotated, Any, Iterable, List, Literal, Optional, Sequence, Set, Tuple, Union
from unittest.mock import Mock
import pytest
from cyclopts import CoercionError, Token
from cyclopts._convert import convert, token_count
def _assert_tuple(expected, actual):
assert type(actual) is tuple
assert len(expected) == len(actual)
for e, a in zip(expected, actual):
assert type(e) is type(a)
assert e == a
def test_token_count_tuple_basic():
assert (3, False) == token_count(Tuple[int, int, int])
def test_token_count_tuple_no_inner_type():
assert (1, True) == token_count(Tuple)
assert (1, True) == token_count(tuple)
def test_token_count_tuple_nested():
assert (4, False) == token_count(Tuple[Tuple[int, int], int, int])
def test_token_count_tuple_ellipsis():
assert (1, True) == token_count(Tuple[int, ...])
def test_token_count_tuple_ellipsis_nested():
assert (2, True) == token_count(Tuple[Tuple[int, int], ...])
def test_token_union():
assert (1, False) == token_count(Union[None, int])
def test_token_count_standard():
assert (1, False) == token_count(int)
def test_token_count_bool():
assert (0, False) == token_count(bool)
def test_token_count_list():
assert (1, True) == token_count(List[int])
def test_token_count_sequence():
assert (1, True) == token_count(Sequence[int])
assert (2, True) == token_count(Sequence[Tuple[int, int]])
def test_token_count_list_generic():
assert (1, True) == token_count(list)
def test_token_count_list_direct():
assert (1, True) == token_count(list[int]) # pyright: ignore
def test_token_count_list_of_tuple():
assert (3, True) == token_count(List[Tuple[int, int, int]])
def test_token_count_list_of_tuple_nested():
assert (4, True) == token_count(List[Tuple[Tuple[int, int], int, int]])
def test_token_count_iterable():
assert (1, True) == token_count(Iterable[int])
assert (2, True) == token_count(Iterable[Tuple[int, int]])
def test_token_count_union():
assert (1, False) == token_count(Union[int, str, float])
def test_token_count_union_error():
with pytest.raises(ValueError):
assert (1, False) == token_count(Union[int, Tuple[int, int]])
def test_coerce_no_tokens():
with pytest.raises(ValueError):
convert(int, [])
def test_coerce_bool():
assert True is convert(bool, ["true"])
assert False is convert(bool, ["false"])
def test_coerce_error():
with pytest.raises(CoercionError):
convert(bool, ["foo"])
def test_coerce_int():
assert 123 == convert(int, ["123"])
def test_coerce_annotated_int():
assert [123, 456] == convert(Annotated[int, "foo"], ["123", "456"])
assert [123, 456] == convert(Annotated[List[int], "foo"], ["123", "456"])
def test_coerce_optional_annotated_int():
assert [123, 456] == convert(Optional[Annotated[int, "foo"]], ["123", "456"])
assert [123, 456] == convert(Optional[Annotated[List[int], "foo"]], ["123", "456"])
def test_coerce_annotated_union_str_secondary_choice():
assert 123 == convert(Union[None, int, str], ["123"])
assert "foo" == convert(Union[None, int, str], ["foo"])
with pytest.raises(CoercionError):
convert(Union[None, int, float], ["invalid-choice"])
def test_coerce_annotated_nested_union_str_secondary_choice():
assert 123 == convert(Union[None, Union[int, str]], ["123"])
assert "foo" == convert(Union[None, Union[int, str]], ["foo"])
def test_coerce_annotated_union_int():
assert 123 == convert(Annotated[Union[None, int, float], "foo"], ["123"])
assert [123, 456] == convert(Annotated[int, "foo"], ["123", "456"])
assert [123, 456] == convert(Annotated[Union[None, int, float], "foo"], ["123", "456"])
def test_coerce_enum():
class SoftwareEnvironment(Enum):
DEV = auto()
STAGING = auto()
PROD = auto()
_PROD_OLD = auto()
# tests case-insensitivity
assert SoftwareEnvironment.STAGING == convert(SoftwareEnvironment, ["staging"])
# tests underscore/hyphen support
assert SoftwareEnvironment._PROD_OLD == convert(SoftwareEnvironment, ["prod_old"])
assert SoftwareEnvironment._PROD_OLD == convert(SoftwareEnvironment, ["prod-old"])
with pytest.raises(CoercionError):
convert(SoftwareEnvironment, ["invalid-choice"])
def test_coerce_tuple_basic_single():
_assert_tuple((1,), convert(Tuple[int], ["1"]))
def test_coerce_tuple_str_single():
_assert_tuple(("foo",), convert(Tuple[str], ["foo"]))
def test_coerce_tuple_basic_double():
_assert_tuple((1, 2.0), convert(Tuple[int, Union[None, float, int]], ["1", "2"]))
def test_coerce_tuple_typing_no_inner_types():
_assert_tuple(("1", "2"), convert(Tuple, ["1", "2"]))
def test_coerce_tuple_builtin_no_inner_types():
_assert_tuple(("1", "2"), convert(tuple, ["1", "2"]))
def test_coerce_tuple_nested():
_assert_tuple(
(1, (2.0, "foo")),
convert(Tuple[int, Tuple[float, Union[None, str, int]]], ["1", "2", "foo"]),
)
def test_coerce_tuple_len_mismatch_underflow():
with pytest.raises(CoercionError):
convert(Tuple[int, int], ["1"])
def test_coerce_tuple_len_mismatch_overflow():
with pytest.raises(CoercionError):
convert(Tuple[int, int], ["1", "2", "3"])
@pytest.mark.skipif(sys.version_info < (3, 11), reason="Typing")
def test_coerce_tuple_ellipsis_too_many_inner_types():
with pytest.raises(ValueError): # This is a ValueError because it happens prior to runtime.
# Only 1 inner type annotation allowed
convert(Tuple[int, int, ...], ["1", "2"]) # pyright: ignore
def test_coerce_tuple_ellipsis_non_divisible():
with pytest.raises(CoercionError):
convert(Tuple[Tuple[int, int], ...], ["1", "2", "3"])
def test_coerce_list():
assert [123, 456] == convert(int, ["123", "456"])
assert [123, 456] == convert(List[int], ["123", "456"])
assert [123] == convert(List[int], ["123"])
def test_coerce_list_of_tuple_str_single_1():
res = convert(List[Tuple[str]], ["foo"])
assert isinstance(res, list)
assert len(res) == 1
_assert_tuple(("foo",), res[0])
def test_coerce_list_of_tuple_str_single_2():
res = convert(List[Tuple[str]], ["foo", "bar"])
assert isinstance(res, list)
assert len(res) == 2
_assert_tuple(("foo",), res[0])
_assert_tuple(("bar",), res[1])
def test_coerce_bare_list():
# Implicit element type: str
assert ["123", "456"] == convert(list, ["123", "456"])
def test_coerce_iterable():
assert [123, 456] == convert(Iterable[int], ["123", "456"])
assert [123] == convert(Iterable[int], ["123"])
def test_coerce_set():
assert {"123", "456"} == convert(Set[str], ["123", "456"])
assert {123, 456} == convert(Set[Union[int, str]], ["123", "456"])
def test_coerce_frozenset():
assert frozenset({"123", "456"}) == convert(frozenset[str], ["123", "456"])
assert frozenset({123, 456}) == convert(frozenset[Union[int, str]], ["123", "456"])
def test_coerce_literal():
assert "foo" == convert(Literal["foo", "bar", 3], ["foo"])
assert "bar" == convert(Literal["foo", "bar", 3], ["bar"])
assert 3 == convert(Literal["foo", "bar", 3], ["3"])
def assert_convert_coercion_error(*args, msg, **kwargs):
mock_argument = Mock()
mock_argument.name = "mocked_argument_name"
with pytest.raises(CoercionError) as e:
try:
convert(*args, **kwargs)
except CoercionError as coercion_error:
coercion_error.argument = mock_argument
raise
exception_message = str(e.value).split("\n", 1)[1]
assert exception_message == msg
def test_coerce_literal_invalid_choice():
assert_convert_coercion_error(
Literal["foo", "bar", 3],
["invalid-choice"],
msg="""Invalid value for "MOCKED_ARGUMENT_NAME": unable to convert "invalid-choice" into one of {'foo', 'bar', 3}.""",
)
def test_coerce_literal_invalid_choice_keyword():
assert_convert_coercion_error(
Literal["foo", "bar", 3],
[Token(keyword="--MY_KEYWORD", value="invalid-choice")],
msg="""Invalid value for "--MY_KEYWORD": unable to convert "invalid-choice" into one of {'foo', 'bar', 3}.""",
)
def test_coerce_literal_invalid_choice_non_cli_token():
assert_convert_coercion_error(
Literal["foo", "bar", 3],
[Token(value="invalid-choice", source="TEST")],
msg="""Invalid value for "MOCKED_ARGUMENT_NAME" from TEST: unable to convert "invalid-choice" into one of {'foo', 'bar', 3}.""",
)
def test_coerce_literal_invalid_choice_keyword_non_cli_token():
assert_convert_coercion_error(
Literal["foo", "bar", 3],
[Token(keyword="--MY-KEYWORD", value="invalid-choice", source="TEST")],
msg="""Invalid value for "--MY-KEYWORD" from TEST: unable to convert "invalid-choice" into one of {'foo', 'bar', 3}.""",
)
def test_coerce_path():
assert Path("foo") == convert(Path, ["foo"])
def test_coerce_any():
assert "foo" == convert(Any, ["foo"])
def test_coerce_bytes():
assert b"foo" == convert(bytes, ["foo"])
assert [b"foo", b"bar"] == convert(bytes, ["foo", "bar"])
def test_coerce_bytearray():
res = convert(bytearray, ["foo"])
assert isinstance(res, bytearray)
assert bytearray(b"foo") == res
assert [bytearray(b"foo"), bytearray(b"bar")] == convert(bytearray, ["foo", "bar"])
def test_coerce_parameter_kind_empty():
assert "foo" == convert(inspect.Parameter.empty, ["foo"])
def test_coerce_datetime():
expected = datetime.strptime("1956-01-31T10:00:00", "%Y-%m-%dT%H:%M:%S")
assert expected == convert(datetime, ["1956-01-31T10:00:00"])
@pytest.mark.parametrize(
"input_string, expected_output",
[
# Basic single unit tests
("30s", timedelta(seconds=30)),
("5m", timedelta(minutes=5)),
("2h", timedelta(hours=2)),
("1d", timedelta(days=1)),
("3w", timedelta(weeks=3)),
("6M", timedelta(days=30 * 6)), # Approximation: 1 month = 30 days
("1y", timedelta(days=365)), # Approximation: 1 year = 365 days
# Combined duration tests
("1h30m", timedelta(hours=1, minutes=30)),
("1d12h", timedelta(days=1, hours=12)),
("2d5h30m", timedelta(days=2, hours=5, minutes=30)),
("1w2d", timedelta(weeks=1, days=2)),
("3h45m20s", timedelta(hours=3, minutes=45, seconds=20)),
# Zero and small values
("0s", timedelta(seconds=0)),
("1s", timedelta(seconds=1)),
# Large values
("100d", timedelta(days=100)),
("10000s", timedelta(seconds=10000)),
# Mixed order (should still work)
("30m1h", timedelta(hours=1, minutes=30)),
("45s2h", timedelta(hours=2, seconds=45)),
# Repeated units (should add them)
("1h1h", timedelta(hours=2)),
("1d1d1d", timedelta(days=3)),
# Negative duration
("-1h", timedelta(hours=-1)),
# Decimal duration
("1.5h", timedelta(hours=1.5)),
],
)
def test_parse_timedelta_valid(input_string, expected_output):
"""Test that valid duration strings are parsed correctly."""
assert convert(timedelta, [input_string]) == expected_output
@pytest.mark.parametrize(
"invalid_input",
[
"", # Empty string
"abc", # No numbers or units
"1", # Number without unit
"1x", # Invalid unit
"h1", # Unit before number
"3 days", # Full unit names with spaces not supported
],
)
def test_parse_timedelta_invalid(invalid_input):
with pytest.raises(CoercionError):
convert(timedelta, [invalid_input])
def test_parse_timedelta_equivalence():
assert convert(timedelta, ["1h"]) == convert(timedelta, ["60m"])
assert convert(timedelta, ["1d"]) == convert(timedelta, ["24h"])
assert convert(timedelta, ["1w"]) == convert(timedelta, ["7d"])
assert convert(timedelta, ["1h30m"]) == convert(timedelta, ["90m"])
assert convert(timedelta, ["1d12h"]) == convert(timedelta, ["36h"])
|