# tests/test_chat.py
import pytest
from unittest.mock import AsyncMock, MagicMock
from maximem_synap import ContextResponse, Fact, ResponseMetadata
from datetime import datetime, timezone
from myapp.chat import handle_turn # your code under test
def make_fake_context(facts: list[str]) -> ContextResponse:
"""Build a realistic ContextResponse without hitting the network."""
return ContextResponse(
facts=[
Fact(
id=f"fact_{i}",
content=content,
confidence=0.9,
source="test",
extracted_at=datetime.now(timezone.utc),
)
for i, content in enumerate(facts)
],
metadata=ResponseMetadata(
correlation_id="test-corr-id",
ttl_seconds=300,
source="cloud",
retrieved_at=datetime.now(timezone.utc),
),
)
@pytest.fixture
def fake_sdk():
sdk = MagicMock()
sdk.conversation.context.fetch = AsyncMock(return_value=make_fake_context([]))
sdk.memories.create = AsyncMock(return_value=MagicMock(ingestion_id="ing_test"))
return sdk
async def test_handle_turn_uses_facts_in_prompt(fake_sdk):
fake_sdk.conversation.context.fetch.return_value = make_fake_context(
["User prefers dark mode", "User is on the Pro plan"]
)
reply = await handle_turn(
sdk=fake_sdk,
user_id="user_test",
customer_id="cust_test",
conversation_id="3f6b1a2c-4d5e-6f7a-8b9c-0d1e2f3a4b5c",
message="What plan am I on?",
)
# Assert the system prompt mentioned both retrieved facts
call_args = fake_sdk.openai_client.chat.completions.create.call_args # if you injected it
system = call_args.kwargs["messages"][0]["content"]
assert "dark mode" in system
assert "Pro plan" in system
async def test_handle_turn_ingests_the_turn(fake_sdk):
await handle_turn(sdk=fake_sdk, user_id="u", customer_id="c",
conversation_id="3f6b1a2c-4d5e-6f7a-8b9c-0d1e2f3a4b5c",
message="Hi")
fake_sdk.memories.create.assert_called_once()
kwargs = fake_sdk.memories.create.call_args.kwargs
assert kwargs["user_id"] == "u"
assert kwargs["customer_id"] == "c"
assert kwargs["document_type"] == "ai-chat-conversation"