Skip to content

Commit ab5adac

Browse files
authored
Merge pull request #553 from OpenCOMPES/fix-552
update tests for env variables
2 parents 1752d34 + b3ad646 commit ab5adac

File tree

3 files changed

+41
-41
lines changed

3 files changed

+41
-41
lines changed

.cspell/custom-dictionary.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,7 @@ datestring
7979
ddir
8080
delaxes
8181
delayeds
82+
delenv
8283
Desy
8384
Deutsches
8485
dfield

src/sed/core/config.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
package_dir = os.path.dirname(find_spec("sed").origin)
2020

2121
USER_CONFIG_PATH = user_config_path(appname="sed", appauthor="OpenCOMPES", ensure_exists=True)
22+
ENV_DIR = Path(".env")
2223

2324
# Configure logging
2425
logger = setup_logging("config")
@@ -295,7 +296,7 @@ def read_env_var(var_name: str) -> str | None:
295296
return value
296297

297298
# Then check .env in current directory
298-
local_vars = _parse_env_file(Path(".env"))
299+
local_vars = _parse_env_file(ENV_DIR)
299300
if var_name in local_vars:
300301
logger.debug(f"Found {var_name} in ./.env file")
301302
return local_vars[var_name]

tests/test_config.py

Lines changed: 38 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@
1515
from sed.core.config import read_env_var
1616
from sed.core.config import save_config
1717
from sed.core.config import save_env_var
18-
from sed.core.config import USER_CONFIG_PATH
1918

2019
test_dir = os.path.dirname(__file__)
2120
test_config_dir = Path(f"{test_dir}/data/loader/")
@@ -235,11 +234,15 @@ def test_invalid_config_wrong_values():
235234
assert "Invalid value 9999 for gid. Group not found." in str(e.value)
236235

237236

238-
def test_env_var_read_write(tmp_path, monkeypatch):
239-
"""Test reading and writing environment variables."""
240-
# Mock USER_CONFIG_PATH to use a temporary directory
237+
@pytest.fixture
238+
def mock_env_file(tmp_path, monkeypatch):
239+
"""Mock the .env file for testing"""
241240
monkeypatch.setattr("sed.core.config.USER_CONFIG_PATH", tmp_path)
241+
yield tmp_path
242+
242243

244+
def test_env_var_read_write(mock_env_file): # noqa: ARG001
245+
"""Test reading and writing environment variables."""
243246
# Test writing a new variable
244247
save_env_var("TEST_VAR", "test_value")
245248
assert read_env_var("TEST_VAR") == "test_value"
@@ -258,16 +261,13 @@ def test_env_var_read_write(tmp_path, monkeypatch):
258261
assert read_env_var("NON_EXISTENT_VAR") is None
259262

260263

261-
def test_env_var_read_no_file(tmp_path, monkeypatch):
264+
def test_env_var_read_no_file(mock_env_file): # noqa: ARG001
262265
"""Test reading environment variables when .env file doesn't exist."""
263-
# Mock USER_CONFIG_PATH to use an empty temporary directory
264-
monkeypatch.setattr("sed.core.config.USER_CONFIG_PATH", tmp_path)
265-
266266
# Test reading from non-existent file
267267
assert read_env_var("TEST_VAR") is None
268268

269269

