test_watch.py 14.4 KB
"""监控与定时:排程解析、下次执行时间、抑制去重、三种数据源、策略触发、失败自停。"""
from __future__ import annotations

import datetime as dt
import sys
from pathlib import Path

import pytest

sys.path.insert(0, str(Path(__file__).parent))

from test_platform import build_basics, env, make_action  # noqa: E402,F401


# ---------------------------------------------------------------- 排程
def test_cron_五段解析_与下次执行时间():
    from app.watch import cron
    n = dt.datetime(2026, 9, 23, 10, 30)
    assert cron.next_fire({"kind": "interval", "every_minutes": 30}, n) == dt.datetime(2026, 9, 23, 11, 0)
    assert cron.next_fire({"kind": "daily", "at": "08:00"}, n) == dt.datetime(2026, 9, 24, 8, 0)
    assert cron.next_fire({"kind": "daily", "at": "23:00"}, n) == dt.datetime(2026, 9, 23, 23, 0)
    # 2026-09-23 是周三,下一个周一是 28 号
    assert cron.next_fire({"kind": "weekly", "at": "09:00", "weekday": 1}, n) == dt.datetime(2026, 9, 28, 9, 0)
    assert cron.next_fire({"kind": "monthly", "at": "07:30", "day": 1}, n) == dt.datetime(2026, 10, 1, 7, 30)
    # 工作日 9~18 点每 15 分钟
    assert cron.next_fire({"kind": "cron", "cron": "*/15 9-18 * * 1-5"}, n) == dt.datetime(2026, 9, 23, 10, 45)


def test_cron_写错了要当场报错_而不是悄悄不跑():
    from app.watch import cron
    for bad in ["", "* * *", "*/0 * * * *", "99 * * * *", "abc * * * *"]:
        with pytest.raises(cron.CronError):
            cron.normalize({"kind": "cron", "cron": bad})
    with pytest.raises(cron.CronError):
        cron.normalize({"kind": "daily", "at": "25:00"})


def test_每月只到28号_二月不会漏跑():
    from app.watch import cron
    assert cron.normalize({"kind": "monthly", "day": 31})["day"] == 28


# ---------------------------------------------------------------- 盯指标
def _metric_watch(**kw) -> dict:
    body = {"title": "缺口监控",
            "schedule": {"kind": "daily", "at": "08:00"},
            "source": {"kind": "metric", "metric": "成交金额", "dimensions": ["网点"]},
            "condition": "value > 0",
            "strategies": [{"kind": "task", "role": "operator", "title": "去看一下"}],
            "dedup": {"key": "$key", "cooldown_hours": 24}}
    body.update(kw)
    return body


def test_盯指标_试扫描只看命中不触发(env):
    from app.watch import engine as wengine, service
    build_basics(env["ds_id"])
    w = service.create(_metric_watch())
    assert w["next_fire_at"]                      # 建好就有下次执行时间,界面能显示
    r = wengine.scan(w["id"], dry=True)
    assert r["hit_count"] >= 1
    assert r["fired"] == [] and r["run_id"] == ""
    assert service.list_runs(w["id"]) == []       # 试扫描不留运行记录


def test_盯指标_正式跑一次_生成待办并写运行记录(env):
    from app.capability import tasks
    from app.watch import engine as wengine, service
    build_basics(env["ds_id"])
    w = service.create(_metric_watch())
    r = wengine.scan(w["id"], dry=False)
    assert r["hit_count"] >= 1
    assert all(f["ok"] for f in r["fired"])
    assert len(tasks.list_tasks()) >= r["hit_count"]
    runs = service.list_runs(w["id"])
    assert len(runs) == 1 and runs[0]["status"] == "done"
    assert runs[0]["hit_count"] == r["hit_count"]
    assert service.get(w["id"])["last_status"] == "ok"


def test_抑制_冷却期内不重复触发_恢复后重新计数(env):
    from app.watch import engine as wengine, service
    build_basics(env["ds_id"])
    w = service.create(_metric_watch())
    first = wengine.scan(w["id"], dry=False)
    assert first["suppressed"] == 0
    second = wengine.scan(w["id"], dry=False)
    assert second["suppressed"] == second["hit_count"] and second["fired"] == []
    # 条件改成永不命中:这一轮把所有键标成已恢复
    service.update(w["id"], {**_metric_watch(), "condition": "value < 0"})
    wengine.scan(w["id"], dry=False)
    # 再改回去,冷却已经因为「恢复过」而重置
    service.update(w["id"], _metric_watch())
    third = wengine.scan(w["id"], dry=False)
    assert third["suppressed"] == 0 and third["fired"]


def test_冷却设为0就每次都触发(env):
    from app.watch import engine as wengine, service
    build_basics(env["ds_id"])
    w = service.create(_metric_watch(dedup={"key": "$key", "cooldown_hours": 0}))
    wengine.scan(w["id"], dry=False)
    again = wengine.scan(w["id"], dry=False)
    assert again["suppressed"] == 0 and again["fired"]


