| 1 |
import pytest |
| 2 |
|
| 3 |
from cyclopts import App |
| 4 |
from cyclopts.config import Dict |
| 5 |
|
| 6 |
|
| 7 |
def test_config_dict_basic(): |
| 8 |
"""Test basic Dict config functionality.""" |
| 9 |
app = App(config=Dict({"name": "Alice", "age": 30}), result_action="return_value") |
| 10 |
|
| 11 |
@app.default |
| 12 |
def main(name: str, age: int): |
| 13 |
return f"{name} is {age} years old." |
| 14 |
|
| 15 |
result = app([]) |
| 16 |
assert result == "Alice is 30 years old." |
| 17 |
|
| 18 |
|
| 19 |
def test_config_dict_with_commands(): |
| 20 |
"""Test Dict config with commands.""" |
| 21 |
config_data = { |
| 22 |
"create": {"name": "Alice", "age": 30}, |
| 23 |
"update": {"name": "Bob", "age": 40}, |
| 24 |
} |
| 25 |
app = App(config=Dict(config_data), result_action="return_value") |
| 26 |
|
| 27 |
@app.command |
| 28 |
def create(name: str, age: int): |
| 29 |
return f"Created: {name} is {age} years old." |
| 30 |
|
| 31 |
@app.command |
| 32 |
def update(name: str, age: int): |
| 33 |
return f"Updated: {name} is {age} years old." |
| 34 |
|
| 35 |
result = app("create") |
| 36 |
assert result == "Created: Alice is 30 years old." |
| 37 |
|
| 38 |
result = app("update") |
| 39 |
assert result == "Updated: Bob is 40 years old." |
| 40 |
|
| 41 |
|
| 42 |
def test_config_dict_with_root_keys(): |
| 43 |
"""Test Dict config with root_keys navigation.""" |
| 44 |
config_data = { |
| 45 |
"production": { |
| 46 |
"database": { |
| 47 |
"host": "prod.example.com", |
| 48 |
"port": 5432, |
| 49 |
} |
| 50 |
} |
| 51 |
} |
| 52 |
app = App( |
| 53 |
config=Dict(config_data, root_keys=["production", "database"]), |
| 54 |
result_action="return_value", |
| 55 |
) |
| 56 |
|
| 57 |
@app.default |
| 58 |
def main(host: str, port: int): |
| 59 |
return f"Connecting to {host}:{port}" |
| 60 |
|
| 61 |
result = app([]) |
| 62 |
assert result == "Connecting to prod.example.com:5432" |
| 63 |
|
| 64 |
|
| 65 |
def test_config_dict_use_commands_as_keys_false(): |
| 66 |
"""Test Dict config with use_commands_as_keys=False.""" |
| 67 |
config_data = {"name": "Alice", "age": 30} |
| 68 |
app = App(config=Dict(config_data, use_commands_as_keys=False), result_action="return_value") |
| 69 |
|
| 70 |
@app.command |
| 71 |
def create(name: str, age: int): |
| 72 |
return f"{name} is {age} years old." |
| 73 |
|
| 74 |
result = app("create") |
| 75 |
assert result == "Alice is 30 years old." |
| 76 |
|
| 77 |
|
| 78 |
def test_config_dict_use_commands_as_keys_false_with_sibling_commands(): |
| 79 |
"""Test Dict config filters sibling command sections when use_commands_as_keys=False. |
| 80 |
|
| 81 |
Regression test for issue where config filtering used command_app instead of parent app, |
| 82 |
causing sibling command sections in the config to not be properly filtered out. |
| 83 |
|
| 84 |
This reproduces the bug fixed in core.py where executing "polygon 1 2 3 4" would fail |
| 85 |
because the "line" section in the config wasn't being filtered correctly. |
| 86 |
""" |
| 87 |
from dataclasses import KW_ONLY, dataclass |
| 88 |
from typing import Annotated |
| 89 |
|
| 90 |
from cyclopts import Parameter |
| 91 |
|
| 92 |
config_data = { |
| 93 |
"units": "meters", |
| 94 |
"line": {"color": "red"}, |
| 95 |
"polygon": {"color": "blue"}, |
| 96 |
"circle": {"color": "green"}, |
| 97 |
} |
| 98 |
|
| 99 |
app = App(config=Dict(config_data, use_commands_as_keys=False), result_action="return_value") |
| 100 |
|
| 101 |
@Parameter(name="*") |
| 102 |
@dataclass |
| 103 |
class DrawConfig: |
| 104 |
_: KW_ONLY |
| 105 |
units: str = "meters" |
| 106 |
color: str = "black" |
| 107 |
|
| 108 |
@app.command |
| 109 |
def line(start: tuple[float, float], end: tuple[float, float], config: DrawConfig | None = None): |
| 110 |
if config is None: |
| 111 |
config = DrawConfig() |
| 112 |
return f"line: {start} to {end} in {config.units}, color={config.color}" |
| 113 |
|
| 114 |
@app.command |
| 115 |
def polygon(*vertices: Annotated[tuple[float, float], Parameter(required=True)], config: DrawConfig | None = None): |
| 116 |
if config is None: |
| 117 |
config = DrawConfig() |
| 118 |
return f"polygon: {len(vertices)} vertices in {config.units}, color={config.color}" |
| 119 |
|
| 120 |
@app.command |
| 121 |
def circle(center: tuple[float, float], radius: float, config: DrawConfig | None = None): |
| 122 |
if config is None: |
| 123 |
config = DrawConfig() |
| 124 |
return f"circle: center={center} radius={radius} in {config.units}, color={config.color}" |
| 125 |
|
| 126 |
result = app("line 0 0 10 10") |
| 127 |
assert result == "line: (0.0, 0.0) to (10.0, 10.0) in meters, color=black" |
| 128 |
|
| 129 |
result = app("polygon 1 2 3 4 5 6") |
| 130 |
assert result == "polygon: 3 vertices in meters, color=black" |
| 131 |
|
| 132 |
result = app("circle 0 0 5") |
| 133 |
assert result == "circle: center=(0.0, 0.0) radius=5.0 in meters, color=black" |
| 134 |
|
| 135 |
|
| 136 |
def test_config_dict_nested_commands_with_use_commands_as_keys_true(): |
| 137 |
"""Test Dict config with nested commands using default use_commands_as_keys=True. |
| 138 |
|
| 139 |
Regression test to ensure that when use_commands_as_keys=True (default), the filtering |
| 140 |
uses command_app (not root_app) so that subcommand sections at the command's config level |
| 141 |
are properly filtered out. |
| 142 |
|
| 143 |
Without the correct fix, this would fail with "Unknown option" errors because cmd1/cmd2 |
| 144 |
sections wouldn't be filtered when executing the sub default command. |
| 145 |
""" |
| 146 |
config_data = { |
| 147 |
"sub": { |
| 148 |
"shared_param": "shared_value", |
| 149 |
"cmd1": {"cmd1_param": "cmd1_value"}, |
| 150 |
"cmd2": {"cmd2_param": "cmd2_value"}, |
| 151 |
} |
| 152 |
} |
| 153 |
|
| 154 |
app = App(config=Dict(config_data), result_action="return_value") |
| 155 |
sub_app = App() |
| 156 |
app.command(sub_app, name="sub") |
| 157 |
|
| 158 |
@sub_app.default |
| 159 |
def sub_default(shared_param: str): |
| 160 |
return f"sub_default: {shared_param}" |
| 161 |
|
| 162 |
@sub_app.command |
| 163 |
def cmd1(cmd1_param: str): |
| 164 |
return f"cmd1: {cmd1_param}" |
| 165 |
|
| 166 |
@sub_app.command |
| 167 |
def cmd2(cmd2_param: str): |
| 168 |
return f"cmd2: {cmd2_param}" |
| 169 |
|
| 170 |
result = app("sub") |
| 171 |
assert result == "sub_default: shared_value" |
| 172 |
|
| 173 |
result = app("sub cmd1") |
| 174 |
assert result == "cmd1: cmd1_value" |
| 175 |
|
| 176 |
result = app("sub cmd2") |
| 177 |
assert result == "cmd2: cmd2_value" |
| 178 |
|
| 179 |
|
| 180 |
def test_config_dict_nested_commands_with_use_commands_as_keys_false(): |
| 181 |
"""Test Dict config with nested App commands using use_commands_as_keys=False. |
| 182 |
|
| 183 |
With use_commands_as_keys=False, config stays at root level and is shared |
| 184 |
across all commands, including nested App commands and their subcommands. |
| 185 |
""" |
| 186 |
config_data = { |
| 187 |
"global_setting": "shared_value", |
| 188 |
} |
| 189 |
|
| 190 |
app = App(config=Dict(config_data, use_commands_as_keys=False), result_action="return_value") |
| 191 |
sub_app = App() |
| 192 |
app.command(sub_app, name="sub") |
| 193 |
|
| 194 |
@sub_app.default |
| 195 |
def sub_default(global_setting: str): |
| 196 |
return f"sub_default: {global_setting}" |
| 197 |
|
| 198 |
@sub_app.command |
| 199 |
def cmd1(global_setting: str): |
| 200 |
return f"cmd1: {global_setting}" |
| 201 |
|
| 202 |
result = app("sub") |
| 203 |
assert result == "sub_default: shared_value" |
| 204 |
|
| 205 |
result = app("sub cmd1") |
| 206 |
assert result == "cmd1: shared_value" |
| 207 |
|
| 208 |
|
| 209 |
def test_config_dict_deeply_nested_with_use_commands_as_keys_false(): |
| 210 |
"""Test Dict config with deeply nested commands and use_commands_as_keys=False. |
| 211 |
|
| 212 |
Ensures that even with multiple levels of nesting, flat config is shared |
| 213 |
across all command levels. |
| 214 |
""" |
| 215 |
config_data = { |
| 216 |
"shared": "value", |
| 217 |
"another": 42, |
| 218 |
} |
| 219 |
|
| 220 |
app = App(config=Dict(config_data, use_commands_as_keys=False), result_action="return_value") |
| 221 |
level1_app = App() |
| 222 |
level2_app = App() |
| 223 |
|
| 224 |
app.command(level1_app, name="level1") |
| 225 |
level1_app.command(level2_app, name="level2") |
| 226 |
|
| 227 |
@level2_app.default |
| 228 |
def deeply_nested(shared: str, another: int): |
| 229 |
return f"deeply_nested: {shared}, {another}" |
| 230 |
|
| 231 |
result = app("level1 level2") |
| 232 |
assert result == "deeply_nested: value, 42" |
| 233 |
|
| 234 |
|
| 235 |
def test_config_dict_mixed_nested_and_flat_commands(): |
| 236 |
"""Test Dict config with mix of nested apps and flat config. |
| 237 |
|
| 238 |
This tests that both simple commands and nested App commands can share |
| 239 |
the same flat config when use_commands_as_keys=False. |
| 240 |
""" |
| 241 |
config_data = { |
| 242 |
"base_value": "base", |
| 243 |
"count": 10, |
| 244 |
} |
| 245 |
|
| 246 |
app = App(config=Dict(config_data, use_commands_as_keys=False), result_action="return_value") |
| 247 |
|
| 248 |
@app.command |
| 249 |
def simple(base_value: str, count: int): |
| 250 |
return f"simple: {base_value}, count={count}" |
| 251 |
|
| 252 |
nested_app = App() |
| 253 |
app.command(nested_app, name="nested") |
| 254 |
|
| 255 |
@nested_app.default |
| 256 |
def nested_default(base_value: str, count: int): |
| 257 |
return f"nested: {base_value}, count={count}" |
| 258 |
|
| 259 |
result = app("simple") |
| 260 |
assert result == "simple: base, count=10" |
| 261 |
|
| 262 |
result = app("nested") |
| 263 |
assert result == "nested: base, count=10" |
| 264 |
|
| 265 |
|
| 266 |
def test_config_dict_use_commands_as_keys_true_filters_subcommands(): |
| 267 |
"""Test that use_commands_as_keys=True correctly filters sibling subcommands. |
| 268 |
|
| 269 |
When navigating into a command's config section, sibling command sections at that |
| 270 |
level should be filtered using the command's app (not root app). This ensures |
| 271 |
that "create" and "delete" sections are filtered when executing each other. |
| 272 |
""" |
| 273 |
config_data = { |
| 274 |
"db": { |
| 275 |
"timeout": 30, |
| 276 |
"create": {"timeout": 10, "operation": "create_op"}, |
| 277 |
"delete": {"timeout": 20, "operation": "delete_op"}, |
| 278 |
} |
| 279 |
} |
| 280 |
|
| 281 |
app = App(config=Dict(config_data, use_commands_as_keys=True), result_action="return_value") |
| 282 |
db_app = App() |
| 283 |
app.command(db_app, name="db") |
| 284 |
|
| 285 |
@db_app.default |
| 286 |
def db_default(timeout: int): |
| 287 |
return f"db: timeout={timeout}" |
| 288 |
|
| 289 |
@db_app.command |
| 290 |
def create(timeout: int, operation: str): |
| 291 |
return f"create: timeout={timeout}, operation={operation}" |
| 292 |
|
| 293 |
@db_app.command |
| 294 |
def delete(timeout: int, operation: str): |
| 295 |
return f"delete: timeout={timeout}, operation={operation}" |
| 296 |
|
| 297 |
result = app("db") |
| 298 |
assert result == "db: timeout=30" |
| 299 |
|
| 300 |
result = app("db create") |
| 301 |
assert result == "create: timeout=10, operation=create_op" |
| 302 |
|
| 303 |
result = app("db delete") |
| 304 |
assert result == "delete: timeout=20, operation=delete_op" |
| 305 |
|
| 306 |
|
| 307 |
def test_config_dict_allow_unknown(): |
| 308 |
"""Test Dict config with allow_unknown=True.""" |
| 309 |
config_data = { |
| 310 |
"name": "Alice", |
| 311 |
"age": 30, |
| 312 |
"unknown_field": "should_be_ignored", |
| 313 |
} |
| 314 |
app = App(config=Dict(config_data, allow_unknown=True), result_action="return_value") |
| 315 |
|
| 316 |
@app.default |
| 317 |
def main(name: str, age: int): |
| 318 |
return f"{name} is {age} years old." |
| 319 |
|
| 320 |
result = app([]) |
| 321 |
assert result == "Alice is 30 years old." |
| 322 |
|
| 323 |
|
| 324 |
def test_config_dict_allow_unknown_nested_user_class(): |
| 325 |
"""Test that unknown nested keys are ignored with user classes when allow_unknown=True. |
| 326 |
|
| 327 |
Regression test for https://github.com/BrianPugh/cyclopts/issues/731 |
| 328 |
""" |
| 329 |
from dataclasses import dataclass |
| 330 |
|
| 331 |
@dataclass |
| 332 |
class ConnectionParameter: |
| 333 |
timeout: float |
| 334 |
|
| 335 |
config_data = { |
| 336 |
"p": {"timeout": 3}, |
| 337 |
"np": {"timeout": 4}, |
| 338 |
} |
| 339 |
app = App( |
| 340 |
config=Dict(config_data, allow_unknown=True, use_commands_as_keys=False), |
| 341 |
result_action="return_value", |
| 342 |
) |
| 343 |
|
| 344 |
@app.default |
| 345 |
def connect(*, p: ConnectionParameter): |
| 346 |
return p.timeout |
| 347 |
|
| 348 |
result = app([]) |
| 349 |
assert result == 3.0 |
| 350 |
|
| 351 |
|
| 352 |
@pytest.mark.parametrize( |
| 353 |
"config_data", |
| 354 |
[ |
| 355 |
{"p": {"timeout": 5}}, |
| 356 |
{"timeout": 5}, |
| 357 |
], |
| 358 |
) |
| 359 |
def test_config_dict_remapped_nested_parameter(config_data): |
| 360 |
"""Test that nested config paths don't match remapped parameters. |
| 361 |
|
| 362 |
When a nested parameter has Parameter(name="--timeout") (remapped to root level), |
| 363 |
config should use {"timeout": 5}, not {"p": {"timeout": 5}}. The nested path |
| 364 |
should raise UnknownOptionError because it doesn't match the remapped CLI name. |
| 365 |
""" |
| 366 |
from dataclasses import dataclass |
| 367 |
from typing import Annotated |
| 368 |
|
| 369 |
from cyclopts import Parameter |
| 370 |
|
| 371 |
@dataclass |
| 372 |
class ConnectionParameter: |
| 373 |
timeout: Annotated[float, Parameter(name="--timeout")] |
| 374 |
|
| 375 |
app = App( |
| 376 |
config=Dict(config_data, use_commands_as_keys=False), |
| 377 |
result_action="return_value", |
| 378 |
) |
| 379 |
|
| 380 |
@app.default |
| 381 |
def connect(*, p: ConnectionParameter): |
| 382 |
return p.timeout |
| 383 |
|
| 384 |
app([], exit_on_error=False) |
| 385 |
|
| 386 |
|
| 387 |
def test_config_dict_partial_override(): |
| 388 |
"""Test that CLI args override Dict config values.""" |
| 389 |
config_data = {"name": "Alice", "age": 30} |
| 390 |
app = App(config=Dict(config_data), result_action="return_value") |
| 391 |
|
| 392 |
@app.default |
| 393 |
def main(name: str, age: int): |
| 394 |
return f"{name} is {age} years old." |
| 395 |
|
| 396 |
result = app("--name Bob") |
| 397 |
assert result == "Bob is 30 years old." |
| 398 |
|
| 399 |
|
| 400 |
def test_config_dict_empty(): |
| 401 |
"""Test Dict config with empty dict.""" |
| 402 |
app = App(config=Dict({}), result_action="return_value") |
| 403 |
|
| 404 |
@app.default |
| 405 |
def main(name: str = "Default", age: int = 0): |
| 406 |
return f"{name} is {age} years old." |
| 407 |
|
| 408 |
result = app([]) |
| 409 |
assert result == "Default is 0 years old." |
| 410 |
|
| 411 |
|
| 412 |
def test_config_dict_nested_structure(): |
| 413 |
"""Test Dict config with nested dataclass-like structures.""" |
| 414 |
from dataclasses import dataclass |
| 415 |
|
| 416 |
@dataclass |
| 417 |
class Database: |
| 418 |
host: str |
| 419 |
port: int |
| 420 |
|
| 421 |
config_data = { |
| 422 |
"database": { |
| 423 |
"host": "localhost", |
| 424 |
"port": 5432, |
| 425 |
} |
| 426 |
} |
| 427 |
app = App(config=Dict(config_data), result_action="return_value") |
| 428 |
|
| 429 |
@app.default |
| 430 |
def main(database: Database): |
| 431 |
return f"{database.host}:{database.port}" |
| 432 |
|
| 433 |
result = app([]) |
| 434 |
assert result == "localhost:5432" |
| 435 |
|
| 436 |
|
| 437 |
def test_config_dict_source(): |
| 438 |
"""Test that Dict.source returns 'dict' by default.""" |
| 439 |
config = Dict({"key": "value"}) |
| 440 |
assert config.source == "dict" |
| 441 |
|
| 442 |
|
| 443 |
def test_config_dict_custom_source(): |
| 444 |
"""Test that Dict.source can be customized.""" |
| 445 |
config = Dict({"key": "value"}, source="api") |
| 446 |
assert config.source == "api" |
| 447 |
|
| 448 |
config_network = Dict({"key": "value"}, source="network") |
| 449 |
assert config_network.source == "network" |
| 450 |
|
| 451 |
|
| 452 |
def test_config_dict_source_setter(): |
| 453 |
"""Test that Dict.source can be modified via setter.""" |
| 454 |
config = Dict({"key": "value"}) |
| 455 |
assert config.source == "dict" |
| 456 |
|
| 457 |
config.source = "api" |
| 458 |
assert config.source == "api" |
| 459 |
|
| 460 |
config.source = "network-response" |
| 461 |
assert config.source == "network-response" |
| 462 |
|
| 463 |
|
| 464 |
def test_config_dict_with_subcommands(): |
| 465 |
"""Test that Dict config correctly filters out subcommand keys.""" |
| 466 |
config_data = { |
| 467 |
"global_flag": True, |
| 468 |
"subcommand": { |
| 469 |
"sub_value": 123, |
| 470 |
}, |
| 471 |
} |
| 472 |
app = App(config=Dict(config_data), result_action="return_value") |
| 473 |
|
| 474 |
@app.default |
| 475 |
def main(global_flag: bool = False): |
| 476 |
return f"global_flag={global_flag}" |
| 477 |
|
| 478 |
@app.command |
| 479 |
def subcommand(sub_value: int): |
| 480 |
return f"sub_value={sub_value}" |
| 481 |
|
| 482 |
result = app([]) |
| 483 |
assert result == "global_flag=True" |
| 484 |
|
| 485 |
result = app("subcommand") |
| 486 |
assert result == "sub_value=123" |
| 487 |
|
| 488 |
|
| 489 |
def test_config_dict_unknown_field_error(): |
| 490 |
"""Test that unknown fields raise error when allow_unknown=False.""" |
| 491 |
import pytest |
| 492 |
|
| 493 |
from cyclopts.exceptions import UnknownOptionError |
| 494 |
|
| 495 |
config_data = { |
| 496 |
"name": "Alice", |
| 497 |
"age": 30, |
| 498 |
"unknown_field": "should_error", |
| 499 |
} |
| 500 |
app = App(config=Dict(config_data, allow_unknown=False), result_action="return_value") |
| 501 |
|
| 502 |
@app.default |
| 503 |
def main(name: str, age: int): |
| 504 |
return f"{name} is {age} years old." |
| 505 |
|
| 506 |
with pytest.raises(UnknownOptionError): |
| 507 |
app([], exit_on_error=False) |
| 508 |
|
| 509 |
|
| 510 |
def test_config_dict_multiple_configs(): |
| 511 |
"""Test using multiple Dict configs in a list.""" |
| 512 |
config1 = Dict({"name": "Alice"}) |
| 513 |
config2 = Dict({"age": 30}) |
| 514 |
|
| 515 |
app = App(config=[config1, config2], result_action="return_value") |
| 516 |
|
| 517 |
@app.default |
| 518 |
def main(name: str, age: int): |
| 519 |
return f"{name} is {age} years old." |
| 520 |
|
| 521 |
result = app([]) |
| 522 |
assert result == "Alice is 30 years old." |
| 523 |
|
| 524 |
|
| 525 |
def test_config_dict_with_env(): |
| 526 |
"""Test combining Dict config with Env config.""" |
| 527 |
import os |
| 528 |
|
| 529 |
from cyclopts.config import Env |
| 530 |
|
| 531 |
config_data = {"name": "Alice"} |
| 532 |
app = App(config=[Dict(config_data), Env("TEST_")], result_action="return_value") |
| 533 |
|
| 534 |
@app.default |
| 535 |
def main(name: str, age: int = 0): |
| 536 |
return f"{name} is {age} years old." |
| 537 |
|
| 538 |
os.environ["TEST_AGE"] = "30" |
| 539 |
try: |
| 540 |
result = app([]) |
| 541 |
assert result == "Alice is 30 years old." |
| 542 |
finally: |
| 543 |
del os.environ["TEST_AGE"] |
| 544 |
|
| 545 |
|
| 546 |
def test_config_dict_modification_after_creation(): |
| 547 |
"""Test modifying Dict config after app creation.""" |
| 548 |
config = Dict({"name": "Alice", "age": 30}) |
| 549 |
app = App(config=config, result_action="return_value") |
| 550 |
|
| 551 |
@app.default |
| 552 |
def main(name: str, age: int): |
| 553 |
return f"{name} is {age} years old." |
| 554 |
|
| 555 |
result = app([]) |
| 556 |
assert result == "Alice is 30 years old." |
| 557 |
|
| 558 |
config.data["name"] = "Bob" |
| 559 |
result = app([]) |
| 560 |
assert result == "Bob is 30 years old." |
| 561 |
|
| 562 |
|
| 563 |
def test_config_dict_with_meta_app(): |
| 564 |
"""Test Dict config with meta app.""" |
| 565 |
from typing import Annotated |
| 566 |
|
| 567 |
from cyclopts import Parameter |
| 568 |
|
| 569 |
app = App(result_action="return_value") |
| 570 |
|
| 571 |
@app.default |
| 572 |
def main(name: str, age: int): |
| 573 |
return f"{name} is {age} years old." |
| 574 |
|
| 575 |
@app.meta.default |
| 576 |
def meta(*tokens: Annotated[str, Parameter(show=False, allow_leading_hyphen=True)], config_source: str = "dict"): |
| 577 |
app.config = Dict({"name": "Alice", "age": 30}, source=config_source) |
| 578 |
return app(tokens) |
| 579 |
|
| 580 |
result = app.meta([]) |
| 581 |
assert result == "Alice is 30 years old." |
| 582 |
|
| 583 |
|
| 584 |
def test_config_dict_deep_nesting(): |
| 585 |
"""Test Dict config with deep root_keys nesting.""" |
| 586 |
config_data = {"level1": {"level2": {"level3": {"level4": {"name": "Alice", "age": 30}}}}} |
| 587 |
app = App( |
| 588 |
config=Dict(config_data, root_keys=["level1", "level2", "level3", "level4"]), |
| 589 |
result_action="return_value", |
| 590 |
) |
| 591 |
|
| 592 |
@app.default |
| 593 |
def main(name: str, age: int): |
| 594 |
return f"{name} is {age} years old." |
| 595 |
|
| 596 |
result = app([]) |
| 597 |
assert result == "Alice is 30 years old." |
| 598 |
|
| 599 |
|
| 600 |
def test_config_dict_cli_priority(): |
| 601 |
"""Test that CLI arguments have priority over Dict config.""" |
| 602 |
config_data = {"name": "Alice", "age": 30} |
| 603 |
app = App(config=Dict(config_data), result_action="return_value") |
| 604 |
|
| 605 |
@app.default |
| 606 |
def main(name: str, age: int): |
| 607 |
return f"{name} is {age} years old." |
| 608 |
|
| 609 |
result = app("--name Bob --age 40") |
| 610 |
assert result == "Bob is 40 years old." |
| 611 |
|
| 612 |
|
| 613 |
def test_config_dict_with_optional(): |
| 614 |
"""Test Dict config with Optional parameters.""" |
| 615 |
from typing import Any |
| 616 |
|
| 617 |
config_data: dict[str, Any] = {"name": "Alice"} |
| 618 |
app = App(config=Dict(config_data), result_action="return_value") |
| 619 |
|
| 620 |
@app.default |
| 621 |
def main(name: str, age: int | None = None): |
| 622 |
if age is None: |
| 623 |
return f"{name} has no age" |
| 624 |
return f"{name} is {age} years old." |
| 625 |
|
| 626 |
result = app([]) |
| 627 |
assert result == "Alice has no age" |
| 628 |
|
| 629 |
config_data["age"] = 30 |
| 630 |
result = app([]) |
| 631 |
assert result == "Alice is 30 years old." |
| 632 |
|
| 633 |
|
| 634 |
def test_config_dict_with_list(): |
| 635 |
"""Test Dict config with list parameters.""" |
| 636 |
config_data = {"names": ["Alice", "Bob", "Charlie"]} |
| 637 |
app = App(config=Dict(config_data), result_action="return_value") |
| 638 |
|
| 639 |
@app.default |
| 640 |
def main(names: list[str]): |
| 641 |
return ", ".join(names) |
| 642 |
|
| 643 |
result = app([]) |
| 644 |
assert result == "Alice, Bob, Charlie" |
| 645 |
|
| 646 |
|
| 647 |
def test_config_dict_with_typed_dict(): |
| 648 |
"""Test Dict config with TypedDict.""" |
| 649 |
from typing import TypedDict |
| 650 |
|
| 651 |
class UserConfig(TypedDict): |
| 652 |
name: str |
| 653 |
age: int |
| 654 |
|
| 655 |
config_data = {"user": {"name": "Alice", "age": 30}} |
| 656 |
app = App(config=Dict(config_data), result_action="return_value") |
| 657 |
|
| 658 |
@app.default |
| 659 |
def main(user: UserConfig): |
| 660 |
return f"{user['name']} is {user['age']} years old." |
| 661 |
|
| 662 |
result = app([]) |
| 663 |
assert result == "Alice is 30 years old." |
| 664 |
|
| 665 |
|
| 666 |
def test_config_dict_immutability(): |
| 667 |
"""Test that Dict.config returns the actual data (not a copy).""" |
| 668 |
config_data = {"name": "Alice", "age": 30} |
| 669 |
config = Dict(config_data) |
| 670 |
|
| 671 |
assert config.config is config.data |
| 672 |
config.config["name"] = "Bob" |
| 673 |
assert config.data["name"] == "Bob" |
| 674 |
|
| 675 |
|
| 676 |
def test_config_dict_missing_root_key(): |
| 677 |
"""Test Dict config when root_keys don't exist in data.""" |
| 678 |
config_data = {"production": {"name": "Alice"}} |
| 679 |
app = App( |
| 680 |
config=Dict(config_data, root_keys=["development", "database"]), |
| 681 |
result_action="return_value", |
| 682 |
) |
| 683 |
|
| 684 |
@app.default |
| 685 |
def main(name: str = "Default", age: int = 0): |
| 686 |
return f"{name} is {age} years old." |
| 687 |
|
| 688 |
result = app([]) |
| 689 |
assert result == "Default is 0 years old." |
| 690 |
|
| 691 |
|
| 692 |
def test_config_dict_reassignment(): |
| 693 |
"""Test reassigning app.config with new Dict.""" |
| 694 |
app = App(config=Dict({"name": "Alice", "age": 30}), result_action="return_value") |
| 695 |
|
| 696 |
@app.default |
| 697 |
def main(name: str, age: int): |
| 698 |
return f"{name} is {age} years old." |
| 699 |
|
| 700 |
result = app([]) |
| 701 |
assert result == "Alice is 30 years old." |
| 702 |
|
| 703 |
app.config = Dict({"name": "Bob", "age": 40}) |
| 704 |
result = app([]) |
| 705 |
assert result == "Bob is 40 years old." |
| 706 |
|
| 707 |
|
| 708 |
def test_config_dict_with_boolean_flags(): |
| 709 |
"""Test Dict config with boolean flags.""" |
| 710 |
config_data = {"verbose": True, "quiet": False, "debug": True} |
| 711 |
app = App(config=Dict(config_data), result_action="return_value") |
| 712 |
|
| 713 |
@app.default |
| 714 |
def main(verbose: bool = False, quiet: bool = False, debug: bool = False): |
| 715 |
flags = [] |
| 716 |
if verbose: |
| 717 |
flags.append("verbose") |
| 718 |
if quiet: |
| 719 |
flags.append("quiet") |
| 720 |
if debug: |
| 721 |
flags.append("debug") |
| 722 |
return ", ".join(flags) if flags else "no flags" |
| 723 |
|
| 724 |
result = app([]) |
| 725 |
assert result == "verbose, debug" |
| 726 |
|
| 727 |
|
| 728 |
def test_config_dict_nested_commands(): |
| 729 |
"""Test Dict config with nested command structure.""" |
| 730 |
config_data = { |
| 731 |
"db": { |
| 732 |
"create": {"name": "testdb", "size": 100}, |
| 733 |
"delete": {"name": "olddb", "force": True}, |
| 734 |
} |
| 735 |
} |
| 736 |
app = App(config=Dict(config_data), result_action="return_value") |
| 737 |
|
| 738 |
db_app = App() |
| 739 |
app.command(db_app, name="db") |
| 740 |
|
| 741 |
@db_app.command |
| 742 |
def create(name: str, size: int): |
| 743 |
return f"Creating {name} with size {size}" |
| 744 |
|
| 745 |
@db_app.command |
| 746 |
def delete(name: str, force: bool = False): |
| 747 |
return f"Deleting {name} (force={force})" |
| 748 |
|
| 749 |
result = app("db create") |
| 750 |
assert result == "Creating testdb with size 100" |
| 751 |
|
| 752 |
result = app("db delete") |
| 753 |
assert result == "Deleting olddb (force=True)" |
| 754 |
|
| 755 |
|
| 756 |
def test_config_dict_error_message_with_custom_source(): |
| 757 |
"""Test that custom source appears in error messages.""" |
| 758 |
import pytest |
| 759 |
|
| 760 |
from cyclopts.exceptions import MissingArgumentError |
| 761 |
|
| 762 |
config_data = {"age": 30} |
| 763 |
app = App(config=Dict(config_data, source="api-response"), result_action="return_value") |
| 764 |
|
| 765 |
@app.default |
| 766 |
def main(name: str, age: int): |
| 767 |
return f"{name} is {age} years old." |
| 768 |
|
| 769 |
with pytest.raises(MissingArgumentError) as exc_info: |
| 770 |
app([], exit_on_error=False) |
| 771 |
|
| 772 |
assert "name" in str(exc_info.value).lower() |
| 773 |
|
| 774 |
|
| 775 |
def test_config_dict_with_default_values(): |
| 776 |
"""Test Dict config interacts correctly with function default values.""" |
| 777 |
config_data = {"name": "Alice"} |
| 778 |
app = App(config=Dict(config_data), result_action="return_value") |
| 779 |
|
| 780 |
@app.default |
| 781 |
def main(name: str = "Default", age: int = 99, city: str = "Unknown"): |
| 782 |
return f"{name}, {age}, {city}" |
| 783 |
|
| 784 |
result = app([]) |
| 785 |
assert result == "Alice, 99, Unknown" |
| 786 |
|
| 787 |
|
| 788 |
def test_config_dict_with_enum(): |
| 789 |
"""Test Dict config with Enum parameters.""" |
| 790 |
from enum import Enum |
| 791 |
|
| 792 |
class Color(Enum): |
| 793 |
RED = "red" |
| 794 |
GREEN = "green" |
| 795 |
BLUE = "blue" |
| 796 |
|
| 797 |
config_data = {"color": "red"} |
| 798 |
app = App(config=Dict(config_data), result_action="return_value") |
| 799 |
|
| 800 |
@app.default |
| 801 |
def main(color: Color): |
| 802 |
return f"Color is {color.value}" |
| 803 |
|
| 804 |
result = app([]) |
| 805 |
assert result == "Color is red" |
| 806 |
|
| 807 |
|
| 808 |
def test_config_dict_with_complex_types(): |
| 809 |
"""Test Dict config with complex nested types.""" |
| 810 |
from dataclasses import dataclass |
| 811 |
|
| 812 |
@dataclass |
| 813 |
class Address: |
| 814 |
street: str |
| 815 |
city: str |
| 816 |
|
| 817 |
@dataclass |
| 818 |
class Person: |
| 819 |
name: str |
| 820 |
address: Address |
| 821 |
|
| 822 |
config_data = { |
| 823 |
"person": { |
| 824 |
"name": "Alice", |
| 825 |
"address": {"street": "123 Main St", "city": "Springfield"}, |
| 826 |
} |
| 827 |
} |
| 828 |
app = App(config=Dict(config_data), result_action="return_value") |
| 829 |
|
| 830 |
@app.default |
| 831 |
def main(person: Person): |
| 832 |
return f"{person.name} lives at {person.address.street}, {person.address.city}" |
| 833 |
|
| 834 |
result = app([]) |
| 835 |
assert result == "Alice lives at 123 Main St, Springfield" |
| 836 |
|
| 837 |
|
| 838 |
def test_config_dict_with_union_types(): |
| 839 |
"""Test Dict config with Union types.""" |
| 840 |
from typing import Any |
| 841 |
|
| 842 |
config_data: dict[str, Any] = {"value": 42} |
| 843 |
app = App(config=Dict(config_data), result_action="return_value") |
| 844 |
|
| 845 |
@app.default |
| 846 |
def main(value: int | str): |
| 847 |
return f"Value is {value} (type: {type(value).__name__})" |
| 848 |
|
| 849 |
result = app([]) |
| 850 |
assert result == "Value is 42 (type: int)" |
| 851 |
|
| 852 |
config_data["value"] = "hello" |
| 853 |
result = app([]) |
| 854 |
assert result == "Value is hello (type: str)" |
| 855 |
|
| 856 |
|
| 857 |
def test_config_dict_empty_root_keys(): |
| 858 |
"""Test Dict config with empty root_keys tuple.""" |
| 859 |
config_data = {"name": "Alice", "age": 30} |
| 860 |
app = App(config=Dict(config_data, root_keys=()), result_action="return_value") |
| 861 |
|
| 862 |
@app.default |
| 863 |
def main(name: str, age: int): |
| 864 |
return f"{name} is {age} years old." |
| 865 |
|
| 866 |
result = app([]) |
| 867 |
assert result == "Alice is 30 years old." |
| 868 |
|
| 869 |
|
| 870 |
def test_config_dict_single_root_key(): |
| 871 |
"""Test Dict config with single root_key.""" |
| 872 |
config_data = {"production": {"name": "Alice", "age": 30}} |
| 873 |
app = App(config=Dict(config_data, root_keys=["production"]), result_action="return_value") |
| 874 |
|
| 875 |
@app.default |
| 876 |
def main(name: str, age: int): |
| 877 |
return f"{name} is {age} years old." |
| 878 |
|
| 879 |
result = app([]) |
| 880 |
assert result == "Alice is 30 years old." |
| 881 |
|
| 882 |
|
| 883 |
def test_config_dict_with_attrs_class(): |
| 884 |
"""Test Dict config with attrs class.""" |
| 885 |
from attrs import define |
| 886 |
|
| 887 |
@define |
| 888 |
class User: |
| 889 |
name: str |
| 890 |
age: int |
| 891 |
|
| 892 |
config_data = {"user": {"name": "Alice", "age": 30}} |
| 893 |
app = App(config=Dict(config_data), result_action="return_value") |
| 894 |
|
| 895 |
@app.default |
| 896 |
def main(user: User): |
| 897 |
return f"{user.name} is {user.age} years old." |
| 898 |
|
| 899 |
result = app([]) |
| 900 |
assert result == "Alice is 30 years old." |
| 901 |
|
| 902 |
|
| 903 |
def test_config_dict_comparison_with_json_file(): |
| 904 |
"""Test that Dict produces same result as Json for equivalent data.""" |
| 905 |
import json |
| 906 |
from pathlib import Path |
| 907 |
|
| 908 |
from cyclopts.config import Json |
| 909 |
|
| 910 |
config_data = {"count": {"character": "t"}} |
| 911 |
|
| 912 |
dict_app = App(config=Dict(config_data), result_action="return_value") |
| 913 |
|
| 914 |
@dict_app.command |
| 915 |
def count(character: str): |
| 916 |
return f"Character: {character}" |
| 917 |
|
| 918 |
dict_result = dict_app("count") |
| 919 |
|
| 920 |
json_app = App(result_action="return_value") |
| 921 |
|
| 922 |
@json_app.command |
| 923 |
def count(character: str): |
| 924 |
return f"Character: {character}" |
| 925 |
|
| 926 |
tmp_file = Path("temp_test.json") |
| 927 |
tmp_file.write_text(json.dumps(config_data)) |
| 928 |
try: |
| 929 |
json_app.config = Json(tmp_file) |
| 930 |
json_result = json_app("count") |
| 931 |
assert dict_result == json_result |
| 932 |
finally: |
| 933 |
tmp_file.unlink() |
| 934 |
|
| 935 |
|
| 936 |
def test_config_dict_repr(): |
| 937 |
"""Test Dict has a useful repr.""" |
| 938 |
config = Dict({"key": "value"}, source="api") |
| 939 |
repr_str = repr(config) |
| 940 |
assert "Dict" in repr_str |
| 941 |
assert "key" in repr_str or "value" in repr_str |
| 942 |
|
| 943 |
|
| 944 |
def test_config_dict_with_tuple_type(): |
| 945 |
"""Test Dict config with tuple parameters.""" |
| 946 |
config_data = {"coordinates": [1, 2, 3]} |
| 947 |
app = App(config=Dict(config_data), result_action="return_value") |
| 948 |
|
| 949 |
@app.default |
| 950 |
def main(coordinates: tuple[int, int, int]): |
| 951 |
return f"Coordinates: {coordinates}" |
| 952 |
|
| 953 |
result = app([]) |
| 954 |
assert result == "Coordinates: (1, 2, 3)" |
| 955 |
|
| 956 |
|
| 957 |
def test_config_dict_with_set_type(): |
| 958 |
"""Test Dict config with set parameters.""" |
| 959 |
config_data = {"tags": ["python", "cli", "config"]} |
| 960 |
app = App(config=Dict(config_data), result_action="return_value") |
| 961 |
|
| 962 |
@app.default |
| 963 |
def main(tags: set[str]): |
| 964 |
return f"Tags: {sorted(tags)}" |
| 965 |
|
| 966 |
result = app([]) |
| 967 |
assert result == "Tags: ['cli', 'config', 'python']" |
| 968 |
|
| 969 |
|
| 970 |
def test_config_dict_with_negative_numbers(): |
| 971 |
"""Test Dict config with negative numbers.""" |
| 972 |
config_data = {"offset": -10, "temperature": -5.5} |
| 973 |
app = App(config=Dict(config_data), result_action="return_value") |
| 974 |
|
| 975 |
@app.default |
| 976 |
def main(offset: int, temperature: float): |
| 977 |
return f"offset={offset}, temperature={temperature}" |
| 978 |
|
| 979 |
result = app([]) |
| 980 |
assert result == "offset=-10, temperature=-5.5" |