Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixes #452 - Adding support for populate_by_name #454

Merged
merged 2 commits into from
Oct 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions pydantic_settings/sources.py
Original file line number Diff line number Diff line change
Expand Up @@ -445,10 +445,12 @@ def _extract_field_info(self, field: FieldInfo, field_name: str) -> list[tuple[s
)
else: # string validation alias
field_info.append((v_alias, self._apply_case_sensitive(v_alias), False))
elif origin_is_union(get_origin(field.annotation)) and _union_is_complex(field.annotation, field.metadata):
field_info.append((field_name, self._apply_case_sensitive(self.env_prefix + field_name), True))
else:
field_info.append((field_name, self._apply_case_sensitive(self.env_prefix + field_name), False))

if not v_alias or self.config.get('populate_by_name', False):
if origin_is_union(get_origin(field.annotation)) and _union_is_complex(field.annotation, field.metadata):
field_info.append((field_name, self._apply_case_sensitive(self.env_prefix + field_name), True))
else:
field_info.append((field_name, self._apply_case_sensitive(self.env_prefix + field_name), False))

return field_info

Expand Down
110 changes: 110 additions & 0 deletions tests/test_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,12 @@ class SettingWithIgnoreEmpty(BaseSettings):
model_config = SettingsConfigDict(env_ignore_empty=True)


class SettingWithPopulateByName(BaseSettings):
apple: str = Field('default', alias='pomo')

model_config = SettingsConfigDict(populate_by_name=True)


def test_sub_env(env):
env.set('apple', 'hello')
s = SimpleSettings()
Expand Down Expand Up @@ -127,6 +133,110 @@ class Settings(BaseSettings):
assert s.a == 'b'


def test_populate_by_name_when_using_alias(env):
env.set('pomo', 'bongusta')
s = SettingWithPopulateByName()
assert s.apple == 'bongusta'


def test_populate_by_name_when_using_name(env):
env.set('apple', 'honeycrisp')
s = SettingWithPopulateByName()
assert s.apple == 'honeycrisp'


def test_populate_by_name_when_using_both(env):
env.set('apple', 'honeycrisp')
env.set('pomo', 'bongusta')
s = SettingWithPopulateByName()
assert s.apple == 'bongusta', 'Expected alias value to be prioritized.'


def test_populate_by_name_with_alias_path_when_using_alias(env):
env.set('fruits', '["empire", "honeycrisp"]')

class Settings(BaseSettings):
apple: str = Field('default', validation_alias=AliasPath('fruits', 0))
model_config = SettingsConfigDict(populate_by_name=True)

s = Settings()
assert s.apple == 'empire'


def test_populate_by_name_with_alias_path_when_using_name(env):
env.set('apple', 'jonathan gold')

class Settings(BaseSettings):
apple: str = Field('default', validation_alias=AliasPath('fruits', 0))
model_config = SettingsConfigDict(populate_by_name=True)

s = Settings()
assert s.apple == 'jonathan gold'


@pytest.mark.parametrize(
'env_vars, expected_value',
[
pytest.param({'pomo': 'pomo-chosen'}, 'pomo-chosen', id='pomo'),
pytest.param({'pomme': 'pomme-chosen'}, 'pomme-chosen', id='pomme'),
pytest.param({'manzano': 'manzano-chosen'}, 'manzano-chosen', id='manzano'),
pytest.param(
{'pomo': 'pomo-chosen', 'pomme': 'pomme-chosen', 'manzano': 'manzano-chosen'},
'pomo-chosen',
id='pomo-priority',
),
pytest.param({'pomme': 'pomme-chosen', 'manzano': 'manzano-chosen'}, 'pomme-chosen', id='pomme-priority'),
],
)
def test_populate_by_name_with_alias_choices_when_using_alias(env, env_vars: Dict[str, str], expected_value: str):
for k, v in env_vars.items():
env.set(k, v)

class Settings(BaseSettings):
apple: str = Field('default', validation_alias=AliasChoices('pomo', 'pomme', 'manzano'))
model_config = SettingsConfigDict(populate_by_name=True)

s = Settings()
assert s.apple == expected_value


def test_populate_by_name_with_dotenv_when_using_alias(tmp_path):
p = tmp_path / '.env'
p.write_text('pomo=bongusta')

class Settings(BaseSettings):
apple: str = Field('default', alias='pomo')
model_config = SettingsConfigDict(env_file=p, populate_by_name=True)

s = Settings()
assert s.apple == 'bongusta'


def test_populate_by_name_with_dotenv_when_using_name(tmp_path):
p = tmp_path / '.env'
p.write_text('apple=honeycrisp')

class Settings(BaseSettings):
apple: str = Field('default', alias='pomo')
model_config = SettingsConfigDict(env_file=p, populate_by_name=True)

s = Settings()
assert s.apple == 'honeycrisp'


def test_populate_by_name_with_dotenv_when_using_both(tmp_path):
p = tmp_path / '.env'
p.write_text('apple=honeycrisp')
p.write_text('pomo=bongusta')

class Settings(BaseSettings):
apple: str = Field('default', alias='pomo')
model_config = SettingsConfigDict(env_file=p, populate_by_name=True)

s = Settings()
assert s.apple == 'bongusta', 'Expected alias value to be prioritized.'


def test_with_prefix(env):
class Settings(BaseSettings):
apple: str
Expand Down
Loading