test_env_loader.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. """Tests for the simple .env loader."""
  2. import os
  3. import pytest
  4. from cq2_sdk.env_loader import load_env
  5. def test_load_env_returns_zero_when_no_file(tmp_path, monkeypatch):
  6. monkeypatch.chdir(tmp_path)
  7. assert load_env() == 0
  8. def test_load_env_parses_key_value_pairs(tmp_path, monkeypatch):
  9. monkeypatch.chdir(tmp_path)
  10. (tmp_path / ".env").write_text(
  11. "FOO=bar\n"
  12. "BAZ=qux\n"
  13. "# this is a comment\n"
  14. "EMPTY=\n"
  15. "QUOTED=\"hello world\"\n"
  16. "SINGLE='single quoted'\n",
  17. encoding="utf-8",
  18. )
  19. loaded = load_env()
  20. # 5 entries: FOO, BAZ, EMPTY (loaded as ""), QUOTED, SINGLE
  21. assert loaded == 5
  22. assert os.environ["FOO"] == "bar"
  23. assert os.environ["BAZ"] == "qux"
  24. assert os.environ["EMPTY"] == ""
  25. assert os.environ["QUOTED"] == "hello world"
  26. assert os.environ["SINGLE"] == "single quoted"
  27. def test_load_env_does_not_overwrite_existing(tmp_path, monkeypatch):
  28. monkeypatch.chdir(tmp_path)
  29. monkeypatch.setenv("FOO", "existing_value")
  30. (tmp_path / ".env").write_text("FOO=new_value\n", encoding="utf-8")
  31. load_env()
  32. assert os.environ["FOO"] == "existing_value" # not overwritten
  33. def test_load_env_skips_blank_and_comment_lines(tmp_path, monkeypatch):
  34. monkeypatch.chdir(tmp_path)
  35. (tmp_path / ".env").write_text(
  36. "\n"
  37. "# comment\n"
  38. "\n"
  39. "VALID=1\n"
  40. " \n"
  41. "ALSO_VALID=2\n",
  42. encoding="utf-8",
  43. )
  44. loaded = load_env()
  45. assert loaded == 2
  46. assert os.environ["VALID"] == "1"
  47. assert os.environ["ALSO_VALID"] == "2"
  48. def test_load_env_explicit_path(tmp_path):
  49. env_file = tmp_path / "custom.env"
  50. env_file.write_text("X=1\nY=2\n", encoding="utf-8")
  51. loaded = load_env(env_file)
  52. assert loaded == 2
  53. assert os.environ["X"] == "1"
  54. assert os.environ["Y"] == "2"