File: test_json_string_dict.py

package info (click to toggle)
python-cyclopts 3.12.0-3
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 3,288 kB
  • sloc: python: 11,445; makefile: 24
file content (59 lines) | stat: -rw-r--r-- 1,308 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import json
from dataclasses import dataclass, field
from typing import Annotated, Dict, Optional

import pytest

from cyclopts import Parameter


@dataclass
class User:
    id: int
    name: str = "John Doe"
    tastes: Dict[str, int] = field(default_factory=dict)


def test_bind_dataclass_from_env_json(app, assert_parse_args, monkeypatch):
    @app.command
    def foo(some_number: int, user: Annotated[User, Parameter(env_var="USER")]):
        pass

    external_data = {
        "id": 123,
        # "name" is purposely missing.
        "tastes": {
            "wine": 9,
            "cheese": 7,
            "cabbage": 1,
        },
    }
    monkeypatch.setenv("USER", json.dumps(external_data))
    assert_parse_args(
        foo,
        "foo 100",
        100,
        User(**external_data),
    )


@pytest.mark.parametrize(
    "cmd_str",
    [
        """--origin='{"x": 1, "y": 2}'""",
        """--origin '{"x": 1, "y": 2}'""",
        """--origin='{"x": 1, "y": 2, "label": null}'""",
    ],
)
def test_bind_dataclass_from_cli_json(app, assert_parse_args, cmd_str):
    @dataclass
    class Coordinate:
        x: int
        y: int
        label: Optional[str] = None

    @app.default
    def main(origin: Coordinate):
        pass

    assert_parse_args(main, cmd_str, Coordinate(1, 2))