# ---------------------------------------------------------------- 盯对象
def test_盯对象_按属性条件逐个实例判(env):
    from app.watch import engine as wengine, service
    b = build_basics(env["ds_id"])
    w = service.create({"title": "盯网点", "schedule": {"kind": "daily", "at": "08:00"},
                        "source": {"kind": "object", "object_type": b["ot"]["id"]},
                        "condition": "等级 == 'A'",
                        "strategies": [{"kind": "notify", "role": "operator", "title": "A 级网点"}]})
    r = wengine.scan(w["id"], dry=True)
    assert r["scanned"] >= r["hit_count"]
    assert all(h.get("等级") == "A" for h in r["hits"])


# ---------------------------------------------------------------- 策略:提交审批
def test_命中后提交审批_审批单带监控作为依据(env):
    from app.capability import actions
    from app.watch import engine as wengine, service
    b = build_basics(env["ds_id"])
    make_action(b["ot"]["id"])
    w = service.create({"title": "自动提审批", "schedule": {"kind": "daily", "at": "08:00"},
                        "source": {"kind": "object", "object_type": b["ot"]["id"]},
                        "condition": "等级 == 'A'",
                        "dedup": {"key": "$key", "cooldown_hours": 24},
                        "strategies": [{"kind": "propose_action", "action": "mark_follow",
                                        "params": {"reason": "监控命中"}, "object_key": "$key"}]})
    r = wengine.scan(w["id"], dry=False)
    assert r["fired"] and all(f["ok"] for f in r["fired"])
    ar = actions.get(r["fired"][0]["ref"])
    assert ar["status"] == "pending_approval"
    assert ar["initiator_kind"] == "watch"
    assert any("预警" in str(e.get("text", "")) for e in ar["evidence"])


# ---------------------------------------------------------------- 调度
def test_到点才跑_挑中就把水位推走_多进程不会重复触发(env):
    from app.watch import engine as wengine, service
    from app.watch.models import Watch
    from app.core.dbx import session
    build_basics(env["ds_id"])
    w = service.create(_metric_watch(schedule={"kind": "interval", "every_minutes": 30}))
    with session() as s:
        s.get(Watch, w["id"]).next_fire_at = dt.datetime.now() - dt.timedelta(minutes=1)
        s.commit()
    at = dt.datetime.now()
    assert [x[0] for x in wengine.due(at)] == [w["id"]]
    assert wengine.due(at) == []                  # 水位已经推走,第二个进程挑不到
    assert service.get(w["id"])["next_fire_at"]


def test_停用的监控不参与调度(env):
    from app.watch import engine as wengine, service
    build_basics(env["ds_id"])
    w = service.create(_metric_watch())
    service.set_enabled(w["id"], False)
    assert service.get(w["id"])["next_fire_at"] is None
    assert wengine.due(dt.datetime.now() + dt.timedelta(days=2)) == []


def test_连续失败三次自动停用并标红(env):
    from app.watch import engine as wengine, service
    build_basics(env["ds_id"])
    w = service.create(_metric_watch(source={"kind": "metric", "metric": "不存在的指标"}))
    for _ in range(3):
        with pytest.raises(Exception):
            wengine.scan(w["id"], dry=False)
    got = service.get(w["id"])
    assert got["last_status"] == "error" and got["fail_count"] >= 3
    assert got["enabled"] is False


# ---------------------------------------------------------------- 接口与校验
def test_校验_条件写错_策略缺失都要当场拒绝(env):
    from fastapi import HTTPException
    from app.watch import service
    build_basics(env["ds_id"])
    with pytest.raises(HTTPException):
        service.create(_metric_watch(condition="value >"))
    with pytest.raises(HTTPException):
        service.create(_metric_watch(strategies=[]))
    with pytest.raises(HTTPException):
        service.create(_metric_watch(source={"kind": "metric", "metric": ""}))


def test_接口_列表_排程预览_试扫描(env):
    from app.watch import service
    build_basics(env["ds_id"])
    w = service.create(_metric_watch())
    from fastapi.testclient import TestClient
    from app.main import app
    c = TestClient(app)
    assert c.get("/api/watch").status_code == 200
    assert any(x["id"] == w["id"] for x in c.get("/api/watch").json())
    r = c.post("/api/watch/preview-schedule",
               json={"schedule": {"kind": "cron", "cron": "*/30 * * * *"}}).json()
    assert r["ok"] and len(r["next"]) == 5
    bad = c.post("/api/watch/preview-schedule",
                 json={"schedule": {"kind": "cron", "cron": "bad"}}).json()
    assert bad["ok"] is False and bad["error"]
    scan = c.post(f"/api/watch/{w['id']}/scan", json={"dry": True})
    assert scan.status_code == 200 and scan.json()["hit_count"] >= 1
    meta = c.get("/api/watch/meta").json()
    assert {k["key"] for k in meta["source_kinds"]} == {"metric", "object", "object_set", "sop"}
    assert {k["key"] for k in meta["trigger_kinds"]} == {"schedule", "change"} and meta["detectors"]


