Skip to content

Commit 0225b19

Browse files
author
Julian Vanden Broeck
committed
Use SettingsErrors for invalid file source
Some file formats (at least yaml) allow to represent non dictionnary values. In such situation we can't add the values read from those files. Instead of raising a ValueError, we now raise a SettingsError and indicate we can't parse the related config file.
1 parent e75711a commit 0225b19

File tree

4 files changed

+11
-4
lines changed

4 files changed

+11
-4
lines changed

pydantic_settings/sources.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -1917,7 +1917,11 @@ def _read_files(self, files: PathType | None) -> dict[str, Any]:
19171917
for file in files:
19181918
file_path = Path(file).expanduser()
19191919
if file_path.is_file():
1920-
vars.update(self._read_file(file_path))
1920+
try:
1921+
settings = self._read_file(file_path)
1922+
except ValueError as e:
1923+
raise SettingsError(f'Failed to parse settings from {file_path}, {e}')
1924+
vars.update(settings)
19211925
return vars
19221926

19231927
@abstractmethod

tests/test_source_json.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
JsonConfigSettingsSource,
1414
PydanticBaseSettingsSource,
1515
SettingsConfigDict,
16+
SettingsError,
1617
)
1718

1819

@@ -91,7 +92,7 @@ def settings_customise_sources(
9192
) -> Tuple[PydanticBaseSettingsSource, ...]:
9293
return (JsonConfigSettingsSource(settings_cls),)
9394

94-
with pytest.raises(ValueError):
95+
with pytest.raises(SettingsError, match='Failed to parse settings from .*, expecting an object'):
9596
Settings()
9697

9798

tests/test_source_toml.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
BaseSettings,
1313
PydanticBaseSettingsSource,
1414
SettingsConfigDict,
15+
SettingsError,
1516
TomlConfigSettingsSource,
1617
)
1718

@@ -97,7 +98,7 @@ def settings_customise_sources(
9798
) -> Tuple[PydanticBaseSettingsSource, ...]:
9899
return (TomlConfigSettingsSource(settings_cls, pyproject),)
99100

100-
with pytest.raises(ValueError):
101+
with pytest.raises(SettingsError, match='Failed to parse settings from'):
101102
Settings()
102103

103104

tests/test_source_yaml.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
BaseSettings,
1212
PydanticBaseSettingsSource,
1313
SettingsConfigDict,
14+
SettingsError,
1415
YamlConfigSettingsSource,
1516
)
1617

@@ -105,7 +106,7 @@ def settings_customise_sources(
105106
) -> Tuple[PydanticBaseSettingsSource, ...]:
106107
return (YamlConfigSettingsSource(settings_cls),)
107108

108-
with pytest.raises(ValueError):
109+
with pytest.raises(SettingsError, match='Failed to parse settings from .*, expecting an object'):
109110
Settings()
110111

111112

0 commit comments

Comments
 (0)