| 1 |
from collections.abc import Iterable, Sequence |
| 2 |
from dataclasses import dataclass |
| 3 |
from typing import Annotated |
| 4 |
|
| 5 |
import pytest |
| 6 |
|
| 7 |
from cyclopts import CycloptsError, Parameter |
| 8 |
|
| 9 |
LIST_STR_LIKE_TYPES = [ |
| 10 |
pytest.param(list, id="list"), |
| 11 |
pytest.param(list[str], id="list[str]"), |
| 12 |
pytest.param(list[str] | None, id="list[str]|None"), |
| 13 |
pytest.param(Sequence, id="Sequence"), |
| 14 |
pytest.param(Sequence[str], id="Sequence[str]"), |
| 15 |
pytest.param(Sequence[str] | None, id="Sequence[str]|None"), |
| 16 |
pytest.param(Iterable, id="Iterable"), |
| 17 |
pytest.param(Iterable[str], id="Iterable[str]"), |
| 18 |
pytest.param(Iterable[str] | None, id="Iterable[str]|None"), |
| 19 |
] |
| 20 |
|
| 21 |
|
| 22 |
@dataclass |
| 23 |
class User: |
| 24 |
name: str |
| 25 |
age: int |
| 26 |
|
| 27 |
|
| 28 |
@pytest.mark.parametrize( |
| 29 |
"cmd_str", |
| 30 |
[ |
| 31 |
"--values=[1,2,3]", |
| 32 |
"--values [1,2,3]", |
| 33 |
"--values [1,2] --values [3]", |
| 34 |
"--values [1] --values '[2, 3]'", |
| 35 |
"--values 1 --values [2,3]", |
| 36 |
"--values [1] --values [2] --values [3]", |
| 37 |
], |
| 38 |
) |
| 39 |
@pytest.mark.parametrize("json_list", [None, True]) |
| 40 |
def test_json_list_cli_str(app, assert_parse_args, cmd_str, json_list): |
| 41 |
@app.default |
| 42 |
def main(values: Annotated[list[int], Parameter(json_list=json_list)]): |
| 43 |
pass |
| 44 |
|
| 45 |
assert_parse_args(main, cmd_str, [1, 2, 3]) |
| 46 |
|
| 47 |
|
| 48 |
@pytest.mark.parametrize("annotation", LIST_STR_LIKE_TYPES) |
| 49 |
def test_json_list_str_none(app, assert_parse_args, annotation): |
| 50 |
"""A ``list`` or ``list[str]`` annotation should **not** be set-able via json-string by default. |
| 51 |
|
| 52 |
May change in v4. |
| 53 |
""" |
| 54 |
|
| 55 |
@app.default |
| 56 |
def main(values: annotation): |
| 57 |
pass |
| 58 |
|
| 59 |
assert_parse_args(main, ['["foo", "bar"]'], ['["foo", "bar"]']) |
| 60 |
|
| 61 |
|
| 62 |
def test_json_list_optional_int(app, assert_parse_args): |
| 63 |
@app.default |
| 64 |
def main(values: list[int | None]): |
| 65 |
pass |
| 66 |
|
| 67 |
assert_parse_args(main, ["[1, null, 2]"], [1, None, 2]) |
| 68 |
|
| 69 |
|
| 70 |
@pytest.mark.parametrize("annotation", LIST_STR_LIKE_TYPES) |
| 71 |
def test_json_list_str_cli_str_true(app, assert_parse_args, annotation): |
| 72 |
@app.default |
| 73 |
def main(values: Annotated[annotation, Parameter(json_list=True)]): |
| 74 |
pass |
| 75 |
|
| 76 |
assert_parse_args(main, ['["foo", "bar"]'], ["foo", "bar"]) |
| 77 |
|
| 78 |
|
| 79 |
@pytest.mark.parametrize("annotation", [list, list[str]]) |
| 80 |
def test_json_list_str_cli_str_false(app, assert_parse_args, annotation): |
| 81 |
@app.default |
| 82 |
def main(values: Annotated[annotation, Parameter(json_list=False)]): |
| 83 |
pass |
| 84 |
|
| 85 |
assert_parse_args(main, ['["foo", "bar"]'], ['["foo", "bar"]']) |
| 86 |
|
| 87 |
|
| 88 |
@pytest.mark.parametrize( |
| 89 |
"env_str", |
| 90 |
[ |
| 91 |
"[1,2,3]", |
| 92 |
"[1, 2, 3]", |
| 93 |
], |
| 94 |
) |
| 95 |
@pytest.mark.parametrize("json_list", [None, True]) |
| 96 |
def test_json_list_env_str(app, assert_parse_args, env_str, monkeypatch, json_list): |
| 97 |
monkeypatch.setenv("VALUES", env_str) |
| 98 |
|
| 99 |
@app.default |
| 100 |
def main(values: Annotated[list[int], Parameter(env_var="VALUES", json_list=json_list)]): |
| 101 |
pass |
| 102 |
|
| 103 |
assert_parse_args(main, "", [1, 2, 3]) |
| 104 |
|
| 105 |
|
| 106 |
def test_json_list_of_dataclass_array(app, assert_parse_args): |
| 107 |
"""Test JSON array input for list of dataclasses.""" |
| 108 |
|
| 109 |
@app.default |
| 110 |
def main(values: list[User]): |
| 111 |
pass |
| 112 |
|
| 113 |
assert_parse_args( |
| 114 |
main, |
| 115 |
["--values", '[{"name": "Alice", "age": 30}, {"name": "Bob", "age": 40}]'], |
| 116 |
[User("Alice", 30), User("Bob", 40)], |
| 117 |
) |
| 118 |
|
| 119 |
|
| 120 |
def test_json_list_of_dataclass_env_var(app, assert_parse_args, monkeypatch): |
| 121 |
"""Test JSON array from environment variable for list of dataclasses.""" |
| 122 |
monkeypatch.setenv("USERS", '[{"name": "Alice", "age": 30}, {"name": "Bob", "age": 40}]') |
| 123 |
|
| 124 |
@app.default |
| 125 |
def main(values: Annotated[list[User], Parameter(env_var="USERS")]): |
| 126 |
pass |
| 127 |
|
| 128 |
assert_parse_args(main, "", [User("Alice", 30), User("Bob", 40)]) |
| 129 |
|
| 130 |
|
| 131 |
def test_json_list_of_dataclass_individual(app, assert_parse_args): |
| 132 |
"""Test multiple individual JSON objects for list of dataclasses.""" |
| 133 |
|
| 134 |
@app.default |
| 135 |
def main(values: list[User]): |
| 136 |
pass |
| 137 |
|
| 138 |
assert_parse_args( |
| 139 |
main, |
| 140 |
["--values", '{"name": "Alice", "age": 30}', "--values", '{"name": "Bob", "age": 40}'], |
| 141 |
[User("Alice", 30), User("Bob", 40)], |
| 142 |
) |
| 143 |
|
| 144 |
|
| 145 |
def test_json_list_of_dataclass_mixed(app, assert_parse_args): |
| 146 |
"""Test mixing individual JSON objects with JSON arrays.""" |
| 147 |
|
| 148 |
@app.default |
| 149 |
def main(values: list[User]): |
| 150 |
pass |
| 151 |
|
| 152 |
assert_parse_args( |
| 153 |
main, |
| 154 |
[ |
| 155 |
"--values", |
| 156 |
'{"name": "Alice", "age": 30}', |
| 157 |
"--values", |
| 158 |
'[{"name": "Bob", "age": 40}, {"name": "Charlie", "age": 50}]', |
| 159 |
"--values", |
| 160 |
'{"name": "David", "age": 60}', |
| 161 |
], |
| 162 |
[User("Alice", 30), User("Bob", 40), User("Charlie", 50), User("David", 60)], |
| 163 |
) |
| 164 |
|
| 165 |
|
| 166 |
def test_json_list_of_dataclass_empty_array(app, assert_parse_args): |
| 167 |
"""Test empty JSON array for list of dataclasses.""" |
| 168 |
|
| 169 |
@app.default |
| 170 |
def main(values: list[User] | None = None): |
| 171 |
pass |
| 172 |
|
| 173 |
assert_parse_args(main, ["--values", "[]"], []) |
| 174 |
|
| 175 |
|
| 176 |
def test_json_list_of_dataclass_single_element_array(app, assert_parse_args): |
| 177 |
"""Test single-element JSON array.""" |
| 178 |
|
| 179 |
@app.default |
| 180 |
def main(values: list[User]): |
| 181 |
pass |
| 182 |
|
| 183 |
assert_parse_args( |
| 184 |
main, |
| 185 |
["--values", '[{"name": "Alice", "age": 30}]'], |
| 186 |
[User("Alice", 30)], |
| 187 |
) |
| 188 |
|
| 189 |
|
| 190 |
|
| 191 |
|
| 192 |
|
| 193 |
|
| 194 |
|
| 195 |
def test_json_list_malformed_json_array(app): |
| 196 |
"""Test that malformed JSON array raises appropriate error.""" |
| 197 |
|
| 198 |
@app.default |
| 199 |
def main(values: list[User]): |
| 200 |
pass |
| 201 |
|
| 202 |
|
| 203 |
with pytest.raises(CycloptsError): |
| 204 |
app(["--values", '[{"name": "Alice", "age": 30}'], exit_on_error=False) |
| 205 |
|
| 206 |
|
| 207 |
def test_json_list_malformed_json_object(app): |
| 208 |
"""Test that malformed JSON object raises appropriate error.""" |
| 209 |
|
| 210 |
@app.default |
| 211 |
def main(values: list[User]): |
| 212 |
pass |
| 213 |
|
| 214 |
|
| 215 |
with pytest.raises(CycloptsError): |
| 216 |
app(["--values", '{"name": "Alice", "age": 30'], exit_on_error=False) |
| 217 |
|
| 218 |
|
| 219 |
def test_json_list_malformed_json_array_env_var(app, monkeypatch): |
| 220 |
"""Test that malformed JSON array from environment variable raises appropriate error.""" |
| 221 |
|
| 222 |
monkeypatch.setenv("USERS", '[{"name": "Alice", "age": 30}') |
| 223 |
|
| 224 |
@app.default |
| 225 |
def main(values: Annotated[list[User], Parameter(env_var="USERS")]): |
| 226 |
pass |
| 227 |
|
| 228 |
with pytest.raises(CycloptsError): |
| 229 |
app([], exit_on_error=False) |
| 230 |
|
| 231 |
|
| 232 |
def test_json_list_malformed_json_object_env_var(app, monkeypatch): |
| 233 |
"""Test that malformed JSON object from environment variable raises appropriate error.""" |
| 234 |
|
| 235 |
monkeypatch.setenv("USER", '{"name": "Alice", "age": 30') |
| 236 |
|
| 237 |
@app.default |
| 238 |
def main(value: Annotated[User, Parameter(env_var="USER")]): |
| 239 |
pass |
| 240 |
|
| 241 |
with pytest.raises(CycloptsError): |
| 242 |
app([], exit_on_error=False) |
| 243 |
|
| 244 |
|
| 245 |
def test_json_list_invalid_json_syntax(app): |
| 246 |
"""Test that invalid JSON syntax raises appropriate error with helpful message.""" |
| 247 |
|
| 248 |
@app.default |
| 249 |
def main(values: list[User]): |
| 250 |
pass |
| 251 |
|
| 252 |
|
| 253 |
with pytest.raises(CycloptsError) as exc_info: |
| 254 |
app(["--values", "{'name': 'Alice', 'age': 30}"], exit_on_error=False) |
| 255 |
|
| 256 |
|
| 257 |
error_str = str(exc_info.value) |
| 258 |
assert "Invalid JSON for User" in error_str |
| 259 |
assert "'" in error_str |
| 260 |
assert "^" in error_str |
| 261 |
assert "Hint: JSON requires double quotes" in error_str |
| 262 |
|
| 263 |
|
| 264 |
def test_json_invalid_syntax_env_var(app, monkeypatch): |
| 265 |
"""Test that invalid JSON syntax from environment variable raises appropriate error.""" |
| 266 |
|
| 267 |
monkeypatch.setenv("USER", '{"name": "Alice", "age": 30, "active": True}') |
| 268 |
|
| 269 |
@app.default |
| 270 |
def main(value: Annotated[User, Parameter(env_var="USER")]): |
| 271 |
pass |
| 272 |
|
| 273 |
with pytest.raises(CycloptsError) as exc_info: |
| 274 |
app([], exit_on_error=False) |
| 275 |
|
| 276 |
error_str = str(exc_info.value) |
| 277 |
|
| 278 |
assert "Invalid value for USER" in error_str |
| 279 |
assert "JSONDecodeError" in error_str |
| 280 |
assert "True" in error_str |
| 281 |
|
| 282 |
|
| 283 |
def test_json_list_python_style_booleans(app): |
| 284 |
"""Test that Python-style booleans (True/False) in JSON raise appropriate error. |
| 285 |
|
| 286 |
JSON requires lowercase 'true' and 'false', not Python's 'True' and 'False'. |
| 287 |
This test ensures we properly handle this common mistake with clear, specific error messages. |
| 288 |
""" |
| 289 |
|
| 290 |
@dataclass |
| 291 |
class Item: |
| 292 |
enabled: bool |
| 293 |
disabled: bool |
| 294 |
name: str |
| 295 |
|
| 296 |
@app.default |
| 297 |
def main(values: list[Item]): |
| 298 |
pass |
| 299 |
|
| 300 |
|
| 301 |
with pytest.raises(CycloptsError) as exc_info: |
| 302 |
app(["--values", '{"enabled": True, "disabled": false, "name": "test"}'], exit_on_error=False) |
| 303 |
|
| 304 |
error_str = str(exc_info.value) |
| 305 |
assert "Invalid JSON for Item" in error_str |
| 306 |
assert "True" in error_str |
| 307 |
assert "^" in error_str |
| 308 |
assert "Hint: Use lowercase 'true' instead of Python's True" in error_str |
| 309 |
|
| 310 |
|
| 311 |
with pytest.raises(CycloptsError) as exc_info: |
| 312 |
app(["--values", '{"enabled": true, "disabled": False, "name": "test"}'], exit_on_error=False) |
| 313 |
|
| 314 |
error_str = str(exc_info.value) |
| 315 |
assert "Invalid JSON for Item" in error_str |
| 316 |
assert "False" in error_str |
| 317 |
assert "^" in error_str |
| 318 |
assert "Hint: Use lowercase 'false' instead of Python's False" in error_str |
| 319 |
|
| 320 |
|
| 321 |
_, bound, _ = app.parse_args(["--values", '{"enabled": true, "disabled": false, "name": "test"}']) |
| 322 |
assert bound.arguments["values"] == [Item(enabled=True, disabled=False, name="test")] |
| 323 |
|
| 324 |
|
| 325 |
def test_json_list_python_none(app): |
| 326 |
"""Test that Python's None in JSON raises appropriate error with specific hint.""" |
| 327 |
|
| 328 |
@dataclass |
| 329 |
class Config: |
| 330 |
name: str |
| 331 |
value: int | None |
| 332 |
|
| 333 |
@app.default |
| 334 |
def main(values: list[Config]): |
| 335 |
pass |
| 336 |
|
| 337 |
|
| 338 |
with pytest.raises(CycloptsError) as exc_info: |
| 339 |
app(["--values", '{"name": "test", "value": None}'], exit_on_error=False) |
| 340 |
|
| 341 |
|
| 342 |
error_str = str(exc_info.value) |
| 343 |
assert "Invalid JSON for Config" in error_str |
| 344 |
assert "None" in error_str |
| 345 |
assert "^" in error_str |
| 346 |
assert "Hint: Use 'null' instead of Python's None" in error_str |
| 347 |
|
| 348 |
|
| 349 |
_, bound, _ = app.parse_args(["--values", '{"name": "test", "value": null}']) |
| 350 |
assert bound.arguments["values"] == [Config(name="test", value=None)] |
| 351 |
|
| 352 |
|
| 353 |
def test_json_list_type_mismatch_in_field(app): |
| 354 |
"""Test that type mismatches in JSON fields now raise errors consistently. |
| 355 |
|
| 356 |
After the fix, both single dataclasses and lists of dataclasses |
| 357 |
perform type conversion and validation on JSON fields. |
| 358 |
""" |
| 359 |
|
| 360 |
@app.default |
| 361 |
def main(values: list[User]): |
| 362 |
pass |
| 363 |
|
| 364 |
|
| 365 |
with pytest.raises(CycloptsError): |
| 366 |
app(["--values", '{"name": "Alice", "age": "thirty"}'], exit_on_error=False) |
| 367 |
|
| 368 |
|
| 369 |
def test_json_list_type_conversion_success(app, assert_parse_args): |
| 370 |
"""Test that valid type conversions work for JSON fields in lists. |
| 371 |
|
| 372 |
String "25" should be converted to int 25. |
| 373 |
""" |
| 374 |
|
| 375 |
@app.default |
| 376 |
def main(values: list[User]): |
| 377 |
pass |
| 378 |
|
| 379 |
|
| 380 |
assert_parse_args( |
| 381 |
main, |
| 382 |
["--values", '{"name": "Alice", "age": "25"}'], |
| 383 |
[User("Alice", 25)], |
| 384 |
) |
| 385 |
|
| 386 |
|
| 387 |
def test_json_list_missing_required_field(app): |
| 388 |
"""Test that missing required fields in JSON raise appropriate errors.""" |
| 389 |
|
| 390 |
@app.default |
| 391 |
def main(values: list[User]): |
| 392 |
pass |
| 393 |
|
| 394 |
|
| 395 |
with pytest.raises(CycloptsError): |
| 396 |
app(["--values", '{"name": "Alice"}'], exit_on_error=False) |
| 397 |
|
| 398 |
|
| 399 |
def test_json_list_extra_field_rejected(app): |
| 400 |
"""Test that extra fields in JSON are rejected. |
| 401 |
|
| 402 |
This ensures consistent validation between single dataclass and list[dataclass]. |
| 403 |
Extra fields in JSON should raise an error to catch typos and invalid data. |
| 404 |
""" |
| 405 |
|
| 406 |
@app.default |
| 407 |
def main(values: list[User]): |
| 408 |
pass |
| 409 |
|
| 410 |
|
| 411 |
with pytest.raises(CycloptsError) as exc_info: |
| 412 |
app(["--values", '{"name": "Alice", "age": 30, "city": "NYC"}'], exit_on_error=False) |
| 413 |
|
| 414 |
error_str = str(exc_info.value) |
| 415 |
assert 'Unknown field "city"' in error_str |
| 416 |
assert "User" in error_str |
| 417 |
|
| 418 |
|
| 419 |
def test_json_list_null_value_in_array(app): |
| 420 |
"""Test that null values in JSON array are handled appropriately.""" |
| 421 |
|
| 422 |
@app.default |
| 423 |
def main(values: list[User]): |
| 424 |
pass |
| 425 |
|
| 426 |
|
| 427 |
with pytest.raises(CycloptsError): |
| 428 |
app(["--values", '[{"name": "Alice", "age": 30}, null]'], exit_on_error=False) |
| 429 |
|
| 430 |
|
| 431 |
def test_json_list_wrong_type_in_array(app): |
| 432 |
"""Test that wrong types in JSON array are caught.""" |
| 433 |
|
| 434 |
@app.default |
| 435 |
def main(values: list[User]): |
| 436 |
pass |
| 437 |
|
| 438 |
|
| 439 |
with pytest.raises(CycloptsError): |
| 440 |
app(["--values", '["Alice", "Bob"]'], exit_on_error=False) |
| 441 |
|
| 442 |
|
| 443 |
def test_json_list_nested_array_produces_empty_list(app, assert_parse_args): |
| 444 |
"""Test that nested arrays result in an empty list. |
| 445 |
|
| 446 |
The current implementation skips non-dict elements in JSON arrays, |
| 447 |
so a nested array (which contains a list, not a dict) results in |
| 448 |
no valid dataclass objects being created. |
| 449 |
""" |
| 450 |
|
| 451 |
@app.default |
| 452 |
def main(values: list[User]): |
| 453 |
pass |
| 454 |
|
| 455 |
|
| 456 |
assert_parse_args( |
| 457 |
main, |
| 458 |
["--values", '[[{"name": "Alice", "age": 30}]]'], |
| 459 |
[], |
| 460 |
) |
| 461 |
|
| 462 |
|
| 463 |
|
| 464 |
|
| 465 |
|
| 466 |
|
| 467 |
|
| 468 |
def test_json_single_dataclass_malformed(app): |
| 469 |
"""Test that malformed JSON for single dataclass raises error.""" |
| 470 |
|
| 471 |
@app.default |
| 472 |
def main(user: User): |
| 473 |
pass |
| 474 |
|
| 475 |
|
| 476 |
with pytest.raises(CycloptsError): |
| 477 |
app(["--user", '{"name": "Alice", "age": 30'], exit_on_error=False) |
| 478 |
|
| 479 |
|
| 480 |
def test_json_single_dataclass_type_mismatch(app): |
| 481 |
"""Test that type mismatches in single dataclass JSON raise errors. |
| 482 |
|
| 483 |
Cyclopts attempts to convert dataclass field values to their proper types |
| 484 |
after JSON parsing. If a value can't be converted (e.g., "thirty" to int), |
| 485 |
an error is raised. |
| 486 |
""" |
| 487 |
|
| 488 |
@app.default |
| 489 |
def main(user: User): |
| 490 |
pass |
| 491 |
|
| 492 |
|
| 493 |
with pytest.raises(CycloptsError): |
| 494 |
app(["--user", '{"name": "Alice", "age": "thirty"}'], exit_on_error=False) |
| 495 |
|
| 496 |
|
| 497 |
def test_json_single_dataclass_type_conversion_success(app, assert_parse_args): |
| 498 |
"""Test that valid type conversions work for JSON fields in single dataclass. |
| 499 |
|
| 500 |
String "25" should be converted to int 25, matching list behavior. |
| 501 |
""" |
| 502 |
|
| 503 |
@app.default |
| 504 |
def main(user: User): |
| 505 |
pass |
| 506 |
|
| 507 |
|
| 508 |
assert_parse_args( |
| 509 |
main, |
| 510 |
["--user", '{"name": "Bob", "age": "25"}'], |
| 511 |
User("Bob", 25), |
| 512 |
) |
| 513 |
|
| 514 |
|
| 515 |
def test_json_single_dataclass_missing_field(app): |
| 516 |
"""Test that missing required fields in single dataclass JSON raise errors.""" |
| 517 |
|
| 518 |
@app.default |
| 519 |
def main(user: User): |
| 520 |
pass |
| 521 |
|
| 522 |
|
| 523 |
with pytest.raises(CycloptsError): |
| 524 |
app(["--user", '{"name": "Alice"}'], exit_on_error=False) |
| 525 |
|
| 526 |
|
| 527 |
|
| 528 |
|
| 529 |
|
| 530 |
|
| 531 |
|
| 532 |
def test_json_list_with_float_to_int_conversion(app, assert_parse_args): |
| 533 |
"""Test that float values in JSON are handled properly for int fields.""" |
| 534 |
|
| 535 |
@app.default |
| 536 |
def main(values: list[User]): |
| 537 |
pass |
| 538 |
|
| 539 |
|
| 540 |
assert_parse_args( |
| 541 |
main, |
| 542 |
["--values", '{"name": "Alice", "age": 30.0}'], |
| 543 |
[User("Alice", 30)], |
| 544 |
) |
| 545 |
|
| 546 |
|
| 547 |
def test_json_list_with_bool_field(app, assert_parse_args): |
| 548 |
"""Test dataclass with boolean field conversion.""" |
| 549 |
|
| 550 |
@dataclass |
| 551 |
class Config: |
| 552 |
enabled: bool |
| 553 |
count: int |
| 554 |
|
| 555 |
@app.default |
| 556 |
def main(configs: list[Config]): |
| 557 |
pass |
| 558 |
|
| 559 |
|
| 560 |
assert_parse_args( |
| 561 |
main, |
| 562 |
["--configs", '[{"enabled": true, "count": 5}, {"enabled": false, "count": 10}]'], |
| 563 |
[Config(True, 5), Config(False, 10)], |
| 564 |
) |
| 565 |
|
| 566 |
|
| 567 |
def test_json_mixed_list_and_single_objects(app, assert_parse_args): |
| 568 |
"""Test that mixed JSON arrays and objects work correctly with type conversion.""" |
| 569 |
|
| 570 |
@app.default |
| 571 |
def main(values: list[User]): |
| 572 |
pass |
| 573 |
|
| 574 |
|
| 575 |
assert_parse_args( |
| 576 |
main, |
| 577 |
[ |
| 578 |
"--values", |
| 579 |
'[{"name": "Alice", "age": "30"}]', |
| 580 |
"--values", |
| 581 |
'{"name": "Bob", "age": "25"}', |
| 582 |
], |
| 583 |
[User("Alice", 30), User("Bob", 25)], |
| 584 |
) |