Skip to content

Commit

Permalink
dotenv no error w/ an env key shorter than prefix (#106) (#107)
Browse files Browse the repository at this point in the history
  • Loading branch information
jvllmr authored Jul 5, 2023
1 parent 373af71 commit 994f4ec
Show file tree
Hide file tree
Showing 2 changed files with 32 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 @@ -578,7 +578,7 @@ def __call__(self) -> dict[str, Any]:
# As `extra` config is allowed in dotenv settings source, We have to
# update data with extra env variabels from dotenv file.
for env_name, env_value in self.env_vars.items():
if env_value is not None:
if env_name.startswith(self.env_prefix) and env_value is not None:
env_name_without_prefix = env_name[self.env_prefix_len :]
first_key, *_ = env_name_without_prefix.split(self.env_nested_delimiter)

Expand Down
31 changes: 31 additions & 0 deletions tests/test_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -680,6 +680,37 @@ class Settings(BaseSettings):
assert s.c == 'best string'


prefix_test_env_file = """\
# this is a comment
prefix_A=good string
# another one, followed by whitespace
prefix_b='better string'
prefix_c="best string"
f="random value"
"""


@pytest.mark.skipif(not dotenv, reason='python-dotenv not installed')
def test_env_file_with_env_prefix(env, tmp_path):
p = tmp_path / '.env'
p.write_text(prefix_test_env_file)

class Settings(BaseSettings):
a: str
b: str
c: str

model_config = ConfigDict(env_file=p, env_prefix='prefix_')

env.set('prefix_A', 'overridden var')

s = Settings()
assert s.a == 'overridden var'
assert s.b == 'better string'
assert s.c == 'best string'


@pytest.mark.skipif(not dotenv, reason='python-dotenv not installed')
def test_env_file_config_case_sensitive(tmp_path):
p = tmp_path / '.env'
Expand Down

0 comments on commit 994f4ec

Please sign in to comment.