Skip to content

Commit c8bc837

Browse files
committed
feat: raise KeyError when yaml_config_section is missing in YAML file
1 parent a3f5389 commit c8bc837

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

pydantic_settings/sources/providers/yaml.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,12 @@ def __init__(
5555
self.yaml_data = self._read_files(self.yaml_file_path)
5656

5757
if self.yaml_config_section:
58-
self.yaml_data = self.yaml_data[self.yaml_config_section]
58+
try:
59+
self.yaml_data = self.yaml_data[self.yaml_config_section]
60+
except KeyError:
61+
raise KeyError(
62+
f'yaml_config_section key "{self.yaml_config_section}" not found in {self.yaml_file_path}'
63+
)
5964
super().__init__(settings_cls, self.yaml_data)
6065

6166
def _read_file(self, file_path: Path) -> dict[str, Any]:

tests/test_source_yaml.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -197,3 +197,34 @@ def settings_customise_sources(
197197

198198
s = Settings()
199199
assert s.nested_field == 'world!'
200+
201+
202+
@pytest.mark.skipif(yaml is None, reason='pyYAML is not installed')
203+
def test_invalid_yaml_config_section(tmp_path):
204+
p = tmp_path / '.env'
205+
p.write_text(
206+
"""
207+
foobar: "Hello"
208+
nested:
209+
nested_field: "world!"
210+
"""
211+
)
212+
213+
class Settings(BaseSettings):
214+
nested_field: str
215+
216+
model_config = SettingsConfigDict(yaml_file=p, yaml_config_section='invalid_key')
217+
218+
@classmethod
219+
def settings_customise_sources(
220+
cls,
221+
settings_cls: type[BaseSettings],
222+
init_settings: PydanticBaseSettingsSource,
223+
env_settings: PydanticBaseSettingsSource,
224+
dotenv_settings: PydanticBaseSettingsSource,
225+
file_secret_settings: PydanticBaseSettingsSource,
226+
) -> tuple[PydanticBaseSettingsSource, ...]:
227+
return (YamlConfigSettingsSource(settings_cls),)
228+
229+
with pytest.raises(KeyError):
230+
Settings()

0 commit comments

Comments
 (0)