Skip to content

Commit

Permalink
Add json env_var tests.
Browse files Browse the repository at this point in the history
  • Loading branch information
BrianPugh committed Jan 4, 2025
1 parent b6735e7 commit 2a944b9
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 2 deletions.
24 changes: 24 additions & 0 deletions tests/test_bind_dataclasses.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import json
import sys
from dataclasses import dataclass, field
from textwrap import dedent
Expand Down Expand Up @@ -42,6 +43,29 @@ def foo(some_number: int, user: User):
)


def test_bind_dataclass_from_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.skipif(sys.version_info < (3, 10), reason="field(kw_only=True) doesn't exist.")
def test_bind_dataclass_recursive(app, assert_parse_args, console):
@dataclass
Expand Down
35 changes: 33 additions & 2 deletions tests/test_pydantic.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import json
from datetime import datetime
from textwrap import dedent
from typing import Dict, Optional, Union
from typing import Annotated, Dict, Optional, Union

import pytest
from pydantic import BaseModel, Field, PositiveInt, validate_call
from pydantic import ValidationError as PydanticValidationError

from cyclopts import MissingArgumentError
from cyclopts import MissingArgumentError, Parameter


def test_pydantic_error_msg(app, console):
Expand Down Expand Up @@ -74,6 +75,36 @@ def foo(user: User):
"has_socks": True,
},
}

assert_parse_args(
foo,
'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',
User(**external_data),
)


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

external_data = {
"id": 123,
"signup_ts": "2019-06-01 12:22",
"tastes": {
"wine": 9,
"cheese": 7,
"cabbage": "1",
},
"outfit": {
"body": "t-shirt",
"head": "baseball-cap",
"has_socks": True,
},
}

monkeypatch.setenv("USER", json.dumps(external_data))

assert_parse_args(
foo,
'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',
Expand Down

0 comments on commit 2a944b9

Please sign in to comment.