File: test_general.py

package info (click to toggle)
pydantic-core 2.41.4-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,828 kB
  • sloc: python: 35,564; javascript: 211; makefile: 128
file content (131 lines) | stat: -rw-r--r-- 4,403 bytes parent folder | download
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
import pytest

from pydantic_core import ArgsKwargs, SchemaValidator, ValidationError
from pydantic_core import core_schema as cs

from ...conftest import Err, PyAndJson, plain_repr


@pytest.mark.parametrize(
    ['input_value', 'expected'],
    (
        [ArgsKwargs(()), ((), {})],
        [{}, ((), {})],
        [ArgsKwargs((1,)), Err('', [{'type': 'unexpected_positional_argument'}])],
        [ArgsKwargs((), {'a': 1}), Err('', [{'type': 'unexpected_keyword_argument'}])],
    ),
)
def test_no_args(py_and_json: PyAndJson, input_value, expected) -> None:
    v = py_and_json(cs.arguments_v3_schema([]))

    if isinstance(expected, Err):
        with pytest.raises(ValidationError) as exc_info:
            v.validate_test(input_value)

        error = exc_info.value.errors()[0]

        assert error['type'] == expected.errors[0]['type']
    else:
        assert v.validate_test(input_value) == expected


@pytest.mark.parametrize(
    ['input_value', 'expected'],
    [
        [ArgsKwargs((1, 2)), ((1, 2), {})],
        [ArgsKwargs((1,)), ((1,), {'b': 42})],
        [ArgsKwargs((1,), {'b': 3}), ((1,), {'b': 3})],
        [ArgsKwargs((), {'a': 1}), ((), {'a': 1, 'b': 42})],
        [{'a': 1, 'b': 2}, ((1, 2), {})],
        [{'a': 1}, ((1, 42), {})],
    ],
    ids=repr,
)
def test_default_factory(py_and_json: PyAndJson, input_value, expected) -> None:
    v = py_and_json(
        cs.arguments_v3_schema(
            [
                cs.arguments_v3_parameter(name='a', schema=cs.int_schema(), mode='positional_or_keyword'),
                cs.arguments_v3_parameter(
                    name='b',
                    schema=cs.with_default_schema(schema=cs.int_schema(), default_factory=lambda: 42),
                    mode='positional_or_keyword',
                ),
            ]
        )
    )

    assert v.validate_test(input_value) == expected


def double_or_bust(input_value):
    if input_value == 1:
        raise RuntimeError('bust')
    return input_value * 2


def test_internal_error(py_and_json: PyAndJson) -> None:
    v = py_and_json(
        cs.arguments_v3_schema(
            [
                cs.arguments_v3_parameter(name='a', schema=cs.int_schema(), mode='positional_only'),
                cs.arguments_v3_parameter(
                    name='b', schema=cs.no_info_plain_validator_function(double_or_bust), mode='positional_only'
                ),
            ]
        )
    )

    assert v.validate_test(ArgsKwargs((1, 2))) == ((1, 4), {})
    with pytest.raises(RuntimeError, match='bust'):
        v.validate_test(ArgsKwargs((1, 1)))


def test_repr() -> None:
    v = SchemaValidator(
        cs.arguments_v3_schema(
            [
                cs.arguments_v3_parameter(name='a', schema=cs.int_schema(), mode='positional_or_keyword'),
                cs.arguments_v3_parameter(
                    name='b',
                    schema=cs.with_default_schema(schema=cs.int_schema(), default_factory=lambda: 42),
                    mode='keyword_only',
                ),
            ]
        )
    )
    assert 'positional_params_count:1,' in plain_repr(v)


@pytest.mark.parametrize(
    ['input_value', 'expected'],
    (
        [ArgsKwargs((1, 't', 2, 3, 4), {'c': True, 'other': 1}), ((1, 't', 2, 3, 4), {'c': True, 'other': 1})],
        [
            {'aa': 1, 'b': 't', 'args': [2, 3, 4], 'c': True, 'kwargs': {'other': 1}},
            ((1, 't', 2, 3, 4), {'c': True, 'other': 1}),
        ],
    ),
)
def test_full(py_and_json: PyAndJson, input_value, expected) -> None:
    """Test inputs against all parameter types:

    ```python
    def func(a: Annotated[int, Field(alias='aa')], /, b: str, *args: int, c: bool, **kwargs: int):
        ...
    ```
    """

    v = py_and_json(
        cs.arguments_v3_schema(
            [
                cs.arguments_v3_parameter(name='a', schema=cs.int_schema(), alias='aa', mode='positional_only'),
                cs.arguments_v3_parameter(name='b', schema=cs.str_schema(), mode='positional_or_keyword'),
                cs.arguments_v3_parameter(name='args', schema=cs.int_schema(), mode='var_args'),
                cs.arguments_v3_parameter(name='c', schema=cs.bool_schema(), mode='keyword_only'),
                cs.arguments_v3_parameter(name='kwargs', schema=cs.int_schema(), mode='var_kwargs_uniform'),
            ]
        )
    )

    assert v.validate_test(input_value) == expected