From 229319c97061e2b4e88d8d1061a08e64eba1020f Mon Sep 17 00:00:00 2001 From: Hasan Ramezani Date: Wed, 3 Jul 2024 11:55:10 +0330 Subject: [PATCH] Fix a bug when loading empty yaml file (#330) Co-authored-by: Sydney Runkle <54324534+sydney-runkle@users.noreply.github.com> --- pydantic_settings/sources.py | 2 +- tests/test_settings.py | 23 +++++++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/pydantic_settings/sources.py b/pydantic_settings/sources.py index 23bbbf13..3f19f9a3 100644 --- a/pydantic_settings/sources.py +++ b/pydantic_settings/sources.py @@ -1692,7 +1692,7 @@ def __init__( def _read_file(self, file_path: Path) -> dict[str, Any]: import_yaml() with open(file_path, encoding=self.yaml_file_encoding) as yaml_file: - return yaml.safe_load(yaml_file) + return yaml.safe_load(yaml_file) or {} def _get_env_var_key(key: str, case_sensitive: bool = False) -> str: diff --git a/tests/test_settings.py b/tests/test_settings.py index e812ffed..de80faeb 100644 --- a/tests/test_settings.py +++ b/tests/test_settings.py @@ -3485,6 +3485,29 @@ def settings_customise_sources( assert s.model_dump() == {} +@pytest.mark.skipif(yaml is None, reason='pyYaml is not installed') +def test_yaml_empty_file(tmp_path): + p = tmp_path / '.env' + p.write_text('') + + class Settings(BaseSettings): + model_config = SettingsConfigDict(yaml_file=p) + + @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 (YamlConfigSettingsSource(settings_cls),) + + s = Settings() + assert s.model_dump() == {} + + @pytest.mark.skipif(sys.version_info <= (3, 11) and tomli is None, reason='tomli/tomllib is not installed') def test_toml_file(tmp_path): p = tmp_path / '.env'