conftest.py
7.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
"""测试夹具:连 .env 那台 MySQL 上的独立测试库(默认 <DB_NAME>_test,不存在就自动创建;可用 TEST_DB_NAME 指定)。
⚠️ 每次跑测试都会清空测试库里的所有表,所以库名必须以 _test 结尾,否则拒绝运行(保护开发库 / 正式库)。
企微网关、邮件、大模型都打桩,不会真的发消息。每个用例开始前清空业务数据,重建一套标准门店配置(StoreKit)。
"""
from __future__ import annotations
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
def _reset_db() -> None:
root = create_engine(f"{_BASE}/?charset=utf8mb4")
with root.begin() as c:
c.execute(text(f"CREATE DATABASE IF NOT EXISTS `{TEST_DB}` DEFAULT CHARACTER SET utf8mb4"))
root.dispose()
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)
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)"))
for cache in (features._cache, stores._cache, settings._cache, texts._cache, edge._dev_cache):
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)。"""
async def run():
return await fn(*a, **kw)
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"]