From dfbc683b61a0322aa149d3866702941182de220a Mon Sep 17 00:00:00 2001 From: Hasan Ramezani Date: Wed, 26 Apr 2023 13:52:43 +0330 Subject: [PATCH] Ignore env_prefix if validation_alias is set --- pydantic_settings/sources.py | 4 +--- tests/test_settings.py | 21 ++++++++++++++++++--- 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/pydantic_settings/sources.py b/pydantic_settings/sources.py index fc039c25..f867f09c 100644 --- a/pydantic_settings/sources.py +++ b/pydantic_settings/sources.py @@ -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) diff --git a/tests/test_settings.py b/tests/test_settings.py index 0f182371..1166c736 100644 --- a/tests/test_settings.py +++ b/tests/test_settings.py @@ -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): @@ -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): @@ -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): @@ -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