test_im_sync.py
6.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
"""imhub 消息同步中断检测(拉消息接口返回空、不报错)和消息记录接口:
发出的消息 3 分钟拉不到回显 → 告警 + 会话里明确提示 imhub 异常(只发一次)→ 重新拉到消息 → 关告警、补收中断期间的消息
(只记成被忽略,不执行)、会话里提示已恢复;不处理的消息不再静默丢弃;消息记录按类型筛选、带助手判定。"""
from __future__ import annotations
import asyncio
import datetime as dt
import time
from sqlalchemy import select
from app.core import db
from app.models import alerts_t, notify_logs_t
from app.services import im
def _iso(ts: float) -> str:
return dt.datetime.fromtimestamp(ts).isoformat()
def _msg(mid: str, ts: float, text: str, sender_type: int = 0, sender_id: str = "u9", sender: str = "张三") -> dict:
return {"msg_id": mid, "sender_type": sender_type, "sender_id": sender_id, "sender": sender, "text": text,
"msg_type": "text", "msg_time": _iso(ts)}
def _open(kit, kind):
return db.rows(select(alerts_t).where(alerts_t.c.store_id == kit.store_id, alerts_t.c.kind == kind,
alerts_t.c.status == "open"))
def test_sync_down_alert_notice_and_recover(client, admin, kit, outbox, monkeypatch):
t = kit.target()
b = im.bot_of(t)
im.SYNC.clear()
loop = asyncio.new_event_loop()
p = im.Poller(None, loop)
store: list[dict] = [] # 网关「聊天记录」:按时间段返回
def fetch(bot, contact, start, end):
lo = dt.datetime.strptime(start, "%Y-%m-%d %H:%M:%S").timestamp()
hi = dt.datetime.strptime(end, "%Y-%m-%d %H:%M:%S").timestamp()
return [m for m in store if lo <= dt.datetime.fromisoformat(m["msg_time"]).timestamp() <= hi]
monkeypatch.setattr(im.imhub, "fetch_msgs", fetch)
try:
im.send_to(t, "📦 补货推荐已生成", event="chat")
assert im.sync_status(t["id"])["waiting_since"]
p.check_sync(t, b, []) # 刚发出:还没到超时,不下结论
assert im.sync_status(t["id"])["state"] != "down"
# 正常情况:回显出现就清掉等待
store.append(_msg("e1", time.time(), "📦 补货推荐已生成", sender_type=1))
p.check_sync(t, b, fetch(b, t["contact_id"], *_win(120)))
assert im.sync_status(t["id"])["state"] == "ok" and not im.sync_status(t["id"])["waiting_since"]
# imhub 不再同步:发出去的消息 3 分钟后还拉不到
store.clear()
im.send_to(t, "⏰ 提醒", event="chat")
im.SYNC[t["id"]]["pending_since"] -= im.ECHO_TIMEOUT + 20
down_at = im.SYNC[t["id"]]["pending_since"]
p.check_sync(t, b, [])
loop.run_until_complete(asyncio.sleep(0.2))
assert im.sync_status(t["id"])["state"] == "down"
notices = [m for m in outbox.to(kit.group) if "imhub 消息网关异常" in m]
assert len(notices) == 1 and "收不到这里的消息" in notices[0]
assert _open(kit, "im.sync_down")
p.check_sync(t, b, []) # 中断期间再拉:不重复提醒
assert len([m for m in outbox.to(kit.group) if "imhub 消息网关异常" in m]) == 1
# 中断期间用户说的话(网关恢复后才补上来)+ 恢复后的回显
store.append(_msg("u-old", down_at + 30, "@补货助手 8713902280 2个"))
store.append(_msg("e2", time.time(), "✅ 检测到", sender_type=1))
p.check_sync(t, b, fetch(b, t["contact_id"], *_win(120)))
loop.run_until_complete(asyncio.sleep(0.2))
assert im.sync_status(t["id"])["state"] == "ok"
assert not _open(kit, "im.sync_down")
up = [m for m in outbox.to(kit.group) if "检测到 imhub 消息网关已恢复" in m]
assert len(up) == 1 and "补收到 1 条" in up[0]
ign = db.one(select(notify_logs_t).where(notify_logs_t.c.msg_id == "u-old"))
assert ign["event"] == "chat_ignored" and "imhub 中断期间" in ign["error"]
# 消息记录:系统提示 / 被忽略分类;未知类型 400
r = client.get("/api/wecom/logs?category=notice", headers=admin).json()
assert {x["category"] for x in r["rows"]} == {"notice"} and len(r["rows"]) == 2
r = client.get("/api/wecom/logs?category=ignored", headers=admin).json()
assert any(x["msg_id"] == "u-old" and x["who"] == "张三" for x in r["rows"])
r = client.get(f"/api/wecom/logs?category=chat&target_id={t['id']}", headers=admin).json()
assert r["rows"] and all(x["category"] == "chat" for x in r["rows"]) and r["targets"]
assert client.get("/api/wecom/logs?category=xx", headers=admin).status_code == 400
ov = client.get("/api/wecom/overview", headers=admin).json()
assert next(x for x in ov["targets"] if x["id"] == t["id"])["sync"]["state"] == "ok"
finally:
loop.close()
im.SYNC.clear()
def _win(seconds: int) -> tuple[str, str]:
now = time.time()
fmt = "%Y-%m-%d %H:%M:%S"
return dt.datetime.fromtimestamp(now - seconds).strftime(fmt), dt.datetime.fromtimestamp(now + 5).strftime(fmt)
def test_wide_check_avoids_false_alarm(client, admin, kit, outbox, monkeypatch):
"""超时那一刻再用大窗口确认:回显其实在(只是正常轮询窗口错过了),不能误报中断。"""
t = kit.target()
im.SYNC.clear()
p = im.Poller(None, None)
im.send_to(t, "📦 清单", event="chat")
since = im.SYNC[t["id"]]["pending_since"] = time.time() - im.ECHO_TIMEOUT - 30
monkeypatch.setattr(im.imhub, "fetch_msgs", lambda bot, c, s, e: [_msg("e9", since + 2, "📦 清单", sender_type=1)])
p.check_sync(t, im.bot_of(t), [])
assert im.sync_status(t["id"])["state"] == "ok"
assert not any("imhub 消息网关异常" in m for m in outbox.to(kit.group))
im.SYNC.clear()
def test_dropped_messages_are_logged(client, admin, kit, outbox, monkeypatch):
"""超时的、非文字的消息不再静默丢弃:记成被忽略并写原因。"""
t = kit.target()
im.SYNC.clear()
p = im.Poller(None, None)
now = time.time()
batches = iter([[_msg("h1", now, "历史")],
[_msg("late1", now - 600, "@补货助手 订"),
{"msg_id": "img1", "sender_type": 0, "sender_id": "u9", "sender": "张三", "text": "",
"msg_type": "image", "msg_time": _iso(now)}]])
monkeypatch.setattr(im.imhub, "fetch_msgs", lambda bot, c, s, e: next(batches))
assert p.poll_one(t) == 0 # 首次接入:历史标为已读
assert p.poll_one(t) == 0
rows = {r["msg_id"]: r for r in db.rows(select(notify_logs_t).where(notify_logs_t.c.msg_id.in_(["late1", "img1"])))}
assert rows["late1"]["event"] == "chat_ignored" and "才收到,为安全未处理" in rows["late1"]["error"]
assert rows["img1"]["event"] == "chat_ignored" and "非文字消息" in rows["img1"]["error"]
im.SYNC.clear()