test_memory.py 2.53 KB
"""SessionMemory unit tests — message add/get/truncation/mark."""
import pytest
from datetime import datetime, timezone
from app.agent_core.memory import SessionMemory
from app.infrastructure.session_store import SessionStore, clear_default_store_for_tests


@pytest.fixture
def store():
    clear_default_store_for_tests()
    return SessionStore()


@pytest.fixture
def active_session(store):
    session_id = "test_session_001"
    store.set(session_id, {
        "session_id": session_id,
        "user_id": "u1",
        "channel": "test",
        "current_agent_id": 101,
        "conversation_history": [
            {"role": "user", "content": "你好", "agent_code": "main",
             "agent_id": None, "intent": None, "timestamp": datetime.now(timezone.utc).isoformat()},
            {"role": "assistant", "content": "你好!有什么可以帮助你的?", "agent_code": "main",
             "agent_id": 101, "intent": None, "timestamp": datetime.now(timezone.utc).isoformat()},
        ],
        "context_entities": {},
        "created_at": datetime.now(timezone.utc).isoformat(),
        "updated_at": datetime.now(timezone.utc).isoformat(),
    })
    return session_id


class TestSessionMemory:
    def test_get_messages_returns_history(self, store, active_session):
        memory = SessionMemory(active_session, store)
        msgs = memory.get_messages()
        assert len(msgs) == 2
        assert msgs[0]["content"] == "你好"

    def test_add_appends_message(self, store, active_session):
        memory = SessionMemory(active_session, store)
        memory.add("user", "天气怎么样?")
        msgs = memory.get_messages()
        assert len(msgs) == 3
        assert msgs[-1]["content"] == "天气怎么样?"

    def test_truncation_with_many_messages(self, store, active_session):
        # Insert 50 messages (total 52 with the 2 seeded) via memory.add()
        memory = SessionMemory(active_session, store, max_rounds=5)
        for i in range(50):
            memory.add("user", f"msg {i}")
        msgs = memory.get_messages()
        # Should contain summary + at most 10 recent messages (5 rounds × 2)
        assert len(msgs) <= 11  # 1 summary + 10 msgs
        # First message should be the summary
        assert "早期对话摘要" in msgs[0]["content"]

    def test_mark_inserts_checkpoint(self, store, active_session):
        memory = SessionMemory(active_session, store)
        memory.mark("checkpoint_1")
        msgs = memory.get_messages()
        assert any("[MARK: checkpoint_1]" in m.get("content", "") for m in msgs)