test_webhook.py 6.32 KB
"""企业微信群机器人 webhook:设置加密打码、按大类路由、并行发送、错误码 / 频控,以及新增的系统运行告警来源。
全部 mock 掉 requests.post,不会真的发到企业微信。"""
from __future__ import annotations

import pytest

from app.core import db
from app.core.db import select
from app.models import notify_logs_t
from app.services import alerts, settings, wecom_webhook
from app.services.scheduler import Scheduler

URL = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=test-key-0000"


class _Resp:
    def __init__(self, status=200, body=None):
        self.status_code, self._body = status, body if body is not None else {"errcode": 0, "errmsg": "ok"}

    def json(self):
        return self._body


@pytest.fixture()
def hook(monkeypatch):
    calls: list[dict] = []
    state = {"resp": _Resp()}

    def fake_post(url, json=None, timeout=None):
        calls.append({"url": url, "json": json})
        return state["resp"]

    monkeypatch.setattr(wecom_webhook.requests, "post", fake_post)
    wecom_webhook._sent.clear()
    yield calls, state
    wecom_webhook._sent.clear()


def _enable(groups=("edge", "restock", "im", "system")):
    settings.save("system", {"wecom_webhook_enabled": True, "wecom_webhook_url": URL,
                             "wecom_webhook_groups": list(groups)}, "test")


def _alerts(client, admin, kind):
    return [a for a in client.get("/api/alerts?size=200", headers=admin).json()["rows"] if a["kind"] == kind]


def test_settings_masked_and_validated(client, admin, kit):
    r = client.put("/api/system/settings", json={"wecom_webhook_url": "https://example.com/hook"}, headers=admin)
    assert r.status_code == 400
    r = client.put("/api/system/settings", json={"wecom_webhook_enabled": True, "wecom_webhook_url": URL,
                                                 "wecom_webhook_groups": ["system", "edge", "bogus"]}, headers=admin)
    assert r.status_code == 200, r.text
    vals = r.json()["values"]
    assert "test-key" not in vals["wecom_webhook_url"] and "•" in vals["wecom_webhook_url"]
    assert vals["wecom_webhook_groups"] == ["edge", "system"]           # 按固定顺序、去掉不认识的
    assert settings.get().wecom_webhook_url == URL
    r = client.put("/api/system/settings", json={"wecom_webhook_url": vals["wecom_webhook_url"]}, headers=admin)
    assert r.status_code == 200 and settings.get().wecom_webhook_url == URL   # 提交打码串 = 不修改
    groups = client.get("/api/system/settings", headers=admin).json()["webhook_groups"]
    assert [g["key"] for g in groups] == ["edge", "restock", "im", "system"]


def test_routing_by_group(client, admin, kit, outbox, hook):
    calls, _ = hook
    kit.call(alerts.open_alert, kit.store_id, "edge.offline", "device:1", "error", "门店取数端离线:x", "没心跳")
    assert calls == [] and outbox.texts                                 # 总开关没开:只走原来的接收对象
    _enable(["restock"])
    kit.call(alerts.open_alert, kit.store_id, "edge.disk_low", "device:1", "warn", "磁盘不足", "只剩 1 MB")
    assert calls == []                                                  # 取数端大类没勾
    n = len(outbox.texts)
    kit.call(alerts.open_alert, kit.store_id, "restock.po_failed", "run:1", "error", "创建采购单失败", "DMS 报错")
    assert len(calls) == 1 and len(outbox.texts) == n + 1               # 并行:群机器人 + 原接收对象都发
    body = calls[0]["json"]
    assert body["msgtype"] == "markdown" and "创建采购单失败" in body["markdown"]["content"]
    kit.call(alerts.resolve_alert, kit.store_id, "restock.po_failed", "run:1", "已处理")
    assert len(calls) == 2 and "已恢复" in calls[1]["json"]["markdown"]["content"]
    from app.services import notify
    kit.call(notify.send, kit.store_id, "restock.daily_summary", "info", "今日补货小结", "x")
    assert len(calls) == 2                                              # info 级小结不是告警
    rows = db.rows(select(notify_logs_t).where(notify_logs_t.c.channel_kind == "webhook"))
    assert len(rows) == 2 and all(r["address"] == "webhook:…0000" and r["ok"] for r in rows)


def test_errcode_truncate_and_rate_limit(client, admin, kit, hook):
    calls, state = hook
    state["resp"] = _Resp(body={"errcode": 93000, "errmsg": "invalid webhook url"})
    ok, err = wecom_webhook.post(URL, "x")
    assert not ok and "93000" in err
    state["resp"] = _Resp()
    wecom_webhook._sent.clear()
    assert wecom_webhook.post(URL, "长" * 3000)[0]
    assert len(calls[-1]["json"]["markdown"]["content"].encode("utf-8")) <= wecom_webhook.MAX_BYTES
    wecom_webhook._sent.clear()
    results = [wecom_webhook.post(URL, str(i))[0] for i in range(wecom_webhook.PER_MINUTE + 1)]
    assert all(results[:-1]) and not results[-1]


def test_test_endpoint(client, admin, kit, hook):
    calls, _ = hook
    r = client.post("/api/system/test-webhook", headers=admin).json()
    assert not r["ok"] and "webhook" in r["error"]                     # 还没填地址
    _enable()
    assert client.post("/api/system/test-webhook", headers=admin).json()["ok"] and len(calls) == 1


def test_scheduler_job_failed_alert(client, admin, kit, hook):
    calls, _ = hook
    _enable(["system"])
    sch = Scheduler()

    async def boom():
        raise RuntimeError("库连不上")

    async def fine():
        return None

    kit.call(sch._guard, boom(), "restock.push@1", kit.store_id, "推送补货清单")
    rows = [a for a in _alerts(client, admin, "system.job_failed") if a["status"] == "open"]
    assert rows and "推送补货清单" in rows[0]["title"] and "库连不上" in calls[-1]["json"]["markdown"]["content"]
    kit.call(sch._guard, fine(), "restock.push@1", kit.store_id, "推送补货清单")
    assert not [a for a in _alerts(client, admin, "system.job_failed") if a["status"] == "open"]


def test_http_500_alert(client, admin, kit, hook):
    calls, _ = hook
    _enable(["system"])

    def _boom():
        raise RuntimeError("意外错误")

    client.app.add_api_route("/api/_test/boom", _boom, methods=["POST"])
    with pytest.raises(RuntimeError):                  # TestClient 默认把服务端异常抛出来;生产环境返回 500
        client.post("/api/_test/boom", headers=admin)
    rows = _alerts(client, admin, "system.http_500")
    assert rows and "/api/_test/boom" in rows[0]["title"] and calls