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 的负责人手机号做脱敏
This commit is contained in:
@@ -0,0 +1,75 @@
|
||||
# -*- 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}")
|
||||
@@ -8,6 +8,9 @@ if hasattr(sys.stdout, "reconfigure"):
|
||||
|
||||
REPO = r"d:\work\code\37duAutomation"
|
||||
sys.path.insert(0, os.path.join(REPO, "desktop", "electron-shell", "python"))
|
||||
sys.path.insert(0, os.path.join(REPO, "tests"))
|
||||
|
||||
from _env import get as env_get # noqa: E402
|
||||
|
||||
PLUGIN_DIR = os.path.join(REPO, "plugins", "XQ0001-0100", "XQ0079 金色湖畔扫码数据导出")
|
||||
|
||||
@@ -24,5 +27,9 @@ from xq0079.data import tianque_browser # noqa: E402
|
||||
config.set_log(lambda m, level="INFO": print(f"[{level}] {m}", flush=True))
|
||||
|
||||
print("登录选项:", config.LOGIN_MODE_CHOICES)
|
||||
result = tianque_browser.manual_login("***REMOVED***", "***REMOVED***", wait_seconds=8)
|
||||
ACCOUNT = env_get("tq_login_username")
|
||||
PASSWORD = env_get("tq_login_password")
|
||||
if not ACCOUNT or not PASSWORD:
|
||||
raise SystemExit("根 .env 缺 tq_login_username / tq_login_password,无法校验人工登录预填")
|
||||
result = tianque_browser.manual_login(ACCOUNT, PASSWORD, wait_seconds=8)
|
||||
print("结果:", result.get("success"), result.get("message"))
|
||||
|
||||
@@ -8,6 +8,9 @@ if hasattr(sys.stdout, "reconfigure"):
|
||||
|
||||
REPO = r"d:\work\code\37duAutomation"
|
||||
sys.path.insert(0, os.path.join(REPO, "desktop", "electron-shell", "python"))
|
||||
sys.path.insert(0, os.path.join(REPO, "tests"))
|
||||
|
||||
from _env import get as env_get # noqa: E402
|
||||
|
||||
PLUGIN_DIR = os.path.join(REPO, "plugins", "XQ0001-0100", "XQ0079 金色湖畔扫码数据导出")
|
||||
|
||||
@@ -24,10 +27,16 @@ from xq0079.data import tianque_browser # noqa: E402
|
||||
config.set_log(lambda m, level="INFO": print(f"[{level}] {m}", flush=True))
|
||||
config.set_debug(True)
|
||||
|
||||
print("profile 根目录:", config.BROWSER_PROFILE_ROOT)
|
||||
print("账号A 目录:", config.get_profile_dir("***REMOVED***"))
|
||||
print("账号B 目录:", config.get_profile_dir("***REMOVED***"))
|
||||
ACCOUNT = env_get("tq_login_username")
|
||||
ACCOUNT2 = env_get("tq_login_username_2") # 可选:第二个账号,用于校验 profile 目录按账号隔离
|
||||
|
||||
result = tianque_browser.manual_login("***REMOVED***", "***REMOVED***", wait_seconds=6)
|
||||
print("profile 根目录:", config.BROWSER_PROFILE_ROOT)
|
||||
print("账号A 目录:", config.get_profile_dir(ACCOUNT))
|
||||
if ACCOUNT2:
|
||||
print("账号B 目录:", config.get_profile_dir(ACCOUNT2))
|
||||
|
||||
if not ACCOUNT or not env_get("tq_login_password"):
|
||||
raise SystemExit("根 .env 缺 tq_login_username / tq_login_password,无法校验人工登录")
|
||||
result = tianque_browser.manual_login(ACCOUNT, env_get("tq_login_password"), wait_seconds=6)
|
||||
print("结果:", result.get("success"), result.get("message"))
|
||||
print("临时公共目录是否被使用:", os.path.join(os.environ.get("TEMP", ""), "DrissionPage", "userData"))
|
||||
|
||||
@@ -9,6 +9,9 @@ if hasattr(sys.stdout, "reconfigure"):
|
||||
|
||||
REPO = r"d:\work\code\37duAutomation"
|
||||
sys.path.insert(0, os.path.join(REPO, "desktop", "electron-shell", "python"))
|
||||
sys.path.insert(0, os.path.join(REPO, "tests"))
|
||||
|
||||
from _env import get as env_get # noqa: E402
|
||||
|
||||
PLUGIN_DIR = os.path.join(REPO, "plugins", "XQ0001-0100", "XQ0079 金色湖畔扫码数据导出")
|
||||
|
||||
@@ -30,10 +33,10 @@ spec.loader.exec_module(mod)
|
||||
|
||||
plugin = mod.PLUGINS.find("xq0079")
|
||||
fields = {
|
||||
"tq_account1": "***REMOVED***",
|
||||
"tq_password1": "***REMOVED***",
|
||||
"tq_account2": "",
|
||||
"tq_password2": "",
|
||||
"tq_account1": env_get("tq_login_username"),
|
||||
"tq_password1": env_get("tq_login_password"),
|
||||
"tq_account2": env_get("tq_login_username_2"),
|
||||
"tq_password2": env_get("tq_login_password_2"),
|
||||
"login_mode": "人工登录",
|
||||
"date_from": "",
|
||||
"date_to": "",
|
||||
|
||||
@@ -44,10 +44,12 @@ KEY_RES = "__cap_res"
|
||||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
LOG_FILE = os.path.join(_HERE, "capture.log")
|
||||
|
||||
try:
|
||||
from tianque_login_test import ACCOUNT as _ACC, PASSWORD as _PWD
|
||||
except Exception:
|
||||
_ACC, _PWD = "", ""
|
||||
# 账号密码只放仓库根 .env(tq_login_username / tq_login_password),account.json 仅兜底
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
from _env import get as _env_get # noqa: E402
|
||||
|
||||
_ACC = _env_get("tq_login_username")
|
||||
_PWD = _env_get("tq_login_password")
|
||||
|
||||
_ACC_FILE = os.path.join(_HERE, "account.json")
|
||||
if os.path.exists(_ACC_FILE):
|
||||
|
||||
@@ -41,10 +41,12 @@ URL_PROBE = "/management/easypay/api/tranInfo/queryTranSumByDate"
|
||||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
TOKEN_FILE = os.path.join(os.environ.get("TEMP", "."), "tianque_token.json")
|
||||
|
||||
try:
|
||||
from tianque_login_test import ACCOUNT as _ACC, PASSWORD as _PWD
|
||||
except Exception:
|
||||
_ACC, _PWD = "", ""
|
||||
# 账号密码只放仓库根 .env(tq_login_username / tq_login_password),account.json 仅兜底
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
from _env import get as _env_get # noqa: E402
|
||||
|
||||
_ACC = _env_get("tq_login_username")
|
||||
_PWD = _env_get("tq_login_password")
|
||||
|
||||
_ACC_FILE = os.path.join(_HERE, "account.json")
|
||||
if os.path.exists(_ACC_FILE):
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
"""天阙会生活商户平台(mch-web.tianquetech.com)接口登录联调脚本。
|
||||
|
||||
用法:
|
||||
1. 在下面「配置区」填 ACCOUNT / PASSWORD(也可写在同目录 account.json)
|
||||
1. 在仓库根 `.env` 配置 `tq_login_username` / `tq_login_password`
|
||||
(也可写在同目录 account.json,作为兜底)
|
||||
2. 运行:d:\\work\\code\\37duAutomation\\.venv\\Scripts\\python.exe tests/tianque_probe/tianque_login_test.py
|
||||
|
||||
流程:imageCode 取图(imageKey + captchaBase64)→ ddddocr 识别(同一 imageKey 只能用一次)
|
||||
@@ -41,8 +42,12 @@ if hasattr(sys.stdout, "reconfigure"):
|
||||
pass
|
||||
|
||||
# ==================== 配置区 ====================
|
||||
ACCOUNT = "***REMOVED***" # 663 账号或手机号
|
||||
PASSWORD = "***REMOVED***" # 登录密码(明文,脚本内部加密)
|
||||
# 账号密码只放仓库根 .env(已 gitignore,不入库):tq_login_username / tq_login_password
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
from _env import get as _env_get # noqa: E402
|
||||
|
||||
ACCOUNT = _env_get("tq_login_username") # 663 账号或手机号
|
||||
PASSWORD = _env_get("tq_login_password") # 登录密码(明文,脚本内部加密)
|
||||
MAX_ATTEMPTS = 5 # 提交轮次上限(服务端不区分验证码错/密码错,只能换图重试)
|
||||
SAVE_TOKEN = True # 登录成功后把用户信息落到临时文件,便于后续接口联调
|
||||
VERIFY_TOKEN = True # 登录成功后调用一次交易汇总接口验证 token 是否可用
|
||||
@@ -81,6 +86,10 @@ if os.path.exists(_ACC_FILE):
|
||||
except Exception as exc: # 配置写坏不应阻断,直接提示
|
||||
print(f"读取 account.json 失败:{exc}")
|
||||
|
||||
if not ACCOUNT or not PASSWORD:
|
||||
raise SystemExit("未取到天阙账号密码:请在仓库根 .env 配置 "
|
||||
"tq_login_username / tq_login_password(或同目录 account.json)")
|
||||
|
||||
|
||||
def log(msg):
|
||||
print(f"[{datetime.now():%H:%M:%S}] {msg}", flush=True)
|
||||
|
||||
Reference in New Issue
Block a user