From 0f7609f116b19ac7355daa6b5d9147a8c5817907 Mon Sep 17 00:00:00 2001 From: srijan2607 <141031709+srijan2607@users.noreply.github.com> Date: Thu, 15 Oct 2026 14:22:09 +0000 Subject: [PATCH] Return false when dotenv contains only valueless declarations Implemented and tested with AI assistance; independently reviewed by a separate AI agent. Pending Srijan's human review; not submitted upstream. --- src/dotenv/main.py | 2 +- tests/test_load_result.py | 48 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 tests/test_load_result.py diff --git a/src/dotenv/main.py b/src/dotenv/main.py index 5faa7f0e..845952d7 100644 --- a/src/dotenv/main.py +++ b/src/dotenv/main.py @@ -102,7 +102,7 @@ def set_as_environment_variables(self) -> bool: """ Load the current dotenv as system environment variable. """ - if not self.dict(): + if not any(value is not None for value in self.dict().values()): return False for k, v in self.dict().items(): diff --git a/tests/test_load_result.py b/tests/test_load_result.py new file mode 100644 index 00000000..7160d0fd --- /dev/null +++ b/tests/test_load_result.py @@ -0,0 +1,48 @@ +import io +import os +from unittest import mock + +import pytest + +from dotenv import dotenv_values, load_dotenv + + +@pytest.mark.parametrize("override", [False, True]) +@pytest.mark.parametrize("source", ["file", "stream"]) +@pytest.mark.parametrize("existing", [False, True]) +@pytest.mark.parametrize( + "content", ["DOTENV_TEST_KEY", "# comment\nDOTENV_TEST_KEY\nOTHER_KEY\n"] +) +def test_load_dotenv_without_values_returns_false( + tmp_path, override, source, existing, content +): + environ = {"DOTENV_TEST_KEY": "existing"} if existing else {} + with mock.patch.dict(os.environ, environ, clear=True): + if source == "file": + path = tmp_path / ".env" + path.write_text(content) + result = load_dotenv(path, override=override) + else: + result = load_dotenv(stream=io.StringIO(content), override=override) + + assert result is False + assert os.environ == environ + + assert dotenv_values(stream=io.StringIO(content))["DOTENV_TEST_KEY"] is None + + +@pytest.mark.parametrize("override", [False, True]) +@pytest.mark.parametrize( + "content", + [ + "DOTENV_TEST_KEY=", + "BARE_KEY\nDOTENV_TEST_KEY=", + "DOTENV_TEST_KEY=value\nBARE_KEY", + ], +) +def test_load_dotenv_with_values_returns_true(override, content): + with mock.patch.dict(os.environ, {}, clear=True): + result = load_dotenv(stream=io.StringIO(content), override=override) + + assert result is True + assert os.environ == {"DOTENV_TEST_KEY": "value" if "=value" in content else ""}