discord-bot / test_memory.py
jay0826's picture
Upload 4 files
b5a10c0 verified
Raw History Blame
7.97 kB
# -*- coding: utf-8 -*-
"""頻道長期記憶:存取截斷、詳細度、主題聚焦、合併/取代、模型指定。
為什麼要有這檔:2026-08-07 抓到一個靜默 bug——合併更新時誤用了「注入用的截斷版」
記憶(只有前 1800 字),導致每存一次就永久吃掉後面的舊記憶。這種錯不會噴例外、
使用者也看不出來,只有測試抓得到。以下 test_merge_uses_full_not_truncated 就是它的守門員。
"""
import discordbot as db
# ── 共用:直接操作記憶體層(SB_DB_ON 在測試環境為 False,不會碰 Supabase)──
def _reset(cid):
db.clear_channel_memory(cid)
def _capture_prompt(monkeypatch):
"""攔截 ask_gemini_raw,回傳 (呼叫參數紀錄, 假回應)。不發任何網路請求。"""
calls = {}
def fake(prompt, **kw):
calls["prompt"] = prompt
calls["kw"] = kw
return "1. 假摘要\n1.1. 內容"
monkeypatch.setattr(db, "ask_gemini_raw", fake)
return calls
# ── 截斷:注入版 vs 完整版(今天那個 bug 的守門員)──
def test_full_vs_truncated_split():
cid = 9001
_reset(cid)
long_mem = "字" * 5000
db.set_channel_memory(cid, long_mem)
assert len(db.get_channel_memory_full(cid)) == 5000 # 完整版不截
assert len(db.get_channel_memory(cid)) == db.CHAN_MEM_INJECT_CHARS # 注入版有截
_reset(cid)
def test_merge_uses_full_not_truncated():
"""★核心迴歸測試:合併路徑必須拿完整記憶,否則每存一次就啃掉一截。"""
import inspect
src = inspect.getsource(db.remember_channel)
assert "get_channel_memory_full" in src, "合併若用截斷版,舊記憶會逐次流失"
assert "existing = get_channel_memory(" not in src
def test_memory_empty_and_clear():
cid = 9002
_reset(cid)
assert db.get_channel_memory(cid) == ""
assert db.get_channel_memory_full(cid) == ""
db.set_channel_memory(cid, "1. 有東西")
assert "有東西" in db.get_channel_memory_full(cid)
db.clear_channel_memory(cid)
assert db.get_channel_memory_full(cid) == ""
# ── 詳細度四級 ──
def test_detail_levels_distinct():
"""四級必須各自不同(項目數遞增),否則選了等於沒選。"""
items = [int(db._MEM_DETAIL[k]["items"]) for k in ("精簡", "標準", "詳細", "鉅細靡遺")]
assert items == sorted(items) and len(set(items)) == 4
assert db.MEM_DETAIL_DEFAULT in db._MEM_DETAIL
def test_detail_output_tokens_scale():
"""輸出上限必須跟著詳細度放大——不然樹會被腰斬(2026-08-07 實案)。"""
tok = [db._MEM_OUT_TOK[k] for k in ("精簡", "標準", "詳細", "鉅細靡遺")]
assert tok == sorted(tok) and len(set(tok)) == 4
assert tok[1] > db.MAX_OUTPUT_HEAVY # 標準也要比預設 heavy 大,否則照樣被砍
def test_detail_reaches_prompt(monkeypatch):
calls = _capture_prompt(monkeypatch)
db.summarize_channel_history("阿樹:測試", detail="鉅細靡遺")
assert "鉅細靡遺" in calls["prompt"]
assert calls["kw"]["max_output_override"] == db._MEM_OUT_TOK["鉅細靡遺"]
assert calls["kw"]["no_search"] is True # 純整理任務不該聯網燒配額
def test_unknown_detail_falls_back(monkeypatch):
"""亂傳詳細度不能炸,要退回預設。"""
calls = _capture_prompt(monkeypatch)
db.summarize_channel_history("阿樹:測試", detail="超級無敵詳細")
assert calls["kw"]["max_output_override"] == 4096 # _MEM_OUT_TOK.get 的預設
# ── 主題聚焦:merge / replace 兩種語意 ──
def test_focus_empty_behaves_as_before(monkeypatch):
calls = _capture_prompt(monkeypatch)
db.summarize_channel_history("阿樹:測試", focus="")
assert "只記這個主題" not in calls["prompt"]
assert "只保留這個主題" not in calls["prompt"]
def test_focus_merge_preserves_other_topics(monkeypatch):
calls = _capture_prompt(monkeypatch)
db.summarize_channel_history("阿樹:測試", existing_memory="1. 舊的", focus="osu", replace=False)
p = calls["prompt"]
assert "osu" in p
assert "原封不動保留" in p # 合併:其他主題舊記憶要留著
assert "判斷放寬" in p # 放寬判定,否則窄主題只撈到寥寥數項
def test_focus_replace_drops_other_topics(monkeypatch):
calls = _capture_prompt(monkeypatch)
db.summarize_channel_history("阿樹:測試", existing_memory="1. 舊的", focus="osu", replace=True)
p = calls["prompt"]
assert "只保留這個主題" in p
assert "不要輸出" in p # 取代:無關的既有項目不得輸出
assert "判斷放寬" in p # ★兩種模式都要放寬(replace 分支曾漏掉)
def test_focus_both_modes_have_depth_instruction(monkeypatch):
"""focus 收窄後,詳細度必須在主題「內部」生效,否則寫 6 項也算交差。"""
for rep in (True, False):
calls = _capture_prompt(monkeypatch)
db.summarize_channel_history("阿樹:測試", focus="身份", replace=rep, detail="鉅細靡遺")
assert "內部" in calls["prompt"] and "150" in calls["prompt"]
def test_focus_forbids_fabrication(monkeypatch):
"""反瞎掰底線:找不到內容時不准硬編(兩種模式都要有)。"""
for rep in (True, False):
calls = _capture_prompt(monkeypatch)
db.summarize_channel_history("阿樹:測試", focus="不存在的主題", replace=rep)
assert "硬編" in calls["prompt"] or "不要硬編" in calls["prompt"]
# ── 模型指定 ──
def test_model_override_passthrough(monkeypatch):
calls = _capture_prompt(monkeypatch)
db.summarize_channel_history("阿樹:測試", model="glm-5.2-nv")
assert calls["kw"]["model_override"] == "glm-5.2-nv"
def test_model_empty_means_auto(monkeypatch):
calls = _capture_prompt(monkeypatch)
db.summarize_channel_history("阿樹:測試", model="")
assert calls["kw"]["model_override"] is None # None=沿用自動路由
def test_memory_model_menu_all_valid():
"""/memory save 的模型選單每一支都要真的叫得動(走 OC 或 Gemini 路),否則選了就 404。"""
import ast
src = open("discordbot.py", encoding="utf-8").read()
fn = next(n for n in ast.walk(ast.parse(src))
if isinstance(n, ast.AsyncFunctionDef) and n.name == "memory_save")
picks = []
for dec in fn.decorator_list:
if isinstance(dec, ast.Call) and getattr(dec.func, "attr", "") == "choices":
for kw in dec.keywords:
if kw.arg == "model":
picks = [[k.value.value for k in e.keywords if k.arg == "value"][0]
for e in kw.value.elts]
assert picks, "選單不該是空的"
for m in picks:
assert m in db._OPENAI_COMPAT or m.startswith("gemini-"), f"{m} 兩條路都走不到"
# ── 對話轉文字(含「圖片有沒有被讀」這個常見誤解)──
class _Att:
def __init__(self, filename):
self.filename = filename
class _Msg:
def __init__(self, content="", attachments=(), embeds=()):
self.content, self.attachments, self.embeds = content, list(attachments), list(embeds)
def test_attachment_only_records_filename():
"""圖片內容不會進記憶——只留檔名。這是刻意的(讀圖要跑視覺模型,配額吃不消)。"""
out = db.message_to_text(_Msg("看這張", [_Att("IMG_1234.png")]))
assert "看這張" in out and "IMG_1234.png" in out
assert "[附件]" in out
def test_message_to_text_empty_cases():
assert db.message_to_text(None) == ""
assert db.message_to_text(_Msg("")) == ""
def test_msgs_to_text_respects_cap():
msgs = [{"author": "阿樹", "content": "字" * 500} for _ in range(200)]
assert len(db._msgs_to_text(msgs)) <= db.CHAN_MEM_RAW_CHARS