import sys from pathlib import Path import pytest sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts")) from _env import credentials, load_env # noqa: E402 KEYS = ("DANBOORU_API_KEY", "DANBOORU_LOGIN") @pytest.fixture(autouse=True) def clean_environment(monkeypatch): for key in KEYS: monkeypatch.delenv(key, raising=False) def write(tmp_path: Path, text: str) -> Path: path = tmp_path / ".env" path.write_text(text, encoding="utf-8") return path def test_missing_file_is_not_an_error(tmp_path): assert credentials(env_file=tmp_path / "absent") == (None, None) def test_reads_a_pair_from_the_file(tmp_path): env = write(tmp_path, "DANBOORU_LOGIN=someone\nDANBOORU_API_KEY=secret\n") assert credentials(env_file=env) == ("secret", "someone") def test_strips_quotes_comments_and_stray_lines(tmp_path): env = write( tmp_path, "# a comment\n" '\nDANBOORU_LOGIN = "spaced-and-quoted"\n' "DANBOORU_API_KEY='single'\n" "NOT_AN_ASSIGNMENT\n", ) assert credentials(env_file=env) == ("single", "spaced-and-quoted") def test_empty_values_mean_anonymous(tmp_path): # 模板文件就是这个形态,它必须表现为「没填」而不是「填了空字符串」。 env = write(tmp_path, "DANBOORU_LOGIN=\nDANBOORU_API_KEY=\n") assert credentials(env_file=env) == (None, None) def test_command_line_beats_the_file(tmp_path): env = write(tmp_path, "DANBOORU_LOGIN=file\nDANBOORU_API_KEY=file\n") assert credentials("cli-key", "cli-login", env_file=env) == ("cli-key", "cli-login") def test_exported_environment_beats_the_file(tmp_path, monkeypatch): monkeypatch.setenv("DANBOORU_LOGIN", "shell") monkeypatch.setenv("DANBOORU_API_KEY", "shell") env = write(tmp_path, "DANBOORU_LOGIN=file\nDANBOORU_API_KEY=file\n") assert credentials(env_file=env) == ("shell", "shell") @pytest.mark.parametrize("present", KEYS) def test_half_a_pair_is_refused(tmp_path, present): # 只给一个会拼出 api_key=None 的请求,几秒后返回 401 —— 看起来像网络问题。 env = write(tmp_path, f"{present}=only-this\n") with pytest.raises(SystemExit, match="必须同时提供"): credentials(env_file=env) def test_load_env_does_not_overwrite_unrelated_variables(tmp_path, monkeypatch): monkeypatch.setenv("PATH_LIKE", "original") load_env(write(tmp_path, "PATH_LIKE=replaced\n")) import os assert os.environ["PATH_LIKE"] == "original"