| 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 |
|
| 15 |
system_env = tmp_path / "system.env" |
| 16 |
system_env.write_text("DUCT_LOG_LEVEL=WARNING\nDUCT_SAMPLE_INTERVAL=2.0\n") |
| 17 |
|
| 18 |
|
| 19 |
user_env = tmp_path / "user.env" |
| 20 |
user_env.write_text("DUCT_LOG_LEVEL=DEBUG\nDUCT_REPORT_INTERVAL=120.0\n") |
| 21 |
|
| 22 |
|
| 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 |
|
| 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 |
|
| 66 |
assert os.environ.get("DUCT_LOG_LEVEL") == "INFO" |
| 67 |
assert os.environ.get("DUCT_MESSAGE") == "test message" |
| 68 |
|
| 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 |
|
| 84 |
assert os.environ.get("DUCT_LOG_LEVEL") == "CRITICAL" |
| 85 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 144 |
monkeypatch.setitem(sys.modules, "dotenv", None) |
| 145 |
|
| 146 |
log_buffer = cli.load_duct_env_files() |
| 147 |
|
| 148 |
|
| 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 |
|
| 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 |
|
| 166 |
assert len(log_buffer) > 0 |
| 167 |
|
| 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 |
|
| 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 |
|
| 188 |
assert len(log_buffer) > 0 |
| 189 |
|
| 190 |
|
| 191 |
with caplog.at_level(logging.DEBUG, logger="con-duct"): |
| 192 |
cli._replay_early_logs(log_buffer) |
| 193 |
|
| 194 |
|
| 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 |
|
| 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 |
|
| 215 |
levels = {level for level, _ in log_buffer} |
| 216 |
assert "DEBUG" in levels |
| 217 |
assert "INFO" in levels |
| 218 |
|
| 219 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 251 |
with patch.object( |
| 252 |
dotenv, "load_dotenv", side_effect=PermissionError("Permission denied") |
| 253 |
): |
| 254 |
|
| 255 |
log_buffer = cli.load_duct_env_files() |
| 256 |
|
| 257 |
|
| 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 |
|
| 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 |
|
| 276 |
log_buffer = cli.load_duct_env_files() |
| 277 |
|
| 278 |
|
| 279 |
messages = [msg for level, msg in log_buffer] |
| 280 |
assert any("Skipping malformed .env file" in msg for msg in messages) |
| 281 |
|
| 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 |
|
| 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 |
|
| 298 |
log_buffer = cli.load_duct_env_files() |
| 299 |
|
| 300 |
|
| 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 |
|
| 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 |
|
| 319 |
clean_env.setattr(cli, "DEFAULT_CONFIG_PATHS", str(env_file)) |
| 320 |
|
| 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 |
|
| 331 |
env_file = tmp_path / "test.env" |
| 332 |
env_file.write_text("DUCT_TEST_BARE_VAR=found\n") |
| 333 |
|
| 334 |
|
| 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 |
|
| 349 |
log_buffer = cli.load_duct_env_files() |
| 350 |
|
| 351 |
|
| 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 |
|
| 361 |
env_file = tmp_path / "test.env" |
| 362 |
env_file.write_text("DUCT_TEST_TILDE=found\n") |
| 363 |
|
| 364 |
|
| 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 |
|
| 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 |
|
| 385 |
cli.load_duct_env_files() |
| 386 |
|
| 387 |
|
| 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 |
|
| 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 |
|
| 407 |
cli.load_duct_env_files() |
| 408 |
|
| 409 |
|
| 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 |
|
| 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" |