Debian Codegraph @

test/test_env_files.py

raw symbols SCIP
1 from __future__ import annotations
2 import logging
3 import os
4 from pathlib import Path
5 import sys
6 from unittest.mock import patch
7 import pytest
8 from con_duct import cli
9
10
11 @pytest.fixture
12 def temp_env_files(tmp_path: Path) -> dict[str, Path]:
13 """Create temporary .env files for testing."""
14 # System-level config
15 system_env = tmp_path / "system.env"
16 system_env.write_text("DUCT_LOG_LEVEL=WARNING\nDUCT_SAMPLE_INTERVAL=2.0\n")
17
18 # User-level config
19 user_env = tmp_path / "user.env"
20 user_env.write_text("DUCT_LOG_LEVEL=DEBUG\nDUCT_REPORT_INTERVAL=120.0\n")
21
22 # Project-level config
23 project_env = tmp_path / "project.env"
24 project_env.write_text("DUCT_LOG_LEVEL=INFO\nDUCT_MESSAGE=test message\n")
25
26 return {
27 "system": system_env,
28 "user": user_env,
29 "project": project_env,
30 }
31
32
33 def test_load_env_files_basic(
34 temp_env_files: dict[str, Path], clean_env: pytest.MonkeyPatch
35 ) -> None:
36 """Test basic .env file loading."""
37 pytest.importorskip("dotenv")
38
39 config_paths = f"{temp_env_files['system']}{os.pathsep}{temp_env_files['user']}"
40 clean_env.setenv("DUCT_CONFIG_PATHS", config_paths)
41
42 cli.load_duct_env_files()
43 # User config should override system config
44 assert os.environ.get("DUCT_LOG_LEVEL") == "DEBUG"
45 assert os.environ.get("DUCT_SAMPLE_INTERVAL") == "2.0"
46 assert os.environ.get("DUCT_REPORT_INTERVAL") == "120.0"
47
48
49 def test_load_env_files_precedence(
50 temp_env_files: dict[str, Path], clean_env: pytest.MonkeyPatch
51 ) -> None:
52 """Test that later files override earlier files."""
53 pytest.importorskip("dotenv")
54
55 config_paths = os.pathsep.join(
56 [
57 str(temp_env_files["system"]),
58 str(temp_env_files["user"]),
59 str(temp_env_files["project"]),
60 ]
61 )
62 clean_env.setenv("DUCT_CONFIG_PATHS", config_paths)
63
64 cli.load_duct_env_files()
65 # Project should override user which overrides system
66 assert os.environ.get("DUCT_LOG_LEVEL") == "INFO"
67 assert os.environ.get("DUCT_MESSAGE") == "test message"
68 # Values from earlier files that weren't overridden
69 assert os.environ.get("DUCT_SAMPLE_INTERVAL") == "2.0"
70 assert os.environ.get("DUCT_REPORT_INTERVAL") == "120.0"
71
72
73 def test_explicit_env_vars_win(
74 temp_env_files: dict[str, Path], clean_env: pytest.MonkeyPatch
75 ) -> None:
76 """Test that explicit environment variables are not overridden by .env files."""
77 pytest.importorskip("dotenv")
78
79 clean_env.setenv("DUCT_CONFIG_PATHS", str(temp_env_files["project"]))
80 clean_env.setenv("DUCT_LOG_LEVEL", "CRITICAL")
81
82 cli.load_duct_env_files()
83 # Explicit env var should NOT be overridden
84 assert os.environ.get("DUCT_LOG_LEVEL") == "CRITICAL"
85 # But .env file should still set other vars
86 assert os.environ.get("DUCT_MESSAGE") == "test message"
87
88
89 def test_missing_env_file_ignored(
90 tmp_path: Path, clean_env: pytest.MonkeyPatch
91 ) -> None:
92 """Test that missing .env files are silently ignored."""
93 pytest.importorskip("dotenv")
94
95 nonexistent = tmp_path / "nonexistent.env"
96 clean_env.setenv("DUCT_CONFIG_PATHS", str(nonexistent))
97
98 # Should not raise an exception
99 cli.load_duct_env_files()
100
101
102 def test_xdg_config_home_expansion(
103 tmp_path: Path, clean_env: pytest.MonkeyPatch
104 ) -> None:
105 """Test that ${XDG_CONFIG_HOME:-~/.config} syntax is expanded correctly."""
106 pytest.importorskip("dotenv")
107
108 # Create a .env file in a custom XDG location
109 xdg_dir = tmp_path / "xdg_config"
110 xdg_dir.mkdir()
111 duct_dir = xdg_dir / "duct"
112 duct_dir.mkdir()
113 env_file = duct_dir / ".env"
114 env_file.write_text("DUCT_LOG_LEVEL=ERROR\n")
115
116 clean_env.setenv("XDG_CONFIG_HOME", str(xdg_dir))
117 clean_env.setenv("DUCT_CONFIG_PATHS", "${XDG_CONFIG_HOME:-~/.config}/duct/.env")
118
119 cli.load_duct_env_files()
120 assert os.environ.get("DUCT_LOG_LEVEL") == "ERROR"
121
122
123 def test_multiline_values(tmp_path: Path, clean_env: pytest.MonkeyPatch) -> None:
124 """Test that multiline values in .env files are handled correctly."""
125 pytest.importorskip("dotenv")
126
127 # Create .env file with multiline value
128 env_file = tmp_path / "multiline.env"
129 env_file.write_text('DUCT_MESSAGE="Line 1\nLine 2\nLine 3"\n')
130
131 clean_env.setenv("DUCT_CONFIG_PATHS", str(env_file))
132
133 cli.load_duct_env_files()
134 message = os.environ.get("DUCT_MESSAGE")
135 assert message is not None
136 assert "Line 1" in message
137 assert "Line 2" in message
138 assert "Line 3" in message
139
140
141 def test_without_python_dotenv(monkeypatch: pytest.MonkeyPatch) -> None:
142 """Test graceful degradation when python-dotenv is not installed."""
143 # Setting module to None in sys.modules causes ImportError on import
144 monkeypatch.setitem(sys.modules, "dotenv", None)
145
146 log_buffer = cli.load_duct_env_files()
147
148 # Should have a message about dotenv not being installed
149 messages = [msg for level, msg in log_buffer]
150 assert any("python-dotenv not installed" in msg for msg in messages)
151
152
153 def test_early_logging_buffer(tmp_path: Path, clean_env: pytest.MonkeyPatch) -> None:
154 """Test that log messages are buffered during .env loading."""
155 pytest.importorskip("dotenv")
156
157 # Create a test .env file
158 env_file = tmp_path / "test.env"
159 env_file.write_text("TEST_VAR=test_value\n")
160
161 clean_env.setenv("DUCT_CONFIG_PATHS", str(env_file))
162
163 log_buffer = cli.load_duct_env_files()
164
165 # Check that messages were buffered
166 assert len(log_buffer) > 0
167 # Should have messages about searching and loading
168 messages = [msg for level, msg in log_buffer]
169 assert any("Searching for .env files" in msg for msg in messages)
170 assert any("Loading .env file" in msg for msg in messages)
171
172
173 def test_early_logging_replay(
174 tmp_path: Path, clean_env: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
175 ) -> None:
176 """Test that buffered messages are replayed through the logger."""
177 pytest.importorskip("dotenv")
178
179 # Create a test .env file
180 env_file = tmp_path / "test.env"
181 env_file.write_text("TEST_VAR=test_value\n")
182
183 clean_env.setenv("DUCT_CONFIG_PATHS", str(env_file))
184
185 log_buffer = cli.load_duct_env_files()
186
187 # Buffer should have messages
188 assert len(log_buffer) > 0
189
190 # Configure logging and replay
191 with caplog.at_level(logging.DEBUG, logger="con-duct"):
192 cli._replay_early_logs(log_buffer)
193
194 # Check that messages were logged
195 assert len(caplog.records) > 0
196 logged_messages = [record.message for record in caplog.records]
197 assert any("Searching for .env files" in msg for msg in logged_messages)
198
199
200 def test_early_logging_respects_level(
201 tmp_path: Path, clean_env: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
202 ) -> None:
203 """Test that replayed messages respect the configured log level."""
204 pytest.importorskip("dotenv")
205
206 # Create a test .env file
207 env_file = tmp_path / "test.env"
208 env_file.write_text("TEST_VAR=test_value\n")
209
210 clean_env.setenv("DUCT_CONFIG_PATHS", str(env_file))
211
212 log_buffer = cli.load_duct_env_files()
213
214 # Buffer should have both DEBUG and INFO messages
215 levels = {level for level, _ in log_buffer}
216 assert "DEBUG" in levels # "Searching for .env files"
217 assert "INFO" in levels # "Loading .env file"
218
219 # Replay at WARNING level - neither DEBUG nor INFO should appear
220 with caplog.at_level(logging.WARNING, logger="con-duct"):
221 cli._replay_early_logs(log_buffer)
222
223 assert len(caplog.records) == 0
224
225 # Replay at INFO level - only INFO messages should appear
226 caplog.clear()
227 clean_env.setenv("DUCT_CONFIG_PATHS", str(env_file))
228
229 log_buffer2 = cli.load_duct_env_files()
230
231 with caplog.at_level(logging.INFO, logger="con-duct"):
232 cli._replay_early_logs(log_buffer2)
233
234 assert len(caplog.records) > 0
235 assert all(r.levelno >= logging.INFO for r in caplog.records)
236
237
238 def test_permission_denied_handling(
239 tmp_path: Path, clean_env: pytest.MonkeyPatch
240 ) -> None:
241 """Test that permission denied errors are handled gracefully."""
242 dotenv = pytest.importorskip("dotenv")
243
244 # Create a .env file that exists (so it passes the exists() check)
245 env_file = tmp_path / "unreadable.env"
246 env_file.write_text("DUCT_LOG_LEVEL=DEBUG\n")
247
248 clean_env.setenv("DUCT_CONFIG_PATHS", str(env_file))
249
250 # Mock load_dotenv to raise PermissionError (works even as root)
251 with patch.object(
252 dotenv, "load_dotenv", side_effect=PermissionError("Permission denied")
253 ):
254 # Should not raise an exception
255 log_buffer = cli.load_duct_env_files()
256
257 # Should have a WARNING message about permission denied
258 messages = [msg for level, msg in log_buffer]
259 assert any("Cannot read .env file" in msg for msg in messages)
260 assert any("Permission denied" in msg for msg in messages)
261
262
263 def test_malformed_env_file_handling(
264 tmp_path: Path, clean_env: pytest.MonkeyPatch
265 ) -> None:
266 """Test that malformed .env files (null bytes) are handled gracefully."""
267 pytest.importorskip("dotenv")
268
269 # Create a .env file with null bytes
270 env_file = tmp_path / "malformed.env"
271 env_file.write_bytes(b"DUCT_MESSAGE=before\x00after\n")
272
273 clean_env.setenv("DUCT_CONFIG_PATHS", str(env_file))
274
275 # Should not raise an exception
276 log_buffer = cli.load_duct_env_files()
277
278 # Should have a WARNING message about malformed file
279 messages = [msg for level, msg in log_buffer]
280 assert any("Skipping malformed .env file" in msg for msg in messages)
281 # The error message varies by python-dotenv version, so just check it's there
282 assert any(level == "WARNING" for level, _ in log_buffer)
283
284
285 def test_invalid_utf8_env_file_handling(
286 tmp_path: Path, clean_env: pytest.MonkeyPatch
287 ) -> None:
288 """Test that .env files with invalid UTF-8 are handled gracefully."""
289 pytest.importorskip("dotenv")
290
291 # Create a .env file with invalid UTF-8 bytes
292 env_file = tmp_path / "bad_encoding.env"
293 env_file.write_bytes(b"DUCT_MESSAGE=hello\xff\xfeworld\n")
294
295 clean_env.setenv("DUCT_CONFIG_PATHS", str(env_file))
296
297 # Should not raise an exception
298 log_buffer = cli.load_duct_env_files()
299
300 # Should have a WARNING message about malformed file
301 messages = [msg for level, msg in log_buffer]
302 assert any("Skipping malformed .env file" in msg for msg in messages)
303 assert any("utf-8" in msg.lower() or "unicode" in msg.lower() for msg in messages)
304
305
306 def test_default_config_paths_used(
307 tmp_path: Path, clean_env: pytest.MonkeyPatch
308 ) -> None:
309 """Test that DEFAULT_CONFIG_PATHS is used when DUCT_CONFIG_PATHS is not set."""
310 pytest.importorskip("dotenv")
311
312 # Create a .env file at the project-level default path (.duct/.env)
313 duct_dir = tmp_path / ".duct"
314 duct_dir.mkdir()
315 env_file = duct_dir / ".env"
316 env_file.write_text("DUCT_TEST_DEFAULT_PATH=found\n")
317
318 # Patch DEFAULT_CONFIG_PATHS to use our temp path
319 clean_env.setattr(cli, "DEFAULT_CONFIG_PATHS", str(env_file))
320 # Ensure DUCT_CONFIG_PATHS is not set (clean_env already handles this)
321
322 cli.load_duct_env_files()
323 assert os.environ.get("DUCT_TEST_DEFAULT_PATH") == "found"
324
325
326 def test_bare_variable_expansion(tmp_path: Path, clean_env: pytest.MonkeyPatch) -> None:
327 """Test that ${VAR} without default is expanded correctly."""
328 pytest.importorskip("dotenv")
329
330 # Create a .env file
331 env_file = tmp_path / "test.env"
332 env_file.write_text("DUCT_TEST_BARE_VAR=found\n")
333
334 # Set up path using bare ${VAR} syntax
335 clean_env.setenv("MY_CONFIG_DIR", str(tmp_path))
336 clean_env.setenv("DUCT_CONFIG_PATHS", "${MY_CONFIG_DIR}/test.env")
337
338 cli.load_duct_env_files()
339 assert os.environ.get("DUCT_TEST_BARE_VAR") == "found"
340
341
342 def test_empty_config_paths(clean_env: pytest.MonkeyPatch) -> None:
343 """Test that empty DUCT_CONFIG_PATHS is handled gracefully."""
344 pytest.importorskip("dotenv")
345
346 clean_env.setenv("DUCT_CONFIG_PATHS", "")
347
348 # Should not raise an exception
349 log_buffer = cli.load_duct_env_files()
350
351 # Should have logged that no files were found
352 messages = [msg for level, msg in log_buffer]
353 assert any("No .env files found" in msg for msg in messages)
354
355
356 def test_tilde_expansion(tmp_path: Path, clean_env: pytest.MonkeyPatch) -> None:
357 """Test that ~ is expanded to home directory in paths."""
358 pytest.importorskip("dotenv")
359
360 # Create a .env file
361 env_file = tmp_path / "test.env"
362 env_file.write_text("DUCT_TEST_TILDE=found\n")
363
364 # Temporarily change HOME to our temp directory
365 clean_env.setenv("HOME", str(tmp_path))
366 clean_env.setenv("DUCT_CONFIG_PATHS", "~/test.env")
367
368 cli.load_duct_env_files()
369 assert os.environ.get("DUCT_TEST_TILDE") == "found"
370
371
372 def test_env_values_flow_to_argparse(
373 tmp_path: Path, clean_env: pytest.MonkeyPatch
374 ) -> None:
375 """Test that .env values are picked up by argparse defaults."""
376 pytest.importorskip("dotenv")
377
378 # Create a .env file with duct settings
379 env_file = tmp_path / "test.env"
380 env_file.write_text("DUCT_SAMPLE_INTERVAL=99.5\nDUCT_REPORT_INTERVAL=300.0\n")
381
382 clean_env.setenv("DUCT_CONFIG_PATHS", str(env_file))
383
384 # Load .env files (normally called at start of main())
385 cli.load_duct_env_files()
386
387 # Now parse args - the defaults should come from env vars set by .env
388 args = cli._create_run_parser().parse_args(["echo", "test"])
389
390 assert args.sample_interval == 99.5
391 assert args.report_interval == 300.0
392
393
394 def test_env_log_level_flows_to_argparse(
395 tmp_path: Path, clean_env: pytest.MonkeyPatch
396 ) -> None:
397 """Test that DUCT_LOG_LEVEL from .env is picked up by the common parser."""
398 pytest.importorskip("dotenv")
399
400 # Create a .env file with log level
401 env_file = tmp_path / "test.env"
402 env_file.write_text("DUCT_LOG_LEVEL=DEBUG\n")
403
404 clean_env.setenv("DUCT_CONFIG_PATHS", str(env_file))
405
406 # Load .env files
407 cli.load_duct_env_files()
408
409 # Parse using main() flow - log_level is in the common parser
410 args = cli._create_common_parser().parse_args([])
411
412 assert args.log_level == "DEBUG"
413
414
415 def test_whitespace_in_config_paths(
416 tmp_path: Path, clean_env: pytest.MonkeyPatch
417 ) -> None:
418 """Test that paths with spaces are handled correctly."""
419 pytest.importorskip("dotenv")
420
421 # Create a directory with spaces in the name
422 spaced_dir = tmp_path / "path with spaces"
423 spaced_dir.mkdir()
424 env_file = spaced_dir / "test.env"
425 env_file.write_text("DUCT_TEST_SPACES=found\n")
426
427 clean_env.setenv("DUCT_CONFIG_PATHS", str(env_file))
428
429 cli.load_duct_env_files()
430 assert os.environ.get("DUCT_TEST_SPACES") == "found"