test_im_foreign.py
12.7 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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
"""留痕:群里出现的机器人消息是不是本系统发的、发送日志、实例信息、请求日志、定时触发说明(2026-11-26 测试群出现生产链接后补的)。"""
from __future__ import annotations
import datetime as dt
import logging
import time
from pathlib import Path
import pytest
from sqlalchemy import select
from app import main as app_main
from app.core import db
from app.core.config import C
from app.core.request_log import mask_path
from app.models import alerts_t, audit_t, events_t, im_targets_t, notify_logs_t
from app.services import events, im, msglog
from app.services.scheduler import _fired_note, _mark, scheduler
from tests.conftest import fake_now
TOKEN = "8a0GvzC3AwtZbkxE"
REMIND = (f"⏰ 今天的补货推荐还没确认(第 1/3 次提醒),16:00 截单。\n请点开链接确认,不确认不会生成采购单 👉\n"
f"https://autorestock.example.com/m/restock/order/{TOKEN}\n⏰ 已过截单时间 16:00,仍可确认 / 提交。")
@pytest.fixture()
def t(kit, outbox):
"""接收对象建立时间提前一小时,否则测试里「60 秒前的消息」会被当成建立之前的历史消息。"""
db.q(im_targets_t.update().where(im_targets_t.c.id == kit.target_id).values(
created_at=db.now() - dt.timedelta(hours=1)))
im.SYNC.clear()
yield kit.target()
im.SYNC.clear()
def own(mid: str, text: str = "", age: float = 60, kind: str = "text", url: str = "") -> dict:
return {"msg_id": mid, "sender_type": "1", "sender_id": "b1", "sender": "补货机器人", "msg_type": kind,
"text": text or None, "url": url or None,
"msg_time": dt.datetime.fromtimestamp(time.time() - age).astimezone().isoformat()}
def age_sent(sec: float = 60) -> None:
"""把已有的发出记录挪到 sec 秒前(真实情况下发送早于核对)。"""
db.q(notify_logs_t.update().where(notify_logs_t.c.direction == "out").values(
ts=db.now() - dt.timedelta(seconds=sec)))
def foreign() -> list[dict]:
return db.rows(select(notify_logs_t).where(notify_logs_t.c.event == "foreign").order_by(notify_logs_t.c.id))
def run(t, raw) -> int:
return im.reconcile_own(t, im.bot_of(t), raw)
def test_own_text_and_image_are_matched(t, kit, outbox):
im.send_to(t, REMIND, at=["zhangsan"])
im.send_image_to(t, Path("po_list.png"))
age_sent()
# 网关在前面加 @、换行变空格也认得出来;图片按地址对
raw = [own("a1", "@张三 " + REMIND.replace("\n", " ")), own("a2", kind="image", url="x")]
for _ in range(3):
assert run(t, raw) == 0
rows = db.rows(select(notify_logs_t).where(notify_logs_t.c.direction == "out").order_by(notify_logs_t.c.id))
assert [(r["msg_id"], r["bot_id"], r["pic_url"]) for r in rows] == [("a1", "bot-1", None), ("a2", "bot-1", "x")]
assert not foreign()
def test_failed_send_that_was_actually_delivered_is_ours(t, kit, outbox):
outbox.wecom_ok = False # 接口超时报失败,其实发出去了
im.send_to(t, REMIND)
age_sent()
assert run(t, [own("f1", REMIND)]) == 0 and not foreign()
def test_incident_replay_is_recorded_once(t, kit, outbox, client, admin):
"""重放 11-26 的 5 条:3 条文字 + 2 张图,本系统一条都没发过。"""
raw = [own("d3d8", REMIND, 110), own("1384", "✅ 单据页访客 已确认,正在 DMS 建单\n43 项 · 202 件,大概 3 分钟", 103),
own("accf", age=60, kind="image", url="https://oss.example.com/multi-webim/1.jpg"),
own("de8a", age=56, kind="image", url="https://oss.example.com/multi-webim/2.jpg"),
own("5800", "✅ 单建好了:S20261126012(待提交)", 50)]
n_sent = len(outbox.texts)
assert run(t, raw) == 5
assert run(t, raw) == 0 # 重复拉取 / 重启后不重复记(状态在库里)
rows = foreign()
assert [r["msg_id"] for r in rows] == ["d3d8", "1384", "accf", "de8a", "5800"]
assert all(r["bot_id"] == "bot-1" and r["direction"] == "out" and "本系统没有这条发送记录" in r["error"] for r in rows)
assert rows[0]["content"] == REMIND and rows[2]["pic_url"].endswith("/1.jpg")
# 运行事件里有消息号和域名,没有单据令牌;不告警、不往群里发话;不进助手上下文
events.flush()
ev = [e["msg"] for e in db.rows(select(events_t).where(events_t.c.msg.like("%非本系统发送%")))]
assert len(ev) == 5 and "msg_id=d3d8" in ev[0] and "https://autorestock.example.com" in ev[0]
assert not any(TOKEN in e for e in ev)
assert len(outbox.texts) == n_sent and not db.rows(select(alerts_t))
assert im.recent_chat(kit.store_id, kit.group) == []
# 后台能筛选;「发送成功 / 失败」都不算它
r = client.get("/api/wecom/logs?category=foreign", headers=admin).json()
assert r["total"] == 5 and {x["category"] for x in r["rows"]} == {"foreign"}
assert r["rows"][0]["who"] == "机器人(非本系统)" and "foreign" in r["categories"]
for res in ("ok", "failed"):
assert msglog.query(kit.store_id, result=res, categories=["foreign"])["total"] == 0
def test_same_words_sent_twice_by_someone_else(t, kit, outbox):
im.send_to(t, REMIND)
age_sent()
assert run(t, [own("m1", REMIND, 60), own("m2", REMIND, 55)]) == 1
assert len(foreign()) == 1 # 一条发出记录只能对上一条回显
def test_not_judged_too_early_or_before_target_created(t, kit, outbox):
assert run(t, [own("e1", REMIND, 20)]) == 0 and not foreign() # 刚发出:记录可能还没写库
assert run(t, [own("e1", REMIND, 50)]) == 1
assert run(t, [own("old", "很久以前", 2 * 3600)]) == 0 # 接收对象建立之前的不归本系统管
assert run(t, [own("u1", REMIND) | {"sender_type": 0}]) == 0 # 人说的话不归这里管
def test_other_bots_record_does_not_match(t, kit, outbox):
im.send_to(t, REMIND)
age_sent()
db.q(notify_logs_t.update().values(bot_id="bot-other"))
assert run(t, [own("x1", REMIND)]) == 1
def test_poll_keeps_working_when_reconcile_breaks(t, kit, outbox, monkeypatch):
seen: list[str] = []
p = im.Poller(None, None)
monkeypatch.setattr(p, "dispatch", lambda t_, sid, sname, text, msg_id="": seen.append(text))
user = {"sender_type": 0, "sender_id": "u9", "sender": "张三", "msg_type": "text",
"msg_time": dt.datetime.now().isoformat()}
batches = iter([[user | {"msg_id": "h", "text": "历史"}], [user | {"msg_id": "n", "text": "@补货助手 查 A"}]])
monkeypatch.setattr(im.imhub, "fetch_msgs", lambda *a: next(batches))
monkeypatch.setattr(im, "reconcile_own", lambda *a: 1 / 0)
p.poll_one(t)
assert p.poll_one(t) == 1 and seen == ["查 A"]
def test_poll_records_foreign(t, kit, outbox, monkeypatch):
monkeypatch.setattr(im.imhub, "fetch_msgs", lambda *a: [own("p1", REMIND)])
p = im.Poller(None, None)
p.poll_one(t)
im.Poller(None, None).poll_one(t) # 重启
assert [r["msg_id"] for r in foreign()] == ["p1"]
# ---------------------------------------------------------------------- 日志
def test_send_log_line(t, kit, outbox, caplog):
with caplog.at_level(logging.INFO, "server.im"):
im.send_to(t, REMIND, ref="restock:run:13")
outbox.wecom_ok = False
im.send_to(t, REMIND)
lines = [r for r in caplog.records if r.getMessage().startswith("企微发送")]
assert [r.levelno for r in lines] == [logging.INFO, logging.WARNING]
m = lines[0].getMessage()
for x in ("restock:run:13", "group-1", "bot-1", "https://autorestock.example.com"):
assert x in m
assert not any(TOKEN in r.getMessage() for r in lines)
def test_log_msg_failure_keeps_content_in_log(t, kit, caplog, monkeypatch):
def boom(*a, **k):
raise RuntimeError("库连不上")
monkeypatch.setattr(im.db, "q", boom)
with caplog.at_level(logging.ERROR, "server.im"):
assert im.log_msg(kit.store_id, "out", "chat", "配件计划群", "group-1", "整条内容在这里", bot_id="bot-1") is None
m = caplog.records[-1].getMessage()
assert "消息记录写入失败" in m and "整条内容在这里" in m and "group-1" in m and "bot-1" in m
def test_startup_info_has_no_secret(kit, monkeypatch):
monkeypatch.setenv("DB_URL", "mysql+pymysql://dbuser:p%40ss-secret@10.0.0.9:3308/some_db?charset=utf8mb4")
assert C.db_label() == "10.0.0.9:3308/some_db"
s = app_main.startup_info()
for x in ("10.0.0.9:3308/some_db", "对外地址", "imhub", "bot-1", "group-1", "PID"):
assert x in s
assert "ss-secret" not in s and "dbuser" not in s
monkeypatch.setenv("DB_URL", "mysql+pymysql://u:p@ss:abc/x")
assert "p@ss" not in C.db_label()
def test_request_log(client, admin, kit, caplog):
assert mask_path(f"/api/public/restock/orders/{TOKEN}/confirm") == "/api/public/restock/orders/8a0Gvz…/confirm"
assert mask_path("/api/restock/runs/13/terminate") == "/api/restock/runs/13/terminate"
with caplog.at_level(logging.INFO, "server.request"):
client.get("/api/wecom/logs", headers=admin) # 正常的读请求不记
client.post(f"/api/public/restock/orders/{TOKEN}/confirm?access_token=qs-secret", json={"pw": "body-secret"},
headers={"X-Forwarded-For": "1.2.3.4, 5.6.7.8", "User-Agent": "UA-X"})
client.get("/api/wecom/logs") # 没登录:401 要记
kit.heartbeat() # 取数端心跳不记
ms = [r.getMessage() for r in caplog.records if r.name == "server.request"]
assert len(ms) == 2
assert "POST" in ms[0] and "1.2.3.4, 5.6.7.8" in ms[0] and "UA-X" in ms[0] and "8a0Gvz…" in ms[0]
assert "401" in ms[1]
assert not any(x in m for m in ms for x in (TOKEN, "qs-secret", "body-secret"))
def test_delete_audit_has_before(client, admin, kit):
bot = kit.target()["bot_ref"]
assert client.delete(f"/api/wecom/targets/{kit.target_id}", headers=admin).status_code == 200
assert client.delete(f"/api/wecom/bots/{bot}", headers=admin).status_code == 200
rows = {r["action"]: db.jload(r["before"], {}) for r in db.rows(select(audit_t).where(
audit_t.c.action.in_(["im.target.delete", "im.bot.delete"])).order_by(audit_t.c.id))}
assert rows["im.target.delete"]["contact_id"] == "group-1" and rows["im.bot.delete"]["bot_id"] == "bot-1"
# ---------------------------------------------------------------------- 定时触发说明
def _fired() -> list[tuple[str, str]]:
events.flush()
return [(e["level"], e["msg"]) for e in db.rows(select(events_t).where(
events_t.c.msg.like("定时触发:%")).order_by(events_t.c.id))]
def test_fired_note_text(kit):
"""改推送时间后当天再次触发:说明里写清晚了多久、今天已经触发过。一天多个时刻的任务(预检)不算重复。"""
day = dt.date(2026, 10, 22)
_mark(kit.store_id, "restock", "push", day, "15:00")
_mark(kit.store_id, "restock", "push", day, "14:30")
at = lambda h, m: dt.datetime(2026, 10, 22, h, m) # noqa: E731
note, level = _fired_note(kit.store_id, "restock", "push", at(17, 2), "14:30", ["14:30"])
assert level == "warn" and "实际 17:02,晚 152 分钟" in note and "今天已在 15:00 触发过" in note
for slot in ("14:00", "14:45"):
_mark(kit.store_id, "restock", "preflight", day, slot)
assert _fired_note(kit.store_id, "restock", "preflight", at(14, 45), "14:45", ["14:00", "14:45"]) == ("14:45", "info")
def test_tick_emits_note(client, admin, kit, outbox, monkeypatch):
from app.features.restock.service import svc
async def noop(*a, **k):
return None
for name in ("push", "close", "summary", "preflight"):
monkeypatch.setattr(svc, name, noop)
db.q(events_t.delete())
fake_now(hh=15, mm=20) # 服务停到 15:20 才起来:补触发
kit.heartbeat()
kit.call(scheduler.tick, True)
push = [x for x in _fired() if "定时推送" in x[1]]
assert len(push) == 1 and push[0][0] == "warn" and "15:00,实际 15:20,晚 20 分钟" in push[0][1]
def test_tick_still_fires_when_note_breaks(client, admin, kit, outbox, monkeypatch):
from app.features.restock.service import svc
from app.services import scheduler as mod
ran: list[str] = []
async def push(sid, now, slot):
ran.append(slot)
async def noop(*a, **k):
return None
monkeypatch.setattr(svc, "push", push)
for name in ("close", "summary", "preflight"):
monkeypatch.setattr(svc, name, noop)
monkeypatch.setattr(mod, "_fired_note", lambda *a: 1 / 0)
fake_now(hh=15)
kit.heartbeat()
kit.call(scheduler.tick, True)
assert ran == ["15:00"]