WalkXR-AI / tests / test_chat_sessions.py
test_chat_sessions.py
Raw

"""
API session management test for the /chat endpoint.

Purpose:
- Verify that the FastAPI /chat endpoint stores conversation history
  in the in-memory session store
- Verify that repeated requests with the same session_id reuse the
  same stored session history
- Verify that the endpoint appends new conversation turns after each request

This test focuses on API/session behavior only. It does not test the real
LLM or retrieval pipeline, which are covered separately by agent/graph
integration tests.

To run this test, enter the following code in the terminal:
    sudo apt install python3-pytest
    .venv/bin/pip install ollama
    PYTHONPATH=src pytest tests/test_chat_sessions.py -q -s
"""

from fastapi.testclient import TestClient
from walkxr_ai.api.main import app, session_store
import walkxr_ai.api.main as main_module


# Create a test client for FastAPI
# This allows us to simulate HTTP requests without running a live server
client = TestClient(app)


def test_chat_endpoint_reuses_session_history(monkeypatch) -> None:
    """
    Verify that repeated /chat requests with the same session_id reuse and
    extend the stored session history.
    """
    # Resets in-memory session store at the start of the test to ensure clean slate
    session_store.clear()

    # Generate a mock response for the agent's get_response method to isolate session behavior
    def mock_get_response(user_input, history, user_id, session_id, stage):
        return {
            "response_text": f"Echo: {user_input}",
            "source_chunks": [],
            "debug": {
                "error": None,
                "phase": "history_updated",
            },
        }

    # Replace the real get_response method with our mock response
    monkeypatch.setattr(main_module.agent, "get_response", mock_get_response)

    # Two sequential requests with the same session_id should build up the session history
    payload = {
        "user_id": "test_user",
        "session_id": "session_123",
        "stage": "conversation",
        "message": "Hello",
    }
    response_1 = client.post("/chat", json=payload)
    assert response_1.status_code == 200

    payload["message"] = "How are you?"
    response_2 = client.post("/chat", json=payload)
    assert response_2.status_code == 200

    # Verify that the session store has the correct history for session_123
    assert "session_123" in session_store
    assert len(session_store["session_123"]) == 2
    assert session_store["session_123"][0] == ("Hello", "Echo: Hello")
    assert session_store["session_123"][1] == ("How are you?", "Echo: How are you?")