test_session_persistence.py
9.38 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
259
260
261
262
263
264
265
266
267
268
269
"""Session 持久化测试"""
import json
import time
import pytest
from app.infrastructure.session_store import (
SessionStore, SESSION_TTL_SECONDS, active_session_key,
)
from app.infrastructure.kv_store import InMemoryKeyValueStore
from app.agent_core.active_session_service import ActiveSessionService, ActiveSessionInfo
class TestSessionStoreTTLRefresh:
def test_get_refreshes_ttl(self):
"""读取 session 时 TTL 自动续期"""
kv = InMemoryKeyValueStore()
store = SessionStore(kv=kv)
store.set("test_ttl", {"session_id": "test_ttl"})
key = active_session_key("test_ttl")
original_expires = kv._store[key].expires_at
time.sleep(0.1)
result = store.get("test_ttl")
assert result is not None
new_expires = kv._store[key].expires_at
assert new_expires > original_expires, "TTL should be refreshed on read"
def test_expired_session_returns_none(self):
"""过期的 session 返回 None"""
kv = InMemoryKeyValueStore()
store = SessionStore(kv=kv)
store.set("expired_sess", {"session_id": "expired_sess"})
# 手动将 expires_at 设为过去时间
key = active_session_key("expired_sess")
kv._store[key].expires_at = time.time() - 1
assert store.get("expired_sess") is None
class TestActiveSessionServiceSimplified:
def test_active_session_info_has_no_user_id(self):
"""ActiveSessionInfo 不再包含 user_id"""
info = ActiveSessionInfo(
id="s1", session_id="s1",
channel="wechat_group", room_id="r1",
)
assert not hasattr(info, "user_id")
assert not hasattr(info, "current_agent_code")
def test_get_or_create_session_no_user_id(self):
"""get_or_create_session 不再接受 user_id 参数"""
svc = ActiveSessionService()
session = svc.get_or_create_session(
session_id="sess_no_uid",
room_id="room_001",
)
assert session.session_id == "sess_no_uid"
assert session.room_id == "room_001"
assert session.channel == "wechat_group"
def test_no_update_current_agent_method(self):
"""update_current_agent 方法已移除"""
svc = ActiveSessionService()
assert not hasattr(svc, "update_current_agent")
def test_payload_no_user_id_or_agent_code(self):
"""KV payload 不包含 user_id 和 current_agent_code"""
svc = ActiveSessionService()
svc.get_or_create_session(session_id="sess_payload", room_id="r1")
data = svc.store.get("sess_payload")
assert "user_id" not in data
assert "current_agent_code" not in data
assert "session_id" in data
assert "conversation_history" in data
assert "channel" in data
assert "room_id" in data
from tests.conftest import TestingSessionLocal, engine as test_engine
from app.infrastructure.database import Base
class TestDatabasePersistence:
@pytest.fixture(autouse=True)
def setup_db(self):
"""确保 ai_sessions 表存在"""
Base.metadata.create_all(bind=test_engine)
@pytest.fixture
def db(self):
db = TestingSessionLocal()
yield db
db.close()
@pytest.fixture
def svc(self, db):
return ActiveSessionService(db_factory=lambda: db)
def test_save_to_db_creates_record(self, svc, db):
"""新 session save_to_db 后 DB 有记录"""
from app.model.session import Session as DbSession
svc.get_or_create_session("db_new", room_id="room_001")
svc.save_to_db("db_new")
db_record = db.query(DbSession).filter(
DbSession.session_id == "db_new"
).first()
assert db_record is not None
assert db_record.room_id == "room_001"
assert db_record.channel == "wechat_group"
def test_save_to_db_upsert(self, svc, db):
"""第二次 save_to_db 更新而非重复创建"""
from app.model.session import Session as DbSession
svc.get_or_create_session("db_upsert", room_id="room_001")
svc.save_to_db("db_upsert")
# 修改内存中的 room_id
data = svc.store.get("db_upsert")
data["room_id"] = "room_002"
svc.store.set("db_upsert", data)
svc.save_to_db("db_upsert")
count = db.query(DbSession).filter(
DbSession.session_id == "db_upsert"
).count()
assert count == 1
record = db.query(DbSession).filter(
DbSession.session_id == "db_upsert"
).first()
assert record.room_id == "room_002"
def test_db_fallback_restores_session(self, svc, db):
"""内存不存在但 DB 存在 → 从 DB 恢复"""
svc.get_or_create_session("db_restore", room_id="room_001")
svc.save_to_db("db_restore")
# 清除内存
svc.store.delete("db_restore")
assert svc.store.get("db_restore") is None
# 再次获取 → 从 DB 恢复
session = svc.get_or_create_session("db_restore")
assert session.session_id == "db_restore"
assert session.room_id == "room_001"
def test_restore_preserves_conversation_history(self, svc, db):
"""恢复后 conversation_history 完整保留"""
from app.agent_core.memory import SessionMemory
svc.get_or_create_session("db_hist", room_id="room_001")
memory = SessionMemory(
session_id="db_hist", store=svc.store, max_rounds=20
)
memory.add("user", "你好", name="main")
memory.add("assistant", "你好!有什么可以帮你的?", name="main")
svc.save_to_db("db_hist")
# 清除内存
svc.store.delete("db_hist")
# 恢复
svc.get_or_create_session("db_hist")
restored_memory = SessionMemory(
session_id="db_hist", store=svc.store, max_rounds=20
)
messages = restored_memory.get_messages()
assert len(messages) == 2
assert messages[0]["role"] == "user"
assert messages[0]["content"] == "你好"
assert "id" in messages[0], "新格式应有 id 字段"
assert messages[1]["role"] == "assistant"
assert "id" in messages[1], "新格式应有 id 字段"
def test_save_to_db_no_db_silent_skip(self):
"""无 DB 连接时 save_to_db 静默跳过"""
svc = ActiveSessionService() # db=None
svc.get_or_create_session("no_db", room_id="room_001")
svc.save_to_db("no_db") # 不应抛异常
class TestIntentSessionPersistence:
"""intent_session 持久化与冷恢复"""
_test_ids = ["sess_intent", "sess_cold_intent", "sess_empty_intent"]
@pytest.fixture(autouse=True)
def _cleanup_intent_data(self, db_session):
yield
from app.model.session import Session
db_session.query(Session).filter(
Session.session_id.in_(self._test_ids)
).delete(synchronize_session=False)
db_session.commit()
def test_save_to_db_writes_intent_session(self, db_session):
"""save_to_db 时将 intent_session 写入 DB"""
from app.model.session import Session
svc = ActiveSessionService(db_factory=lambda: db_session)
svc.get_or_create_session(session_id="sess_intent", room_id="r1")
data = svc.store.get("sess_intent")
data["intent_session"] = [
{"role": "user", "content": "测试消息1"},
{"role": "user", "content": "测试消息2"},
]
svc.store.set("sess_intent", data)
svc.save_to_db("sess_intent")
db_row = db_session.query(Session).filter(
Session.session_id == "sess_intent"
).first()
assert db_row is not None
restored = json.loads(db_row.intent_session)
assert len(restored) == 2
assert restored[0]["content"] == "测试消息1"
def test_cold_recovery_restores_intent_session(self, db_session):
"""冷恢复时 intent_session 从 DB 回到 KV"""
from app.model.session import Session
# 先写入 DB
db_sess_row = Session(
session_id="sess_cold_intent",
room_id="r1",
channel="wechat_group",
conversation_history="[]",
intent_session=json.dumps([
{"role": "user", "content": "恢复消息"},
], ensure_ascii=False),
)
db_session.add(db_sess_row)
db_session.commit()
# 新的 ActiveSessionService(KV 为空)冷恢复
svc2 = ActiveSessionService(db_factory=lambda: db_session)
svc2.get_or_create_session(session_id="sess_cold_intent", room_id="r1")
data = svc2.store.get("sess_cold_intent")
assert data is not None
assert data["intent_session"] == [
{"role": "user", "content": "恢复消息"},
]
def test_empty_intent_session_in_db(self, db_session):
"""intent_session 为空时冷恢复也不报错"""
from app.model.session import Session
db_sess_row = Session(
session_id="sess_empty_intent",
room_id="r1",
channel="wechat_group",
conversation_history="[]",
intent_session="",
)
db_session.add(db_sess_row)
db_session.commit()
svc = ActiveSessionService(db_factory=lambda: db_session)
svc.get_or_create_session(session_id="sess_empty_intent", room_id="r1")
data = svc.store.get("sess_empty_intent")
assert data["intent_session"] == []