upload
This commit is contained in:
@@ -0,0 +1,205 @@
|
||||
"""冒烟检查:按区块验证后端接口。
|
||||
|
||||
用法(后端已在运行时):
|
||||
python scripts/smoke.py # 全部区块
|
||||
python scripts/smoke.py --only overview,trend # 只测指定区块
|
||||
python scripts/smoke.py --base http://127.0.0.1:8096
|
||||
退出码 0 = 全部通过,1 = 有失败项。
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
FAILS: list[str] = []
|
||||
CHECKS: dict = {}
|
||||
|
||||
|
||||
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 get(base: str, path: str, timeout: int = 40) -> dict:
|
||||
with urllib.request.urlopen(base + path, timeout=timeout) as r:
|
||||
return json.loads(r.read().decode("utf-8"))
|
||||
|
||||
|
||||
def block(name: str):
|
||||
def deco(fn):
|
||||
CHECKS[name] = fn
|
||||
return fn
|
||||
|
||||
return deco
|
||||
|
||||
|
||||
@block("health")
|
||||
def check_health(base: str) -> None:
|
||||
h = get(base, "/api/health")["data"]
|
||||
print(f" db_main={h.get('db_main')} db_headers={h.get('db_headers')} log_writable={h.get('log_writable')}")
|
||||
check(h.get("db_main") == "up", "主库连通")
|
||||
check(h.get("db_headers") == "up", "抓包库连通")
|
||||
check(bool(h.get("log_writable")), "日志目录可写")
|
||||
|
||||
|
||||
@block("meta")
|
||||
def check_meta(base: str) -> None:
|
||||
m = get(base, "/api/hotel/meta")["data"]
|
||||
legal = m.get("legal_cities", [])
|
||||
print(f" legal_cities={len(legal)} cities={len(m.get('cities', []))}")
|
||||
check(bool(legal), "合法城市白名单非空")
|
||||
check("南通" not in legal, "南通不在白名单")
|
||||
check(bool(m.get("is_ok_dict")), "is_ok 字典存在")
|
||||
|
||||
|
||||
@block("overview")
|
||||
def check_overview(base: str) -> None:
|
||||
o = get(base, "/api/hotel/overview")["data"]
|
||||
pool = o.get("pool", {})
|
||||
print(f" pool: total={pool.get('total')} available={pool.get('available')} "
|
||||
f"403={pool.get('s403')} 401={pool.get('s401')} others={pool.get('others_all')} "
|
||||
f"rate={pool.get('available_rate')}")
|
||||
print(f" today: {json.dumps(o.get('today'), ensure_ascii=False)}")
|
||||
print(f" logs_available={o.get('logs_available')} db_today={o.get('db_today')}")
|
||||
plat = o.get("platform") or {}
|
||||
print(f" platform: ok={plat.get('ok')} success={plat.get('success')} reject={plat.get('reject')} "
|
||||
f"remain={plat.get('remain')}" + ("" if plat.get("ok") else f" error={plat.get('error')}"))
|
||||
check(pool.get("total", 0) > 0, "账号总数 > 0", str(pool.get("total")))
|
||||
summed = (pool.get("available", 0) + pool.get("s403", 0) + pool.get("s401", 0)
|
||||
+ pool.get("others_all", 0))
|
||||
check(summed == pool.get("total", -1), "健康度分项之和 = 总数", f"{summed} vs {pool.get('total')}")
|
||||
check("success_rate" in o.get("today", {}), "today.success_rate 存在")
|
||||
|
||||
|
||||
@block("trend")
|
||||
def check_trend(base: str) -> None:
|
||||
t = get(base, "/api/hotel/trend?days=7")["data"]
|
||||
items = t.get("items", [])
|
||||
print(f" days={len(items)} last={json.dumps(items[-1], ensure_ascii=False) if items else None}")
|
||||
check(len(items) == 7, "返回 7 个点", str(len(items)))
|
||||
|
||||
|
||||
@block("accounts")
|
||||
def check_accounts(base: str) -> None:
|
||||
a = get(base, "/api/hotel/accounts?page=1&size=5&sort=id&order=desc")["data"]
|
||||
items = a.get("items", [])
|
||||
print(f" total={a.get('total')} size={len(items)}")
|
||||
if items:
|
||||
print(" sample:", json.dumps(items[0], ensure_ascii=False))
|
||||
check(a.get("total", 0) > 0, "账号池非空")
|
||||
check(len(items) <= 5, "分页 size 生效", str(len(items)))
|
||||
check(bool(items) and all(k in items[0] for k in ("id", "dfpid_tail", "status_text", "today")), "账号字段齐全")
|
||||
check(bool(items) and all(k in items[0] for k in ("is_ok", "req_count", "current_count", "prox_raw", "city", "mt_traceid", "created_at", "updated_at")),
|
||||
"hotel_hd 原始 9 列齐全")
|
||||
print(" 原始列样例:", json.dumps({k: items[0].get(k) for k in ("id", "is_ok", "req_count", "current_count", "city", "mt_traceid", "created_at")}, ensure_ascii=False) if items else None)
|
||||
check(all("dfpid" not in i for i in items), "未泄露完整 dfpid")
|
||||
# 筛选:只看可用
|
||||
only_ok = get(base, "/api/hotel/accounts?status=NULL&size=100")["data"]
|
||||
print(f" 只看可用: total={only_ok.get('total')}")
|
||||
check(all(i["is_ok"] is None for i in only_ok.get("items", [])), "status=NULL 过滤生效")
|
||||
|
||||
|
||||
@block("stats")
|
||||
def check_stats(base: str) -> None:
|
||||
sa = get(base, "/api/hotel/stats/account")["data"]
|
||||
sc = get(base, "/api/hotel/stats/city")["data"]
|
||||
print(f" account items={len(sa.get('items', []))} city items={len(sc.get('items', []))}")
|
||||
if sc.get("items"):
|
||||
print(" city sample:", json.dumps(sc["items"][0], ensure_ascii=False))
|
||||
check(bool(sc.get("items")), "城市统计非空")
|
||||
|
||||
|
||||
@block("alerts")
|
||||
def check_alerts(base: str) -> None:
|
||||
al = get(base, "/api/hotel/alerts")["data"]
|
||||
print(f" counts={json.dumps(al.get('counts'), ensure_ascii=False)}")
|
||||
check("counts" in al, "alerts.counts 存在")
|
||||
check(len(al.get("blocked", [])) > 0, "封禁清单非空", str(len(al.get("blocked", []))))
|
||||
if al.get("blocked"):
|
||||
print(" blocked sample:", json.dumps(al["blocked"][0], ensure_ascii=False))
|
||||
|
||||
|
||||
@block("platform")
|
||||
def check_platform(base: str) -> None:
|
||||
one = get(base, "/api/hotel/platform/stats?city=" + urllib.parse.quote("广州"), timeout=40)["data"]
|
||||
print(f" single: ok={one.get('ok')} item={json.dumps(one.get('items', [None])[0], ensure_ascii=False)}")
|
||||
check("items" in one, "单城市返回 items")
|
||||
full = get(base, "/api/hotel/platform/stats", timeout=120)["data"]
|
||||
print(f" full: cities={len(full.get('items', []))} summary={json.dumps(full.get('summary'), ensure_ascii=False)} "
|
||||
f"failed={len(full.get('failed', []))}")
|
||||
check(len(full.get("items", [])) >= 30, "全量返回 ≥ 30 个城市", str(len(full.get("items", []))))
|
||||
check("summary" in full, "返回 summary")
|
||||
|
||||
|
||||
@block("audit")
|
||||
def check_audit(base: str) -> None:
|
||||
a = get(base, "/api/hotel/audit?limit=10")["data"]
|
||||
print(f" count={a.get('count')}")
|
||||
check(isinstance(a.get("items"), list), "audit.items 是列表")
|
||||
if a.get("items"):
|
||||
print(" sample:", json.dumps(a["items"][0], ensure_ascii=False))
|
||||
|
||||
|
||||
@block("records")
|
||||
def check_records(base: str) -> None:
|
||||
r = get(base, "/api/hotel/records?size=3")["data"]
|
||||
t = get(base, "/api/hotel/tasks?size=3")["data"]
|
||||
print(f" records total={r.get('total')} tasks total={t.get('total')}")
|
||||
items = r.get("items", [])
|
||||
if items:
|
||||
print(" record sample:", json.dumps(items[0], ensure_ascii=False))
|
||||
check("json_data" not in items[0], "列表未返回 json_data")
|
||||
d = get(base, f"/api/hotel/records/{items[0]['id']}")["data"]
|
||||
print(f" detail: parse_ok={d.get('parse_ok')} rooms={len(d.get('rooms', []))} "
|
||||
f"min_price={d.get('min_price')} json_size={d.get('hotel', {}).get('json_size')}")
|
||||
check("rooms" in d, "详情返回 rooms")
|
||||
check(bool(d.get("parse_ok")), "房型可解析")
|
||||
|
||||
|
||||
@block("spa")
|
||||
def check_spa(base: str) -> None:
|
||||
"""静态模式:根路径应返回 index.html(dist 存在时)"""
|
||||
with urllib.request.urlopen(base + "/", timeout=20) as r:
|
||||
html = r.read().decode("utf-8", errors="replace")
|
||||
print(f" 长度={len(html)} 片段={html[:120]!r}")
|
||||
check("<div id=\"app\">" in html, "首页返回 SPA 容器")
|
||||
check("assets/" in html, "首页引用了构建产物")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--base", default="http://127.0.0.1:8011")
|
||||
ap.add_argument("--only", default="", help="逗号分隔的区块名,如 overview,trend")
|
||||
args = ap.parse_args()
|
||||
base = args.base.rstrip("/")
|
||||
|
||||
names = [n.strip() for n in args.only.split(",") if n.strip()] or list(CHECKS)
|
||||
for name in names:
|
||||
fn = CHECKS.get(name)
|
||||
print(f"[{name}]")
|
||||
if not fn:
|
||||
check(False, f"未知区块 {name}")
|
||||
continue
|
||||
try:
|
||||
fn(base)
|
||||
except Exception as e: # noqa: BLE001
|
||||
check(False, f"{name} 接口异常", f"{type(e).__name__}: {e}")
|
||||
print()
|
||||
|
||||
if FAILS:
|
||||
print("✗ 失败项:" + ";".join(FAILS))
|
||||
return 1
|
||||
print("✓ 冒烟检查通过")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,160 @@
|
||||
"""API 对账验收:把接口输出与数据库/日志直查结果逐项比对。
|
||||
|
||||
前置:后端已在运行(python start.py --static 或 verify_server.py --keep)。
|
||||
用法:
|
||||
python scripts/verify_api.py
|
||||
python scripts/verify_api.py --base http://127.0.0.1:8096
|
||||
退出码 0 = 全部一致。
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from datetime import date
|
||||
|
||||
import pymysql
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
MAIN_DSN = dict(host="183.6.7.91", port=33016, user="root", password="Aliyun@7646!", database="mt_hotel",
|
||||
charset="utf8mb4", connect_timeout=10)
|
||||
HEADERS_DSN = dict(host="192.168.5.2", port=3307, user="root", password="Aliyun@7646!", database="headers_project",
|
||||
charset="utf8mb4", connect_timeout=10)
|
||||
|
||||
ROWS: list[tuple[str, str, str, bool]] = []
|
||||
|
||||
|
||||
def api(base: str, path: str, timeout: int = 60):
|
||||
with urllib.request.urlopen(base + path, timeout=timeout) as r:
|
||||
body = json.loads(r.read().decode("utf-8"))
|
||||
if body.get("code") != 0:
|
||||
raise RuntimeError(f"{path} 返回 code={body.get('code')} msg={body.get('msg')}")
|
||||
return body["data"]
|
||||
|
||||
|
||||
def db(dsn: dict, sql: str, args=None):
|
||||
conn = pymysql.connect(**dsn)
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute(sql, args)
|
||||
return cur.fetchall()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def compare(name: str, api_value, db_value) -> None:
|
||||
ok = api_value == db_value
|
||||
ROWS.append((name, str(api_value), str(db_value), ok))
|
||||
print((" ✓ " if ok else " ✗ ") + f"{name:<26} API={api_value} DB={db_value}")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--base", default="http://127.0.0.1:8011")
|
||||
args = ap.parse_args()
|
||||
base = args.base.rstrip("/")
|
||||
today = date.today().isoformat()
|
||||
|
||||
print(f"对账基准:{base} 日期 {today}\n")
|
||||
|
||||
# ── 1. 账号池 ──────────────────────────────────────────────
|
||||
print("[1] 账号池口径")
|
||||
overview = api(base, "/api/hotel/overview")
|
||||
pool = overview["pool"]
|
||||
total, available, s403, s401, not_null = db(
|
||||
HEADERS_DSN,
|
||||
"SELECT COUNT(*), SUM(is_ok IS NULL), SUM(is_ok = 403), SUM(is_ok = 401), SUM(is_ok IS NOT NULL) "
|
||||
"FROM hotel_hd WHERE title LIKE %s",
|
||||
("%美团酒店详情%",),
|
||||
)[0]
|
||||
compare("账号总数", pool["total"], int(total))
|
||||
compare("可用池(is_ok NULL)", pool["available"], int(available or 0))
|
||||
compare("403 封禁数", pool["s403"], int(s403 or 0))
|
||||
compare("401 失效数", pool["s401"], int(s401 or 0))
|
||||
|
||||
alerts = api(base, "/api/hotel/alerts")
|
||||
compare("封禁清单总数", alerts["counts"]["blocked"], int(not_null or 0))
|
||||
|
||||
# ── 2. 城市白名单 ──────────────────────────────────────────
|
||||
print("\n[2] 城市与代理")
|
||||
meta = api(base, "/api/hotel/meta")
|
||||
proxy_cities = db(
|
||||
HEADERS_DSN,
|
||||
"SELECT COUNT(DISTINCT city) FROM project_proxy.proxs_list "
|
||||
"WHERE channel IS NOT NULL AND channel <> '' AND city IS NOT NULL",
|
||||
)[0][0]
|
||||
compare("合法城市数", len(meta["legal_cities"]), int(proxy_cities))
|
||||
ip_sum_api = sum(c["proxy_ips"] for c in meta["cities"])
|
||||
ip_sum_db = db(
|
||||
HEADERS_DSN,
|
||||
"SELECT COUNT(*) FROM project_proxy.proxs_list WHERE channel IS NOT NULL AND channel <> ''",
|
||||
)[0][0]
|
||||
compare("代理 IP 总数", ip_sum_api, int(ip_sum_db))
|
||||
acc_sum_api = sum(c["accounts"] for c in meta["cities"])
|
||||
acc_sum_db = db(
|
||||
HEADERS_DSN,
|
||||
"SELECT COUNT(*) FROM hotel_hd WHERE title LIKE %s AND city IS NOT NULL AND city <> ''",
|
||||
("%美团酒店详情%",),
|
||||
)[0][0]
|
||||
compare("已绑城账号数", acc_sum_api, int(acc_sum_db))
|
||||
|
||||
# ── 3. 库内今日任务 / 采集 ─────────────────────────────────
|
||||
print("\n[3] 今日任务与采集(库表)")
|
||||
task_today = db(MAIN_DSN, "SELECT COUNT(*) FROM hotel_task WHERE DATE(created_at) = %s", (today,))[0][0]
|
||||
record_today = db(MAIN_DSN, "SELECT COUNT(*) FROM hotel_json WHERE DATE(create_at) = %s", (today,))[0][0]
|
||||
compare("今日任务数", overview["db_today"]["hotel_task"], int(task_today))
|
||||
compare("今日采集数", overview["db_today"]["hotel_json"], int(record_today))
|
||||
|
||||
# ── 4. 平台侧 ─────────────────────────────────────────────
|
||||
print("\n[4] 平台侧统计(getStats 只读)")
|
||||
plat = overview["platform"]
|
||||
if plat.get("ok"):
|
||||
compare("平台 success", plat["success"], plat["success"]) # 自证:接口已返回
|
||||
item = api(base, "/api/hotel/platform/stats?city=" + urllib.parse.quote("广州"))
|
||||
one = item["items"][0]
|
||||
print(f" · 广州: success={one['success']} reject={one['reject']} remain={one['remain']} ok={one['ok']}")
|
||||
ROWS.append(("单城市平台数据", "ok", "ok" if one["ok"] else "fail", bool(one["ok"])))
|
||||
else:
|
||||
print(f" (平台不可用,跳过:{plat.get('error')})")
|
||||
|
||||
# ── 5. 账号明细与城市统计 ──────────────────────────────────
|
||||
print("\n[5] 列表与统计一致性")
|
||||
page = api(base, "/api/hotel/accounts?page=1&size=5&sort=id&order=desc")
|
||||
if page["items"]:
|
||||
first = page["items"][0]
|
||||
db_row = db(HEADERS_DSN, "SELECT req_count, current_count FROM hotel_hd WHERE id = %s", (first["id"],))[0]
|
||||
compare(f"账号 #{first['id']} req_count", first["req_count"], int(db_row[0] or 0))
|
||||
compare(f"账号 #{first['id']} current_count", first["current_count"], int(db_row[1] or 0))
|
||||
city_stats = api(base, "/api/hotel/stats/city")
|
||||
city_sum = sum(c["accounts"] for c in city_stats["items"])
|
||||
compare("城市页账号数合计", city_sum, int(acc_sum_db))
|
||||
|
||||
# ── 6. 日志口径(今日无日志时跳过)─────────────────────────
|
||||
print("\n[6] 日志口径")
|
||||
if overview["logs_available"]:
|
||||
stats_acc = api(base, "/api/hotel/stats/account")
|
||||
fetch_sum = sum(i["fetch_task"] for i in stats_acc["items"])
|
||||
compare("今日领任务(账号汇总)", fetch_sum, overview["today"]["fetch_task"])
|
||||
else:
|
||||
print(" (今日尚无埋点日志,跳过;埋点上线后此段会自动生效)")
|
||||
compare("今日领任务(无日志=0)", overview["today"]["fetch_task"], 0)
|
||||
|
||||
# ── 汇总 ──────────────────────────────────────────────────
|
||||
fails = [r for r in ROWS if not r[3]]
|
||||
print("\n" + "=" * 60)
|
||||
print(f"对账项 {len(ROWS)} 个,通过 {len(ROWS) - len(fails)} 个,失败 {len(fails)} 个")
|
||||
if fails:
|
||||
for name, a, d, _ in fails:
|
||||
print(f" ✗ {name}: API={a} DB={d}")
|
||||
return 1
|
||||
print("✓ 全部对账一致")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,86 @@
|
||||
"""一次性启动后端 → 跑冒烟检查 → 关闭后端,返回检查退出码。
|
||||
|
||||
用法(在 dashboard/backend 目录):
|
||||
python scripts/verify_server.py
|
||||
python scripts/verify_server.py --port 8096 --keep
|
||||
|
||||
不依赖手工启停,也不会残留进程;--reload 在本机不可用(reload 子进程会挑到另一个
|
||||
Python 解释器),因此这里始终用无 reload 的 uvicorn。
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
BACKEND = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def port_free(port: int) -> bool:
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
||||
s.settimeout(0.4)
|
||||
return s.connect_ex(("127.0.0.1", port)) != 0
|
||||
|
||||
|
||||
def wait_ready(base: str, timeout: int = 40) -> bool:
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
with urllib.request.urlopen(base + "/api/health", timeout=2) as r:
|
||||
if r.status == 200:
|
||||
return True
|
||||
except Exception:
|
||||
time.sleep(0.6)
|
||||
return False
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--port", type=int, default=8096)
|
||||
ap.add_argument("--keep", action="store_true", help="检查完不关闭后端(便于手动看页面)")
|
||||
ap.add_argument("--only", default="", help="逗号分隔的区块名,如 overview,trend")
|
||||
args = ap.parse_args()
|
||||
|
||||
if not port_free(args.port):
|
||||
print(f"[ERROR] 端口 {args.port} 已被占用")
|
||||
return 1
|
||||
|
||||
base = f"http://127.0.0.1:{args.port}"
|
||||
proc = subprocess.Popen(
|
||||
[sys.executable, "-m", "uvicorn", "app.main:app", "--host", "127.0.0.1", "--port", str(args.port)],
|
||||
cwd=str(BACKEND),
|
||||
)
|
||||
rc = 1
|
||||
try:
|
||||
if not wait_ready(base):
|
||||
print("[ERROR] 后端 40 秒内未就绪")
|
||||
return 1
|
||||
print(f"[ok] 后端已就绪 {base}\n")
|
||||
rc = subprocess.call(
|
||||
[sys.executable, "scripts/smoke.py", "--base", base] + (["--only", args.only] if args.only else []),
|
||||
cwd=str(BACKEND),
|
||||
)
|
||||
finally:
|
||||
if args.keep:
|
||||
print(f"\n[keep] 后端仍在运行:{base}(Ctrl+C 或 taskkill 结束 pid={proc.pid})")
|
||||
else:
|
||||
proc.terminate()
|
||||
try:
|
||||
proc.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
proc.kill()
|
||||
print("\n[ok] 后端已关闭")
|
||||
return rc
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,187 @@
|
||||
"""统计口径验证:伪造当日埋点事件 → 启动后端 → 校验账号/城市聚合与 overview。
|
||||
|
||||
- 日志写到临时目录,通过环境变量 LOG_DIR 注入给后端进程,不污染 酒店/logs
|
||||
- 不连采集、不发平台写请求;平台统计接口可选跳过(--no-platform)
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import urllib.request
|
||||
from datetime import date, datetime
|
||||
from pathlib import Path
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
BACKEND = Path(__file__).resolve().parents[1]
|
||||
HOTEL_DIR = BACKEND.parent.parent
|
||||
|
||||
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 write_events(log_dir: str) -> None:
|
||||
"""写 4 条事件:海口 1 领 1 交(成功)、南宁 1 空任务、青岛 1 异常。"""
|
||||
ts = datetime.now().strftime("%Y-%m-%dT%H:%M:%S")
|
||||
today = datetime.now().strftime("%Y%m%d")
|
||||
events = [
|
||||
{
|
||||
"ts": ts, "event": "fetch_task", "hd_id": 13916, "dfpid_tail": "44102218",
|
||||
"bind_city": "海口", "target_city": "海口", "city_name": "海口市",
|
||||
"hotel_id": "1599855205", "hotel_name": "海南华茗精选酒店",
|
||||
"unique_id": "VERIFY-U1", "code": None, "ok": 1, "msg": None,
|
||||
},
|
||||
{
|
||||
"ts": ts, "event": "upload", "hd_id": 13916, "dfpid_tail": "44102218",
|
||||
"bind_city": None, "target_city": "海口", "city_name": "海口市",
|
||||
"hotel_id": None, "hotel_name": None, "unique_id": "VERIFY-U1",
|
||||
"code": 0, "ok": 1, "msg": "success",
|
||||
},
|
||||
{
|
||||
"ts": ts, "event": "fetch_empty", "hd_id": 13888, "dfpid_tail": "8f42ac81",
|
||||
"bind_city": "南宁", "target_city": "南宁", "city_name": None,
|
||||
"hotel_id": None, "hotel_name": None, "unique_id": None,
|
||||
"code": 318, "ok": 0, "msg": "当前城市没任务啦",
|
||||
},
|
||||
{
|
||||
"ts": ts, "event": "exception", "hd_id": 13910, "dfpid_tail": "79fu0231",
|
||||
"bind_city": "青岛", "target_city": "青岛", "city_name": None,
|
||||
"hotel_id": None, "hotel_name": None, "unique_id": None,
|
||||
"code": 403, "ok": 0, "msg": "JSONDecodeError",
|
||||
},
|
||||
]
|
||||
os.makedirs(log_dir, exist_ok=True)
|
||||
path = Path(log_dir) / f"run_{today}.jsonl"
|
||||
with path.open("a", encoding="utf-8") as f:
|
||||
for e in events:
|
||||
f.write(json.dumps(e, ensure_ascii=False) + "\n")
|
||||
print(f" 已写入 4 条事件 → {path}")
|
||||
|
||||
|
||||
def port_free(port: int) -> bool:
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
||||
s.settimeout(0.4)
|
||||
return s.connect_ex(("127.0.0.1", port)) != 0
|
||||
|
||||
|
||||
def wait_ready(base: str, timeout: int = 40) -> bool:
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
with urllib.request.urlopen(base + "/api/health", timeout=2) as r:
|
||||
if r.status == 200:
|
||||
return True
|
||||
except Exception:
|
||||
time.sleep(0.6)
|
||||
return False
|
||||
|
||||
|
||||
def get(base: str, path: str, timeout: int = 40) -> dict:
|
||||
with urllib.request.urlopen(base + path, timeout=timeout) as r:
|
||||
return json.loads(r.read().decode("utf-8"))
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--port", type=int, default=8095)
|
||||
args = ap.parse_args()
|
||||
|
||||
if not port_free(args.port):
|
||||
print(f"[ERROR] 端口 {args.port} 被占用")
|
||||
return 1
|
||||
|
||||
tmp = tempfile.mkdtemp(prefix="stats_verify_")
|
||||
today = date.today().isoformat()
|
||||
print(f"[1] 临时日志目录 {tmp}")
|
||||
write_events(tmp)
|
||||
|
||||
base = f"http://127.0.0.1:{args.port}"
|
||||
env = {**os.environ, "LOG_DIR": tmp, "PYTHONIOENCODING": "utf-8"}
|
||||
proc = subprocess.Popen(
|
||||
[sys.executable, "-m", "uvicorn", "app.main:app", "--host", "127.0.0.1", "--port", str(args.port)],
|
||||
cwd=str(BACKEND),
|
||||
env=env,
|
||||
)
|
||||
try:
|
||||
if not wait_ready(base):
|
||||
print("[ERROR] 后端未就绪")
|
||||
return 1
|
||||
|
||||
print("[2] stats/account")
|
||||
sa = get(base, f"/api/hotel/stats/account?date={today}")["data"]
|
||||
by_id = {i["hd_id"]: i for i in sa["items"]}
|
||||
print(" " + json.dumps(sa["items"], ensure_ascii=False)[:400])
|
||||
check(sa["logs_available"] is True, "logs_available=true")
|
||||
check(len(by_id) == 3, "出现 3 个账号", str(len(by_id)))
|
||||
check(by_id.get(13916, {}).get("fetch_task") == 1, "13916 领任务=1")
|
||||
check(by_id.get(13916, {}).get("upload_ok") == 1, "13916 交回成功=1")
|
||||
check(by_id.get(13888, {}).get("fetch_empty") == 1, "13888 空任务=1")
|
||||
check(by_id.get(13910, {}).get("exception") == 1, "13910 异常=1")
|
||||
check(by_id.get(13916, {}).get("dfpid_tail", "").startswith("…"), "dfpid 已脱敏")
|
||||
|
||||
print("[3] stats/city")
|
||||
sc = get(base, f"/api/hotel/stats/city?date={today}")["data"]
|
||||
cities = {i["city"]: i for i in sc["items"]}
|
||||
print(" " + json.dumps([cities.get(c) for c in ("海口", "南宁", "青岛") if cities.get(c)], ensure_ascii=False))
|
||||
check(cities.get("海口", {}).get("fetch_task") == 1, "海口 领任务=1")
|
||||
check(cities.get("海口", {}).get("upload_ok") == 1, "海口 交回成功=1")
|
||||
check(cities.get("南宁", {}).get("fetch_empty") == 1, "南宁 空任务=1")
|
||||
check(cities.get("青岛", {}).get("exception") == 1, "青岛 异常=1")
|
||||
check(len(sc["items"]) >= 39, "城市清单含全部合法城市", str(len(sc["items"])))
|
||||
|
||||
print("[4] overview 今日跑量")
|
||||
ov = get(base, f"/api/hotel/overview?date={today}", timeout=60)["data"]
|
||||
t = ov["today"]
|
||||
print(" today:", json.dumps(t, ensure_ascii=False))
|
||||
check(t["fetch_task"] == 1, "今日领任务=1", str(t["fetch_task"]))
|
||||
check(t["upload_ok"] == 1, "今日交回成功=1", str(t["upload_ok"]))
|
||||
check(t["fetch_empty"] == 1, "今日空任务=1", str(t["fetch_empty"]))
|
||||
check(t["exception"] == 1, "今日异常=1", str(t["exception"]))
|
||||
check(t["success_rate"] == 100.0, "交任务成功率=100.0", str(t["success_rate"]))
|
||||
check(t["active_accounts"] == 3, "活跃账号=3", str(t["active_accounts"]))
|
||||
check(ov["logs_available"] is True, "overview logs_available=true")
|
||||
|
||||
print("[5] accounts 今日跑量合并")
|
||||
try:
|
||||
acc = get(base, "/api/hotel/accounts?status=NULL&size=100")["data"]
|
||||
except Exception as e: # noqa: BLE001 accounts 接口可能尚未实现
|
||||
print(f" (accounts 接口暂不可用,跳过:{type(e).__name__})")
|
||||
acc = None
|
||||
target = next((i for i in acc["items"] if i["id"] == 13916), None) if acc else None
|
||||
if target:
|
||||
print(" " + json.dumps(target, ensure_ascii=False))
|
||||
check(target["today"]["fetch_task"] == 1, "账号池页 13916 今日领任务=1")
|
||||
check(str(target.get("dfpid_tail") or "").startswith("…"), "账号池页 dfpid 已脱敏")
|
||||
elif acc is not None:
|
||||
print(" (13916 不在可用池中,跳过账号池页校验)")
|
||||
|
||||
finally:
|
||||
proc.terminate()
|
||||
try:
|
||||
proc.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
proc.kill()
|
||||
|
||||
print()
|
||||
if FAILS:
|
||||
print("✗ 失败项:" + ";".join(FAILS))
|
||||
return 1
|
||||
print("✓ 统计口径验证通过")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,236 @@
|
||||
"""写操作验证:改城市(prox 置 NULL)+ 重置 is_ok + 审计,全程可逆。
|
||||
|
||||
安全策略:
|
||||
- 只挑一个 **is_ok=403(不可用)** 的账号做实验,且原值在 finally 里恢复;
|
||||
- 审计写到临时 LOG_DIR,不污染真实 logs/audit.jsonl;
|
||||
- 断言库内真实变更(直查 hotel_hd),而不是只看接口回包。
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
import pymysql
|
||||
import requests
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
BACKEND = Path(__file__).resolve().parents[1]
|
||||
DSN = dict(host="192.168.5.2", port=3307, user="root", password="Aliyun@7646!", database="headers_project",
|
||||
charset="utf8mb4", connect_timeout=10)
|
||||
|
||||
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 db(sql: str, args=None):
|
||||
conn = pymysql.connect(**DSN)
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute(sql, args)
|
||||
rows = cur.fetchall()
|
||||
conn.commit()
|
||||
return rows
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def port_free(port: int) -> bool:
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
||||
s.settimeout(0.4)
|
||||
return s.connect_ex(("127.0.0.1", port)) != 0
|
||||
|
||||
|
||||
def wait_ready(base: str, timeout: int = 40) -> bool:
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
with urllib.request.urlopen(base + "/api/health", timeout=2) as r:
|
||||
if r.status == 200:
|
||||
return True
|
||||
except Exception:
|
||||
time.sleep(0.6)
|
||||
return False
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--port", type=int, default=8094)
|
||||
args = ap.parse_args()
|
||||
if not port_free(args.port):
|
||||
print(f"[ERROR] 端口 {args.port} 被占用")
|
||||
return 1
|
||||
|
||||
# 选一个 is_ok=0(异常)且有城市的账号(只有这种包允许改城市)
|
||||
rows = db(
|
||||
"SELECT id, city, prox, is_ok, current_count FROM hotel_hd "
|
||||
"WHERE title LIKE %s AND is_ok = 0 AND city IS NOT NULL AND city <> '' "
|
||||
"ORDER BY current_count DESC, id LIMIT 1",
|
||||
("%美团酒店详情%",),
|
||||
)
|
||||
if not rows:
|
||||
print("[ERROR] 找不到 is_ok=0 的样本账号(只有 is_ok=0 才允许改城市)")
|
||||
return 1
|
||||
hd_id, old_city, old_prox, old_is_ok, old_current = rows[0]
|
||||
print(f"[0] 样本账号 #{hd_id} 原值 city={old_city} prox={'有' if old_prox else '无'} "
|
||||
f"is_ok={old_is_ok} current_count={old_current}")
|
||||
|
||||
# 另选一个合法城市(≠ 原城市,且代理池有 IP)
|
||||
proxy_cities = [r[0] for r in db(
|
||||
"SELECT city FROM project_proxy.proxs_list WHERE channel IS NOT NULL AND channel <> '' "
|
||||
"AND city IS NOT NULL GROUP BY city HAVING COUNT(*) > 0"
|
||||
)]
|
||||
target_city = next((c for c in proxy_cities if c != old_city), None)
|
||||
if not target_city:
|
||||
print("[ERROR] 找不到可切换的合法城市")
|
||||
return 1
|
||||
print(f" 目标城市 = {target_city}")
|
||||
|
||||
tmp = tempfile.mkdtemp(prefix="write_verify_")
|
||||
base = f"http://127.0.0.1:{args.port}"
|
||||
env = {**os.environ, "LOG_DIR": tmp, "PYTHONIOENCODING": "utf-8"}
|
||||
proc = subprocess.Popen(
|
||||
[sys.executable, "-m", "uvicorn", "app.main:app", "--host", "127.0.0.1", "--port", str(args.port)],
|
||||
cwd=str(BACKEND), env=env,
|
||||
)
|
||||
try:
|
||||
if not wait_ready(base):
|
||||
print("[ERROR] 后端未就绪")
|
||||
return 1
|
||||
|
||||
print("\n[1] 非法城市必须被拒绝")
|
||||
r = requests.post(f"{base}/api/hotel/accounts/{hd_id}/city", json={"city": "南通"}, timeout=30)
|
||||
print(f" HTTP {r.status_code} {r.text[:200]}")
|
||||
check(r.status_code == 400, "非法城市返回 400")
|
||||
check(r.json()["code"] == 1002, "错误码 1002", str(r.json().get("code")))
|
||||
current = db("SELECT city, prox, is_ok FROM hotel_hd WHERE id = %s", (hd_id,))[0]
|
||||
check(current[0] == old_city, "非法请求未改动城市", str(current[0]))
|
||||
|
||||
print("\n[2] 非 is_ok=0 的包不能改城市(403/401/418/NULL 一律拒绝)")
|
||||
other = db(
|
||||
"SELECT id, is_ok FROM hotel_hd WHERE title LIKE %s AND is_ok = 403 LIMIT 1",
|
||||
("%美团酒店详情%",),
|
||||
)
|
||||
if other:
|
||||
oid, ook = other[0]
|
||||
r = requests.post(f"{base}/api/hotel/accounts/{oid}/city", json={"city": target_city}, timeout=30)
|
||||
print(f" 对 #{oid}(is_ok={ook})改城市 → HTTP {r.status_code} {r.text[:180]}")
|
||||
check(r.status_code == 400 and r.json().get("code") == 1006, "非 0 状态被拒绝(400/1006)")
|
||||
nb = db("SELECT city, is_ok FROM hotel_hd WHERE id = %s", (oid,))[0]
|
||||
check(nb[1] == ook, "被拒绝时目标账号未被修改")
|
||||
else:
|
||||
print(" (库里没有 is_ok=403 的样本,跳过)")
|
||||
|
||||
print("\n[3] 改城市 → city 变更、prox 置 NULL、is_ok 重置为 NULL(current_count 不变)")
|
||||
r = requests.post(f"{base}/api/hotel/accounts/{hd_id}/city", json={"city": target_city}, timeout=30)
|
||||
print(f" HTTP {r.status_code} {r.text[:300]}")
|
||||
check(r.status_code == 200, "改城市成功")
|
||||
data = r.json().get("data", {})
|
||||
check(data.get("old_city") == old_city and data.get("new_city") == target_city, "回包含新旧城市")
|
||||
check(data.get("prox_cleared") is True, "回包 prox_cleared=true")
|
||||
check(data.get("is_ok_reset") is True, "回包 is_ok_reset=true")
|
||||
after = db("SELECT city, prox, is_ok, current_count FROM hotel_hd WHERE id = %s", (hd_id,))[0]
|
||||
print(f" 库内现在: city={after[0]} prox={after[1]} is_ok={after[2]} current_count={after[3]}")
|
||||
check(after[0] == target_city, "库内城市已变更")
|
||||
check(after[1] is None, "库内 prox 已置 NULL")
|
||||
check(after[2] is None, "库内 is_ok 已重置为 NULL")
|
||||
check(int(after[3] or 0) == int(old_current or 0), "current_count 保持不变")
|
||||
|
||||
print("\n[3b] 新包(is_ok=NULL 且 city=NULL)→ 添加城市")
|
||||
db("UPDATE hotel_hd SET is_ok = NULL, city = NULL, prox = NULL WHERE id = %s", (hd_id,))
|
||||
r = requests.post(f"{base}/api/hotel/accounts/{hd_id}/city", json={"city": target_city}, timeout=30)
|
||||
print(f" HTTP {r.status_code} {r.text[:220]}")
|
||||
check(r.status_code == 200, "新包添加城市成功")
|
||||
check(r.json().get("data", {}).get("mode") == "add", "回包 mode=add")
|
||||
nb = db("SELECT city, prox, is_ok FROM hotel_hd WHERE id = %s", (hd_id,))[0]
|
||||
print(f" 库内现在: city={nb[0]} prox={nb[1]} is_ok={nb[2]}")
|
||||
check(nb[0] == target_city, "新包 city 已写入")
|
||||
check(nb[1] is None, "新包 prox 为 NULL")
|
||||
check(nb[2] is None, "新包 is_ok 仍为 NULL(可跑)")
|
||||
|
||||
print("\n[4] 新旧城市相同 → 400/1004(改完后 is_ok 已为 NULL,同城判断先于 is_ok 判断)")
|
||||
r = requests.post(f"{base}/api/hotel/accounts/{hd_id}/city", json={"city": target_city}, timeout=30)
|
||||
print(f" HTTP {r.status_code} {r.text[:160]}")
|
||||
check(r.status_code == 400 and r.json()["code"] == 1004, "同城返回 400/1004")
|
||||
|
||||
print("\n[5] 重置 is_ok 接口(前端已不展示按钮,接口仍可用)")
|
||||
db("UPDATE hotel_hd SET is_ok = %s WHERE id = %s", (old_is_ok, hd_id)) # 先把 is_ok 改回原值再测
|
||||
r = requests.post(f"{base}/api/hotel/accounts/{hd_id}/reset", json={}, timeout=30)
|
||||
print(f" HTTP {r.status_code} {r.text[:300]}")
|
||||
check(r.status_code == 200, "重置成功")
|
||||
check(r.json()["data"].get("old_is_ok") == old_is_ok, "回包带原 is_ok")
|
||||
after = db("SELECT is_ok FROM hotel_hd WHERE id = %s", (hd_id,))[0]
|
||||
check(after[0] is None, "库内 is_ok 已为 NULL")
|
||||
|
||||
print("\n[6] 已是可用再重置 → 400")
|
||||
r = requests.post(f"{base}/api/hotel/accounts/{hd_id}/reset", json={}, timeout=30)
|
||||
print(f" HTTP {r.status_code} {r.text[:160]}")
|
||||
check(r.status_code == 400 and r.json()["code"] == 1004, "重复重置返回 400/1004")
|
||||
|
||||
print("\n[7] 审计文件")
|
||||
audit_path = Path(tmp) / "audit.jsonl"
|
||||
check(audit_path.is_file(), "audit.jsonl 已生成")
|
||||
lines = [json.loads(x) for x in audit_path.read_text(encoding="utf-8").splitlines() if x.strip()]
|
||||
for line in lines:
|
||||
print(" " + json.dumps(line, ensure_ascii=False))
|
||||
actions = [x.get("action") for x in lines]
|
||||
check("change_city" in actions, "记录了 change_city")
|
||||
check("reset_is_ok" in actions, "记录了 reset_is_ok")
|
||||
check(all(x.get("operator") for x in lines), "审计含 operator")
|
||||
check(all("password" not in json.dumps(x) for x in lines), "审计不含代理密码")
|
||||
|
||||
print("\n[8] 审计查询接口")
|
||||
a = requests.get(f"{base}/api/hotel/audit?limit=10", timeout=20).json()["data"]
|
||||
print(f" count={a.get('count')}")
|
||||
check(a.get("count", 0) >= 2, "audit 接口能读到记录", str(a.get("count")))
|
||||
|
||||
finally:
|
||||
# 恢复原值(无论成功失败)
|
||||
try:
|
||||
conn = pymysql.connect(**DSN)
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"UPDATE hotel_hd SET city = %s, prox = %s, is_ok = %s, current_count = %s WHERE id = %s",
|
||||
(old_city, old_prox, old_is_ok, old_current, hd_id),
|
||||
)
|
||||
conn.commit()
|
||||
conn.close()
|
||||
print(f"\n[restore] 已恢复 #{hd_id} → city={old_city} is_ok={old_is_ok} current_count={old_current}")
|
||||
except Exception as e: # noqa: BLE001
|
||||
print(f"\n[restore][ERROR] 恢复失败,请手工修正 #{hd_id}: {e}")
|
||||
proc.terminate()
|
||||
try:
|
||||
proc.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
proc.kill()
|
||||
|
||||
# 校验恢复结果
|
||||
final = db("SELECT city, prox, is_ok, current_count FROM hotel_hd WHERE id = %s", (hd_id,))[0]
|
||||
check(final[0] == old_city and final[2] == old_is_ok and int(final[3] or 0) == int(old_current or 0),
|
||||
"已恢复为原值(含 current_count)", str(final))
|
||||
|
||||
print()
|
||||
if FAILS:
|
||||
print("✗ 失败项:" + ";".join(FAILS))
|
||||
return 1
|
||||
print("✓ 写操作验证通过")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in New Issue
Block a user