feat: add summary configuration and sync controls
This commit is contained in:
223
tests/test_web.py
Normal file
223
tests/test_web.py
Normal file
@ -0,0 +1,223 @@
|
||||
import http.client
|
||||
import json
|
||||
import stat
|
||||
import threading
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import yaml
|
||||
|
||||
from snooper_web import (
|
||||
ChatConfig,
|
||||
SnooperWebServer,
|
||||
WebError,
|
||||
chat_snapshot,
|
||||
fill_member_names,
|
||||
update_yaml_excludes,
|
||||
)
|
||||
|
||||
|
||||
def test_update_yaml_excludes_preserves_other_settings_and_comments():
|
||||
original = """# local settings
|
||||
output:
|
||||
summary: \"~/summaries/{date}.md\"
|
||||
chats:
|
||||
exclude:
|
||||
- \"old-chat\" # keep this note
|
||||
# prompt rules
|
||||
prompts:
|
||||
\"prompt-chat\": | # business
|
||||
保留这条总结要求。
|
||||
"""
|
||||
rendered = update_yaml_excludes(original, ["old-chat", "new-chat"])
|
||||
|
||||
assert '# \"old-chat\"' not in rendered
|
||||
assert '- \"old-chat\" # keep this note' in rendered
|
||||
assert '- \"new-chat\"' in rendered
|
||||
assert "# prompt rules\n prompts:" in rendered
|
||||
assert "保留这条总结要求。" in rendered
|
||||
assert yaml.safe_load(rendered)["output"]["summary"] == "~/summaries/{date}.md"
|
||||
assert yaml.safe_load(rendered)["chats"]["exclude"] == ["old-chat", "new-chat"]
|
||||
|
||||
restored = update_yaml_excludes(rendered, ["new-chat"])
|
||||
assert "keep this note" not in restored
|
||||
assert yaml.safe_load(restored)["chats"]["exclude"] == ["new-chat"]
|
||||
assert yaml.safe_load(restored)["chats"]["prompts"]["prompt-chat"].strip() == "保留这条总结要求。"
|
||||
|
||||
|
||||
def test_update_yaml_excludes_supports_empty_and_inline_config():
|
||||
assert yaml.safe_load(update_yaml_excludes("", []))["chats"]["exclude"] == []
|
||||
created = update_yaml_excludes("output: {}\n", ["group-a"])
|
||||
assert yaml.safe_load(created)["chats"]["exclude"] == ["group-a"]
|
||||
assert yaml.safe_load(created)["output"] == {}
|
||||
|
||||
inline = update_yaml_excludes("chats: {} # local\n", ["group-a"])
|
||||
assert "# local" in inline
|
||||
assert yaml.safe_load(inline)["chats"]["exclude"] == ["group-a"]
|
||||
|
||||
emptied = update_yaml_excludes("chats:\n exclude: [group-a]\n", [])
|
||||
assert yaml.safe_load(emptied)["chats"]["exclude"] == []
|
||||
|
||||
unsupported = "chats: {exclude: [old], prompts: {old: keep}}\n"
|
||||
with pytest.raises(WebError, match="原配置未修改"):
|
||||
update_yaml_excludes(unsupported, ["new"])
|
||||
|
||||
|
||||
def test_chat_config_set_ignored_is_persistent_and_keeps_mode(tmp_path):
|
||||
path = tmp_path / "config.yaml"
|
||||
path.write_text("output: {}\nchats:\n exclude: []\n", encoding="utf-8")
|
||||
path.chmod(0o640)
|
||||
config = ChatConfig(path)
|
||||
|
||||
assert config.set_ignored("group-a", True) == ["group-a"]
|
||||
assert config.set_ignored("group-a", True) == ["group-a"]
|
||||
assert config.excluded() == ["group-a"]
|
||||
assert stat.S_IMODE(path.stat().st_mode) == 0o640
|
||||
|
||||
assert config.set_ignored("group-a", False) == []
|
||||
assert config.excluded() == []
|
||||
with pytest.raises(WebError, match="布尔值"):
|
||||
config.set_ignored("group-a", "yes")
|
||||
|
||||
|
||||
def test_chat_snapshot_merges_local_and_stale_excluded_chats(tmp_path, monkeypatch):
|
||||
path = tmp_path / "config.yaml"
|
||||
path.write_text(
|
||||
"chats:\n exclude:\n - local-chat\n - stale-chat\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
class FakeStorage:
|
||||
def list_chats(self, limit):
|
||||
assert limit == 100000
|
||||
return [
|
||||
SimpleNamespace(chat_id="local-chat", name="本地群", chat_type=2),
|
||||
SimpleNamespace(chat_id="other-chat", name="另一个群", chat_type=3),
|
||||
]
|
||||
|
||||
monkeypatch.setattr("snooper_storage.SnifferStorage", FakeStorage)
|
||||
snapshot = chat_snapshot(ChatConfig(path), refresh=False)
|
||||
|
||||
assert snapshot["refreshed"] is False
|
||||
assert [chat["chat_id"] for chat in snapshot["chats"]] == [
|
||||
"local-chat",
|
||||
"other-chat",
|
||||
"stale-chat",
|
||||
]
|
||||
assert snapshot["chats"][0]["ignored"] is True
|
||||
assert snapshot["chats"][0]["sources"] == ["local"]
|
||||
assert snapshot["chats"][2]["sources"] == ["config"]
|
||||
assert snapshot["excluded"] == ["local-chat", "stale-chat"]
|
||||
|
||||
|
||||
def test_fill_member_names_batches_private_peers_and_names_groups():
|
||||
class FakeClient:
|
||||
auth = SimpleNamespace(user_id="self")
|
||||
|
||||
def __init__(self):
|
||||
self.chatter_requests = []
|
||||
|
||||
def api(self, name, data):
|
||||
if name == "chatters.PullChattersByIdsRequest":
|
||||
self.chatter_requests.append(data["chatterIds"])
|
||||
return {
|
||||
"chatters": {
|
||||
user_id: {"id": user_id, "name": f"同事-{user_id}"}
|
||||
for user_id in data["chatterIds"]
|
||||
}
|
||||
}
|
||||
assert name == "chats.PullChatChattersRequest"
|
||||
assert data["chatId"] == "unnamed-group"
|
||||
return {
|
||||
"chatters": {
|
||||
"self": {"id": "self", "name": "自己"},
|
||||
"member-a": {"id": "member-a", "name": "成员甲"},
|
||||
"member-b": {"id": "member-b", "name": "成员乙"},
|
||||
}
|
||||
}
|
||||
|
||||
client = FakeClient()
|
||||
chats = [
|
||||
{"id": "private-a", "type": 1, "key": "self:peer-a"},
|
||||
{"id": "private-b", "type": 1, "key": "peer-b:self"},
|
||||
{"id": "named-private", "type": 1, "name": "已有名字", "ownerId": "peer-c"},
|
||||
{"id": "unnamed-group", "type": 2},
|
||||
{"id": "named-group", "type": 2, "name": "已有群名"},
|
||||
]
|
||||
|
||||
resolved, warnings = fill_member_names(client, chats)
|
||||
|
||||
assert warnings == []
|
||||
assert client.chatter_requests == [["peer-a", "peer-b"]]
|
||||
assert [chat["name"] for chat in resolved] == [
|
||||
"同事-peer-a",
|
||||
"同事-peer-b",
|
||||
"已有名字",
|
||||
"成员甲、成员乙",
|
||||
"已有群名",
|
||||
]
|
||||
assert all("name" not in chat for chat in chats[:2])
|
||||
|
||||
|
||||
def test_fill_member_names_falls_back_to_private_chat_members():
|
||||
class FakeClient:
|
||||
auth = SimpleNamespace(user_id="self")
|
||||
|
||||
def api(self, name, data):
|
||||
if name == "chatters.PullChattersByIdsRequest":
|
||||
return {"chatters": {}}
|
||||
assert name == "chats.PullChatChattersRequest"
|
||||
return {
|
||||
"chatters": {
|
||||
"self": {"id": "self", "name": "自己"},
|
||||
"peer": {"id": "peer", "name": "私聊对方"},
|
||||
}
|
||||
}
|
||||
|
||||
resolved, warnings = fill_member_names(
|
||||
FakeClient(), [{"id": "private", "type": 1, "key": "self:peer"}]
|
||||
)
|
||||
|
||||
assert warnings == []
|
||||
assert resolved[0]["name"] == "私聊对方"
|
||||
|
||||
|
||||
def test_http_write_requires_csrf_token_and_updates_real_config(tmp_path):
|
||||
path = tmp_path / "config.yaml"
|
||||
path.write_text("chats:\n exclude: []\n", encoding="utf-8")
|
||||
server = SnooperWebServer(("127.0.0.1", 0), ChatConfig(path))
|
||||
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
connection = http.client.HTTPConnection("127.0.0.1", server.server_port, timeout=5)
|
||||
payload = json.dumps({"chat_id": "group-a", "ignored": True})
|
||||
try:
|
||||
connection.request(
|
||||
"POST",
|
||||
"/api/ignore",
|
||||
body=payload,
|
||||
headers={"Content-Type": "application/json"},
|
||||
)
|
||||
response = connection.getresponse()
|
||||
response.read()
|
||||
assert response.status == 403
|
||||
assert ChatConfig(path).excluded() == []
|
||||
|
||||
connection.request(
|
||||
"POST",
|
||||
"/api/ignore",
|
||||
body=payload,
|
||||
headers={
|
||||
"Content-Type": "application/json",
|
||||
"X-CSRF-Token": server.csrf_token,
|
||||
},
|
||||
)
|
||||
response = connection.getresponse()
|
||||
result = json.loads(response.read())
|
||||
assert response.status == 200
|
||||
assert result["ignored"] is True
|
||||
assert ChatConfig(path).excluded() == ["group-a"]
|
||||
finally:
|
||||
connection.close()
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
thread.join(timeout=5)
|
||||
Reference in New Issue
Block a user