Skip to content

Commit

Permalink
Fix a bug when loading empty yaml file (#330)
Browse files Browse the repository at this point in the history
Co-authored-by: Sydney Runkle <54324534+sydney-runkle@users.noreply.github.com>
  • Loading branch information
hramezani and sydney-runkle authored Jul 3, 2024
1 parent d6db0f9 commit 229319c
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
2 changes: 1 addition & 1 deletion pydantic_settings/sources.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
23 changes: 23 additions & 0 deletions tests/test_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down

0 comments on commit 229319c

Please sign in to comment.