| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 |
- """Tests for the simple .env loader."""
- import os
- import pytest
- from cq2_sdk.env_loader import load_env
- def test_load_env_returns_zero_when_no_file(tmp_path, monkeypatch):
- monkeypatch.chdir(tmp_path)
- assert load_env() == 0
- def test_load_env_parses_key_value_pairs(tmp_path, monkeypatch):
- monkeypatch.chdir(tmp_path)
- (tmp_path / ".env").write_text(
- "FOO=bar\n"
- "BAZ=qux\n"
- "# this is a comment\n"
- "EMPTY=\n"
- "QUOTED=\"hello world\"\n"
- "SINGLE='single quoted'\n",
- encoding="utf-8",
- )
- loaded = load_env()
- # 5 entries: FOO, BAZ, EMPTY (loaded as ""), QUOTED, SINGLE
- assert loaded == 5
- assert os.environ["FOO"] == "bar"
- assert os.environ["BAZ"] == "qux"
- assert os.environ["EMPTY"] == ""
- assert os.environ["QUOTED"] == "hello world"
- assert os.environ["SINGLE"] == "single quoted"
- def test_load_env_does_not_overwrite_existing(tmp_path, monkeypatch):
- monkeypatch.chdir(tmp_path)
- monkeypatch.setenv("FOO", "existing_value")
- (tmp_path / ".env").write_text("FOO=new_value\n", encoding="utf-8")
- load_env()
- assert os.environ["FOO"] == "existing_value" # not overwritten
- def test_load_env_skips_blank_and_comment_lines(tmp_path, monkeypatch):
- monkeypatch.chdir(tmp_path)
- (tmp_path / ".env").write_text(
- "\n"
- "# comment\n"
- "\n"
- "VALID=1\n"
- " \n"
- "ALSO_VALID=2\n",
- encoding="utf-8",
- )
- loaded = load_env()
- assert loaded == 2
- assert os.environ["VALID"] == "1"
- assert os.environ["ALSO_VALID"] == "2"
- def test_load_env_explicit_path(tmp_path):
- env_file = tmp_path / "custom.env"
- env_file.write_text("X=1\nY=2\n", encoding="utf-8")
- loaded = load_env(env_file)
- assert loaded == 2
- assert os.environ["X"] == "1"
- assert os.environ["Y"] == "2"
|