270-
def test_env_var_special_characters():
270+
def test_env_var_special_characters(mock_env_file): # noqa: ARG001
271271
"""Test reading and writing environment variables with special characters."""
272272
test_cases = {
273273
"TEST_URL": "http://example.com/path?query=value",
@@ -280,50 +280,42 @@ def test_env_var_special_characters():
280280
assert read_env_var(var_name) == value
281281

282282

283-
@pytest.fixture
284-
def cleanup_env_files():
285-
"""Cleanup any .env files before and after tests"""
286-
# Clean up any existing .env files
287-
for path in [Path(".env"), USER_CONFIG_PATH / ".env"]:
288-
if path.exists():
289-
path.unlink()
290-
291-
yield
292-
293-
# Clean up after tests
294-
for path in [Path(".env"), USER_CONFIG_PATH / ".env"]:
295-
if path.exists():
296-
path.unlink()
297-
298-
299-
def test_env_var_precedence(cleanup_env_files): # noqa: ARG001
283+
def test_env_var_precedence(mock_env_file, tmp_path, monkeypatch): # noqa: ARG001
300284
"""Test that environment variables are read in correct order of precedence"""
285+
# Create local .env directory if it doesn't exist
286+
local_env_dir = tmp_path / "local"
287+
local_env_dir.mkdir(exist_ok=True)
288+
monkeypatch.setattr("sed.core.config.ENV_DIR", local_env_dir / ".env")
289+
301290
# Set up test values in different locations
302291
os.environ["TEST_VAR"] = "os_value"
303292

304-
with open(".env", "w") as f:
305-
f.write("TEST_VAR=local_value\n")
306-
307-
save_env_var("TEST_VAR", "user_value") # Saves to USER_CONFIG_PATH
293+
# Save to user config first (lowest precedence)
294+
save_env_var("TEST_VAR", "user_value")
308295

309-
# Should get OS value first
310-
assert read_env_var("TEST_VAR") == "os_value"
296+
# Create local .env file (medium precedence)
297+
with open(local_env_dir / ".env", "w") as f:
298+
f.write("TEST_VAR=local_value\n")
311299

312-
# Remove from OS env and should get local value
313-
del os.environ["TEST_VAR"]
300+
# Remove from OS env to test other precedence levels
301+
monkeypatch.delenv("TEST_VAR", raising=False)
314302
assert read_env_var("TEST_VAR") == "local_value"
315303

316304
# Remove local .env and should get user config value
317-
Path(".env").unlink()
305+
(local_env_dir / ".env").unlink()
318306
assert read_env_var("TEST_VAR") == "user_value"
319307

320308
# Remove user config and should get None
321-
(USER_CONFIG_PATH / ".env").unlink()
309+
(mock_env_file / ".env").unlink()
322310
assert read_env_var("TEST_VAR") is None
323311

324312

325-
def test_env_var_save_and_load(cleanup_env_files): # noqa: ARG001
313+
def test_env_var_save_and_load(mock_env_file, monkeypatch): # noqa: ARG001
326314
"""Test saving and loading environment variables"""
315+
# Clear any existing OS environment variables
316+
monkeypatch.delenv("TEST_VAR", raising=False)
317+
monkeypatch.delenv("OTHER_VAR", raising=False)
318+
327319
# Save a variable
328320
save_env_var("TEST_VAR", "test_value")
329321

@@ -336,14 +328,20 @@ def test_env_var_save_and_load(cleanup_env_files): # noqa: ARG001
336328
assert read_env_var("OTHER_VAR") == "other_value"
337329

338330

339-
def test_env_var_not_found(cleanup_env_files): # noqa: ARG001
331+
def test_env_var_not_found(mock_env_file): # noqa: ARG001
340332
"""Test behavior when environment variable is not found"""
341333
assert read_env_var("NONEXISTENT_VAR") is None
342334

343335

344-
def test_env_file_format(cleanup_env_files): # noqa: ARG001
336+
def test_env_file_format(mock_env_file, monkeypatch): # noqa: ARG001
345337
"""Test that .env file parsing handles different formats correctly"""
346-
with open(".env", "w") as f:
338+
# Clear any existing OS environment variables
339+
monkeypatch.delenv("TEST_VAR", raising=False)
340+
monkeypatch.delenv("SPACES_VAR", raising=False)
341+
monkeypatch.delenv("EMPTY_VAR", raising=False)
342+
monkeypatch.delenv("COMMENT", raising=False)
343+
344+
with open(mock_env_file / ".env", "w") as f:
347345
f.write(
348346
"""
349347
TEST_VAR=value1

0 commit comments

Comments
 (0)