File: test_extra.py

package info (click to toggle)
pydantic-core 2.41.5-1
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 3,836 kB
  • sloc: python: 35,821; javascript: 211; makefile: 128
file content (72 lines) | stat: -rw-r--r-- 2,130 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
60
61
62
63
64
65
66
67
68
69
70
71
72
from typing import Any, Union

import pytest

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

from ...conftest import PyAndJson


@pytest.mark.parametrize(
    'schema_extra_behavior,validate_fn_extra_kw',
    [
        ('forbid', None),
        ('ignore', 'forbid'),
    ],
)
@pytest.mark.parametrize(
    ['input_value', 'err_type'],
    (
        [ArgsKwargs((), {'a': 1, 'b': 2, 'c': 3}), 'unexpected_keyword_argument'],
        [ArgsKwargs((), {'a': 1, 'c': 3, 'extra': 'value'}), 'unexpected_keyword_argument'],
        [{'a': 1, 'b': 2, 'c': 3}, 'extra_forbidden'],
        [{'a': 1, 'c': 3, 'extra': 'value'}, 'extra_forbidden'],
    ),
)
def test_extra_forbid(
    py_and_json: PyAndJson,
    schema_extra_behavior: dict[str, Any],
    validate_fn_extra_kw: Union[cs.ExtraBehavior, None],
    input_value,
    err_type,
) -> None:
    v = py_and_json(
        cs.arguments_v3_schema(
            [
                cs.arguments_v3_parameter(name='a', schema=cs.int_schema()),
                cs.arguments_v3_parameter(name='b', schema=cs.int_schema(), alias='c'),
            ],
            extra_behavior=schema_extra_behavior,
        ),
    )

    with pytest.raises(ValidationError) as exc_info:
        v.validate_test(input_value, extra=validate_fn_extra_kw)

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

    assert error['type'] == err_type


@pytest.mark.parametrize(
    'input_value',
    [
        ArgsKwargs((), {'a': 1, 'b': 2, 'c': 3}),
        ArgsKwargs((), {'a': 1, 'c': 3, 'extra': 'value'}),
        {'a': 1, 'b': 2, 'c': 3},
        {'a': 1, 'c': 3, 'extra': 'value'},
    ],
)
def test_extra_ignore(py_and_json: PyAndJson, input_value) -> None:
    v = py_and_json(
        cs.arguments_v3_schema(
            [
                cs.arguments_v3_parameter(name='a', schema=cs.int_schema(), mode='keyword_only'),
                cs.arguments_v3_parameter(name='b', schema=cs.int_schema(), alias='c', mode='keyword_only'),
            ],
            extra_behavior='ignore',
        ),
    )

    assert v.validate_test(input_value) == ((), {'a': 1, 'b': 3})