Debian Codegraph @

tests/test_coercion.py

raw symbols SCIP
1 import inspect
2 import sys
3 from collections.abc import Iterable, Sequence
4 from collections.abc import MutableSequence as AbcMutableSequence
5 from collections.abc import MutableSet as AbcMutableSet
6 from collections.abc import Set as AbcSet
7 from datetime import date, datetime, timedelta
8 from enum import Enum, auto
9 from pathlib import Path
10 from typing import Annotated, Any, Literal, Optional, Union
11 from unittest.mock import Mock
12
13 import pytest
14
15 from cyclopts import CoercionError, Token
16 from cyclopts._convert import convert, token_count
17 from cyclopts.utils import default_name_transform
18
19
20 def _assert_tuple(expected, actual):
21 assert type(actual) is tuple
22 assert len(expected) == len(actual)
23 for e, a in zip(expected, actual, strict=False):
24 assert type(e) is type(a)
25 assert e == a
26
27
28 def test_token_count_tuple_basic():
29 assert (3, False) == token_count(tuple[int, int, int])
30
31
32 def test_token_count_tuple_no_inner_type():
33 assert (1, True) == token_count(tuple)
34 assert (1, True) == token_count(tuple)
35
36
37 def test_token_count_tuple_nested():
38 assert (4, False) == token_count(tuple[tuple[int, int], int, int])
39
40
41 def test_token_count_tuple_ellipsis():
42 assert (1, True) == token_count(tuple[int, ...])
43
44
45 def test_token_count_tuple_ellipsis_nested():
46 assert (2, True) == token_count(tuple[tuple[int, int], ...])
47
48
49 def test_token_union():
50 assert (1, False) == token_count(Union[None, int])
51
52
53 def test_token_count_standard():
54 assert (1, False) == token_count(int)
55
56
57 def test_token_count_bool():
58 assert (0, False) == token_count(bool)
59
60
61 def test_token_count_list():
62 assert (1, True) == token_count(list[int])
63
64
65 def test_token_count_sequence():
66 assert (1, True) == token_count(Sequence[int])
67 assert (2, True) == token_count(Sequence[tuple[int, int]])
68
69
70 def test_token_count_list_generic():
71 assert (1, True) == token_count(list)
72
73
74 def test_token_count_list_direct():
75 assert (1, True) == token_count(list[int]) # pyright: ignore
76
77
78 def test_token_count_list_of_tuple():
79 assert (3, True) == token_count(list[tuple[int, int, int]])
80
81
82 def test_token_count_list_of_tuple_nested():
83 assert (4, True) == token_count(list[tuple[tuple[int, int], int, int]])
84
85
86 def test_token_count_iterable():
87 assert (1, True) == token_count(Iterable[int])
88 assert (2, True) == token_count(Iterable[tuple[int, int]])
89
90
91 def test_token_count_union():
92 assert (1, False) == token_count(Union[int, str, float])
93
94
95 def test_token_count_union_error():
96 with pytest.raises(ValueError):
97 assert (1, False) == token_count(Union[int, tuple[int, int]])
98
99
100 def test_coerce_no_tokens():
101 with pytest.raises(ValueError):
102 convert(int, [])
103
104
105 def test_coerce_bool():
106 assert True is convert(bool, ["true"])
107 assert False is convert(bool, ["false"])
108
109
110 def test_coerce_error():
111 with pytest.raises(CoercionError):
112 convert(bool, ["foo"])
113
114
115 def test_coerce_int():
116 assert 123 == convert(int, ["123"])
117
118
119 def test_coerce_annotated_int():
120 assert [123, 456] == convert(Annotated[int, "foo"], ["123", "456"])
121 assert [123, 456] == convert(Annotated[list[int], "foo"], ["123", "456"])
122
123
124 def test_coerce_optional_annotated_int():
125 assert [123, 456] == convert(Optional[Annotated[int, "foo"]], ["123", "456"])
126 assert [123, 456] == convert(Optional[Annotated[list[int], "foo"]], ["123", "456"])
127
128
129 def test_coerce_annotated_union_str_secondary_choice():
130 assert 123 == convert(Union[None, int, str], ["123"])
131 assert "foo" == convert(Union[None, int, str], ["foo"])
132
133 with pytest.raises(CoercionError):
134 convert(Union[None, int, float], ["invalid-choice"])
135
136
137 def test_coerce_annotated_nested_union_str_secondary_choice():
138 assert 123 == convert(Union[None, int | str], ["123"])
139 assert "foo" == convert(Union[None, int | str], ["foo"])
140
141
142 def test_coerce_annotated_union_int():
143 assert 123 == convert(Annotated[None | int | float, "foo"], ["123"])
144 assert [123, 456] == convert(Annotated[int, "foo"], ["123", "456"])
145 assert [123, 456] == convert(Annotated[None | int | float, "foo"], ["123", "456"])
146
147
148 def test_coerce_enum():
149 class SoftwareEnvironment(Enum):
150 DEV = auto()
151 STAGING = auto()
152 PROD = auto()
153 _PROD_OLD = (
154 auto()
155 ) # test that leading underscores are stripped and then hyphens can be used instead of underscores.
156
157 DEVELOPMENT = DEV # Tests that aliases resolve
158
159 # tests case-insensitivity
160 assert SoftwareEnvironment.STAGING == convert(SoftwareEnvironment, ["staging"])
161
162 # tests underscore/hyphen support
163 assert SoftwareEnvironment._PROD_OLD == convert(SoftwareEnvironment, ["prod_old"])
164 assert SoftwareEnvironment._PROD_OLD == convert(SoftwareEnvironment, ["prod-old"])
165
166 # Test aliases
167 assert SoftwareEnvironment.DEV == convert(SoftwareEnvironment, ["development"])
168
169 with pytest.raises(CoercionError):
170 convert(SoftwareEnvironment, ["invalid-choice"])
171
172
173 def test_coerce_enum_invalid_choice():
174 class GroupedConstants(Enum):
175 FOO = auto()
176 BAR = auto()
177
178 assert_convert_coercion_error(
179 GroupedConstants,
180 ["invalid-choice"],
181 msg='Invalid value "invalid-choice" for MOCKED_ARGUMENT_NAME. Choose from: "foo", "bar".',
182 )
183
184
185 def test_coerce_enum_invalid_choice_name_transform():
186 class SoftwareEnvironment(Enum):
187 DEV_LOCAL = 1
188 STAGING_US = 2
189 PROD_WEST = 3
190
191 assert_convert_coercion_error(
192 SoftwareEnvironment,
193 ["invalid"],
194 msg='Invalid value "invalid" for MOCKED_ARGUMENT_NAME. Choose from: "dev-local", "staging-us", "prod-west".',
195 )
196
197
198 def test_coerce_enum_invalid_choice_custom_name_transform():
199 class SoftwareEnvironment(Enum):
200 dev_local = 1
201 staging_us = 2
202
203 assert_convert_coercion_error(
204 SoftwareEnvironment,
205 ["invalid"],
206 name_transform=str.upper,
207 msg='Invalid value "invalid" for MOCKED_ARGUMENT_NAME. Choose from: "DEV_LOCAL", "STAGING_US".',
208 )
209
210
211 def test_coerce_tuple_basic_single():
212 _assert_tuple((1,), convert(tuple[int], ["1"]))
213
214
215 def test_coerce_tuple_str_single():
216 _assert_tuple(("foo",), convert(tuple[str], ["foo"]))
217
218
219 def test_coerce_tuple_basic_double():
220 _assert_tuple((1, 2.0), convert(tuple[int, None | float | int], ["1", "2"]))
221
222
223 def test_coerce_tuple_typing_no_inner_types():
224 _assert_tuple(("1", "2"), convert(tuple, ["1", "2"]))
225
226
227 def test_coerce_tuple_builtin_no_inner_types():
228 _assert_tuple(("1", "2"), convert(tuple, ["1", "2"]))
229
230
231 def test_coerce_tuple_nested():
232 _assert_tuple(
233 (1, (2.0, "foo")),
234 convert(tuple[int, tuple[float, None | str | int]], ["1", "2", "foo"]),
235 )
236
237
238 def test_coerce_tuple_len_mismatch_underflow():
239 with pytest.raises(CoercionError):
240 convert(tuple[int, int], ["1"])
241
242
243 def test_coerce_tuple_len_mismatch_overflow():
244 with pytest.raises(CoercionError):
245 convert(tuple[int, int], ["1", "2", "3"])
246
247
248 @pytest.mark.skipif(sys.version_info < (3, 11), reason="Typing")
249 def test_coerce_tuple_ellipsis_too_many_inner_types():
250 with pytest.raises(ValueError): # This is a ValueError because it happens prior to runtime.
251 # Only 1 inner type annotation allowed
252 convert(tuple[int, int, ...], ["1", "2"]) # pyright: ignore
253
254
255 def test_coerce_tuple_ellipsis_non_divisible():
256 with pytest.raises(CoercionError):
257 convert(tuple[tuple[int, int], ...], ["1", "2", "3"])
258
259
260 def test_coerce_list():
261 assert [123, 456] == convert(int, ["123", "456"])
262 assert [123, 456] == convert(list[int], ["123", "456"])
263 assert [123] == convert(list[int], ["123"])
264
265
266 def test_coerce_list_of_tuple_str_single_1():
267 res = convert(list[tuple[str]], ["foo"])
268 assert isinstance(res, list)
269 assert len(res) == 1
270 _assert_tuple(("foo",), res[0])
271
272
273 def test_coerce_list_of_tuple_str_single_2():
274 res = convert(list[tuple[str]], ["foo", "bar"])
275 assert isinstance(res, list)
276 assert len(res) == 2
277 _assert_tuple(("foo",), res[0])
278 _assert_tuple(("bar",), res[1])
279
280
281 def test_coerce_bare_list():
282 # Implicit element type: str
283 assert ["123", "456"] == convert(list, ["123", "456"])
284
285
286 def test_coerce_iterable():
287 assert [123, 456] == convert(Iterable[int], ["123", "456"])
288 assert [123] == convert(Iterable[int], ["123"])
289
290
291 def test_coerce_set():
292 assert {"123", "456"} == convert(set[str], ["123", "456"])
293 assert {123, 456} == convert(set[int | str], ["123", "456"])
294
295
296 def test_coerce_frozenset():
297 assert frozenset({"123", "456"}) == convert(frozenset[str], ["123", "456"])
298 assert frozenset({123, 456}) == convert(frozenset[int | str], ["123", "456"])
299
300
301 @pytest.mark.parametrize(
302 "hint,expected",
303 [
304 (AbcSet[str], {"123", "456"}),
305 (AbcMutableSet[str], {"123", "456"}),
306 (AbcMutableSequence[str], ["123", "456"]),
307 (AbcSet, {"123", "456"}),
308 (AbcMutableSet, {"123", "456"}),
309 (AbcMutableSequence, ["123", "456"]),
310 ],
311 )
312 def test_coerce_abstract_collection_types(hint, expected):
313 """Test that collections.abc abstract types are supported (issue #702).
314
315 Tests both parameterized types (e.g., Set[str]) and bare types (e.g., Set).
316 Bare abstract types should default to [str] like bare concrete types do.
317 """
318 result = convert(hint, ["123", "456"])
319 assert expected == result
320
321
322 def test_coerce_literal():
323 assert "foo" == convert(Literal["foo", "bar", 3], ["foo"])
324 assert "bar" == convert(Literal["foo", "bar", 3], ["bar"])
325 assert 3 == convert(Literal["foo", "bar", 3], ["3"])
326
327
328 def assert_convert_coercion_error(*args, msg, name_transform=None, **kwargs):
329 if name_transform is None:
330 name_transform = default_name_transform
331 mock_argument = Mock()
332 mock_argument.name = "mocked_argument_name"
333 mock_argument.parameter.name_transform = name_transform
334 kwargs.setdefault("name_transform", name_transform)
335 with pytest.raises(CoercionError) as e:
336 try:
337 convert(*args, **kwargs)
338 except CoercionError as coercion_error:
339 coercion_error.argument = mock_argument
340 raise
341 exception_message = str(e.value).split("\n", 1)[1]
342 assert exception_message == msg
343
344
345 def test_coerce_literal_invalid_choice():
346 assert_convert_coercion_error(
347 Literal["foo", "bar", 3],
348 ["invalid-choice"],
349 msg='Invalid value "invalid-choice" for MOCKED_ARGUMENT_NAME. Choose from: "foo", "bar", 3.',
350 )
351
352
353 def test_coerce_literal_invalid_choice_keyword():
354 assert_convert_coercion_error(
355 Literal["foo", "bar", 3],
356 [Token(keyword="--MY_KEYWORD", value="invalid-choice")],
357 msg='Invalid value "invalid-choice" for --MY_KEYWORD. Choose from: "foo", "bar", 3.',
358 )
359
360
361 def test_coerce_literal_invalid_choice_non_cli_token():
362 assert_convert_coercion_error(
363 Literal["foo", "bar", 3],
364 [Token(value="invalid-choice", source="TEST")],
365 msg='Invalid value "invalid-choice" for MOCKED_ARGUMENT_NAME from TEST. Choose from: "foo", "bar", 3.',
366 )
367
368
369 def test_coerce_literal_invalid_choice_keyword_non_cli_token():
370 assert_convert_coercion_error(
371 Literal["foo", "bar", 3],
372 [Token(keyword="--MY-KEYWORD", value="invalid-choice", source="TEST")],
373 msg='Invalid value "invalid-choice" for --MY-KEYWORD from TEST. Choose from: "foo", "bar", 3.',
374 )
375
376
377 def test_coerce_literal_invalid_choice_did_you_mean():
378 assert_convert_coercion_error(
379 Literal["pishock", "openshock"],
380 ["pisock"],
381 msg='Invalid value "pisock" for MOCKED_ARGUMENT_NAME. Choose from: "pishock", "openshock". Did you mean "pishock"?',
382 )
383
384
385 def test_coerce_literal_invalid_choice_no_did_you_mean():
386 assert_convert_coercion_error(
387 Literal["pishock", "openshock"],
388 ["auth"],
389 msg='Invalid value "auth" for MOCKED_ARGUMENT_NAME. Choose from: "pishock", "openshock".',
390 )
391
392
393 def test_coerce_enum_invalid_choice_did_you_mean_uses_name_transform():
394 class SoftwareEnvironment(Enum):
395 DEV_LOCAL = 1
396 STAGING_US = 2
397 PROD_WEST = 3
398
399 assert_convert_coercion_error(
400 SoftwareEnvironment,
401 ["staging-uss"],
402 msg='Invalid value "staging-uss" for MOCKED_ARGUMENT_NAME. Choose from: "dev-local", "staging-us", "prod-west". Did you mean "staging-us"?',
403 )
404
405
406 def test_coerce_path():
407 assert Path("foo") == convert(Path, ["foo"])
408
409
410 def test_coerce_any():
411 assert "foo" == convert(Any, ["foo"])
412
413
414 def test_coerce_bytes():
415 assert b"foo" == convert(bytes, ["foo"])
416 assert [b"foo", b"bar"] == convert(bytes, ["foo", "bar"])
417
418
419 def test_coerce_bytearray():
420 res = convert(bytearray, ["foo"])
421 assert isinstance(res, bytearray)
422 assert bytearray(b"foo") == res
423
424 assert [bytearray(b"foo"), bytearray(b"bar")] == convert(bytearray, ["foo", "bar"])
425
426
427 def test_coerce_parameter_kind_empty():
428 assert "foo" == convert(inspect.Parameter.empty, ["foo"])
429
430
431 def test_coerce_date():
432 expected = date(year=1956, month=1, day=31)
433 assert expected == convert(date, ["1956-01-31"])
434
435
436 @pytest.mark.skipif(sys.version_info < (3, 11), reason="Not implemented in stdlib")
437 def test_coerce_date_other_iso_formats():
438 expected = date(year=2021, month=1, day=4)
439 assert expected == convert(date, ["2021-W01-1"])
440
441
442 @pytest.mark.parametrize(
443 "input_string, format_str",
444 [
445 ("1956-01-31", "%Y-%m-%d"), # ISO 8601 date only
446 ("1956-01-31T10:00:00", "%Y-%m-%dT%H:%M:%S"), # ISO 8601 with time
447 ("1956-01-31 10:00:00", "%Y-%m-%d %H:%M:%S"), # Space separator
448 ("1956-01-31T10:00:00.123456", "%Y-%m-%dT%H:%M:%S.%f"), # With microseconds
449 ],
450 )
451 def test_coerce_datetime(input_string, format_str):
452 """Test that various datetime formats are supported."""
453 expected = datetime.strptime(input_string, format_str)
454 assert expected == convert(datetime, [input_string])
455
456
457 @pytest.mark.parametrize(
458 "input_string, expected_output",
459 [
460 # Basic single unit tests
461 ("30s", timedelta(seconds=30)),
462 ("5m", timedelta(minutes=5)),
463 ("2h", timedelta(hours=2)),
464 ("1d", timedelta(days=1)),
465 ("3w", timedelta(weeks=3)),
466 ("6M", timedelta(days=30 * 6)), # Approximation: 1 month = 30 days
467 ("1y", timedelta(days=365)), # Approximation: 1 year = 365 days
468 # Combined duration tests
469 ("1h30m", timedelta(hours=1, minutes=30)),
470 ("1d12h", timedelta(days=1, hours=12)),
471 ("2d5h30m", timedelta(days=2, hours=5, minutes=30)),
472 ("1w2d", timedelta(weeks=1, days=2)),
473 ("3h45m20s", timedelta(hours=3, minutes=45, seconds=20)),
474 # Zero and small values
475 ("0s", timedelta(seconds=0)),
476 ("1s", timedelta(seconds=1)),
477 # Large values
478 ("100d", timedelta(days=100)),
479 ("10000s", timedelta(seconds=10000)),
480 # Mixed order (should still work)
481 ("30m1h", timedelta(hours=1, minutes=30)),
482 ("45s2h", timedelta(hours=2, seconds=45)),
483 # Repeated units (should add them)
484 ("1h1h", timedelta(hours=2)),
485 ("1d1d1d", timedelta(days=3)),
486 # Negative duration
487 ("-1h", timedelta(hours=-1)),
488 # Decimal duration
489 ("1.5h", timedelta(hours=1.5)),
490 ],
491 )
492 def test_parse_timedelta_valid(input_string, expected_output):
493 """Test that valid duration strings are parsed correctly."""
494 assert convert(timedelta, [input_string]) == expected_output
495
496
497 @pytest.mark.parametrize(
498 "invalid_input",
499 [
500 "", # Empty string
501 "abc", # No numbers or units
502 "1", # Number without unit
503 "1x", # Invalid unit
504 "h1", # Unit before number
505 "3 days", # Full unit names with spaces not supported
506 ],
507 )
508 def test_parse_timedelta_invalid(invalid_input):
509 with pytest.raises(CoercionError):
510 convert(timedelta, [invalid_input])
511
512
513 def test_coerce_date_invalid_format():
514 """Test that invalid date format raises CoercionError."""
515 with pytest.raises(CoercionError):
516 convert(date, ["not-a-date"])
517
518
519 def test_coerce_datetime_invalid_format():
520 """Test that invalid datetime format raises CoercionError."""
521 with pytest.raises(CoercionError):
522 convert(datetime, ["not-a-date"])
523
524
525 def test_parse_timedelta_equivalence():
526 """Test that equivalent timedelta formats produce the same result."""
527 assert convert(timedelta, ["1h"]) == convert(timedelta, ["60m"])
528 assert convert(timedelta, ["1d"]) == convert(timedelta, ["24h"])
529 assert convert(timedelta, ["1w"]) == convert(timedelta, ["7d"])
530 assert convert(timedelta, ["1h30m"]) == convert(timedelta, ["90m"])
531 assert convert(timedelta, ["1d12h"]) == convert(timedelta, ["36h"])