Files
Lark-Snooper/tests/test_summary.py

390 lines
13 KiB
Python

import argparse
import json
import stat
from datetime import date, datetime
from types import SimpleNamespace
from zoneinfo import ZoneInfo
import pytest
from larkx.cli import cmd_summarize
from larkx.storage import Storage
from larkx.summary import (
DEFAULT_MODEL,
MagpieClient,
SummaryError,
chunk_messages,
require_efund_model,
resolve_day,
summarize_messages,
write_summary,
)
class FakeResponse:
def __init__(self, data, status_code=200):
self.data = data
self.status_code = status_code
def json(self):
return self.data
class FakeSession:
def __init__(self, models=None, completions=None):
self.models = models if models is not None else [DEFAULT_MODEL]
self.completions = list(completions or [])
self.get_calls = []
self.post_calls = []
def get(self, url, **kwargs):
self.get_calls.append((url, kwargs))
return FakeResponse({"data": [{"id": model} for model in self.models]})
def post(self, url, **kwargs):
self.post_calls.append((url, kwargs))
if not self.completions:
return FakeResponse({"model": DEFAULT_MODEL, "choices": []})
model, content = self.completions.pop(0)
return FakeResponse(
{"model": model, "choices": [{"message": {"content": content}}]}
)
def synthetic_row(
msg_id="m1",
content="合成消息",
create_time=1_792_000_000,
chat_id="chat-test",
chat_name="合成群",
chat_type=2,
):
return SimpleNamespace(
msg_id=msg_id,
create_time=create_time,
chat_id=chat_id,
chat_name=chat_name,
chat_type=chat_type,
sender_id="sender-test",
sender_name="合成用户",
msg_type_name="TEXT",
direction="in",
content=content,
)
def test_model_policy_checks_actual_model_after_optional_routing_prefix():
assert require_efund_model(DEFAULT_MODEL) == DEFAULT_MODEL
assert require_efund_model("EFundGPT-other") == "EFundGPT-other"
routed_model = "maqqie/gg-chat/EFundGPT-dsv4pro"
assert require_efund_model(routed_model) == routed_model
for model in (
"",
"deepseek-v4-pro",
"efundgpt-dsv4-pro",
"maqqie/gg-chat/deepseek-v4-pro",
"maqqie/gg-chat/efundgpt-dsv4-pro",
"maqqie/gg-chat/",
" EFundGPT-dsv4-pro",
):
with pytest.raises(SummaryError):
require_efund_model(model)
def test_preflight_requires_exact_model_and_sends_no_chat():
session = FakeSession(models=["maqqie/gg-chat/EFundGPT-dsv4pro"])
client = MagpieClient(DEFAULT_MODEL, session=session)
with pytest.raises(SummaryError, match="已拒绝读取消息"):
client.assert_model_available()
assert len(session.get_calls) == 1
assert session.post_calls == []
def test_non_efund_response_is_not_returned():
session = FakeSession(completions=[("deepseek-v4-pro", "不应返回")])
client = MagpieClient(DEFAULT_MODEL, session=session)
with pytest.raises(SummaryError, match="EFundGPT"):
client.complete("仅含合成数据的测试")
def test_http_error_does_not_expose_response_body():
class ErrorSession(FakeSession):
def post(self, url, **kwargs):
return FakeResponse({"echo": "敏感合成正文"}, status_code=400)
client = MagpieClient(DEFAULT_MODEL, session=ErrorSession())
with pytest.raises(SummaryError) as error:
client.complete("敏感合成正文")
assert "敏感合成正文" not in str(error.value)
def test_chunking_preserves_every_character_and_respects_limit():
original = "甲" * 4700
rows = [synthetic_row(content=original), synthetic_row("m2", content="第二条")]
messages = [
{
"msg_id": row.msg_id,
"time": "2026-11-03T10:00:00+08:00",
"chat_id": row.chat_id,
"content": row.content,
}
for row in rows
]
chunks = chunk_messages(messages, max_chars=2000)
assert len(chunks) > 1
flattened = [message for chunk in chunks for message in chunk]
assert "".join(
message["content"] for message in flattened if message["msg_id"] == "m1"
) == original
assert [message["content"] for message in flattened if message["msg_id"] == "m2"] == [
"第二条"
]
for chunk in chunks:
assert sum(len(json.dumps(item, ensure_ascii=False)) for item in chunk) < 2300
def test_multi_chunk_summary_uses_same_approved_model_for_all_calls():
session = FakeSession(
completions=[
(DEFAULT_MODEL, "第一部分"),
(DEFAULT_MODEL, "第二部分"),
(DEFAULT_MODEL, "单对话摘要"),
(DEFAULT_MODEL, "最终总结"),
]
)
client = MagpieClient(DEFAULT_MODEL, session=session)
rows = [synthetic_row(content="一" * 1200), synthetic_row("m2", content="二" * 1200)]
_, _, _, tz = resolve_day("2026-11-03", "Asia/Shanghai")
result = summarize_messages(client, rows, date(2026, 11, 3), tz, max_chars=2000)
assert result == "最终总结"
assert len(session.post_calls) == 4
for _, kwargs in session.post_calls:
assert kwargs["json"]["model"] == DEFAULT_MODEL
def test_summary_is_per_conversation_before_daily_combination():
session = FakeSession(
completions=[
(DEFAULT_MODEL, "群聊摘要"),
(DEFAULT_MODEL, "私聊摘要"),
(DEFAULT_MODEL, "最终日度总结"),
]
)
client = MagpieClient(DEFAULT_MODEL, session=session)
rows = [
synthetic_row(
"group-message",
content="群聊原始内容",
chat_id="group-a",
chat_name="项目群",
chat_type=2,
),
synthetic_row(
"private-message",
content="私聊原始内容",
chat_id="private-b",
chat_name="同事甲",
chat_type=1,
),
]
_, _, _, tz = resolve_day("2026-11-03", "Asia/Shanghai")
result = summarize_messages(client, rows, date(2026, 11, 3), tz)
assert result == "最终日度总结"
assert len(session.post_calls) == 3
prompts = [
kwargs["json"]["messages"][1]["content"]
for _, kwargs in session.post_calls
]
assert "群聊原始内容" in prompts[0]
assert "私聊原始内容" not in prompts[0]
assert "私聊原始内容" in prompts[1]
assert "群聊原始内容" not in prompts[1]
assert "群聊摘要" in prompts[2]
assert "私聊摘要" in prompts[2]
assert "群聊原始内容" not in prompts[2]
assert "私聊原始内容" not in prompts[2]
def test_storage_selects_only_received_messages_inside_day_and_chat():
storage = Storage(url="sqlite:///:memory:")
tz = ZoneInfo("Asia/Shanghai")
start = int(datetime(2026, 11, 3, 0, 0, tzinfo=tz).timestamp())
end = int(datetime(2026, 11, 4, 0, 0, tzinfo=tz).timestamp())
base = {
"chat_id": "chat-a",
"chat_type": 2,
"from_id": "sender-a",
"msg_type": 4,
"msg_type_name": "TEXT",
"create_time": start + 100,
}
storage.save_message({**base, "msg_id": "in-day", "content": "合成收到"}, direction="in")
storage.save_message({**base, "msg_id": "out-day", "content": "合成发出"}, direction="out")
storage.save_message(
{**base, "msg_id": "in-other-chat", "chat_id": "chat-b", "content": "其他会话"},
direction="in",
)
storage.save_message(
{**base, "msg_id": "before-day", "create_time": start - 1}, direction="in"
)
storage.save_message(
{**base, "msg_id": "at-end", "create_time": end}, direction="in"
)
rows = storage.get_received_messages(start, end, chat_ids=["chat-a"])
assert [row.msg_id for row in rows] == ["in-day"]
def test_yaml_config_resolves_dated_output_paths(tmp_path):
from larkx.summary import configured_output_path, load_output_config
config_file = tmp_path / "larksniffer.yaml"
config_file.write_text(
"output:\n"
f" summary: '{tmp_path}/summaries/{{date}}.md'\n"
f" dry_run: '{tmp_path}/dry-runs/{{date}}.json'\n",
encoding="utf-8",
)
config = load_output_config(config_file)
target_day = date(2026, 11, 3)
assert configured_output_path(config, "summary", target_day) == (
tmp_path / "summaries" / "2026-11-03.md"
)
assert configured_output_path(config, "dry_run", target_day) == (
tmp_path / "dry-runs" / "2026-11-03.json"
)
def test_summary_file_is_private(tmp_path):
output = write_summary(tmp_path / "private" / "summary.md", "合成总结")
assert output.read_text(encoding="utf-8") == "合成总结\n"
assert stat.S_IMODE(output.stat().st_mode) == 0o600
def test_cli_end_to_end_with_synthetic_db_and_fake_magpie(
tmp_path, monkeypatch, capsys
):
database_url = f"sqlite:///{tmp_path / 'synthetic.db'}"
storage = Storage(url=database_url)
_, start, _, _ = resolve_day("2026-11-03", "Asia/Shanghai")
base = {
"chat_id": "chat-synthetic",
"chat_type": 2,
"from_id": "sender-synthetic",
"msg_type": 4,
"msg_type_name": "TEXT",
"create_time": int(start.timestamp()) + 60,
}
storage.save_message(
{**base, "msg_id": "incoming", "content": "合成收到内容"}, direction="in"
)
storage.save_message(
{**base, "msg_id": "outgoing", "content": "合成发出内容"}, direction="out"
)
monkeypatch.setenv("LARKX_STORAGE_URL", database_url)
session = FakeSession(
completions=[(DEFAULT_MODEL, "单对话摘要"), (DEFAULT_MODEL, "# 合成总结")]
)
monkeypatch.setattr("larkx.summary.requests.Session", lambda: session)
output = tmp_path / "summary.md"
args = argparse.Namespace(
date="2026-11-03",
timezone="Asia/Shanghai",
model=DEFAULT_MODEL,
base_url="http://127.0.0.1:3425/v1",
timeout=1,
chat=None,
max_chars=80000,
output=output,
check=False,
dry_run=False,
)
assert cmd_summarize(args) == 0
assert output.read_text(encoding="utf-8") == "# 合成总结\n"
request_text = session.post_calls[0][1]["json"]["messages"][1]["content"]
assert "合成收到内容" in request_text
assert "合成发出内容" not in request_text
terminal = capsys.readouterr()
assert "合成收到内容" not in terminal.out + terminal.err
def test_cli_dry_run_exports_records_without_calling_model(
tmp_path, monkeypatch, capsys
):
database_url = f"sqlite:///{tmp_path / 'synthetic.db'}"
storage = Storage(url=database_url)
_, start, _, _ = resolve_day("2026-11-03", "Asia/Shanghai")
base = {
"chat_id": "chat-synthetic",
"chat_type": 2,
"from_id": "sender-synthetic",
"msg_type": 4,
"msg_type_name": "TEXT",
"create_time": int(start.timestamp()) + 60,
}
storage.save_message(
{**base, "msg_id": "incoming", "content": "合成收到内容"}, direction="in"
)
storage.save_message(
{**base, "msg_id": "outgoing", "content": "合成发出内容"}, direction="out"
)
monkeypatch.setenv("LARKX_STORAGE_URL", database_url)
session = FakeSession(completions=[(DEFAULT_MODEL, "不应生成")])
monkeypatch.setattr("larkx.summary.requests.Session", lambda: session)
output = tmp_path / "from-yaml" / "2026-11-03.json"
config_file = tmp_path / "larksniffer.yaml"
config_file.write_text(
f"output:\n dry_run: '{tmp_path}/from-yaml/{{date}}.json'\n",
encoding="utf-8",
)
args = argparse.Namespace(
date="2026-11-03",
timezone="Asia/Shanghai",
model=DEFAULT_MODEL,
base_url="http://127.0.0.1:3425/v1",
timeout=1,
chat=None,
max_chars=80000,
output=None,
config=config_file,
check=False,
dry_run=True,
)
assert cmd_summarize(args) == 0
assert session.post_calls == []
records = json.loads(output.read_text(encoding="utf-8"))
assert [record["msg_id"] for record in records] == ["incoming"]
assert records[0]["content"] == "合成收到内容"
assert stat.S_IMODE(output.stat().st_mode) == 0o600
terminal = capsys.readouterr()
assert "合成收到内容" not in terminal.out + terminal.err
def test_cli_model_failure_happens_before_storage_is_opened(monkeypatch):
monkeypatch.setattr(
MagpieClient,
"assert_model_available",
lambda self: (_ for _ in ()).throw(SummaryError("合成模型错误")),
)
def storage_must_not_open():
raise AssertionError("模型检查失败时不应打开消息库")
monkeypatch.setattr("larkx.cli.Storage", storage_must_not_open)
args = argparse.Namespace(
date="2026-11-03",
timezone="Asia/Shanghai",
model=DEFAULT_MODEL,
base_url="http://127.0.0.1:3425/v1",
timeout=1,
chat=None,
max_chars=2000,
output=None,
check=False,
dry_run=False,
)
assert cmd_summarize(args) == 1