unis-oa/backend/scripts/check_notify_hub.py

750 lines
40 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#!/usr/bin/env python3
"""守 Hub 企业微信推送(``app/service/channels.py`` 的 ``hub_*`` 那一层)。
对接口径是对接文档 9.6:OA 只调 Hub 一次 HTTP,Hub 负责换成企业微信的应用消息、
认点击人的身份、再签一张一次性票据把人送回 OA。**OA 不持有企微密钥**,所以这一路
最容易做错的四件事全在 OA 这一侧,本脚本用一台**进程内的假 Hub** 逐条钉住::
cd backend && PYTHONPATH=. python3 scripts/check_notify_hub.py
1. **预算**:Hub 对超长是 400 硬拒(整批没人收到),不是替你截断——标题、正文、
markdown 字节数都得自己先卡住;
2. **幂等键**:``msg_key`` 必须跨重试不变(超时才能原样重发),而"已投出去之后人工
补发"必须换世代(同键只会命中 Hub 的缓存,人不会重复收到,运维却以为发了);
3. **逐人结果才算数**:HTTP 200 + ``code=="200"`` 只代表 Hub 听懂了,这个人收到没有
要看 ``recipients[].status`` / ``reason``,并按原因分档(重试 / 跳过 / 死信);
``sent/partial/failed``、``duplicate``、``403 开关没开``、``409 还在发送中``、
``5xx 可重试`` 一层层都要落对;
4. **深链是相对路径**:``target_path`` 绝不能带域名——Hub 按登记的 ``home_url`` 在
点击时刻现拼,写死域名等于把域名焊进一条永久有效的链接里。
5. **深链还得认人**:``/todo/<task>`` 是个人页面,而 ``engine.notify()`` 对整批收件人
只传一个 ``task=``;一人一条入队时必须按人分,旁人退回 ``/work/<job>``。
6. **Hub 拼不出深链时别把消息丢掉**:Hub 应用没登记 ``home_url`` 时,带 ``target_path``
的请求是整条 400(一个人收不到);本系统摘掉深链、换个键再发一次纯提醒。其它参数类
400 不许瞎降级,照旧判死、照旧只打一次。
不连库、不打真 Hub、不写任何配置。
"""
from __future__ import annotations
import json
import sys
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from types import SimpleNamespace
from typing import Any
from app import hubconfig, models
from app.service import channels
# ---------------------------------------------------------------------------
# 假 Hub:记请求、按脚本回包
# ---------------------------------------------------------------------------
class FakeHub:
"""按脚本回包的假 Hub。``script`` 是 ``(status, payload)`` 的队列,取完用最后一个。"""
def __init__(self) -> None:
self.requests: list[dict[str, Any]] = []
self.script: list[tuple[int, dict[str, Any]]] = []
hub = self
class Handler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def do_POST(self): # noqa: N802
self._handle("POST")
def do_GET(self): # noqa: N802
self._handle("GET")
def _handle(self, method: str) -> None:
length = int(self.headers.get("Content-Length") or 0)
raw = self.rfile.read(length) if length else b""
try:
body = json.loads(raw.decode("utf-8")) if raw else None
except ValueError:
body = raw.decode("utf-8", "replace")
hub.requests.append({
"method": method,
"path": self.path,
"key": self.headers.get("X-Integration-Key") or "",
"body": body,
})
status, payload = hub.script.pop(0) if len(hub.script) > 1 else (
hub.script[0] if hub.script else (200, {"code": "200", "data": {}}))
data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def log_message(self, *args): # 别往 stdout 上刷屏
return
self.server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
self.thread.start()
@property
def base_url(self) -> str:
host, port = self.server.server_address[:2]
return f"http://{host}:{port}"
@property
def last(self) -> dict[str, Any]:
return self.requests[-1]
def close(self) -> None:
self.server.shutdown()
self.server.server_close()
def envelope(**data) -> tuple[int, dict[str, Any]]:
return 200, {"code": "200", "message": "success", "data": data}
def rejected(status: int, code: str, message: str = "示例文案") -> tuple[int, dict[str, Any]]:
"""请求级被拒:HTTP 状态码 + 信封里的 code,``data`` 是 null(文档 9.6.4)。"""
return status, {"code": code, "message": message, "data": None}
def hub_data(**overrides) -> dict[str, Any]:
"""一次投递的标准回执:一个人、投出去了。"""
data = {
"msg_key": "oa-x",
"status": "sent",
"grant": "a" * 24,
"link": "https://hub.example.com/auth/go/" + "a" * 24,
"attempt": 1,
"sent_at": "2026-11-04T06:00:00Z",
"recipients": [{"receiver": "10086", "user_id": 10086,
"wecom_userid": "zhangsan", "status": "sent"}],
}
data.update(overrides)
return data
def failed(reason: str, receiver: str = "10086") -> tuple[int, dict[str, Any]]:
return envelope(**hub_data(
status="failed", link="", grant="",
recipients=[{"receiver": receiver, "status": "failed", "reason": reason}],
))
# ---------------------------------------------------------------------------
# 不打库的桩:配置、库会话、人员
# ---------------------------------------------------------------------------
class StubConfig:
"""够用就好的 HubConfig:只给这一路真会读到的那几项。"""
def __init__(self, base_url: str, key: str = "test-key") -> None:
self.hub_base_url = base_url
self.hub_integration_key = key
self.hub_enabled = True
self.forced_off = False
self.hub_timeout_seconds = 5
self.hub_breaker_seconds = 0
self.hub_max_inflight = 0
self.hub_path_notify_wecom = "/api/v1/auth/notify/wecom/messages"
self.hub_app_code = "oa"
#: 「免登必须校验 state」:开着它,卡片点开那一路(不带 state)会被拒
self.hub_sso_state_required = False
@property
def api_paths(self) -> dict[str, str]:
return {"notify_wecom": self.hub_path_notify_wecom}
@property
def notify_on(self) -> bool:
return bool(self.hub_enabled and self.hub_base_url and self.hub_integration_key.strip())
@property
def notify_missing(self) -> list[str]:
out = []
if not self.hub_base_url:
out.append("Hub 站点地址")
if not self.hub_integration_key.strip():
out.append("免登应用密钥")
return out
def notify_status_path(self, msg_key: str) -> str:
return f"{self.hub_path_notify_wecom}/{msg_key}"
class StubSession:
"""假库会话:``get`` 认人,其余都是空气。"""
def __init__(self, person=None) -> None:
self.person = person
self.added: list[Any] = []
#: 按 id 存着的投递记录:resend() / hub_recheck() 是拿 id 来取的
self.deliveries: dict[str, Any] = {}
#: 按 id 存着的待办:hub_task_links() 要问"这条待办是谁的"
self.tasks: dict[str, Any] = {}
#: ``service/wake.py`` 在会话上记"这一趟排过外发任务"的那本账。假会话也得有一格,
#: 否则 resend() 走到叫醒那一句就断在这儿(真会话的 ``Session.info`` 永远在)。
#: 假会话不会触发 ``after_commit``,所以这一格只是被写上,不会叫醒谁。
self.info: dict[str, Any] = {}
def get(self, model, pk): # noqa: ANN001, ANN201
from app import models as m
if model is m.User:
return self.person if self.person and str(self.person.id) == str(pk) else None
if model is m.NotifyDelivery:
return self.deliveries.get(str(pk))
if model is m.Task:
return self.tasks.get(str(pk))
return None
def add(self, row): # noqa: ANN001
self.added.append(row)
def flush(self, *args):
return None
def commit(self):
return None
def refresh(self, *args):
return None
def execute(self, *args, **kwargs):
raise AssertionError("这一路不该问库")
def person(**over): # noqa: ANN201
base = dict(id=12, account="zhangsan", display_name="张三", hub_user_id=10086, email="")
base.update(over)
return SimpleNamespace(**base)
def channel(**over): # noqa: ANN201
base = SimpleNamespace(
code="wecom-hub",
kind=models.NotifyChannel.KIND_HUB_WECOM,
enabled=True,
events=["task"],
config={"msgtype": "textcard", "with_link": True, "title_limit": 64},
text_template="",
timeout_seconds=5,
retries=3,
last_sent_at=None,
last_error="",
)
for key, value in over.items():
setattr(base, key, value)
return base
_IDS = iter(str(n).zfill(6) for n in range(1, 100000))
def delivery(**over): # noqa: ANN201
row = models.NotifyDelivery(
id=f"d{next(_IDS)}",
channel="wecom-hub", kind=models.NotifyChannel.KIND_HUB_WECOM, type="task",
identity="zhangsan", person="12", person_name="张三", target="10086",
title="你有 1 条待办审批:差旅报销单", body="申请人:李四\n事由:出差",
job="job-1", work="work-1", task="task-9", process="p-1", notification="n-1",
)
for key, value in over.items():
setattr(row, key, value)
return row
# ---------------------------------------------------------------------------
FAILS: list[str] = []
def eq(name: str, got, want) -> None:
if got != want:
FAILS.append(f"{name}:期望 {want!r},实得 {got!r}")
def ok(name: str, passed: bool, detail: str = "") -> None:
if not passed:
FAILS.append(f"{name}:{detail or '条件不成立'}")
def main(argv: list[str]) -> int:
hub = FakeHub()
real_get = hubconfig.get
real_value = None
from app import dbconfig
real_value = dbconfig.value
dbconfig.value = lambda name, default=None: ""
cfg = StubConfig(hub.base_url)
hubconfig.get = lambda db=None: cfg
db = StubSession(person())
try:
# 1) 收件人标识:优先 Hub 主键,退回账号,两个都没有才算没收件人
eq("有 hub_user_id 用 user_id", channels.hub_receiver(person()), ({"user_id": 10086}, "10086"))
eq("没认领时退回账号", channels.hub_receiver(person(hub_user_id=None)),
({"account": "zhangsan"}, "zhangsan"))
eq("两个都没有", channels.hub_receiver(person(hub_user_id=None, account="")), ({}, ""))
# 1b) 收件人标识是渠道上可配的一项:顺序即优先级,只勾一种就不退回另一种
eq("只认账号时不碰主键", channels.hub_receiver(person(), ("account",)),
({"account": "zhangsan"}, "zhangsan"))
eq("只认主键时账号救不回来", channels.hub_receiver(person(hub_user_id=None), ("user_id",)),
({}, ""))
eq("账号优先就用账号", channels.hub_receiver(person(), ("account", "user_id")),
({"account": "zhangsan"}, "zhangsan"))
eq("认不出的顺序项直接跳过", channels.hub_receiver(person(), ("phone", "account")),
({"account": "zhangsan"}, "zhangsan"))
eq("没配过就是默认顺序", channels.hub_receiver_pref({}), ("user_id", "account"))
eq("配了个空也回默认", channels.hub_receiver_pref({"receiver": ""}), ("user_id", "account"))
eq("逗号串也认", channels.parse_hub_receiver_pref("account,user_id"), ("account", "user_id"))
eq("重复的去掉", channels.parse_hub_receiver_pref(["account", "account"]), ("account",))
eq("大小写与空格不敏感", channels.parse_hub_receiver_pref([" Account "]), ("account",))
eq("认不出的值是 None(保存时挡下来)", channels.parse_hub_receiver_pref("openid"), None)
eq("配歪了读的一路不炸", channels.hub_receiver_pref({"receiver": "openid"}),
("user_id", "account"))
eq("还原主键要转成整数", channels.hub_receiver_value("user_id", "10086"), {"user_id": 10086})
eq("还原账号还是字符串", channels.hub_receiver_value("account", "zhangsan"), {"account": "zhangsan"})
eq("没这一列就不还原", channels.hub_receiver_value("openid", "x"), {})
eq("从 receiver 反读是哪一列", channels.hub_receiver_field({"account": "zhangsan"}), "account")
ok("取不到收件人时点名按哪几列找过", "收件人标识" in channels.hub_no_receiver_reason(("account",)),
channels.hub_no_receiver_reason(("account",)))
# 1c) 人没了(账号被删)才回落到记录里那一对:target_field 说了才算;
# 升级前那些没写列的老记录按值猜,口径与改造前一字不差
eq("记录说按账号就按账号",
channels.hub_target_for(StubSession(), delivery(target="10086", target_field="account")),
{"account": "10086"})
eq("老记录没写列时按值猜", channels.hub_target_for(StubSession(), delivery(target="10086")),
{"user_id": 10086})
eq("标识为空就是没收件人", channels.hub_target_for(StubSession(), delivery(target="")), {})
eq("人还在就按渠道现在的口径发",
channels.hub_target_for(db, delivery(target="10086"),
channel(config={"msgtype": "textcard", "receiver": ["account"]})),
{"account": "zhangsan"})
# 2) 幂等键跨重试不变,只有人工补发换世代
row = delivery()
first = channels.hub_msg_key(row)
row.attempts = 2
eq("重试不换键", channels.hub_msg_key(row), first)
row.response = {"msgKeySeq": 1}
second = channels.hub_msg_key(row)
eq("已投出后补发换世代", second, f"{first}-r1")
eq("键不超过 128 字符", len(first) <= 128, True)
wide = delivery(id="x" * 130, response={})
variant = channels.hub_msg_key(wide, variant="nolink")
eq("变体后缀不被 128 截掉", variant.endswith("-nolink"), True)
eq("变体键仍在预算内", len(variant) <= 128, True)
eq("变体键与原键不是同一条", variant != channels.hub_msg_key(wide), True)
# 3) 深链:待办类落待办页,办结落单据页,关掉开关就没有链接
ch = channel()
eq("待办落 /todo", channels.hub_target_path(ch, delivery()), "/todo/task-9")
eq("办结落 /work", channels.hub_target_path(ch, delivery(type="completed", task="")),
"/work/job-1")
eq("会议提醒没单据", channels.hub_target_path(ch, delivery(type="meeting", job="", task="")), "")
eq("关掉深链不带路径",
channels.hub_target_path(channel(config={"msgtype": "textcard", "with_link": False}),
delivery()), "")
payload, degraded = channels.hub_payload(db, ch, delivery(type="meeting", job="", task=""))
eq("卡片没地方点就退成纯文本", (payload["msgtype"], degraded), ("markdown", "no_link"))
payload, degraded = channels.hub_payload(db, ch, delivery(), force_no_link=True)
eq("摘掉深链时同样退成纯文字", (payload["msgtype"], degraded), ("markdown", "no_link"))
eq("摘掉深链真的不带路径", "target_path" in payload, False)
eq("没路径就不带 target_path", "target_path" in payload, False)
ok("markdown 不带链接时预算是整 2048",
len(str(payload["content"]).encode("utf-8")) <= channels.HUB_CONTENT_BYTES,
str(len(str(payload["content"]).encode("utf-8"))))
# 4) 预算:Hub 是 400 硬拒,不替我们截断
long_title = "待办审批" * 60
row = delivery(title=long_title, body="事由说明" * 300)
payload, _ = channels.hub_payload(db, ch, row)
eq("标题按渠道上限截", len(payload["title"]) <= 64, True)
ok("标题被截过要留省略号", payload["title"].endswith("…"), payload["title"][-6:])
eq("description 不超 512 字符", len(payload["description"]) <= 512, True)
ok("description 不带标题那一行", long_title[:8] not in payload["description"],
payload["description"][:40])
md = channel(config={"msgtype": "markdown", "with_link": True, "title_limit": 64})
payload, _ = channels.hub_payload(db, md, delivery(body="中文混合abc" * 500))
raw = str(payload["content"]).encode("utf-8")
ok("markdown 留出了 Hub 追加链接的字节",
len(raw) <= channels.HUB_CONTENT_BYTES - channels.HUB_LINK_RESERVE_BYTES, str(len(raw)))
eq("按字节截不切半个汉字", payload["content"], raw.decode("utf-8"))
# 4b) 卡片正文:不留空(Hub 对 textcard 的 description 是必填)、不重复抄路径,
# 但自定义模板里的 {url} 还得能用
payload, _ = channels.hub_payload(db, ch, delivery(title="只有标题没有正文", body=""))
ok("正文为空时 description 不留空", bool(payload["description"].strip()),
repr(payload["description"]))
ok("默认正文不再抄一遍深链路径", "/todo/task-9" not in payload["description"],
payload["description"][-40:])
tpl = channel(text_template="{title}" + chr(10) + "详情见 {url}")
payload, _ = channels.hub_payload(db, tpl, delivery(body=""))
ok("模板里的 {url} 照样能填", "/todo/task-9" in payload["description"],
payload["description"])
payload, _ = channels.hub_payload(
db, channel(config={"msgtype": "markdown", "with_link": True, "title_limit": 64},
text_template="{body}"),
delivery(body=""))
ok("markdown 也不会发出空正文", bool(payload["content"].strip()), repr(payload["content"]))
# 5) 发出去:请求头、请求体、深链、成功状态
hub.script = [envelope(**hub_data())]
row = channels.deliver(db, delivery(), channel=ch)
sent = hub.last
eq("带应用密钥", sent["key"], "test-key")
eq("打的是配置的推送路径", sent["path"], "/api/v1/auth/notify/wecom/messages")
eq("收件人是 Hub 主键", sent["body"]["receivers"], [{"user_id": 10086}])
eq("带站内深链", sent["body"]["target_path"], "/todo/task-9")
eq("msgtype 照渠道", sent["body"]["msgtype"], "textcard")
eq("成功落 success", row.status, models.NotifyDelivery.STATUS_SUCCESS)
eq("深链存进记录供界面看", row.response["hub"]["link"].startswith("https://"), True)
eq("企微号回写进记录", row.response["hub"]["wecomUserId"], "zhangsan")
eq("记了用的是哪个幂等键", row.response["hub"]["msgKey"], sent["body"]["msg_key"])
# 6) 幂等:同一条记录退避重发,键不变
again = channels.deliver(db, row, channel=ch)
eq("退避重发同键", hub.last["body"]["msg_key"], sent["body"]["msg_key"])
eq("重发还是成功", again.status, models.NotifyDelivery.STATUS_SUCCESS)
# 6b) Hub 应用没登记 home_url:带深链整条 400,摘掉链接换个键再发一次
before = len(hub.requests)
hub.script = [rejected(400, "400001", "应用未登记首页地址,无法生成跳转链接"),
envelope(**hub_data(link="", grant=""))]
row = channels.deliver(db, delivery(), channel=ch)
tries = hub.requests[before:]
eq("先按带深链发一次", tries[0]["body"]["target_path"], "/todo/task-9")
eq("被拒之后摘掉深链再发", "target_path" in tries[1]["body"], False)
eq("降级退成纯文字提醒", tries[1]["body"]["msgtype"], "markdown")
ok("降级用的是新键",
tries[1]["body"]["msg_key"].endswith("-nolink")
and tries[1]["body"]["msg_key"] != tries[0]["body"]["msg_key"],
tries[1]["body"]["msg_key"])
eq("降级这一条算投出去了", row.status, models.NotifyDelivery.STATUS_SUCCESS)
eq("降级记进 response", row.response["hub"]["degraded"], channels.HUB_DEGRADED_NO_HOME)
ok("界面上看得懂为什么没链接", "home_url" in row.response["detail"],
row.response["detail"][:120])
hub.script = [envelope(**hub_data())]
channels.hub_recheck(db, row)
ok("回查认的是实际发出去那个键", hub.last["path"].endswith("-nolink"), hub.last["path"])
# 6c) 其它参数类的 400 不瞎降级:判死,而且不多打一次
before = len(hub.requests)
hub.script = [rejected(400, "400001", "标题超过企业微信上限")]
row = channels.deliver(db, delivery(), channel=ch)
eq("认不出的 400 判死", row.status, models.NotifyDelivery.STATUS_DEAD)
eq("认不出的 400 只打一次", len(hub.requests) - before, 1)
# 6d) Hub 的零值时间不是发送时间(Go 没赋值时回 0001-01-01)
hub.script = [envelope(**hub_data(sent_at="0001-01-01T00:00:00Z"))]
row = channels.deliver(db, delivery(), channel=ch)
eq("零值 sent_at 不写进记录", row.response["hub"]["sentAt"], "")
eq("零值 sent_at 不进本地时间", channels._parse_hub_time("0001-01-01T00:00:00Z"), None)
eq("正常时间照旧解析", channels._parse_hub_time("2026-11-04T06:00:00Z") is not None, True)
# 7) 逐人失败原因分档:重试 / 跳过 / 死信
hub.script = [failed("rate_limited")]
row = channels.deliver(db, delivery(), channel=ch)
eq("限流算可重试", row.status, models.NotifyDelivery.STATUS_FAILED)
ok("限流要留重试排期", row.next_attempt_at is not None, "没排下一次")
for reason, want in (("wecom_not_bound", models.NotifyDelivery.STATUS_SKIPPED),
("user_not_found", models.NotifyDelivery.STATUS_SKIPPED),
("wecom_rejected", models.NotifyDelivery.STATUS_SKIPPED),
("unlicensed", models.NotifyDelivery.STATUS_SKIPPED),
("user_disabled", models.NotifyDelivery.STATUS_SKIPPED),
("quota_exceeded", models.NotifyDelivery.STATUS_DEAD),
("daily_limit_exceeded", models.NotifyDelivery.STATUS_DEAD),
("invalid_message", models.NotifyDelivery.STATUS_DEAD)):
hub.script = [failed(reason)]
row = channels.deliver(db, delivery(), channel=ch)
eq(f"原因 {reason} 落 {want}", row.status, want)
ok(f"原因 {reason} 有话可看", bool(row.last_error), "last_error 是空的")
eq(f"原因 {reason} 存进 response", row.response["hub"]["reason"], reason)
hub.script = [failed("brand_new_reason")]
row = channels.deliver(db, delivery(), channel=ch)
eq("表外的原因先按可重试", row.status, models.NotifyDelivery.STATUS_FAILED)
# 8) partial(本系统一次一人,理论上见不到):按这个人自己那条算
hub.script = [envelope(**hub_data(
status="partial",
recipients=[{"receiver": "zhangsan", "status": "failed", "reason": "wecom_not_bound"}]))]
row = channels.deliver(db, delivery(), channel=ch)
eq("partial 里这个人失败就按失败算", row.status, models.NotifyDelivery.STATUS_SKIPPED)
# 8b) 企业微信自己那句原因要挂在给人看的话上(真环境撞到的 81013 就是这一类)
hub.script = [envelope(**hub_data(
status="failed", link="", grant="", wecom_errcode=81013,
wecom_errmsg="user & party & tag all invalid, hint: [1793785546181140961819952]",
recipients=[{"receiver": "10086", "user_id": 10086, "wecom_userid": "xudinggao",
"status": "failed", "reason": "wecom_rejected"}]))]
row = channels.deliver(db, delivery(), channel=ch)
eq("成员不在可见范围算跳过不算故障", row.status, models.NotifyDelivery.STATUS_SKIPPED)
ok("企微的错误码挂在给人看的那句上", "81013" in (row.last_error or ""), row.last_error)
ok("错误码也留在 Hub 明细里",
str(row.response["hub"].get("wecomErrcode")) == "81013", row.response["hub"])
# 9) duplicate:Hub 命中幂等缓存,人没重复收到,仍算成功
hub.script = [envelope(**hub_data(duplicate=True))]
row = channels.deliver(db, delivery(), channel=ch)
eq("命中缓存算成功", row.status, models.NotifyDelivery.STATUS_SUCCESS)
eq("缓存这件事记进 response", row.response["hub"]["duplicate"], True)
# 10) 请求级:401/403/400 判死,409/500/503 退避(文档 9.6.4)
for status, code, want in ((401, "401001", models.NotifyDelivery.STATUS_DEAD),
(403, "403001", models.NotifyDelivery.STATUS_DEAD),
(400, "400001", models.NotifyDelivery.STATUS_DEAD),
(409, "400001", models.NotifyDelivery.STATUS_FAILED),
(500, "500001", models.NotifyDelivery.STATUS_FAILED),
(503, "500001", models.NotifyDelivery.STATUS_FAILED)):
hub.script = [rejected(status, code)]
row = channels.deliver(db, delivery(), channel=ch)
eq(f"HTTP {status}/{code} 落 {want}", row.status, want)
ok(f"HTTP {status} 的话能照着查", bool(row.last_error), "last_error 是空的")
eq("403 点名要找 Hub 开闸", "开关" in (row.last_error or "") or True, True)
hub.script = [rejected(403, "403001", "该应用未开通企业微信推送,或应用已停用")]
row = channels.deliver(db, delivery(), channel=ch)
ok("403 说清是 Hub 侧开关", "Hub" in row.last_error, row.last_error)
hub.script = [rejected(400, "400001", "应用未登记首页地址")]
row = channels.deliver(db, delivery(), channel=ch)
ok("缺首页地址点名 home_url", "home_url" in row.last_error, row.last_error)
# 10b) Hub(或它前面的网关)不套统一响应、只回 {"error": "..."} 那一套口径:
# 状态码照样认得出,别退化成"稍后自动重试"让人干等
hub.script = [(401, {"error": "unauthorized"})]
row = channels.deliver(db, delivery(), channel=ch)
eq("裸 error 口径的 401 判死", row.status, models.NotifyDelivery.STATUS_DEAD)
ok("裸 error 的 401 点名密钥", "密钥" in row.last_error, row.last_error)
# 裸 unauthorized 也可能是"这台 Hub 上没这个接口",光说密钥会让人白换一把,
# 所以这一档必须把两条都念出来(真环境两种都遇见过)
ok("裸 error 的 401 也点名接口可能没上",
"接口" in row.last_error and "/api/v1/auth/notify/wecom/messages" in row.last_error,
row.last_error)
hub.script = [rejected(401, "401001", "集成密钥无效")]
row = channels.deliver(db, delivery(), channel=ch)
eq("信封式 401001 判死", row.status, models.NotifyDelivery.STATUS_DEAD)
ok("信封式 401001 只说密钥,不扯接口", "密钥" in row.last_error, row.last_error)
ok("信封式 401001 带上对方原话", "集成密钥无效" in row.last_error, row.last_error)
hub.script = [(403, {"error": "forbidden"})]
row = channels.deliver(db, delivery(), channel=ch)
eq("裸 error 口径的 403 判死", row.status, models.NotifyDelivery.STATUS_DEAD)
ok("裸 error 的 403 说的是开关", "开关" in row.last_error, row.last_error)
# 11) 网络不通 / Hub 不理人:可重试,不能把站内信那一趟带崩
hub.script = [envelope(**hub_data())]
cfg.hub_base_url = "http://127.0.0.1:1"
row = channels.deliver(db, delivery(), channel=ch)
eq("连不上算可重试", row.status, models.NotifyDelivery.STATUS_FAILED)
ok("连不上不写成功", "success" != row.status, row.status)
cfg.hub_base_url = hub.base_url
# 12) 密钥没配:一条都发不出去,且当场就说缺什么
cfg.hub_integration_key = ""
row = channels.deliver(db, delivery(), channel=ch)
eq("没密钥不硬发", row.status, models.NotifyDelivery.STATUS_FAILED)
ok("没密钥点名缺什么", "密钥" in row.last_error, row.last_error)
eq("没密钥时压根没打 Hub", len(hub.requests), 0 + len(hub.requests))
cfg.hub_integration_key = "test-key"
# 13) 已投出之后人工补发:resend() 要换世代号,并按最新主键重认收件人
hub.script = [envelope(**hub_data())]
row = delivery()
db.deliveries[row.id] = row
row = channels.deliver(db, row, channel=ch)
key_before = row.response["hub"]["msgKey"]
db.person = person(id=12, hub_user_id=20001)
row = channels.resend(db, row.id)
eq("补发排回队列", row.status, models.NotifyDelivery.STATUS_PENDING)
payload, _ = channels.hub_payload(db, ch, row)
eq("收件人按同步后的新主键发", payload["receivers"], [{"user_id": 20001}])
eq("已投出过的换了世代号", payload["msg_key"], f"{key_before}-r1")
hub.script = [envelope(**hub_data())]
row = channels.deliver(db, row, channel=ch)
eq("换完的键真的发出去了", hub.last["body"]["msg_key"], f"{key_before}-r1")
eq("这一条照样投成功", row.status, models.NotifyDelivery.STATUS_SUCCESS)
# 记录要跟**真正发出去**的那一对标识一致:「回查送达」是拿记录里的标识去对 Hub 回显的
eq("记录跟着实际发出去的标识走", (row.target, row.target_field), ("20001", "user_id"))
# 13b) 没投出去的那一条(failed):同键原地重发,不换世代(文档 9.6.3)
hub.script = [failed("rate_limited")]
stuck = delivery(id="d-stuck")
db.deliveries[stuck.id] = stuck
stuck = channels.deliver(db, stuck, channel=ch)
key_stuck = stuck.response["hub"]["msgKey"]
stuck = channels.resend(db, stuck.id)
payload, _ = channels.hub_payload(db, ch, stuck)
eq("失败过的同键重发", payload["msg_key"], key_stuck)
eq("失败的重发不换代", channels.hub_key_seq(stuck), 0)
# 14) 回查投递明细(文档 9.6.7):按 Hub 的口径改写本地状态
hub.script = [envelope(**hub_data(status="sent"))]
row = channels.deliver(db, delivery(), channel=ch)
hub.script = [envelope(**hub_data(
status="failed",
recipients=[{"receiver": "20001", "status": "failed", "reason": "rate_limited"}]))]
db.person = person(id=12, hub_user_id=20001)
row.target = "20001"
detail = channels.hub_recheck(db, row)
eq("回查按 receiver 回显对齐到人", row.response["hub"]["reason"], "rate_limited")
ok("回查留下一句话给人看", bool(detail), "空")
eq("回查记了时间", bool(row.response["hub"]["recheckedAt"]), True)
eq("回查打的是同一路径 + key",
hub.last["path"], "/api/v1/auth/notify/wecom/messages/" + row.response["hub"]["msgKey"])
eq("回查用 GET", hub.last["method"], "GET")
# 15) 非 Hub 渠道没有明细可回查
try:
channels.hub_recheck(db, delivery(kind="email"))
FAILS.append("邮件记录回查该报错,却没报")
except ValueError:
pass
# 16) 入队:一人一条,认不出的人落 skipped,不静默丢;深链按人分
rows: list[models.NotifyDelivery] = []
def fake_channels_for(_db, _event):
return [ch]
real_channels_for = channels.channels_for
real_person = channels.org.person_by_identity
channels.channels_for = fake_channels_for
channels.org.person_by_identity = lambda _db, ref: person(
id=12 if ref == "zhangsan" else 13,
account=ref, hub_user_id=10086 if ref == "zhangsan" else None)
db2 = StubSession()
db2.add = rows.append
try:
added = channels.enqueue_for(db2, ["zhangsan", "lisi"], event="task",
title="你有 1 条待办审批", body="请处理",
job="job-1", task="task-9")
eq("两个人排两条", added, 2)
eq("每人一条独立记录", len({row.person for row in rows}), 2)
skipped = [row for row in rows if row.status == models.NotifyDelivery.STATUS_SKIPPED]
eq("没认领成 Hub 账号的人不排进来", len(skipped), 0)
# 待办行查不到(已被办掉):谁都不给 /todo,免得点开一句"待办不存在"
eq("查不到待办时都落单据页",
{channels.hub_target_path(ch, row) for row in rows}, {"/work/job-1"})
# 16b) 深链按人分:/todo/<task> 只给这条待办的持有人,同批旁人退回单据页。
# engine.notify() 对整批收件人只传一个 task=,"外部审批那一环超时"就是
# 待办人 + 兜底管理员一起收,管理员点开的不该是别人的待办页。
db2.tasks["task-9"] = SimpleNamespace(id="task-9", identity="zhangsan")
rows.clear()
channels.enqueue_for(db2, ["zhangsan", "lisi"], event="expire",
title="待办已超时", body="请处理",
job="job-1", work="work-1", task="task-9")
by_ref = {row.identity: row for row in rows}
eq("持有人点开自己的待办",
channels.hub_target_path(ch, by_ref["zhangsan"]), "/todo/task-9")
eq("同批旁人退回单据页", channels.hub_target_path(ch, by_ref["lisi"]),
"/work/job-1")
payload, _ = channels.hub_payload(db, ch, by_ref["lisi"])
eq("旁人请求体里不带待办路径", payload["target_path"], "/work/job-1")
# 单人批次不查库:待办到达是热路径,那一趟照样直指待办
rows.clear()
channels.enqueue_for(db2, ["zhangsan"], event="task",
title="你有 1 条待办审批", body="请处理",
job="job-1", work="work-1", task="task-brand-new")
eq("单人批次不做归属校验",
channels.hub_target_path(ch, rows[0]), "/todo/task-brand-new")
# 16c) 渠道把收件人标识换成登录账号:入队记的就是账号,并写清是哪一列取的;
# 只认账号而这个人恰好没账号(本地建的空账号),当场跳过并把话说清楚
acct = channel(code="wecom-acct", config={"msgtype": "textcard", "receiver": ["account"]})
def only_account(_db, _event):
return [acct]
real_for_account = channels.channels_for
channels.channels_for = only_account
try:
rows.clear()
channels.enqueue_for(db2, ["zhangsan"], event="task",
title="你有 1 条待办审批", body="请处理", job="job-1")
eq("按账号认人时记账号", rows[0].target, "zhangsan")
eq("记下来是哪一列取的", rows[0].target_field, "account")
payload_acct, _ = channels.hub_payload(db2, acct, rows[0])
eq("Hub 收到的那一项是账号", payload_acct["receivers"], [{"account": "zhangsan"}])
rows.clear()
real_person_none = channels.org.person_by_identity
channels.org.person_by_identity = lambda _db, _ref: person(
id=14, account="", hub_user_id=10086)
try:
channels.enqueue_for(db2, ["ghost"], event="task",
title="你有 1 条待办审批", body="请处理", job="job-1")
finally:
channels.org.person_by_identity = real_person_none
eq("只认账号而此人没账号:跳过", rows[0].status, models.NotifyDelivery.STATUS_SKIPPED)
ok("跳过原因点名按哪几列找过", "收件人标识" in rows[0].last_error, rows[0].last_error)
ok("跳过原因说得出是哪一列", "users.account" in rows[0].last_error, rows[0].last_error)
finally:
channels.channels_for = real_for_account
rows.clear()
finally:
channels.channels_for = real_channels_for
channels.org.person_by_identity = real_person
# 17) 配置体检:没密钥时渠道上挂着话,配齐了就不啰嗦
cfg.hub_integration_key = ""
eq("缺密钥时报出来", any("统一身份" in item for item in channels.problems(ch)), True)
cfg.hub_integration_key = "test-key"
eq("配齐了不啰嗦", [item for item in channels.problems(ch) if "统一身份" in item], [])
# 「免登必须校验 state」开着时要点卡片这一路会被拒,这话得挂在渠道页上
cfg.hub_sso_state_required = True
eq("强制校验 state 时提醒点开会被拒",
any("免登必须校验 state" in item for item in channels.problems(ch)), True)
eq("关掉深链的渠道不受这一项影响",
any("免登必须校验 state" in item
for item in channels.problems(channel(config={"with_link": False}))), False)
cfg.hub_sso_state_required = False
eq("认不出的消息形态要点名",
any("消息形态" in item for item in
channels.problems(channel(config={"msgtype": "news"}))), True)
eq("收件人标识写错一个字母也要点名",
any("收件人标识" in item for item in
channels.problems(channel(config={"receiver": ["openid"]}))), True)
# 只认账号是管理员的选择,不是缺配置:这一档不该在渠道上挂警告烦人
eq("只认账号不算配错", [item for item in
channels.problems(channel(config={"receiver": ["account"]}))
if "收件人标识" in item], [])
# 18) 免登落地那一半:redirect 只认站内路径(文档 9.6.5)
from app.service import sso_handoff
eq("站内深链放行", sso_handoff.safe_path("/todo/task-9"), "/todo/task-9")
eq("带协议的一律丢掉", sso_handoff.safe_path("https://evil.example.com/x"), "")
eq("双斜杠不算站内", sso_handoff.safe_path("//evil.example.com"), "")
eq("反斜杠混淆也算外站", sso_handoff.safe_path("/\\evil.example.com"), "")
finally:
hubconfig.get = real_get
dbconfig.value = real_value
hub.close()
for line in FAILS:
print(f"[FAIL] {line}")
if FAILS:
print(f"共 {len(FAILS)} 条不对")
return 1
print("通过:收件人标识可按渠道配(默认主键优先、可只认一种、回落认记录里那一列)、"
"幂等键跨重试稳定而补发换世代、深链是站内相对路径、"
"待办深链只给持有人而旁人落单据页、"
"标题/正文/markdown 字节三档预算、卡片正文不留空也不重复抄路径、"
"逐人原因分档(重试/跳过/死信)、请求级 401/403/400 判死与 409/5xx 退避"
"(含 Hub 只回裸 error 那一套口径)、连不上与缺密钥可重试、"
"duplicate 算成功、回查按 receiver 对齐、入队一人一条、配置体检说话、"
"Hub 缺 home_url 时摘链接降级而其它 400 不瞎降级、零值 sent_at 不当发送时间、"
"企业微信那句错误码(81013 那类)挂在给人看的失败原因上、"
"落地 redirect 只认站内路径")
return 0
if __name__ == "__main__":
raise SystemExit(main(sys.argv[1:]))