| 1 | from textwrap import dedent |
| 2 | from typing import Annotated |
| 3 | |
| 4 | from cyclopts import Parameter |
| 5 | from cyclopts.config import Env, Toml |
| 6 | |
| 7 | |
| 8 | def test_config_end2end(app, tmp_path, assert_parse_args): |
| 9 | config_fn = tmp_path / "config.toml" |
| 10 | |
| 11 | config_fn.write_text( |
| 12 | dedent( |
| 13 | """\ |
| 14 | [tool.cyclopts] |
| 15 | key1 = "foo1" |
| 16 | key2 = "foo2" |
| 17 | list1 = [] |
| 18 | |
| 19 | [tool.cyclopts.function1] |
| 20 | key3 = "bar1" |
| 21 | key4 = "bar2" |
| 22 | """ |
| 23 | ) |
| 24 | ) |
| 25 | |
| 26 | app.config = Toml(config_fn, root_keys=["tool", "cyclopts"]) |
| 27 | |
| 28 | @app.default |
| 29 | def default(key1, key2, *, list1: list[int]): |
| 30 | pass |
| 31 | |
| 32 | @app.command |
| 33 | def function1(key3, key4): |
| 34 | pass |
| 35 | |
| 36 | assert_parse_args(default, "foo", key1="foo", key2="foo2", list1=[]) |
| 37 | assert_parse_args(default, "foo --key2=fizz", key1="foo", key2="fizz", list1=[]) |
| 38 | assert_parse_args(default, "foo --list1 1", key1="foo", key2="foo2", list1=[1]) |
| 39 | assert_parse_args(function1, "function1 --key4=fizz", key3="bar1", key4="fizz") |
| 40 | |
| 41 | |
| 42 | def test_config_env_repeated(app, monkeypatch, assert_parse_args): |
| 43 | monkeypatch.setenv("FOO", "bar") |
| 44 | |
| 45 | app.config = Env() |
| 46 | |
| 47 | @app.default |
| 48 | def default(foo: Annotated[str, Parameter(env_var="FOO")]): |
| 49 | pass |
| 50 | |
| 51 | assert_parse_args(default, "", "bar") |
| 52 | |
| 53 | |
| 54 | def test_config_env_help(app, assert_parse_args, console): |
| 55 | """Special-case for :class:`.config.Env` to get added to help-page.""" |
| 56 | app.config = Env() |
| 57 | |
| 58 | @app.default |
| 59 | def default(foo: Annotated[str, Parameter(env_var="BAR")]): |
| 60 | pass |
| 61 | |
| 62 | with console.capture() as capture: |
| 63 | app(["--help"], console=console) |
| 64 | |
| 65 | actual = capture.get() |
| 66 | expected = dedent( |
| 67 | """\ |
| 68 | Usage: test_end2end FOO |
| 69 | |
| 70 | ╭─ Commands ─────────────────────────────────────────────────────────╮ |
| 71 | │ --help (-h) Display this message and exit. │ |
| 72 | │ --version Display application version. │ |
| 73 | ╰────────────────────────────────────────────────────────────────────╯ |
| 74 | ╭─ Parameters ───────────────────────────────────────────────────────╮ |
| 75 | │ * FOO --foo [env var: BAR, FOO] [required] │ |
| 76 | ╰────────────────────────────────────────────────────────────────────╯ |
| 77 | """ |
| 78 | ) |
| 79 | assert actual == expected |