|
2 | 2 | Test pydantic_settings.JsonConfigSettingsSource. |
3 | 3 | """ |
4 | 4 |
|
| 5 | +import importlib.resources |
5 | 6 | import json |
6 | 7 | from pathlib import Path |
7 | 8 |
|
@@ -132,3 +133,33 @@ def settings_customise_sources( |
132 | 133 |
|
133 | 134 | s = Settings() |
134 | 135 | assert s.model_dump() == {'hello': 'world', 'nested': {'foo': 3, 'bar': 2 if deep_merge else 0}} |
| 136 | + |
| 137 | + |
| 138 | +def test_traversable_support(): |
| 139 | + # get Traversable object |
| 140 | + tests_package_dir = importlib.resources.files('tests') |
| 141 | + json_config_path = tests_package_dir / 'example_test_config.json' |
| 142 | + assert json_config_path.is_file() |
| 143 | + |
| 144 | + class Settings(BaseSettings): |
| 145 | + foobar: str |
| 146 | + |
| 147 | + model_config = SettingsConfigDict( |
| 148 | + # Traversable is not added in annotation, but is supported |
| 149 | + json_file=json_config_path, |
| 150 | + ) |
| 151 | + |
| 152 | + @classmethod |
| 153 | + def settings_customise_sources( |
| 154 | + cls, |
| 155 | + settings_cls: type[BaseSettings], |
| 156 | + init_settings: PydanticBaseSettingsSource, |
| 157 | + env_settings: PydanticBaseSettingsSource, |
| 158 | + dotenv_settings: PydanticBaseSettingsSource, |
| 159 | + file_secret_settings: PydanticBaseSettingsSource, |
| 160 | + ) -> tuple[PydanticBaseSettingsSource, ...]: |
| 161 | + return (JsonConfigSettingsSource(settings_cls),) |
| 162 | + |
| 163 | + s = Settings() |
| 164 | + # "test" value in file |
| 165 | + assert s.foobar == 'test' |
0 commit comments