conftest.py
10.6 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
"""测试夹具:连 .env 那台 MySQL 上的独立测试库(默认 <DB_NAME>_test,必须事先手工建好,不会自动建库;可用 TEST_DB_NAME 指定)。
⚠️ 每次跑测试都会清空测试库里的所有表,所以库名必须以 _test 结尾,否则拒绝运行(保护开发库 / 正式库)。
企微网关、邮件、大模型都打桩,不会真的发消息。每个用例开始前清空业务数据,重建一套标准门店配置(StoreKit)。
"""
from __future__ import annotations
import asyncio
import datetime as dt
import os
import sys
import tempfile
from pathlib import Path
from urllib.parse import quote_plus
import pytest
from dotenv import dotenv_values
SERVER = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(SERVER))
_ENV = dotenv_values(SERVER.parent / ".env") # 仓库根目录的 .env
REAL_LLM_KEY = _ENV.get("LLM_API_KEY") or "" # 只给 RUN_LLM=1 的真实模型测试用
TEST_DB = os.environ.get("TEST_DB_NAME") or (str(_ENV.get("DB_NAME") or "restock") + "_test")
if not TEST_DB.endswith("_test"):
raise SystemExit(f"测试库名必须以 _test 结尾(当前 {TEST_DB}),测试会清空整个库")
_BASE = "mysql+pymysql://{u}:{p}@{h}:{port}".format(
u=quote_plus(str(_ENV.get("DB_USER") or "")), p=quote_plus(str(_ENV.get("DB_PASSWORD") or "")),
h=_ENV.get("DB_HOST") or "127.0.0.1", port=_ENV.get("DB_PORT") or "3306")
os.environ.update({
"APP_ENV": "test", "DB_URL": f"{_BASE}/{TEST_DB}?charset=utf8mb4", "LLM_API_KEY": "",
"SECRET_KEY": "test-secret-key", "DATA_DIR": tempfile.mkdtemp(prefix="restock_test_"),
"DEMO_MOCK_DMS": "", "ADMIN_USERNAME": "admin", "ADMIN_PASSWORD": "",
"OPERATOR_USERNAME": "", "SMTP_HOST": ""})
from fastapi.testclient import TestClient # noqa: E402
from sqlalchemy import create_engine, text # noqa: E402
from app import features # noqa: E402
from app.core import clock, db # noqa: E402
from app.models import stores_t, users_t # noqa: E402
from app.services import edge, im, imhub, notify, settings, stores, texts # noqa: E402
CALL_TIMEOUT_S = float(os.environ.get("TEST_CALL_TIMEOUT") or 120) # StoreKit.call 单次最长等待
_LOCK_CONN = None # 整个测试进程一直占着的 MySQL 命名锁连接(进程退出 / 被杀,MySQL 自动释放锁)
def _take_db_lock(root) -> None:
"""同一个测试库同一时间只允许一个 pytest 进程用:每次运行开头会清空整个库,两个会话同时跑会互相删表,
表现为测到一半卡死或莫名失败。拿不到锁就直接退出并说明,不等待。"""
global _LOCK_CONN
_LOCK_CONN = root.connect()
got = _LOCK_CONN.execute(text("SELECT GET_LOCK(:n, 0)"), {"n": f"pytest:{TEST_DB}"}).scalar()
if got != 1:
who = _LOCK_CONN.execute(text("SELECT IS_USED_LOCK(:n)"), {"n": f"pytest:{TEST_DB}"}).scalar()
pytest.exit(f"测试库 {TEST_DB} 正被另一个 pytest 进程使用(MySQL 连接 {who}),"
"等它跑完再试;或用 TEST_DB_NAME 指定另一个已有的 _test 库", returncode=3)
def _reset_db() -> None:
root = create_engine(f"{_BASE}/?charset=utf8mb4")
with root.connect() as c:
exists = c.execute(text("SELECT 1 FROM information_schema.schemata WHERE schema_name = :n"),
{"n": TEST_DB}).first()
if not exists: # 不自动建库:测试库必须由人手工建好
root.dispose()
raise SystemExit(f"测试库 {TEST_DB} 不存在。请先手工建库(CREATE DATABASE `{TEST_DB}` "
f"DEFAULT CHARACTER SET utf8mb4),或用 TEST_DB_NAME 指定已有的 _test 库")
_take_db_lock(root)
eng = db.init_engine()
with eng.begin() as c:
names = [r[0] for r in c.execute(text(
"SELECT table_name FROM information_schema.tables WHERE table_schema = DATABASE()"))]
c.execute(text("SET FOREIGN_KEY_CHECKS=0"))
for n in names:
c.execute(text(f"DROP TABLE `{n}`"))
c.execute(text("SET FOREIGN_KEY_CHECKS=1"))
class Outbox:
"""打桩的企微 / 邮件:记录所有发出的消息。"""
def __init__(self) -> None:
self.texts: list[dict] = []
self.images: list[dict] = []
self.emails: list[dict] = []
self.wecom_ok = True
def clear(self) -> None:
self.texts.clear()
self.images.clear()
self.emails.clear()
self.wecom_ok = True
def to(self, address: str) -> list[str]:
return [m["text"] for m in self.texts if m["to"] == address]
OUT = Outbox()
@pytest.fixture(scope="session", autouse=True)
def _patch_network():
imhub.send_text = lambda bot, to, txt, at=None: (OUT.texts.append({"to": to, "text": txt, "at": at or [],
"bot": bot["bot_id"]}),
(OUT.wecom_ok, "" if OUT.wecom_ok else "网关不可达"))[1]
imhub.send_image = lambda bot, to, path, url="": (OUT.images.append({"to": to, "path": str(path)}), (True, "", "x"))[1]
imhub.fetch_msgs = lambda bot, contact, start, end: []
notify.send_email = lambda to, subject, body: (OUT.emails.append({"to": to, "subject": subject, "body": body}),
(True, ""))[1]
yield
@pytest.fixture(scope="session")
def client():
_reset_db()
from app.main import create_app
app = create_app(background=False)
with TestClient(app) as c:
edge._started_at = edge._started_mono = None # 用例里的假时钟不受「云端刚启动」宽限期影响
yield c
clock.set_fake(None)
@pytest.fixture()
def outbox():
OUT.clear()
yield OUT
OUT.clear()
@pytest.fixture(autouse=True)
def _real_clock():
yield
clock.set_fake(None)
@pytest.fixture(autouse=True)
def fake_model(monkeypatch):
"""默认用假大模型(tests/fake_llm.py:按关键词选工具),并当作大模型已配置。
要测「大模型不可用」:monkeypatch.setattr(agent, "llm_ready", lambda: "原因")。"""
from app.services import agent
from tests import fake_llm
monkeypatch.setattr(agent, "llm_ready", lambda: "")
monkeypatch.setattr(agent.Assistant, "_run_llm", fake_llm.run)
def login(client, username: str, password: str) -> dict:
r = client.post("/api/auth/login", json={"username": username, "password": password})
assert r.status_code == 200, r.text
return {"Authorization": "Bearer " + r.json()["access_token"]}
@pytest.fixture(scope="session")
def admin(client) -> dict:
return login(client, "admin", "admin123")
KEEP = {users_t.name, stores_t.name, db.VERSION_TABLE}
def clean_business_data() -> None:
with db.tx() as c:
names = [r[0] for r in c.execute(text(
"SELECT table_name FROM information_schema.tables WHERE table_schema = DATABASE()"))]
for n in names:
if n not in KEEP:
c.execute(text(f"DELETE FROM `{n}`"))
st = stores_t.name
c.execute(text(f"DELETE FROM `{st}` WHERE id <> (SELECT m FROM (SELECT MIN(id) m FROM `{st}`) x)"))
from app.features import skills
from app.features.restock.skills import part_query
for cache in (features._cache, skills._cache, stores._cache, settings._cache, texts._cache, edge._dev_cache,
part_query._asked):
cache.clear()
class StoreKit:
"""默认门店的一套标准配置:开通补货、厂商账号、企微机器人 + 群(补货对话 + 告警)、取数端设备。"""
def __init__(self, client, admin) -> None:
clean_business_data()
self.c = client
self.h = admin
self.store_id = stores.default_store_id()
features.save(self.store_id, "restock", enabled=True, values={}, by="test")
r = client.put("/api/client/dms/gtmc", json={"username": "dms_user", "password": "dms-pass-1"}, headers=admin)
assert r.status_code == 200, r.text
bot = client.post("/api/wecom/bots", json={"name": "补货机器人", "bot_id": "bot-1"}, headers=admin).json()["id"]
self.group = "group-1"
self.contact = self.group
r = client.post("/api/wecom/targets", json={"name": "配件计划群", "bot_ref": bot, "kind": "group",
"contact_id": self.group, "at_ids": "zhangsan",
"bot_names": "补货助手",
"purposes": ["chat", "alert"], "alert_min": "warn"}, headers=admin)
assert r.status_code == 200, r.text
self.target_id = r.json()["id"]
d = client.post("/api/client/devices", json={"name": "配件部电脑"}, headers=admin).json()
self.device_id, self.token = d["id"], d["token"]
self.eh = {"X-Edge-Token": self.token}
def heartbeat(self, **kw) -> dict:
body = {"version": "3.0.0", "state": "idle"} | kw
r = self.c.post("/api/edge/v1/heartbeat", json=body, headers=self.eh)
assert r.status_code == 200, r.text
return r.json()
def svc(self):
from app.features.restock.service import svc
return svc
def call(self, fn, *a, **kw):
"""在应用的事件循环里执行协程函数(TestClient 的 portal)。
超过 CALL_TIMEOUT_S 没结束就失败并列出还挂着的后台任务(以前会无限等,整个测试卡死、没有任何输出)。"""
async def run():
try:
return await asyncio.wait_for(fn(*a, **kw), CALL_TIMEOUT_S)
except asyncio.TimeoutError:
me = asyncio.current_task()
stuck = []
for t in asyncio.all_tasks():
if t is me or t.done():
continue
frames = t.get_stack(limit=4)
where = " <- ".join(f"{Path(f.f_code.co_filename).name}:{f.f_lineno} {f.f_code.co_name}"
for f in frames) or "?"
stuck.append(f" {t.get_name()}: {where}")
raise AssertionError(f"{getattr(fn, '__qualname__', fn)} 超过 {CALL_TIMEOUT_S:.0f} 秒没结束,"
"还挂着的后台任务:\n" + "\n".join(stuck[:20])) from None
return self.c.portal.call(run)
def target(self) -> dict:
return im.target(self.target_id)
@pytest.fixture()
def kit(client, admin) -> StoreKit:
return StoreKit(client, admin)
def fake_now(y=2026, m=10, d=22, hh=15, mm=0) -> dt.datetime:
t = dt.datetime(y, m, d, hh, mm)
clock.set_fake(t)
return t
__all__ = ["login", "StoreKit", "fake_now", "OUT", "db", "clean_business_data"]