| 1 |
import sys |
| 2 |
from dataclasses import dataclass, field |
| 3 |
from textwrap import dedent |
| 4 |
from typing import Annotated |
| 5 |
|
| 6 |
import pytest |
| 7 |
|
| 8 |
from cyclopts import Parameter |
| 9 |
from cyclopts.exceptions import ( |
| 10 |
ArgumentOrderError, |
| 11 |
MissingArgumentError, |
| 12 |
UnusedCliTokensError, |
| 13 |
) |
| 14 |
|
| 15 |
|
| 16 |
@dataclass |
| 17 |
class User: |
| 18 |
id: int |
| 19 |
name: str = "John Doe" |
| 20 |
tastes: dict[str, int] = field(default_factory=dict) |
| 21 |
|
| 22 |
|
| 23 |
def test_bind_dataclass(app, assert_parse_args, console): |
| 24 |
@app.command |
| 25 |
def foo(some_number: int, user: User): |
| 26 |
pass |
| 27 |
|
| 28 |
external_data = { |
| 29 |
"id": 123, |
| 30 |
|
| 31 |
"tastes": { |
| 32 |
"wine": 9, |
| 33 |
"cheese": 7, |
| 34 |
"cabbage": 1, |
| 35 |
}, |
| 36 |
} |
| 37 |
assert_parse_args( |
| 38 |
foo, |
| 39 |
"foo 100 --user.id=123 --user.tastes.wine=9 --user.tastes.cheese=7 --user.tastes.cabbage=1", |
| 40 |
100, |
| 41 |
User(**external_data), |
| 42 |
) |
| 43 |
|
| 44 |
|
| 45 |
def test_bind_dataclass_missing_all_arguments(app, assert_parse_args, console): |
| 46 |
"""We expect to see the first subargument (--user.id) in the error message, |
| 47 |
not the root "--user". |
| 48 |
""" |
| 49 |
|
| 50 |
@app.default |
| 51 |
def default(some_number: int, user: User): |
| 52 |
pass |
| 53 |
|
| 54 |
with console.capture() as capture, pytest.raises(MissingArgumentError): |
| 55 |
app("123", error_console=console, exit_on_error=False) |
| 56 |
actual = capture.get() |
| 57 |
|
| 58 |
expected = dedent( |
| 59 |
"""\ |
| 60 |
╭─ Error ────────────────────────────────────────────────────────────╮ |
| 61 |
│ Parameter --user.id requires an argument. │ |
| 62 |
╰────────────────────────────────────────────────────────────────────╯ |
| 63 |
""" |
| 64 |
) |
| 65 |
|
| 66 |
assert actual == expected |
| 67 |
|
| 68 |
|
| 69 |
def test_bind_dataclass_recursive(app, assert_parse_args, console, normalize_trailing_whitespace): |
| 70 |
@dataclass |
| 71 |
class Wheel: |
| 72 |
diameter: int |
| 73 |
"Diameter of wheel in inches." |
| 74 |
|
| 75 |
@dataclass |
| 76 |
class Engine: |
| 77 |
cylinders: int |
| 78 |
"Number of cylinders the engine has." |
| 79 |
|
| 80 |
hp: Annotated[float, Parameter(name=("horsepower", "p"))] |
| 81 |
"Amount of horsepower the engine can generate." |
| 82 |
|
| 83 |
diesel: bool = False |
| 84 |
"If this engine consumes diesel, instead of gasoline." |
| 85 |
|
| 86 |
@dataclass |
| 87 |
class Car: |
| 88 |
name: str |
| 89 |
"The name/model of the car." |
| 90 |
|
| 91 |
mileage: float |
| 92 |
"How many miles the car has driven." |
| 93 |
|
| 94 |
engine: Annotated[Engine, Parameter(name="*", group="Engine")] = field(kw_only=True) |
| 95 |
"The kind of engine the car is using." |
| 96 |
|
| 97 |
wheel: Wheel |
| 98 |
"The kind of wheels the car is using." |
| 99 |
|
| 100 |
n_axles: int = 2 |
| 101 |
"Number of axles the car has." |
| 102 |
|
| 103 |
@app.command |
| 104 |
def build(*, license_plate: str, car: Car): |
| 105 |
"""Build a car. |
| 106 |
|
| 107 |
Parameters |
| 108 |
---------- |
| 109 |
license_plate: str |
| 110 |
License plate identifier to give to car. |
| 111 |
car: Car |
| 112 |
Car specifications. |
| 113 |
""" |
| 114 |
|
| 115 |
assert_parse_args( |
| 116 |
build, |
| 117 |
"build --car.name=ford --car.mileage=500 --car.cylinders=4 --car.p=200 --car.wheel.diameter=18 --license-plate=ABCDEFG", |
| 118 |
car=Car( |
| 119 |
name="ford", |
| 120 |
mileage=500, |
| 121 |
engine=Engine(cylinders=4, hp=200), |
| 122 |
wheel=Wheel(diameter=18), |
| 123 |
), |
| 124 |
license_plate="ABCDEFG", |
| 125 |
) |
| 126 |
|
| 127 |
with console.capture() as capture: |
| 128 |
app("build --help", console=console) |
| 129 |
|
| 130 |
actual = capture.get() |
| 131 |
|
| 132 |
expected = dedent( |
| 133 |
"""\ |
| 134 |
Usage: test_bind_dataclasses build --license-plate STR --car.name STR |
| 135 |
--car.mileage FLOAT --car.cylinders INT --car.horsepower FLOAT |
| 136 |
--car.wheel.diameter INT [OPTIONS] |
| 137 |
|
| 138 |
Build a car. |
| 139 |
|
| 140 |
╭─ Parameters ───────────────────────────────────────────────────────╮ |
| 141 |
│ * --license-plate License plate identifier to give to car. │ |
| 142 |
│ [required] │ |
| 143 |
│ * --car.name The name/model of the car. [required] │ |
| 144 |
│ * --car.mileage How many miles the car has driven. │ |
| 145 |
│ [required] │ |
| 146 |
│ * --car.wheel.diameter Diameter of wheel in inches. [required] │ |
| 147 |
│ --car.n-axles Number of axles the car has. [default: 2] │ |
| 148 |
╰────────────────────────────────────────────────────────────────────╯ |
| 149 |
╭─ Engine ───────────────────────────────────────────────────────────╮ |
| 150 |
│ * --car.cylinders Number of cylinders the engine has. │ |
| 151 |
│ [required] │ |
| 152 |
│ * --car.horsepower --car.p Amount of horsepower the engine can │ |
| 153 |
│ generate. [required] │ |
| 154 |
│ --car.diesel If this engine consumes diesel, │ |
| 155 |
│ --car.no-diesel instead of gasoline. [default: False] │ |
| 156 |
╰────────────────────────────────────────────────────────────────────╯ |
| 157 |
""" |
| 158 |
) |
| 159 |
|
| 160 |
assert normalize_trailing_whitespace(actual) == expected |
| 161 |
|
| 162 |
|
| 163 |
def test_bind_dataclass_recursive_missing_arg(app, assert_parse_args, console): |
| 164 |
"""The ``engine`` parameter itself is optional, but if specified it has 2 required fields.""" |
| 165 |
|
| 166 |
@dataclass |
| 167 |
class Engine: |
| 168 |
cylinders: int |
| 169 |
hp: float = 100 |
| 170 |
|
| 171 |
@dataclass |
| 172 |
class Car: |
| 173 |
name: str |
| 174 |
mileage: float |
| 175 |
engine: Annotated[Engine, Parameter(name="*", group="Engine")] = field(default_factory=lambda: Engine(8, 500)) |
| 176 |
|
| 177 |
@app.command |
| 178 |
def build(*, license_plate: str, car: Car): |
| 179 |
pass |
| 180 |
|
| 181 |
|
| 182 |
assert_parse_args( |
| 183 |
build, |
| 184 |
"build --car.name=ford --car.mileage=500 --car.cylinders=4 --car.hp=200 --license-plate=ABCDEFG", |
| 185 |
car=Car(name="ford", mileage=500, engine=Engine(cylinders=4, hp=200)), |
| 186 |
license_plate="ABCDEFG", |
| 187 |
) |
| 188 |
|
| 189 |
|
| 190 |
assert_parse_args( |
| 191 |
build, |
| 192 |
"build --car.name=ford --car.mileage=500 --license-plate=ABCDEFG", |
| 193 |
car=Car(name="ford", mileage=500), |
| 194 |
license_plate="ABCDEFG", |
| 195 |
) |
| 196 |
|
| 197 |
|
| 198 |
with console.capture() as capture, pytest.raises(MissingArgumentError): |
| 199 |
app.parse_args( |
| 200 |
"build --car.name=ford --car.mileage=500 --car.hp=200 --license-plate=ABCDEFG", |
| 201 |
error_console=console, |
| 202 |
exit_on_error=False, |
| 203 |
) |
| 204 |
|
| 205 |
actual = capture.get() |
| 206 |
|
| 207 |
expected = dedent( |
| 208 |
"""\ |
| 209 |
╭─ Error ────────────────────────────────────────────────────────────╮ |
| 210 |
│ Command "build" parameter --car.cylinders requires an argument. │ |
| 211 |
╰────────────────────────────────────────────────────────────────────╯ |
| 212 |
""" |
| 213 |
) |
| 214 |
|
| 215 |
assert actual == expected |
| 216 |
|
| 217 |
|
| 218 |
@pytest.mark.parametrize( |
| 219 |
"cmd", |
| 220 |
[ |
| 221 |
"'Bob Smith' 30", |
| 222 |
"--nickname='Bob Smith' --player.years-young=30", |
| 223 |
], |
| 224 |
) |
| 225 |
def test_bind_dataclass_double_name_override_no_hyphen(app, assert_parse_args, console, cmd): |
| 226 |
@dataclass |
| 227 |
class User: |
| 228 |
|
| 229 |
name: Annotated[str, Parameter(name="--nickname")] |
| 230 |
|
| 231 |
age: Annotated[int, Parameter(name="years-young")] |
| 232 |
|
| 233 |
@app.default |
| 234 |
def main(user: Annotated[User, Parameter(name="player")]): |
| 235 |
print(user) |
| 236 |
|
| 237 |
assert_parse_args(main, cmd, user=User("Bob Smith", 30)) |
| 238 |
|
| 239 |
|
| 240 |
@pytest.mark.parametrize( |
| 241 |
"cmd_str", |
| 242 |
[ |
| 243 |
"100 200", |
| 244 |
"--a 100 --bar 200", |
| 245 |
"--bar 200 100", |
| 246 |
], |
| 247 |
) |
| 248 |
def test_bind_dataclass_positionally(app, assert_parse_args, cmd_str, console): |
| 249 |
@dataclass |
| 250 |
class Config: |
| 251 |
a: int = field() |
| 252 |
"""Docstring for a.""" |
| 253 |
|
| 254 |
b: Annotated[int, Parameter(name="bar")] = 2 |
| 255 |
"""This is the docstring for python parameter "b".""" |
| 256 |
|
| 257 |
@app.default |
| 258 |
def my_default_command(config: Annotated[Config, Parameter(name="*")]): |
| 259 |
print(f"{config=}") |
| 260 |
|
| 261 |
assert_parse_args(my_default_command, cmd_str, Config(a=100, b=200)) |
| 262 |
|
| 263 |
with console.capture() as capture: |
| 264 |
app("build --help", console=console) |
| 265 |
|
| 266 |
actual = capture.get() |
| 267 |
expected = dedent( |
| 268 |
"""\ |
| 269 |
Usage: test_bind_dataclasses A [ARGS] |
| 270 |
|
| 271 |
╭─ Commands ─────────────────────────────────────────────────────────╮ |
| 272 |
│ --help (-h) Display this message and exit. │ |
| 273 |
│ --version Display application version. │ |
| 274 |
╰────────────────────────────────────────────────────────────────────╯ |
| 275 |
╭─ Parameters ───────────────────────────────────────────────────────╮ |
| 276 |
│ * A --a Docstring for a. [required] │ |
| 277 |
│ BAR --bar This is the docstring for python parameter "b". │ |
| 278 |
│ [default: 2] │ |
| 279 |
╰────────────────────────────────────────────────────────────────────╯ |
| 280 |
""" |
| 281 |
) |
| 282 |
assert actual == expected |
| 283 |
|
| 284 |
|
| 285 |
def test_bind_dataclass_default_factory_help(app, console): |
| 286 |
@dataclass |
| 287 |
class Config: |
| 288 |
a: int = field(default_factory=lambda: 5) |
| 289 |
"""Docstring for a.""" |
| 290 |
|
| 291 |
@app.default |
| 292 |
def my_default_command(config: Annotated[Config | None, Parameter(name="*")] = None): |
| 293 |
print(f"{config=}") |
| 294 |
|
| 295 |
with console.capture() as capture: |
| 296 |
app("--help", console=console) |
| 297 |
|
| 298 |
actual = capture.get() |
| 299 |
expected = dedent( |
| 300 |
"""\ |
| 301 |
Usage: test_bind_dataclasses [ARGS] |
| 302 |
|
| 303 |
╭─ Commands ─────────────────────────────────────────────────────────╮ |
| 304 |
│ --help (-h) Display this message and exit. │ |
| 305 |
│ --version Display application version. │ |
| 306 |
╰────────────────────────────────────────────────────────────────────╯ |
| 307 |
╭─ Parameters ───────────────────────────────────────────────────────╮ |
| 308 |
│ A --a Docstring for a. [default: 5] │ |
| 309 |
╰────────────────────────────────────────────────────────────────────╯ |
| 310 |
""" |
| 311 |
) |
| 312 |
assert actual == expected |
| 313 |
|
| 314 |
|
| 315 |
def test_bind_dataclass_positionally_with_keyword_only_exception_no_default(app, assert_parse_args): |
| 316 |
@dataclass |
| 317 |
class Config: |
| 318 |
a: int = 1 |
| 319 |
"""Docstring for a.""" |
| 320 |
|
| 321 |
b: Annotated[int, Parameter(name="bar")] = 2 |
| 322 |
"""This is the docstring for python parameter "b".""" |
| 323 |
|
| 324 |
c: int = field(kw_only=True) |
| 325 |
|
| 326 |
@app.default |
| 327 |
def my_default_command(foo, config: Annotated[Config, Parameter(name="*")], bar): |
| 328 |
print(f"{config=}") |
| 329 |
|
| 330 |
expected = ("v1", Config(100, 200, c=300), "v2") |
| 331 |
assert_parse_args(my_default_command, "v1 100 200 v2 --c=300", *expected) |
| 332 |
assert_parse_args(my_default_command, "--c=300 v1 100 200 v2", *expected) |
| 333 |
with pytest.raises(MissingArgumentError): |
| 334 |
app.parse_args("v1 100 200 300 v2", exit_on_error=False) |
| 335 |
with pytest.raises(ArgumentOrderError): |
| 336 |
app.parse_args("v1 --a=100 200 300 v2", exit_on_error=False) |
| 337 |
with pytest.raises(ArgumentOrderError): |
| 338 |
app.parse_args("v1 --bar=v2 100 200 --c=300", exit_on_error=False) |
| 339 |
|
| 340 |
|
| 341 |
def test_bind_dataclass_positionally_with_keyword_only_exception_with_default(app, assert_parse_args): |
| 342 |
@dataclass |
| 343 |
class Config: |
| 344 |
a: int = 1 |
| 345 |
"""Docstring for a.""" |
| 346 |
|
| 347 |
b: Annotated[int, Parameter(name="bar")] = 2 |
| 348 |
"""This is the docstring for python parameter "b".""" |
| 349 |
|
| 350 |
c: int = field(default=5, kw_only=True) |
| 351 |
|
| 352 |
@app.default |
| 353 |
def my_default_command(config: Annotated[Config | None, Parameter(name="*")] = None): |
| 354 |
print(f"{config=}") |
| 355 |
|
| 356 |
with pytest.raises(UnusedCliTokensError): |
| 357 |
app.parse_args("100 200 300", exit_on_error=False) |
| 358 |
|
| 359 |
|
| 360 |
def test_bind_dataclass_tuple_in_var_args(app, assert_parse_args): |
| 361 |
@dataclass |
| 362 |
class Square: |
| 363 |
center: tuple[float, float] |
| 364 |
side_length: float |
| 365 |
|
| 366 |
@app.default |
| 367 |
def my_default_command(*squares: Square): |
| 368 |
pass |
| 369 |
|
| 370 |
assert_parse_args(my_default_command, "10 20 30", Square(center=(10.0, 20.0), side_length=30.0)) |
| 371 |
|
| 372 |
|
| 373 |
def test_bind_dataclass_with_alias_attribute(app, assert_parse_args): |
| 374 |
"""https://github.com/BrianPugh/cyclopts/issues/505""" |
| 375 |
|
| 376 |
@Parameter(name="*", negative=False) |
| 377 |
@dataclass |
| 378 |
class DataclassParameters: |
| 379 |
with_alias: Annotated[ |
| 380 |
bool, |
| 381 |
Parameter( |
| 382 |
alias="-a", |
| 383 |
help="Parameter that uses alias.", |
| 384 |
), |
| 385 |
] = False |
| 386 |
|
| 387 |
with_iterable: Annotated[ |
| 388 |
bool, Parameter(["--with-iterable", "-i"], help="Parameter that uses an iterable as name.") |
| 389 |
] = False |
| 390 |
|
| 391 |
@app.default |
| 392 |
def main(*, params: DataclassParameters | None = None) -> None: |
| 393 |
pass |
| 394 |
|
| 395 |
assert_parse_args(main, "-a", params=DataclassParameters(with_alias=True, with_iterable=False)) |
| 396 |
assert_parse_args(main, "--with-alias", params=DataclassParameters(with_alias=True, with_iterable=False)) |
| 397 |
|
| 398 |
|
| 399 |
def test_bind_dataclass_star_parameter_better_error_message(app, console): |
| 400 |
"""Test that Parameter(name="*") raises ValueError at app setup time when parameter has no default.""" |
| 401 |
|
| 402 |
@Parameter(name="*") |
| 403 |
@dataclass |
| 404 |
class Foo: |
| 405 |
bar: int = 12 |
| 406 |
|
| 407 |
def cmd(foo: Foo): |
| 408 |
print(foo) |
| 409 |
|
| 410 |
expected_message = ( |
| 411 |
r'Parameter "foo" in function .* has all optional values, uses Parameter\(name="\*"\), but itself has no default value\. Consider either:\n' |
| 412 |
r' 1\) If immutable, providing a default value "foo: Foo = Foo\(\)"\n' |
| 413 |
r' 2\) Otherwise, declaring it optional like "foo: Foo \| None = None" and instanting the foo object in the function body:\n' |
| 414 |
r" if foo is None:\n" |
| 415 |
r" foo = Foo\(\)" |
| 416 |
) |
| 417 |
|
| 418 |
with pytest.raises(ValueError, match=expected_message): |
| 419 |
app.default(cmd) |
| 420 |
|
| 421 |
|
| 422 |
def test_bind_dataclass_with_varargs_consume_all(app, assert_parse_args): |
| 423 |
"""Test dataclass with *args field that consumes all remaining tokens.""" |
| 424 |
|
| 425 |
@dataclass |
| 426 |
class FileProcessor: |
| 427 |
output: str |
| 428 |
inputs: tuple[str, ...] |
| 429 |
|
| 430 |
@app.default |
| 431 |
def process(config: Annotated[FileProcessor, Parameter(name="*")]): |
| 432 |
pass |
| 433 |
|
| 434 |
assert_parse_args( |
| 435 |
process, |
| 436 |
"out.txt in1.txt in2.txt in3.txt", |
| 437 |
config=FileProcessor(output="out.txt", inputs=("in1.txt", "in2.txt", "in3.txt")), |
| 438 |
) |
| 439 |
|
| 440 |
|
| 441 |
def test_dataclass_field_metadata_help(app, console): |
| 442 |
"""Test that dataclass Field metadata={"help": "..."} is used for help text.""" |
| 443 |
|
| 444 |
@dataclass |
| 445 |
class Config: |
| 446 |
name: str = field(default="default", metadata={"help": "Help from metadata."}) |
| 447 |
|
| 448 |
age: Annotated[int, Parameter(help="Parameter help takes precedence.")] = field( |
| 449 |
default=25, metadata={"help": "This metadata help is ignored."} |
| 450 |
) |
| 451 |
|
| 452 |
count: int = field(default=10) |
| 453 |
"""Docstring for count.""" |
| 454 |
|
| 455 |
size: int = field(default=5, metadata={"help": "Metadata help overrides docstring."}) |
| 456 |
"""This docstring is ignored.""" |
| 457 |
|
| 458 |
@app.default |
| 459 |
def main(config: Config): |
| 460 |
pass |
| 461 |
|
| 462 |
with console.capture() as capture: |
| 463 |
app("--help", console=console) |
| 464 |
|
| 465 |
actual = capture.get() |
| 466 |
|
| 467 |
assert "Help from metadata." in actual |
| 468 |
|
| 469 |
assert "Parameter help takes precedence." in actual |
| 470 |
assert "This metadata help is ignored." not in actual |
| 471 |
|
| 472 |
assert "Docstring for count." in actual |
| 473 |
|
| 474 |
assert "Metadata help overrides docstring." in actual |
| 475 |
assert "This docstring is ignored." not in actual |
| 476 |
|
| 477 |
|
| 478 |
def test_bind_dataclass_direct_parent_match_issue_647(app, assert_parse_args): |
| 479 |
"""Test that --foo bar baz correctly converts to Foo(name="bar", age=25). |
| 480 |
|
| 481 |
Previously, parent arguments with children would match directly (e.g., --foo), |
| 482 |
consume tokens, but then fail to properly construct the object because |
| 483 |
children had no tokens. The fix allows parent arguments to convert their |
| 484 |
tokens as positional arguments to the structured type. |
| 485 |
|
| 486 |
See: https://github.com/BrianPugh/cyclopts/issues/647 |
| 487 |
""" |
| 488 |
|
| 489 |
@dataclass |
| 490 |
class Foo: |
| 491 |
name: str |
| 492 |
age: int |
| 493 |
|
| 494 |
@app.default |
| 495 |
def cmd(*, foo: Annotated[Foo, Parameter()] = Foo(name="default", age=0)): |
| 496 |
return foo |
| 497 |
|
| 498 |
|
| 499 |
assert_parse_args(cmd, "--foo bar 25", foo=Foo(name="bar", age=25)) |
| 500 |
|
| 501 |
|
| 502 |
assert_parse_args(cmd, "--foo.name baz --foo.age 30", foo=Foo(name="baz", age=30)) |
| 503 |
|
| 504 |
|
| 505 |
_, bound, _ = app.parse_args("", print_error=False, exit_on_error=False) |
| 506 |
assert "foo" not in bound.arguments |
| 507 |
result = cmd(**bound.arguments) |
| 508 |
assert result == Foo(name="default", age=0) |
| 509 |
|
| 510 |
|
| 511 |
def test_bind_dataclass_kw_only_with_accepts_keys_false_issue_648(app, assert_parse_args): |
| 512 |
"""Test that kw_only dataclass with accepts_keys=False works. |
| 513 |
|
| 514 |
When a dataclass is kw_only=True, it cannot accept positional arguments. |
| 515 |
With accepts_keys=False, Cyclopts should still pass values as keyword arguments. |
| 516 |
|
| 517 |
See: https://github.com/BrianPugh/cyclopts/issues/648 |
| 518 |
""" |
| 519 |
|
| 520 |
@dataclass(kw_only=True) |
| 521 |
class Foo: |
| 522 |
name: str |
| 523 |
|
| 524 |
@app.default |
| 525 |
def cmd(*, foo: Annotated[Foo, Parameter(accepts_keys=False)]) -> Foo: |
| 526 |
return foo |
| 527 |
|
| 528 |
assert_parse_args(cmd, "--foo Alice", foo=Foo(name="Alice")) |
| 529 |
|
| 530 |
|
| 531 |
@pytest.mark.skipif(sys.version_info < (3, 14), reason="Requires Python 3.14+ for field(doc=...)") |
| 532 |
def test_dataclass_field_doc_parameter_help(app, console): |
| 533 |
"""Test that Python 3.14's dataclass field(doc=...) parameter is used for help text.""" |
| 534 |
|
| 535 |
@dataclass |
| 536 |
class Config: |
| 537 |
name: str = field(default="default", doc="Help from doc parameter.") |
| 538 |
|
| 539 |
age: Annotated[int, Parameter(help="Parameter help takes precedence.")] = field( |
| 540 |
default=25, |
| 541 |
doc="This doc is ignored.", |
| 542 |
) |
| 543 |
|
| 544 |
count: int = field(default=10, doc="Doc parameter help.") |
| 545 |
|
| 546 |
size: int = field( |
| 547 |
default=5, |
| 548 |
metadata={"help": "Metadata help takes precedence over doc."}, |
| 549 |
doc="This doc is ignored.", |
| 550 |
) |
| 551 |
|
| 552 |
height: int = field(default=8) |
| 553 |
"""Docstring for height.""" |
| 554 |
|
| 555 |
width: int = field(default=12, doc="Doc parameter overrides docstring.") |
| 556 |
"""This docstring is ignored.""" |
| 557 |
|
| 558 |
@app.default |
| 559 |
def main(config: Config): |
| 560 |
pass |
| 561 |
|
| 562 |
with console.capture() as capture: |
| 563 |
app("--help", console=console) |
| 564 |
|
| 565 |
actual = capture.get() |
| 566 |
|
| 567 |
assert "Help from doc parameter." in actual |
| 568 |
|
| 569 |
assert "Parameter help takes precedence." in actual |
| 570 |
assert "This doc is ignored." not in actual |
| 571 |
|
| 572 |
assert "Doc parameter help." in actual |
| 573 |
|
| 574 |
assert "Metadata help takes precedence" in actual |
| 575 |
|
| 576 |
assert "Docstring for height." in actual |
| 577 |
|
| 578 |
assert "Doc parameter overrides docstring." in actual |
| 579 |
assert "This docstring is ignored." not in actual |
| 580 |
|
| 581 |
|
| 582 |
def test_dataclass_inheritance_simple(app, console): |
| 583 |
"""Test that docstrings from base dataclass are inherited by derived class. |
| 584 |
|
| 585 |
Regression test for: https://github.com/BrianPugh/cyclopts/issues/691 |
| 586 |
""" |
| 587 |
|
| 588 |
@dataclass |
| 589 |
class BaseClass: |
| 590 |
"""Base class.""" |
| 591 |
|
| 592 |
some_arg: int = 42 |
| 593 |
"""BaseClass.some_arg docstring.""" |
| 594 |
|
| 595 |
@dataclass |
| 596 |
class DerivedClass(BaseClass): |
| 597 |
"""Derived class.""" |
| 598 |
|
| 599 |
some_other_arg: str = "some_other_arg default value" |
| 600 |
"""DerivedClass.some_other_arg docstring.""" |
| 601 |
|
| 602 |
@app.default |
| 603 |
def main(params: DerivedClass): |
| 604 |
pass |
| 605 |
|
| 606 |
with console.capture() as capture: |
| 607 |
app("--help", console=console) |
| 608 |
|
| 609 |
actual = capture.get() |
| 610 |
|
| 611 |
|
| 612 |
assert "BaseClass.some_arg docstring." in actual |
| 613 |
assert "DerivedClass.some_other_arg docstring." in actual |
| 614 |
|
| 615 |
|
| 616 |
def test_dataclass_inheritance_multi_level(app, console): |
| 617 |
"""Test that docstrings propagate through multiple inheritance levels.""" |
| 618 |
|
| 619 |
@dataclass |
| 620 |
class GrandparentClass: |
| 621 |
"""Grandparent class.""" |
| 622 |
|
| 623 |
grandparent_field: int = 1 |
| 624 |
"""Grandparent field doc.""" |
| 625 |
|
| 626 |
@dataclass |
| 627 |
class ParentClass(GrandparentClass): |
| 628 |
"""Parent class.""" |
| 629 |
|
| 630 |
parent_field: int = 2 |
| 631 |
"""Parent field doc.""" |
| 632 |
|
| 633 |
@dataclass |
| 634 |
class ChildClass(ParentClass): |
| 635 |
"""Child class.""" |
| 636 |
|
| 637 |
child_field: int = 3 |
| 638 |
"""Child field doc.""" |
| 639 |
|
| 640 |
@app.default |
| 641 |
def main(params: ChildClass): |
| 642 |
pass |
| 643 |
|
| 644 |
with console.capture() as capture: |
| 645 |
app("--help", console=console) |
| 646 |
|
| 647 |
actual = capture.get() |
| 648 |
|
| 649 |
|
| 650 |
assert "Grandparent field doc." in actual |
| 651 |
assert "Parent field doc." in actual |
| 652 |
assert "Child field doc." in actual |
| 653 |
|
| 654 |
|
| 655 |
def test_dataclass_inheritance_override_docstring(app, console): |
| 656 |
"""Test that derived class can override base class docstrings.""" |
| 657 |
|
| 658 |
@dataclass |
| 659 |
class BaseClass: |
| 660 |
"""Base class.""" |
| 661 |
|
| 662 |
shared_field: int = 1 |
| 663 |
"""Base docstring.""" |
| 664 |
|
| 665 |
@dataclass |
| 666 |
class DerivedClass(BaseClass): |
| 667 |
"""Derived class.""" |
| 668 |
|
| 669 |
shared_field: int = 2 |
| 670 |
"""Derived docstring overrides base.""" |
| 671 |
|
| 672 |
new_field: str = "new" |
| 673 |
"""New field in derived.""" |
| 674 |
|
| 675 |
@app.default |
| 676 |
def main(params: DerivedClass): |
| 677 |
pass |
| 678 |
|
| 679 |
with console.capture() as capture: |
| 680 |
app("--help", console=console) |
| 681 |
|
| 682 |
actual = capture.get() |
| 683 |
|
| 684 |
|
| 685 |
assert "Derived docstring overrides base." in actual |
| 686 |
assert "Base docstring." not in actual |
| 687 |
assert "New field in derived." in actual |
| 688 |
|
| 689 |
|
| 690 |
def test_dataclass_inheritance_with_parameter_name_star(app, console, normalize_trailing_whitespace): |
| 691 |
"""Test inheritance with Parameter(name='*') works correctly.""" |
| 692 |
|
| 693 |
@dataclass |
| 694 |
class BaseConfig: |
| 695 |
"""Base configuration.""" |
| 696 |
|
| 697 |
verbose: bool = False |
| 698 |
"""Enable verbose output.""" |
| 699 |
|
| 700 |
@dataclass |
| 701 |
class ExtendedConfig(BaseConfig): |
| 702 |
"""Extended configuration.""" |
| 703 |
|
| 704 |
debug: bool = False |
| 705 |
"""Enable debug mode.""" |
| 706 |
|
| 707 |
@app.default |
| 708 |
def main(config: Annotated[ExtendedConfig | None, Parameter(name="*")] = None): |
| 709 |
pass |
| 710 |
|
| 711 |
with console.capture() as capture: |
| 712 |
app("--help", console=console) |
| 713 |
|
| 714 |
actual = capture.get() |
| 715 |
|
| 716 |
|
| 717 |
assert "Enable verbose output." in actual |
| 718 |
assert "Enable debug mode." in actual |
| 719 |
|
| 720 |
|
| 721 |
def test_dataclass_inheritance_no_docstrings_in_derived(app, console): |
| 722 |
"""Test that base docstrings work even if derived class has no docstrings.""" |
| 723 |
|
| 724 |
@dataclass |
| 725 |
class BaseClass: |
| 726 |
"""Base class.""" |
| 727 |
|
| 728 |
base_field: int = 1 |
| 729 |
"""Base field documentation.""" |
| 730 |
|
| 731 |
@dataclass |
| 732 |
class DerivedClass(BaseClass): |
| 733 |
"""Derived class.""" |
| 734 |
|
| 735 |
|
| 736 |
derived_field: int = 2 |
| 737 |
|
| 738 |
@app.default |
| 739 |
def main(params: DerivedClass): |
| 740 |
pass |
| 741 |
|
| 742 |
with console.capture() as capture: |
| 743 |
app("--help", console=console) |
| 744 |
|
| 745 |
actual = capture.get() |
| 746 |
|
| 747 |
|
| 748 |
assert "Base field documentation." in actual |
| 749 |
|
| 750 |
|
| 751 |
def test_bind_dataclass_with_parameter_alias_issue_696(app, assert_parse_args, console): |
| 752 |
"""Test that user class with parameter alias generates correct arguments. |
| 753 |
|
| 754 |
https://github.com/BrianPugh/cyclopts/issues/696 |
| 755 |
|
| 756 |
When using a user class as a parameter with an alias, the generated |
| 757 |
arguments should use the class attribute names, not the parameter alias. |
| 758 |
|
| 759 |
For example, parameter `source` with alias `from`, and class attribute `server`: |
| 760 |
- Should generate: --source.server, --from.server |
| 761 |
- Should NOT generate: --source.from, --from.from |
| 762 |
""" |
| 763 |
|
| 764 |
@dataclass |
| 765 |
class Source: |
| 766 |
server: str |
| 767 |
port: int = 8080 |
| 768 |
|
| 769 |
@app.default |
| 770 |
def main(source: Annotated[Source, Parameter(name="source", alias="from")]): |
| 771 |
return source |
| 772 |
|
| 773 |
|
| 774 |
with console.capture() as capture: |
| 775 |
app("--help", console=console) |
| 776 |
|
| 777 |
actual = capture.get() |
| 778 |
|
| 779 |
|
| 780 |
assert "--source.server" in actual, "Missing --source.server" |
| 781 |
assert "--from.server" in actual, "Missing --from.server" |
| 782 |
|
| 783 |
|
| 784 |
assert "--source.from" not in actual, "Incorrectly generated --source.from" |
| 785 |
assert "--from.from" not in actual, "Incorrectly generated --from.from" |
| 786 |
|
| 787 |
|
| 788 |
assert_parse_args( |
| 789 |
main, |
| 790 |
"--source.server=localhost --source.port=9000", |
| 791 |
source=Source(server="localhost", port=9000), |
| 792 |
) |
| 793 |
|
| 794 |
|
| 795 |
assert_parse_args( |
| 796 |
main, |
| 797 |
"--from.server=localhost --from.port=9000", |
| 798 |
source=Source(server="localhost", port=9000), |
| 799 |
) |
| 800 |
|
| 801 |
|
| 802 |
assert_parse_args( |
| 803 |
main, |
| 804 |
"--source.server=localhost --from.port=9000", |
| 805 |
source=Source(server="localhost", port=9000), |
| 806 |
) |