返回 last30days-skill
test_env_encoding.py
根目录 / tests / test_env_encoding.py
1 from lib import env
2
3
4 def test_load_env_file_strips_utf8_bom(tmp_path):
5 # A Windows editor (e.g. Notepad) commonly saves .env with a UTF-8 BOM.
6 # Without an explicit encoding, open() prepends the BOM to the first key,
7 # corrupting it (KeyError below). utf-8-sig transparently strips the BOM.
8 env_path = tmp_path / ".env"
9 env_path.write_bytes("DISPLAY_NAME=café\nREAL_KEY=ok\n".encode("utf-8-sig"))
10
11 loaded = env.load_env_file(env_path)
12
13 assert loaded["DISPLAY_NAME"] == "café"
14 assert loaded["REAL_KEY"] == "ok"
15
16
17 def test_load_env_file_falls_back_to_locale_encoding(tmp_path, monkeypatch):
18 # A pre-existing .env saved in a legacy codepage (e.g. cp1252 on Windows)
19 # loaded fine when open() used the locale decoder. Force the fallback locale
20 # to cp1252 so the test is deterministic on any runner, and assert the value
21 # decodes correctly rather than being replaced/corrupted.
22 monkeypatch.setattr(
23 env.locale, "getpreferredencoding", lambda do_setlocale=True: "cp1252"
24 )
25 env_path = tmp_path / ".env"
26 env_path.write_bytes("DISPLAY_NAME=Jos\xe9\nREAL_KEY=ok\n".encode("cp1252"))
27
28 loaded = env.load_env_file(env_path)
29
30 assert loaded["DISPLAY_NAME"] == "José"
31 assert loaded["REAL_KEY"] == "ok"
32
32 lines PYTHON