Files
37duAutomation/tests/_env.py
T
puddy b20fc3d099 refactor(tests): 探针脚本凭据改为从根 .env 读取,移除硬编码账号密码
- 新增 tests/_env.py:统一读仓库根 .env(仅标准库,进程内缓存)
- tianque 探针 6 个脚本改读 tq_login_username / tq_login_password,account.json 仅兜底
- workflows/share/erp_login.py 的 __main__ 去掉硬编码 ERP 账号密码(改由 .env 提供)
- docs/需求单/README.md 的负责人手机号做脱敏
2026-11-18 20:22:38 +08:00

76 lines
2.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""测试/探针脚本统一读仓库根 `.env`(与 `workflows/share` 同口径:只读根 .env)。
为什么要有它:
探针脚本里曾经硬编码过真实账号密码,一旦脚本入库就等于把凭据写进了 git 历史。
现在统一改成:
1) 值只写在仓库根 `.env`(已在 `.gitignore` 里,不入库);
2) 脚本用 `get("key")` 取,缺省返回空串,缺失时按空值降级而不是报错。
用法(脚本在 tests/ 子目录下)::
import os, sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from _env import get as env_get
ACCOUNT = env_get("tq_login_username")
PASSWORD = env_get("tq_login_password")
键名沿用根 .env 现有约定:``<平台>_login_username`` / ``<平台>_login_password``。
"""
from __future__ import annotations
import os
from typing import Dict
#: 仓库根(tests/ 的上一级)
REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
ENV_PATH = os.path.join(REPO_ROOT, ".env")
_CACHE: Dict[str, str] = {}
def _parse(path: str) -> Dict[str, str]:
"""逐行解析 KEY=VALUE;忽略空行/注释,值两端成对引号去掉(不裁行内 #)。"""
data: Dict[str, str] = {}
try:
with open(path, encoding="utf-8", errors="replace") as fp:
for line in fp:
line = line.strip().lstrip("\ufeff")
if not line or line.startswith("#") or "=" not in line:
continue
key, value = line.split("=", 1)
key, value = key.strip(), value.strip()
if len(value) >= 2 and value[0] == value[-1] and value[0] in ("'", '"'):
value = value[1:-1]
if key:
data[key] = value
except OSError:
pass
return data
def load(path: str = "") -> Dict[str, str]:
"""读根 .env(进程内缓存一次);文件不存在返回空 dict。"""
if not _CACHE:
_CACHE.update(_parse(path or ENV_PATH))
return _CACHE
def get(key: str, default: str = "") -> str:
"""取一个配置项;不存在或为空时返回 ``default``。"""
value = load().get(key, "")
return value if value else default
def require(keys, hint: str = "") -> None:
"""校验必需项非空,缺失时抛 RuntimeError(提示去根 .env 补哪几个键)。"""
names = [keys] if isinstance(keys, str) else list(keys)
missing = [name for name in names if not get(name)]
if missing:
raise RuntimeError(
f"缺少根 .env 配置:{', '.join(missing)}"
+ (f"({hint})" if hint else "")
+ f";文件:{ENV_PATH}")