Skip to content

Commit

Permalink
Ignore env_prefix if validation_alias is set (#25)
Browse files Browse the repository at this point in the history
  • Loading branch information
hramezani authored Apr 27, 2023
1 parent 607f1e8 commit 6d9c1a2
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 6 deletions.
4 changes: 1 addition & 3 deletions pydantic_settings/sources.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,9 +129,7 @@ def _extract_field_info(self, field: FieldInfo, field_name: str) -> List[Tuple[s
(alias[0], self._apply_case_sensitive(alias[0]), True if len(alias) > 1 else False)
)
else: # string validation alias
field_info.append(
(v_alias, self._apply_case_sensitive(self.config.get('env_prefix', '') + v_alias), False)
)
field_info.append((v_alias, self._apply_case_sensitive(v_alias), False))
else:
field_info.append(
(field_name, self._apply_case_sensitive(self.config.get('env_prefix', '') + field_name), False)
Expand Down
21 changes: 18 additions & 3 deletions tests/test_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -418,7 +418,7 @@ def test_env_inheritance_config(env):
env.set('foobar_parent_from_config', 'foobar_parent_from_config')
env.set('foobar_child_from_config', 'foobar_child_from_config')

env.set('prefix_foobar_child_from_field', 'prefix_foobar_child_from_field')
env.set('foobar_child_from_field', 'foobar_child_from_field')

# a. Child class config overrides prefix
class Parent(BaseSettings):
Expand All @@ -429,7 +429,7 @@ class Parent(BaseSettings):
class Child(Parent):
model_config = ConfigDict(env_prefix='prefix_')

assert Child().foobar == 'prefix_foobar_parent_from_field'
assert Child().foobar == 'foobar_parent_from_field'

# b. Child class overrides field
class Parent(BaseSettings):
Expand All @@ -451,7 +451,7 @@ class Child(Parent):

model_config = ConfigDict(env_prefix='prefix_')

assert Child().foobar == 'prefix_foobar_child_from_field'
assert Child().foobar == 'foobar_child_from_field'


def test_invalid_validation_alias(env):
Expand Down Expand Up @@ -498,6 +498,21 @@ class Settings(BaseSettings):
assert Settings().foobar == 'val3'


def test_validation_alias_with_env_prefix(env):
class Settings(BaseSettings):
foobar: str = Field(validation_alias='foo')

model_config = ConfigDict(env_prefix='p_')

env.set('p_foo', 'bar')
with pytest.raises(ValidationError) as exc_info:
Settings()
assert exc_info.value.errors() == [{'type': 'missing', 'loc': ('foo',), 'msg': 'Field required', 'input': {}}]

env.set('foo', 'bar')
assert Settings().foobar == 'bar'


def test_case_sensitive(monkeypatch):
class Settings(BaseSettings):
foo: str
Expand Down

0 comments on commit 6d9c1a2

Please sign in to comment.