# ---------------------------------------------------------------- v9
def test_排程按监控器自己的时区算_换回服务器时间():
    from app.watch import cron
    n = dt.datetime(2026, 9, 23, 10, 30)
    here = cron.next_fire({"kind": "daily", "at": "08:00"}, n)
    tokyo = cron.next_fire({"kind": "daily", "at": "08:00", "tz": "Asia/Tokyo"}, n)
    off = dt.datetime(2026, 9, 23, 12).astimezone().utcoffset()          # 服务器自己的时区
    assert tokyo > n and tokyo != here or off == dt.timedelta(hours=9)
    # 东京的 08:00 换成 UTC 是前一天 23:00
    assert (tokyo - off).time() == dt.time(23, 0)
    with pytest.raises(cron.CronError):
        cron.normalize({"kind": "daily", "at": "08:00", "tz": "Mars/Base"})


def test_盯对象_翻页扫完整张表_不再只看前几百个(env, monkeypatch):
    from app.watch import engine as wengine, service
    b = build_basics(env["ds_id"])
    monkeypatch.setattr(wengine, "PAGE", 1)                              # 一页一个,逼它翻页
    w = service.create({"title": "盯网点", "schedule": {"kind": "daily", "at": "08:00"},
                        "source": {"kind": "object", "object_type": b["ot"]["id"], "limit": 1},
                        "condition": "True", "strategies": [{"kind": "task", "role": "operator"}]})
    assert "limit" not in w["source"]
    from app.kernel import objects
    total = objects.query(b["ot"]["id"], limit=1)["total"]
    r = wengine.scan(w["id"], dry=True)
    assert total > 1 and r["scanned"] == total == r["hit_count"] and r["unscanned"] == 0


def test_发通知和派任务是两回事(env):
    from app.capability import tasks
    from app.governance import notify
    from app.core import identity
    from app.watch import engine as wengine, service
    from test_platform import as_user
    b = build_basics(env["ds_id"])
    w = service.create({"title": "A 级提醒", "schedule": {"kind": "daily", "at": "08:00"},
                        "source": {"kind": "object", "object_type": b["ot"]["id"]}, "condition": "等级 == 'A'",
                        "strategies": [{"kind": "notify", "role": "operator", "subject": "$label 是 A 级"}]})
    before = len(tasks.list_tasks(scope="all"))
    r = wengine.scan(w["id"], dry=False)
    assert r["fired"] and all(f["ok"] and f["kind"] == "notify" for f in r["fired"])
    assert len(tasks.list_tasks(scope="all")) == before                  # 通知不占待办
    tok = as_user("operator")
    try:
        got = notify.list_for(identity.current())
    finally:
        identity.reset(tok)
    assert any(x["title"].endswith("是 A 级") and "$" not in x["title"] for x in got)
    with pytest.raises(Exception):
        service.create(_metric_watch(strategies=[{"kind": "notify", "subject": "没选角色"}]))


def test_连续失败停用时通知负责人(env):
    from app.core import identity
    from app.governance import notify
    from app.watch import engine as wengine, service
    build_basics(env["ds_id"])
    w = service.create(_metric_watch(source={"kind": "metric", "metric": "不存在的指标"}))
    for _ in range(4):
        with pytest.raises(Exception):
            wengine.scan(w["id"], dry=False)
    got = [x for x in notify.list_for(identity.current()) if "已自动停用" in x["title"]]
    assert len(got) == 1 and "不存在的指标" in got[0]["body"]              # 第 3 次失败时通知一次,之后不再重复


def test_只按点跑流程卡的监控_每一档都跑_不受冷却去重影响(env):
    from test_platform import sop_spec
    from app.sop import engine as sop_engine, service as sop_service
    from app.watch import engine as wengine, service
    b = build_basics(env["ds_id"])
    make_action(b["ot"]["id"])
    d = sop_service.create("整改", spec=sop_spec(b["ot"]["id"]))
    sop_service.publish(d["id"])
    w = service.create({"title": "到点跑", "schedule": {"kind": "interval", "every_minutes": 15},
                        "source": {"kind": "sop", "sop": d["id"]},
                        "strategies": [{"kind": "run_sop", "sop": d["id"], "params": {"store": "1"}}]})
    assert w["dedup"]["cooldown_hours"] == 24                           # 默认值还在,但对这类监控不生效
    first, second = wengine.scan(w["id"], dry=False), wengine.scan(w["id"], dry=False)
    assert first["fired"] and second["fired"] and second["suppressed"] == 0
    assert len(sop_engine.list_runs(d["id"])) == 2


def test_改监控时审计里记下改了哪几项和前后的值(env):
    from app.core import identity
    from app.governance import audit
    from app.watch import service
    build_basics(env["ds_id"])
    w = service.create(_metric_watch())
    service.update(w["id"], {"condition": "value > 100"})
    rec = audit.query(workspace=identity.current().workspace, event="watch.update", full=True)["items"][0]
    assert "触发条件" in rec["summary"] and "排程" not in rec["summary"]
    assert rec["before"] == {"condition": "value > 0"} and rec["after"] == {"condition": "value > 100"}