| 1 |
import json |
| 2 |
from dataclasses import dataclass |
| 3 |
from datetime import datetime |
| 4 |
from textwrap import dedent |
| 5 |
from typing import Annotated, Literal |
| 6 |
|
| 7 |
import pydantic |
| 8 |
import pytest |
| 9 |
from pydantic import BaseModel, ConfigDict, Field, PositiveInt, SecretBytes, SecretStr, model_validator, validate_call |
| 10 |
from pydantic import ValidationError as PydanticValidationError |
| 11 |
from pydantic.alias_generators import to_camel |
| 12 |
|
| 13 |
from cyclopts import MissingArgumentError, Parameter, ValidationError |
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
class Outfit(BaseModel): |
| 18 |
body: str |
| 19 |
head: str |
| 20 |
has_socks: bool |
| 21 |
|
| 22 |
|
| 23 |
class User(BaseModel): |
| 24 |
id: PositiveInt |
| 25 |
name: str = Field(default="John Doe") |
| 26 |
signup_ts: datetime | None |
| 27 |
tastes: dict[str, PositiveInt] |
| 28 |
outfit: Outfit | None = None |
| 29 |
|
| 30 |
|
| 31 |
def test_pydantic_error_msg(app, console): |
| 32 |
@app.command |
| 33 |
@validate_call |
| 34 |
def foo(value: PositiveInt): |
| 35 |
print(value) |
| 36 |
|
| 37 |
assert app["foo"].default_command == foo |
| 38 |
|
| 39 |
|
| 40 |
with pytest.raises(PydanticValidationError): |
| 41 |
foo(-1) |
| 42 |
|
| 43 |
with console.capture() as capture, pytest.raises(ValidationError): |
| 44 |
app(["foo", "-1"], error_console=console, exit_on_error=False, print_error=True) |
| 45 |
|
| 46 |
actual = capture.get() |
| 47 |
|
| 48 |
expected_prefix = dedent( |
| 49 |
"""\ |
| 50 |
╭─ Error ────────────────────────────────────────────────────────────╮ |
| 51 |
│ Invalid value "-1" for VALUE. 1 validation error for │ |
| 52 |
│ constrained-int │ |
| 53 |
│ Input should be greater than 0 [type=greater_than, │ |
| 54 |
│ input_value=-1, input_type=int] │ |
| 55 |
│ For further information visit │ |
| 56 |
""" |
| 57 |
) |
| 58 |
|
| 59 |
assert actual.startswith(expected_prefix) |
| 60 |
|
| 61 |
|
| 62 |
def test_pydantic_validator_called_once(app): |
| 63 |
class M(BaseModel): |
| 64 |
x: list = Field(default_factory=list) |
| 65 |
|
| 66 |
@model_validator(mode="after") |
| 67 |
def fill(self): |
| 68 |
self.x.append("validator called") |
| 69 |
return self |
| 70 |
|
| 71 |
@app.default |
| 72 |
def default( |
| 73 |
m: Annotated[M, Field(default_factory=M)], |
| 74 |
): |
| 75 |
assert m.x == ["foo", "validator called"] |
| 76 |
|
| 77 |
app(["foo"]) |
| 78 |
|
| 79 |
|
| 80 |
def test_pydantic_error_from_function_body(app): |
| 81 |
@app.command |
| 82 |
def foo(value: int): |
| 83 |
|
| 84 |
User(id=-1, signup_ts=None, tastes={}) |
| 85 |
|
| 86 |
with pytest.raises(PydanticValidationError): |
| 87 |
app(["foo", "-1"]) |
| 88 |
|
| 89 |
|
| 90 |
def test_bind_pydantic_basemodel(app, assert_parse_args): |
| 91 |
@app.command |
| 92 |
def foo(user: User): |
| 93 |
pass |
| 94 |
|
| 95 |
external_data = { |
| 96 |
"id": 123, |
| 97 |
"signup_ts": "2019-06-01 12:22", |
| 98 |
"tastes": { |
| 99 |
"wine": 9, |
| 100 |
b"cheese": 7, |
| 101 |
"cabbage": "1", |
| 102 |
}, |
| 103 |
"outfit": { |
| 104 |
"body": "t-shirt", |
| 105 |
"head": "baseball-cap", |
| 106 |
"has_socks": True, |
| 107 |
}, |
| 108 |
} |
| 109 |
|
| 110 |
assert_parse_args( |
| 111 |
foo, |
| 112 |
'foo --user.id=123 --user.signup-ts="2019-06-01 12:22" --user.tastes.wine=9 --user.tastes.cheese=7 --user.tastes.cabbage=1 --user.outfit.body=t-shirt --user.outfit.head=baseball-cap --user.outfit.has-socks', |
| 113 |
User(**external_data), |
| 114 |
) |
| 115 |
|
| 116 |
|
| 117 |
def test_bind_pydantic_basemodel_from_json(app, assert_parse_args, monkeypatch): |
| 118 |
@app.command |
| 119 |
def foo(user: Annotated[User, Parameter(env_var="USER")]): |
| 120 |
pass |
| 121 |
|
| 122 |
external_data = { |
| 123 |
"id": 123, |
| 124 |
"signup_ts": "2019-06-01 12:22", |
| 125 |
"tastes": { |
| 126 |
"wine": 9, |
| 127 |
"cheese": 7, |
| 128 |
"cabbage": "1", |
| 129 |
}, |
| 130 |
"outfit": { |
| 131 |
"body": "t-shirt", |
| 132 |
"head": "baseball-cap", |
| 133 |
"has_socks": True, |
| 134 |
}, |
| 135 |
} |
| 136 |
|
| 137 |
monkeypatch.setenv("USER", json.dumps(external_data)) |
| 138 |
|
| 139 |
assert_parse_args( |
| 140 |
foo, |
| 141 |
'foo --user.id=123 --user.signup-ts="2019-06-01 12:22" --user.tastes.wine=9 --user.tastes.cheese=7 --user.tastes.cabbage=1 --user.outfit.body=t-shirt --user.outfit.head=baseball-cap --user.outfit.has-socks', |
| 142 |
User(**external_data), |
| 143 |
) |
| 144 |
|
| 145 |
|
| 146 |
def test_bind_pydantic_basemodel_help(app, console): |
| 147 |
@app.default |
| 148 |
def foo(user: User): |
| 149 |
pass |
| 150 |
|
| 151 |
with console.capture() as capture: |
| 152 |
app("--help", console=console) |
| 153 |
actual = capture.get() |
| 154 |
expected = dedent( |
| 155 |
"""\ |
| 156 |
Usage: test_pydantic USER.ID USER.SIGNUP-TS USER.TASTES [ARGS] |
| 157 |
|
| 158 |
╭─ Commands ─────────────────────────────────────────────────────────╮ |
| 159 |
│ --help (-h) Display this message and exit. │ |
| 160 |
│ --version Display application version. │ |
| 161 |
╰────────────────────────────────────────────────────────────────────╯ |
| 162 |
╭─ Parameters ───────────────────────────────────────────────────────╮ |
| 163 |
│ * USER.ID --user.id [required] │ |
| 164 |
│ USER.NAME --user.name [default: John Doe] │ |
| 165 |
│ * USER.SIGNUP-TS [required] │ |
| 166 |
│ --user.signup-ts │ |
| 167 |
│ * --user.tastes [required] │ |
| 168 |
│ --user.outfit.body │ |
| 169 |
│ --user.outfit.head │ |
| 170 |
│ --user.outfit.has-socks - │ |
| 171 |
│ -user.outfit.no-has-soc │ |
| 172 |
│ ks │ |
| 173 |
╰────────────────────────────────────────────────────────────────────╯ |
| 174 |
""" |
| 175 |
) |
| 176 |
assert actual == expected |
| 177 |
|
| 178 |
|
| 179 |
def test_bind_pydantic_basemodel_missing_arg(app, console): |
| 180 |
"""Partially defining an Outfit should raise a MissingArgumentError.""" |
| 181 |
|
| 182 |
@app.command |
| 183 |
def foo(user: User): |
| 184 |
pass |
| 185 |
|
| 186 |
with console.capture() as capture, pytest.raises(MissingArgumentError): |
| 187 |
app.parse_args( |
| 188 |
'foo --user.id=123 --user.signup-ts="2019-06-01 12:22" --user.tastes.wine=9 --user.tastes.cheese=7 --user.tastes.cabbage=1 --user.outfit.body=t-shirt', |
| 189 |
error_console=console, |
| 190 |
exit_on_error=False, |
| 191 |
) |
| 192 |
|
| 193 |
actual = capture.get() |
| 194 |
|
| 195 |
expected = dedent( |
| 196 |
"""\ |
| 197 |
╭─ Error ────────────────────────────────────────────────────────────╮ |
| 198 |
│ Command "foo" parameter --user.outfit.head requires an argument. │ |
| 199 |
╰────────────────────────────────────────────────────────────────────╯ |
| 200 |
""" |
| 201 |
) |
| 202 |
|
| 203 |
assert actual == expected |
| 204 |
|
| 205 |
|
| 206 |
def test_pydantic_alias_1(app, console, assert_parse_args): |
| 207 |
class User(BaseModel): |
| 208 |
model_config = ConfigDict( |
| 209 |
|
| 210 |
alias_generator=to_camel, |
| 211 |
|
| 212 |
|
| 213 |
populate_by_name=True, |
| 214 |
|
| 215 |
from_attributes=True, |
| 216 |
) |
| 217 |
|
| 218 |
user_name: str |
| 219 |
"Name of user." |
| 220 |
|
| 221 |
age_in_years: int |
| 222 |
"Age of user in years." |
| 223 |
|
| 224 |
@app.command |
| 225 |
def foo(user: User): |
| 226 |
pass |
| 227 |
|
| 228 |
with console.capture() as capture: |
| 229 |
app("foo --help", console=console) |
| 230 |
|
| 231 |
actual = capture.get() |
| 232 |
|
| 233 |
expected = dedent( |
| 234 |
"""\ |
| 235 |
Usage: test_pydantic foo USER.USER-NAME USER.AGE-IN-YEARS |
| 236 |
|
| 237 |
╭─ Parameters ───────────────────────────────────────────────────────╮ |
| 238 |
│ * USER.USER-NAME Name of user. [required] │ |
| 239 |
│ --user.user-name │ |
| 240 |
│ --user.username │ |
| 241 |
│ * USER.AGE-IN-YEARS Age of user in years. [required] │ |
| 242 |
│ --user.age-in-years │ |
| 243 |
│ --user.ageinyears │ |
| 244 |
╰────────────────────────────────────────────────────────────────────╯ |
| 245 |
""" |
| 246 |
) |
| 247 |
|
| 248 |
assert actual == expected |
| 249 |
|
| 250 |
|
| 251 |
assert_parse_args( |
| 252 |
foo, |
| 253 |
"foo --user.user-name='Bob Smith' --user.age-in-years=100", |
| 254 |
user=User(user_name="Bob Smith", age_in_years=100), |
| 255 |
) |
| 256 |
|
| 257 |
assert_parse_args( |
| 258 |
foo, |
| 259 |
"foo --user.username='Alice Jones' --user.ageinyears=50", |
| 260 |
user=User(user_name="Alice Jones", age_in_years=50), |
| 261 |
) |
| 262 |
|
| 263 |
|
| 264 |
@pytest.mark.parametrize( |
| 265 |
"env_var", |
| 266 |
[ |
| 267 |
'{"storage_class": "longhorn"}', |
| 268 |
'{"storageclass": "longhorn"}', |
| 269 |
|
| 270 |
'{"storage_class": "longhorn", "limit": null}', |
| 271 |
|
| 272 |
'{"storageClass": "longhorn"}', |
| 273 |
], |
| 274 |
) |
| 275 |
def test_pydantic_alias_env_var_json(app, assert_parse_args, monkeypatch, env_var): |
| 276 |
""" |
| 277 |
https://github.com/BrianPugh/cyclopts/issues/332 |
| 278 |
""" |
| 279 |
monkeypatch.setenv("SPEC", env_var) |
| 280 |
|
| 281 |
class BaseK8sModel(BaseModel): |
| 282 |
model_config = ConfigDict( |
| 283 |
alias_generator=to_camel, |
| 284 |
populate_by_name=True, |
| 285 |
from_attributes=True, |
| 286 |
) |
| 287 |
|
| 288 |
class Spec(BaseK8sModel): |
| 289 |
storage_class: str |
| 290 |
limit: int | None = None |
| 291 |
|
| 292 |
@app.default |
| 293 |
def run(spec: Annotated[Spec, Parameter(env_var="SPEC")]) -> None: |
| 294 |
pass |
| 295 |
|
| 296 |
assert_parse_args(run, "", Spec(storage_class="longhorn")) |
| 297 |
|
| 298 |
|
| 299 |
def test_parameter_decorator_pydantic_nested_1(app, console): |
| 300 |
""" |
| 301 |
https://github.com/BrianPugh/cyclopts/issues/320 |
| 302 |
|
| 303 |
See Also |
| 304 |
-------- |
| 305 |
test_parameter_decorator_dataclass_nested_1 |
| 306 |
""" |
| 307 |
|
| 308 |
class S3Path(BaseModel): |
| 309 |
bucket: Annotated[str, Parameter()] |
| 310 |
key: str |
| 311 |
|
| 312 |
@Parameter(name="*") |
| 313 |
class S3CliParams(BaseModel): |
| 314 |
path: Annotated[S3Path, Parameter(name="*")] |
| 315 |
region: Annotated[str, Parameter(name="area")] |
| 316 |
|
| 317 |
@app.command |
| 318 |
def action(*, s3_path: S3CliParams): |
| 319 |
pass |
| 320 |
|
| 321 |
with console.capture() as capture: |
| 322 |
app("action --help", console=console) |
| 323 |
|
| 324 |
actual = capture.get() |
| 325 |
expected = dedent( |
| 326 |
"""\ |
| 327 |
Usage: test_pydantic action --bucket STR --key STR --area STR |
| 328 |
|
| 329 |
╭─ Parameters ───────────────────────────────────────────────────────╮ |
| 330 |
│ * --bucket [required] │ |
| 331 |
│ * --key [required] │ |
| 332 |
│ * --area [required] │ |
| 333 |
╰────────────────────────────────────────────────────────────────────╯ |
| 334 |
""" |
| 335 |
) |
| 336 |
assert actual == expected |
| 337 |
|
| 338 |
|
| 339 |
def test_pydantic_field_description(app, console): |
| 340 |
"""Test that pydantic Field.description is used for help text.""" |
| 341 |
|
| 342 |
class UserModel(BaseModel): |
| 343 |
|
| 344 |
name: str = Field(description="User name.") |
| 345 |
|
| 346 |
|
| 347 |
name_with_param: Annotated[ |
| 348 |
str, |
| 349 |
Parameter(help="User name with Parameter help."), |
| 350 |
] = "Jane Doe" |
| 351 |
|
| 352 |
|
| 353 |
name_with_field_in_annotated: Annotated[ |
| 354 |
str, |
| 355 |
Field(description="Description from Field in Annotated."), |
| 356 |
] = "John Doe" |
| 357 |
|
| 358 |
|
| 359 |
age: int = Field(description="User age in years.") |
| 360 |
|
| 361 |
@app.default |
| 362 |
def main(user: UserModel): |
| 363 |
pass |
| 364 |
|
| 365 |
with console.capture() as capture: |
| 366 |
app("--help", console=console) |
| 367 |
|
| 368 |
actual = capture.get() |
| 369 |
|
| 370 |
|
| 371 |
|
| 372 |
|
| 373 |
assert "User name." in actual |
| 374 |
|
| 375 |
|
| 376 |
assert "User name with Parameter help." in actual |
| 377 |
|
| 378 |
|
| 379 |
assert "Description from Field in Annotated." in actual |
| 380 |
|
| 381 |
|
| 382 |
assert "User age in years." in actual |
| 383 |
|
| 384 |
|
| 385 |
def test_pydantic_annotated_field_discriminator(app, assert_parse_args, console): |
| 386 |
"""From https://github.com/BrianPugh/cyclopts/issues/377""" |
| 387 |
|
| 388 |
class DatasetImage(pydantic.BaseModel): |
| 389 |
type: Literal["image"] = "image" |
| 390 |
path: str |
| 391 |
resolution: tuple[int, int] |
| 392 |
|
| 393 |
class DatasetVideo(pydantic.BaseModel): |
| 394 |
type: Literal["video"] = "video" |
| 395 |
path: str |
| 396 |
resolution: tuple[int, int] |
| 397 |
fps: int |
| 398 |
|
| 399 |
Dataset = Annotated[DatasetImage | DatasetVideo, pydantic.Field(discriminator="type")] |
| 400 |
|
| 401 |
@dataclass |
| 402 |
class Config: |
| 403 |
dataset: Dataset |
| 404 |
|
| 405 |
@app.default |
| 406 |
def main( |
| 407 |
config: Annotated[Config | None, Parameter(name="*")] = None, |
| 408 |
): |
| 409 |
pass |
| 410 |
|
| 411 |
assert_parse_args( |
| 412 |
main, |
| 413 |
"--dataset.type=image --dataset.path foo.png --dataset.resolution 640 480", |
| 414 |
Config(DatasetImage(path="foo.png", resolution=(640, 480))), |
| 415 |
) |
| 416 |
assert_parse_args( |
| 417 |
main, |
| 418 |
"--dataset.type=video --dataset.path foo.mp4 --dataset.resolution 640 480 --dataset.fps 30", |
| 419 |
Config(DatasetVideo(path="foo.mp4", resolution=(640, 480), fps=30)), |
| 420 |
) |
| 421 |
|
| 422 |
with console.capture() as capture: |
| 423 |
app("--help", console=console) |
| 424 |
|
| 425 |
actual = capture.get() |
| 426 |
expected = dedent( |
| 427 |
"""\ |
| 428 |
Usage: test_pydantic [ARGS] |
| 429 |
|
| 430 |
╭─ Commands ─────────────────────────────────────────────────────────╮ |
| 431 |
│ --help (-h) Display this message and exit. │ |
| 432 |
│ --version Display application version. │ |
| 433 |
╰────────────────────────────────────────────────────────────────────╯ |
| 434 |
╭─ Parameters ───────────────────────────────────────────────────────╮ |
| 435 |
│ DATASET.TYPE [choices: image, video] │ |
| 436 |
│ --dataset.type │ |
| 437 |
│ DATASET.PATH │ |
| 438 |
│ --dataset.path │ |
| 439 |
│ DATASET.RESOLUTION │ |
| 440 |
│ --dataset.resolution -- │ |
| 441 |
│ dataset.empty-resolutio │ |
| 442 |
│ n │ |
| 443 |
│ DATASET.FPS --dataset.fps │ |
| 444 |
╰────────────────────────────────────────────────────────────────────╯ |
| 445 |
""" |
| 446 |
) |
| 447 |
assert actual == expected |
| 448 |
|
| 449 |
|
| 450 |
def test_pydantic_annotated_field_discriminator_basemodel_container(app, assert_parse_args): |
| 451 |
"""Regression test for https://github.com/BrianPugh/cyclopts/issues/726 |
| 452 |
|
| 453 |
Discriminated unions should work when the container is also a pydantic.BaseModel. |
| 454 |
""" |
| 455 |
|
| 456 |
class DatasetImage(pydantic.BaseModel): |
| 457 |
type: Literal["image"] = "image" |
| 458 |
path: str |
| 459 |
|
| 460 |
class DatasetVideo(pydantic.BaseModel): |
| 461 |
type: Literal["video"] = "video" |
| 462 |
path: str |
| 463 |
fps: int |
| 464 |
|
| 465 |
class Config(pydantic.BaseModel): |
| 466 |
dataset: Annotated[DatasetImage | DatasetVideo, pydantic.Field(discriminator="type")] |
| 467 |
|
| 468 |
@app.default |
| 469 |
def main( |
| 470 |
config: Annotated[Config | None, Parameter(name="*")] = None, |
| 471 |
): |
| 472 |
pass |
| 473 |
|
| 474 |
assert_parse_args( |
| 475 |
main, |
| 476 |
"--dataset.type=image --dataset.path foo.png", |
| 477 |
Config(dataset=DatasetImage(path="foo.png")), |
| 478 |
) |
| 479 |
assert_parse_args( |
| 480 |
main, |
| 481 |
"--dataset.type=video --dataset.path foo.mp4 --dataset.fps 30", |
| 482 |
Config(dataset=DatasetVideo(path="foo.mp4", fps=30)), |
| 483 |
) |
| 484 |
|
| 485 |
|
| 486 |
def test_pydantic_annotated_field_discriminator_list(app, assert_parse_args): |
| 487 |
"""Regression test for https://github.com/BrianPugh/cyclopts/issues/785 |
| 488 |
|
| 489 |
list[DiscriminatedUnion] fields in a BaseModel should not crash with |
| 490 |
``ValueError: Cannot Union types that consume different numbers of tokens``. |
| 491 |
""" |
| 492 |
|
| 493 |
class Cat(pydantic.BaseModel): |
| 494 |
dead_birds: int |
| 495 |
dead_rats: int |
| 496 |
type: Literal["cat"] = "cat" |
| 497 |
|
| 498 |
class Dog(pydantic.BaseModel): |
| 499 |
type: Literal["dog"] = "dog" |
| 500 |
|
| 501 |
Animal = Annotated[Cat | Dog, pydantic.Field(discriminator="type")] |
| 502 |
|
| 503 |
class Home(pydantic.BaseModel): |
| 504 |
animals: list[Animal] |
| 505 |
|
| 506 |
@app.default |
| 507 |
def main( |
| 508 |
home: Annotated[Home | None, Parameter(name="*")] = None, |
| 509 |
): |
| 510 |
pass |
| 511 |
|
| 512 |
|
| 513 |
assert_parse_args( |
| 514 |
main, |
| 515 |
"""--animals '{"type": "dog"}'""", |
| 516 |
Home(animals=[Dog()]), |
| 517 |
) |
| 518 |
|
| 519 |
|
| 520 |
assert_parse_args( |
| 521 |
main, |
| 522 |
"""--animals '{"type": "cat", "dead_birds": 1, "dead_rats": 2}'""", |
| 523 |
Home(animals=[Cat(dead_birds=1, dead_rats=2)]), |
| 524 |
) |
| 525 |
|
| 526 |
|
| 527 |
assert_parse_args( |
| 528 |
main, |
| 529 |
"""--animals '{"type": "dog"}' --animals '{"type": "cat", "dead_birds": 3, "dead_rats": 4}'""", |
| 530 |
Home(animals=[Dog(), Cat(dead_birds=3, dead_rats=4)]), |
| 531 |
) |
| 532 |
|
| 533 |
|
| 534 |
def test_pydantic_roundtrip_json_with_aliases(app, assert_parse_args, monkeypatch): |
| 535 |
""" |
| 536 |
Test that Pydantic's own JSON serialization (which uses aliases by default) |
| 537 |
can be round-tripped through cyclopts environment variable loading. |
| 538 |
|
| 539 |
This ensures that if a user saves a Pydantic model to JSON and then loads it |
| 540 |
back through cyclopts, it works correctly. |
| 541 |
""" |
| 542 |
import json |
| 543 |
|
| 544 |
class BaseK8sModel(BaseModel): |
| 545 |
model_config = ConfigDict( |
| 546 |
alias_generator=to_camel, |
| 547 |
populate_by_name=True, |
| 548 |
from_attributes=True, |
| 549 |
) |
| 550 |
|
| 551 |
class DatabaseConfig(BaseK8sModel): |
| 552 |
host: str = "localhost" |
| 553 |
port: int = 5432 |
| 554 |
connection_timeout: int = 30 |
| 555 |
max_pool_size: int = 10 |
| 556 |
|
| 557 |
class Spec(BaseK8sModel): |
| 558 |
storage_class: str |
| 559 |
enable_caching: bool = True |
| 560 |
database_config: DatabaseConfig | None = None |
| 561 |
api_key: str | None = None |
| 562 |
|
| 563 |
|
| 564 |
original_spec = Spec( |
| 565 |
storage_class="fast-ssd", |
| 566 |
enable_caching=False, |
| 567 |
database_config=DatabaseConfig(host="db.example.com", port=3306, connection_timeout=60, max_pool_size=50), |
| 568 |
api_key="secret123", |
| 569 |
) |
| 570 |
|
| 571 |
|
| 572 |
|
| 573 |
json_str = original_spec.model_dump_json(by_alias=True) |
| 574 |
|
| 575 |
|
| 576 |
json_data = json.loads(json_str) |
| 577 |
expected_json = { |
| 578 |
"storageClass": "fast-ssd", |
| 579 |
"enableCaching": False, |
| 580 |
"databaseConfig": {"host": "db.example.com", "port": 3306, "connectionTimeout": 60, "maxPoolSize": 50}, |
| 581 |
"apiKey": "secret123", |
| 582 |
} |
| 583 |
assert json_data == expected_json |
| 584 |
|
| 585 |
|
| 586 |
monkeypatch.setenv("SPEC", json_str) |
| 587 |
|
| 588 |
@app.default |
| 589 |
def run(spec: Annotated[Spec, Parameter(env_var="SPEC")]) -> None: |
| 590 |
pass |
| 591 |
|
| 592 |
|
| 593 |
assert_parse_args(run, "", original_spec) |
| 594 |
|
| 595 |
|
| 596 |
@pytest.mark.parametrize( |
| 597 |
"dataclass_decorator", |
| 598 |
[ |
| 599 |
dataclass, |
| 600 |
pydantic.dataclasses.dataclass, |
| 601 |
], |
| 602 |
) |
| 603 |
def test_pydantic_annotated_field_discriminator_dataclass(app, assert_parse_args, dataclass_decorator): |
| 604 |
"""Pydantic discriminator should work, even if the union'd types are not pydantic.BaseModel.""" |
| 605 |
|
| 606 |
@dataclass_decorator |
| 607 |
class DatasetImage: |
| 608 |
type: Literal["image"] |
| 609 |
path: str |
| 610 |
resolution: tuple[int, int] |
| 611 |
|
| 612 |
@dataclass_decorator |
| 613 |
class DatasetVideo: |
| 614 |
type: Literal["video"] |
| 615 |
path: str |
| 616 |
resolution: tuple[int, int] |
| 617 |
fps: int |
| 618 |
|
| 619 |
Dataset = Annotated[DatasetImage | DatasetVideo, pydantic.Field(discriminator="type")] |
| 620 |
|
| 621 |
@dataclass_decorator |
| 622 |
class Config: |
| 623 |
dataset: Dataset |
| 624 |
|
| 625 |
@app.default |
| 626 |
def main( |
| 627 |
config: Annotated[Config | None, Parameter(name="*")] = None, |
| 628 |
): |
| 629 |
pass |
| 630 |
|
| 631 |
assert_parse_args( |
| 632 |
main, |
| 633 |
"--dataset.type=image --dataset.path foo.png --dataset.resolution 640 480", |
| 634 |
Config(DatasetImage(type="image", path="foo.png", resolution=(640, 480))), |
| 635 |
) |
| 636 |
assert_parse_args( |
| 637 |
main, |
| 638 |
"--dataset.type=video --dataset.path foo.mp4 --dataset.resolution 640 480 --dataset.fps 30", |
| 639 |
Config(DatasetVideo(type="video", path="foo.mp4", resolution=(640, 480), fps=30)), |
| 640 |
) |
| 641 |
|
| 642 |
|
| 643 |
def test_pydantic_annotated_field_discriminator_missing_argument(app): |
| 644 |
"""Regression test for https://github.com/BrianPugh/cyclopts/issues/725 |
| 645 |
|
| 646 |
Missing required field in a discriminated union should raise MissingArgumentError, |
| 647 |
not an IndexError. |
| 648 |
""" |
| 649 |
|
| 650 |
@dataclass |
| 651 |
class Cat: |
| 652 |
rainbow: bool |
| 653 |
type: Literal["cat"] |
| 654 |
|
| 655 |
@dataclass |
| 656 |
class Dog: |
| 657 |
type: Literal["dog"] |
| 658 |
|
| 659 |
@dataclass |
| 660 |
class AnimalParameter: |
| 661 |
animal: Annotated[Cat | Dog, pydantic.Field(discriminator="type")] |
| 662 |
|
| 663 |
@app.default |
| 664 |
def main(animal_parameter: Annotated[AnimalParameter, Parameter(name="*")]): |
| 665 |
pass |
| 666 |
|
| 667 |
with pytest.raises(MissingArgumentError) as exc_info: |
| 668 |
app(["--animal.type", "cat"], exit_on_error=False) |
| 669 |
|
| 670 |
assert exc_info.value.argument is not None |
| 671 |
assert exc_info.value.argument.parameter.name == ("--animal.rainbow",) |
| 672 |
|
| 673 |
|
| 674 |
def test_pydantic_discriminated_union_in_list_sibling_field(app): |
| 675 |
"""Regression test for follow-up to issue #785 surfaced during PR #789 review. |
| 676 |
|
| 677 |
When a pydantic BaseModel contains both a ``list[DiscriminatedUnion]`` field |
| 678 |
and a sibling field that's provided on the CLI, a missing nested field inside |
| 679 |
the list element's JSON must raise a ValidationError naming the nested path, |
| 680 |
not a bogus MissingArgumentError on the populated sibling. |
| 681 |
""" |
| 682 |
|
| 683 |
class AnimalBase(pydantic.BaseModel): |
| 684 |
name: str |
| 685 |
|
| 686 |
class Cat(AnimalBase): |
| 687 |
dead_birds: int |
| 688 |
dead_rats: int |
| 689 |
type: Literal["cat"] = "cat" |
| 690 |
|
| 691 |
class Dog(AnimalBase): |
| 692 |
type: Literal["dog"] = "dog" |
| 693 |
|
| 694 |
Animal = Annotated[Cat | Dog, pydantic.Field(discriminator="type")] |
| 695 |
|
| 696 |
class Home(pydantic.BaseModel): |
| 697 |
animals: list[Animal] |
| 698 |
name: str |
| 699 |
|
| 700 |
@app.default |
| 701 |
def main(*, home: Home): |
| 702 |
pass |
| 703 |
|
| 704 |
with pytest.raises(ValidationError) as exc_info: |
| 705 |
app( |
| 706 |
["--home.animals", '{"type": "dog"}', "--home.name", "ISS"], |
| 707 |
exit_on_error=False, |
| 708 |
) |
| 709 |
|
| 710 |
message = str(exc_info.value) |
| 711 |
assert "animals" in message |
| 712 |
assert "name" in message |
| 713 |
assert not isinstance(exc_info.value, MissingArgumentError) |
| 714 |
|
| 715 |
|
| 716 |
def test_pydantic_discriminated_union_in_list_sibling_field_success(app, assert_parse_args): |
| 717 |
"""Happy-path counterpart to ``test_pydantic_discriminated_union_in_list_sibling_field``. |
| 718 |
|
| 719 |
When a list-element's JSON provides all required fields (including those |
| 720 |
inherited from a common base), it must parse successfully alongside a |
| 721 |
sibling field on the parent model. |
| 722 |
""" |
| 723 |
|
| 724 |
class AnimalBase(pydantic.BaseModel): |
| 725 |
name: str |
| 726 |
|
| 727 |
class Cat(AnimalBase): |
| 728 |
dead_birds: int |
| 729 |
dead_rats: int |
| 730 |
type: Literal["cat"] = "cat" |
| 731 |
|
| 732 |
class Dog(AnimalBase): |
| 733 |
type: Literal["dog"] = "dog" |
| 734 |
|
| 735 |
Animal = Annotated[Cat | Dog, pydantic.Field(discriminator="type")] |
| 736 |
|
| 737 |
class Home(pydantic.BaseModel): |
| 738 |
animals: list[Animal] |
| 739 |
name: str |
| 740 |
|
| 741 |
@app.default |
| 742 |
def main(*, home: Home): |
| 743 |
pass |
| 744 |
|
| 745 |
assert_parse_args( |
| 746 |
main, |
| 747 |
"""--home.animals '{"type": "dog", "name": "Rex"}' --home.name "ISS" """, |
| 748 |
home=Home(animals=[Dog(name="Rex")], name="ISS"), |
| 749 |
) |
| 750 |
|
| 751 |
|
| 752 |
def test_pydantic_list_empty_flag(app, assert_parse_args): |
| 753 |
"""Regression test for https://github.com/BrianPugh/cyclopts/issues/572""" |
| 754 |
|
| 755 |
@Parameter(name="*") |
| 756 |
class Config(BaseModel): |
| 757 |
urls: Annotated[ |
| 758 |
list[str] | None, |
| 759 |
Field(default=None, description="Optional list of URLs"), |
| 760 |
Parameter( |
| 761 |
consume_multiple=True, |
| 762 |
), |
| 763 |
] |
| 764 |
|
| 765 |
@app.default |
| 766 |
def command(config: Config | None = None): |
| 767 |
pass |
| 768 |
|
| 769 |
assert_parse_args(command, "--empty-urls", Config(urls=[])) |
| 770 |
|
| 771 |
|
| 772 |
def test_pydantic_list_with_value(app, assert_parse_args): |
| 773 |
@Parameter(name="*") |
| 774 |
class Config(BaseModel): |
| 775 |
urls: Annotated[ |
| 776 |
list[str] | None, |
| 777 |
Field(default=None, description="Optional list of URLs"), |
| 778 |
Parameter( |
| 779 |
consume_multiple=True, |
| 780 |
), |
| 781 |
] |
| 782 |
|
| 783 |
@app.default |
| 784 |
def command(config: Config | None = None): |
| 785 |
pass |
| 786 |
|
| 787 |
assert_parse_args( |
| 788 |
command, |
| 789 |
"--urls http://example.com http://example2.com", |
| 790 |
Config( |
| 791 |
urls=["http://example.com", "http://example2.com"], |
| 792 |
), |
| 793 |
) |
| 794 |
|
| 795 |
|
| 796 |
def test_pydantic_list_omitted(app, assert_parse_args): |
| 797 |
@Parameter(name="*") |
| 798 |
class Config(BaseModel): |
| 799 |
urls: Annotated[ |
| 800 |
list[str] | None, |
| 801 |
Field(default=None, description="Optional list of URLs"), |
| 802 |
Parameter( |
| 803 |
consume_multiple=True, |
| 804 |
), |
| 805 |
] |
| 806 |
|
| 807 |
@app.default |
| 808 |
def command(config: Config | None = None): |
| 809 |
pass |
| 810 |
|
| 811 |
assert_parse_args(command, "") |
| 812 |
|
| 813 |
|
| 814 |
def test_pydantic_nested_list_json(app): |
| 815 |
"""Test that nested lists with JSON-serialized dicts are correctly parsed. |
| 816 |
|
| 817 |
Regression test for issue where JSON dict strings in lists were not being |
| 818 |
deserialized, causing Pydantic validation errors. |
| 819 |
Related to https://github.com/BrianPugh/cyclopts/issues/507 |
| 820 |
""" |
| 821 |
|
| 822 |
class SimpleConfig(BaseModel): |
| 823 |
bar: str |
| 824 |
|
| 825 |
class NestedConfig(BaseModel): |
| 826 |
foo: str |
| 827 |
simple_list: list[SimpleConfig] |
| 828 |
|
| 829 |
@app.command |
| 830 |
def nested_cmd(config: NestedConfig) -> NestedConfig: |
| 831 |
return config |
| 832 |
|
| 833 |
result = app( |
| 834 |
[ |
| 835 |
"nested-cmd", |
| 836 |
"--config", |
| 837 |
'{"foo": "test", "simple_list": [{"bar": "simple1"}]}', |
| 838 |
], |
| 839 |
exit_on_error=False, |
| 840 |
) |
| 841 |
|
| 842 |
assert result == NestedConfig( |
| 843 |
foo="test", |
| 844 |
simple_list=[SimpleConfig(bar="simple1")], |
| 845 |
) |
| 846 |
|
| 847 |
|
| 848 |
def test_pydantic_secretstr_from_env(app, assert_parse_args, monkeypatch): |
| 849 |
"""Test that Pydantic SecretStr works with environment variables. |
| 850 |
|
| 851 |
Regression test for https://github.com/BrianPugh/cyclopts/issues/619 |
| 852 |
""" |
| 853 |
monkeypatch.setenv("SOME_SECRET", "cycloptsIsAmazing") |
| 854 |
|
| 855 |
class ScriptSettings(BaseModel): |
| 856 |
some_secret: Annotated[SecretStr, Parameter(env_var="SOME_SECRET")] |
| 857 |
|
| 858 |
@app.command |
| 859 |
def test_cmd(s: Annotated[ScriptSettings, Parameter(name="*")]): |
| 860 |
pass |
| 861 |
|
| 862 |
assert_parse_args( |
| 863 |
test_cmd, |
| 864 |
"test-cmd", |
| 865 |
ScriptSettings(some_secret=SecretStr("cycloptsIsAmazing")), |
| 866 |
) |
| 867 |
|
| 868 |
|
| 869 |
@pytest.mark.parametrize( |
| 870 |
"secret_type,value,expected_value", |
| 871 |
[ |
| 872 |
(SecretStr, "mySecretValue", SecretStr("mySecretValue")), |
| 873 |
(SecretBytes, "mySecretBytes", SecretBytes(b"mySecretBytes")), |
| 874 |
], |
| 875 |
) |
| 876 |
def test_pydantic_secret_explicit_value(app, assert_parse_args, secret_type, value, expected_value): |
| 877 |
"""Test that Pydantic secret types work with explicit CLI values. |
| 878 |
|
| 879 |
Regression test for https://github.com/BrianPugh/cyclopts/issues/619 |
| 880 |
""" |
| 881 |
|
| 882 |
class ScriptSettings(BaseModel): |
| 883 |
some_secret: secret_type |
| 884 |
|
| 885 |
@app.command |
| 886 |
def test_cmd(s: Annotated[ScriptSettings, Parameter(name="*")]): |
| 887 |
pass |
| 888 |
|
| 889 |
assert_parse_args( |
| 890 |
test_cmd, |
| 891 |
f"test-cmd --some-secret {value}", |
| 892 |
ScriptSettings(some_secret=expected_value), |
| 893 |
) |
| 894 |
|
| 895 |
|
| 896 |
def test_pydantic_inheritance_simple(app, console): |
| 897 |
"""Test that Field descriptions from base pydantic model are inherited by derived model.""" |
| 898 |
|
| 899 |
class BaseModelCustom(BaseModel): |
| 900 |
"""Base pydantic model.""" |
| 901 |
|
| 902 |
base_field: int = Field(default=42, description="Field from base pydantic model") |
| 903 |
|
| 904 |
class DerivedModel(BaseModelCustom): |
| 905 |
"""Derived pydantic model.""" |
| 906 |
|
| 907 |
derived_field: str = Field(default="test", description="Field from derived pydantic model") |
| 908 |
|
| 909 |
@app.default |
| 910 |
def main(params: DerivedModel): |
| 911 |
pass |
| 912 |
|
| 913 |
with console.capture() as capture: |
| 914 |
app("--help", console=console) |
| 915 |
|
| 916 |
actual = capture.get() |
| 917 |
|
| 918 |
|
| 919 |
assert "Field from base pydantic model" in actual |
| 920 |
assert "Field from derived pydantic model" in actual |