upload
This commit is contained in:
@@ -0,0 +1,170 @@
|
||||
"""埋点验证:静态检查埋点位置 + 动态验证 run_one 的两条链路。
|
||||
|
||||
用法(在 dashboard 目录):
|
||||
python scripts/verify_insight.py
|
||||
|
||||
特点:不会发真实网络请求、不会写数据库(update_headers 被替换为空实现),
|
||||
日志写到临时目录,不污染 酒店/logs。
|
||||
"""
|
||||
|
||||
import json
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1] # dashboard/
|
||||
HOTEL_DIR = ROOT.parent # 酒店/
|
||||
sys.path.insert(0, str(HOTEL_DIR))
|
||||
|
||||
import hotel_insight as insight # noqa: E402
|
||||
import 酒店详情 as hd # noqa: E402
|
||||
|
||||
FAILS: list[str] = []
|
||||
|
||||
|
||||
def check(cond: bool, label: str, detail: str = "") -> None:
|
||||
print((" ✓ " if cond else " ✗ ") + label + (f" {detail}" if detail else ""))
|
||||
if not cond:
|
||||
FAILS.append(label)
|
||||
|
||||
|
||||
def static_checks() -> None:
|
||||
print("[1] 静态检查(酒店详情.py 埋点位置)")
|
||||
src = (HOTEL_DIR / "酒店详情.py").read_text(encoding="utf-8")
|
||||
check("import hotel_insight as insight" in src, "已 import 埋点模块")
|
||||
check("mt_traceid,dfpid FROM" in src, "get_headers 的 SELECT 已追加 dfpid 列")
|
||||
check("ind, hd, prox, city, mt_traceid, dfpid = item" in src, "item 已改为 6 元组解包")
|
||||
check(src.count("insight.log_fetch(") == 1, "log_fetch 调用 1 处", f"实际 {src.count('insight.log_fetch(')}")
|
||||
check(src.count("insight.log_fetch_empty(") == 1, "log_fetch_empty 调用 1 处", f"实际 {src.count('insight.log_fetch_empty(')}")
|
||||
check(src.count("insight.log_upload(") == 2, "log_upload 调用 2 处(shelf / prepayList)", f"实际 {src.count('insight.log_upload(')}")
|
||||
check(src.count("insight.log_exception(") == 5, "log_exception 调用 5 处(except + 两处 418/401)", f"实际 {src.count('insight.log_exception(')}")
|
||||
# upload 埋点必须紧跟在 upload_one_task 之后
|
||||
idx_upload = src.find("_upload_resp = upload_one_task(")
|
||||
check(idx_upload > 0 and "insight.log_upload(" in src[idx_upload : idx_upload + 600], "log_upload 紧跟 upload_one_task")
|
||||
# except 分支的 is_ok 判定逻辑未被改动
|
||||
check("if 'Expecting value: line 1 column 1 (char 0)' in str(e):" in src, "except 分支原判定逻辑保留")
|
||||
|
||||
|
||||
def make_run():
|
||||
"""构造不连库的 hotel_run 实例(跳过 __init__)。"""
|
||||
obj = hd.hotel_run.__new__(hd.hotel_run)
|
||||
obj.proxy_list = [
|
||||
(json.dumps({"http": "http://u:p@1.2.3.4:1", "https": "http://u:p@1.2.3.4:1"}), "南宁"),
|
||||
]
|
||||
obj.bound_city = "南宁"
|
||||
obj.last_trace_id = None
|
||||
obj.update_headers = lambda *a, **k: None # 不写库
|
||||
return obj
|
||||
|
||||
|
||||
TASK = {
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": {
|
||||
"hotelId": "938833723",
|
||||
"cityId": "50",
|
||||
"hotelName": "杭州拱墅大运河轻居酒店",
|
||||
"cityName": "南宁市",
|
||||
"checkInDate": "2026-10-21",
|
||||
"checkOutDate": "2026-10-22",
|
||||
"uniqueId": "20261020120000-32-32-3000001-443-411",
|
||||
"selectedCity": "广西壮族自治区:50_南宁市",
|
||||
},
|
||||
}
|
||||
|
||||
ITEMS = [(13888, '["https://ihotel.meituan.com/unknown/path", {}, ""]', None, "南宁", None, "abcdefgh8f42ac81")]
|
||||
|
||||
|
||||
def dyn_empty(tmp: str) -> None:
|
||||
print("[2] 动态:get_one_task 返回 False(拿任务失败链路)")
|
||||
obj = make_run()
|
||||
with mock.patch.object(hd, "get_one_task", return_value=False):
|
||||
ret = obj.run_one(list(ITEMS))
|
||||
check(ret == -1, "run_one 返回 -1(原行为不变)", f"实际 {ret}")
|
||||
events = read_events(tmp)
|
||||
empty = [e for e in events if e["event"] == "fetch_empty"]
|
||||
check(len(empty) == 1, "写入 1 条 fetch_empty", f"实际 {len(empty)}")
|
||||
if empty:
|
||||
e = empty[0]
|
||||
check(e["hd_id"] == 13888, "fetch_empty 带 hd_id")
|
||||
check(e["dfpid_tail"] == "8f42ac81", "dfpid 已脱敏为后 8 位", e["dfpid_tail"])
|
||||
check(e["target_city"] == "南宁", "带目标城市")
|
||||
|
||||
|
||||
def dyn_task(tmp: str) -> None:
|
||||
print("[3] 动态:领到任务(fetch_task 链路)")
|
||||
obj = make_run()
|
||||
with mock.patch.object(hd, "get_one_task", return_value=TASK):
|
||||
# hd 里的 url 不命中任何接口分支 → 走“未知接口,跳过”,不会发网络请求
|
||||
obj.run_one(list(ITEMS))
|
||||
events = read_events(tmp)
|
||||
fetched = [e for e in events if e["event"] == "fetch_task"]
|
||||
check(len(fetched) == 1, "写入 1 条 fetch_task", f"实际 {len(fetched)}")
|
||||
if fetched:
|
||||
e = fetched[0]
|
||||
check(e["hd_id"] == 13888 and e["hotel_id"] == "938833723", "带账号与酒店 ID")
|
||||
check(e["city_name"] == "南宁市", "带任务城市名")
|
||||
check(e["unique_id"] == TASK["data"]["uniqueId"], "带 uniqueId")
|
||||
|
||||
|
||||
def read_events(tmp: str) -> list[dict]:
|
||||
path = Path(tmp) / ("run_" + __import__("datetime").datetime.now().strftime("%Y%m%d") + ".jsonl")
|
||||
if not path.is_file():
|
||||
return []
|
||||
out = []
|
||||
for line in path.read_text(encoding="utf-8").splitlines():
|
||||
line = line.strip()
|
||||
if line:
|
||||
out.append(json.loads(line))
|
||||
return out
|
||||
|
||||
|
||||
def dyn_no_log() -> None:
|
||||
"""写日志失败不得影响采集主流程(05 文档 8.3 第 3 条)。"""
|
||||
print("[4] 动态:日志目录不可写时的降级")
|
||||
obj = make_run()
|
||||
old = insight.LOG_DIR
|
||||
insight.LOG_DIR = "Z:\\definitely-not-exist\\logs"
|
||||
try:
|
||||
with mock.patch.object(hd, "get_one_task", return_value=False):
|
||||
ret_empty = obj.run_one(list(ITEMS))
|
||||
check(ret_empty == -1, "写日志失败时 run_one 仍返回 -1(未崩溃)", f"实际 {ret_empty}")
|
||||
with mock.patch.object(hd, "get_one_task", return_value=TASK):
|
||||
obj.run_one(list(ITEMS))
|
||||
check(True, "写日志失败时 fetch_task 链路也正常结束")
|
||||
except Exception as e: # noqa: BLE001
|
||||
check(False, "写日志失败时 run_one 抛异常", f"{type(e).__name__}: {e}")
|
||||
finally:
|
||||
insight.LOG_DIR = old
|
||||
|
||||
|
||||
def main() -> int:
|
||||
# import 无副作用检查
|
||||
print("[0] import 检查")
|
||||
check(hasattr(hd, "hotel_run"), "import 酒店详情 成功(顶层无副作用)")
|
||||
|
||||
tmp = tempfile.mkdtemp(prefix="insight_verify_")
|
||||
insight.LOG_DIR = tmp
|
||||
print(f"\n临时日志目录: {tmp}\n")
|
||||
static_checks()
|
||||
dyn_empty(tmp)
|
||||
dyn_task(tmp)
|
||||
dyn_no_log()
|
||||
print("\n[5] 产生的原始事件:")
|
||||
for e in read_events(tmp):
|
||||
print(" " + json.dumps(e, ensure_ascii=False))
|
||||
if FAILS:
|
||||
print("\n✗ 失败项:" + ";".join(FAILS))
|
||||
return 1
|
||||
print("\n✓ 埋点验证全部通过")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in New Issue
Block a user