forked from pydantic/pydantic-settings
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_multi_source.py
87 lines (77 loc) · 2.55 KB
/
test_multi_source.py
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
"""
Integration tests with multiple sources
"""
from typing import Tuple, Type, Union
import pytest
from pydantic import BaseModel, ValidationError
from pydantic_settings import (
BaseSettings,
JsonConfigSettingsSource,
PydanticBaseSettingsSource,
SettingsConfigDict,
)
def test_line_errors_from_source(monkeypatch, tmp_path):
monkeypatch.setenv('SETTINGS_NESTED__NESTED_FIELD', 'a')
p = tmp_path / 'settings.json'
p.write_text(
"""
{"foobar": 0, "null_field": null}
"""
)
class Nested(BaseModel):
nested_field: int
class Settings(BaseSettings):
model_config = SettingsConfigDict(
json_file=p, env_prefix='SETTINGS_', env_nested_delimiter='__', validate_each_source=True
)
foobar: str
nested: Nested
null_field: Union[str, None]
extra: bool
@classmethod
def settings_customise_sources(
cls,
settings_cls: Type[BaseSettings],
init_settings: PydanticBaseSettingsSource,
env_settings: PydanticBaseSettingsSource,
dotenv_settings: PydanticBaseSettingsSource,
file_secret_settings: PydanticBaseSettingsSource,
) -> Tuple[PydanticBaseSettingsSource, ...]:
return (JsonConfigSettingsSource(settings_cls), env_settings, init_settings)
with pytest.raises(ValidationError) as exc_info:
_ = Settings(null_field=0)
assert exc_info.value.errors(include_url=False) == [
{
'ctx': {'source': 'JsonConfigSettingsSource'},
'input': 0,
'loc': (
'JsonConfigSettingsSource',
'foobar',
),
'msg': 'Input should be a valid string',
'type': 'string_type',
},
{
'ctx': {'source': 'EnvSettingsSource'},
'input': 'a',
'loc': ('EnvSettingsSource', 'nested', 'nested_field'),
'msg': 'Input should be a valid integer, unable to parse string as an integer',
'type': 'int_parsing',
},
{
'ctx': {'source': 'InitSettingsSource'},
'input': 0,
'loc': (
'InitSettingsSource',
'null_field',
),
'msg': 'Input should be a valid string',
'type': 'string_type',
},
{
'input': {'foobar': 0, 'nested': {'nested_field': 'a'}, 'null_field': None},
'loc': ('extra',),
'msg': 'Field required',
'type': 'missing',
},
]