返回 last30days-skill
test_secret_hygiene.py
根目录 / tests / test_secret_hygiene.py
1 """Tests for secret-file write hygiene (U7)."""
2
3 import os
4 import stat
5 from pathlib import Path
6
7 from lib import env, setup_wizard
8
9
10 def _mode(path: Path) -> int:
11 return stat.S_IMODE(os.stat(path).st_mode)
12
13
14 class TestSecureEnvWrite:
15 def test_new_env_file_is_0600(self, tmp_path):
16 env_path = tmp_path / "cfg" / ".env"
17 assert setup_wizard.write_setup_config(env_path, from_browser="auto") is True
18 assert env_path.exists()
19 assert _mode(env_path) == 0o600
20
21 def test_existing_loose_file_tightened_to_0600(self, tmp_path):
22 env_path = tmp_path / ".env"
23 env_path.write_text("EXISTING_KEY=value\n", encoding="utf-8")
24 os.chmod(env_path, 0o644)
25 setup_wizard.write_setup_config(env_path, from_browser="auto")
26 assert _mode(env_path) == 0o600
27
28 def test_written_config_is_loadable(self, tmp_path):
29 env_path = tmp_path / ".env"
30 setup_wizard.write_setup_config(env_path, from_browser="auto")
31 loaded = env.load_env_file(env_path)
32 assert loaded.get("SETUP_COMPLETE") == "true"
33 assert loaded.get("FROM_BROWSER") == "auto"
34
35
36 class TestFormatEnvValue:
37 def test_plain_token_unchanged(self):
38 assert setup_wizard._format_env_value("abc123-TOKEN_x") == "abc123-TOKEN_x"
39
40 def test_value_with_spaces_roundtrips(self, tmp_path):
41 env_path = tmp_path / ".env"
42 line = f"SOME_KEY={setup_wizard._format_env_value('two words')}\n"
43 # Write 0o600 via the loader-compatible path and confirm the loader
44 # strips the quoting back to the original value.
45 env_path.write_text(line, encoding="utf-8")
46 os.chmod(env_path, 0o600)
47 loaded = env.load_env_file(env_path)
48 assert loaded["SOME_KEY"] == "two words"
49
50 def test_newline_is_stripped(self):
51 out = setup_wizard._format_env_value("line1\nline2")
52 assert "\n" not in out
53
53 lines PYTHON