Skip to content

Commit 3a444b1

Browse files
add test for chat context (#2677)
# Add Comprehensive Tests for Chat Context Module ## Overview This PR adds comprehensive test coverage for the `chat_context` module, ensuring robust testing of message history management, session isolation, and OpenAI format conversion functionality. ## Changes - **New Test File**: `backend/tests/test_chat_context.py` with 28 test cases - **Test Coverage**: Message management (get, add, remove, clear), OpenAI conversion, and edge cases - **Context Helper**: Custom `mock_chainlit_context()` helper for proper Chainlit context initialization ## Test Suites ### 1. Core Functionality Tests (22 tests) - **`get()` method** (4 tests) - Returns empty list without session - Creates new chat context for new sessions - Returns copy of messages (not original reference) - Retrieves existing messages correctly - **`add()` method** (5 tests) - Does nothing without session - Creates new context and adds message - Appends to existing context - Prevents duplicate messages - Returns message for method chaining - **`remove()` method** (5 tests) - Returns False without session - Returns False for nonexistent context - Returns False for nonexistent message - Successfully removes existing message - Maintains remaining messages after removal - **`clear()` method** (3 tests) - Does nothing without session - Does nothing for nonexistent context - Empties existing context while preserving structure - **`to_openai()` method** (10 tests) - Converts assistant messages to `{"role": "assistant", "content": "..."}` - Converts user messages to `{"role": "user", "content": "..."}` - Converts system messages to `{"role": "system", "content": "..."}` - Treats unknown message types as system messages - Handles multiple messages in sequence - Returns empty list for empty context - Returns empty list without session ### 2. Edge Cases Tests (6 tests) - **Session Isolation**: Different sessions maintain separate message contexts - **Operation Sequences**: Add → Remove → Add again workflow - **Clear and Add**: Adding messages after clearing context - **Mixed Message Types**: Various message types in OpenAI conversion - **Singleton Verification**: `chat_context` instance consistency - **Return Value Chaining**: `add()` returns message for fluent API ## Technical Implementation ### Context Helper Function ```python @contextmanager def mock_chainlit_context(session=None): """Context manager to set up and tear down Chainlit context.""" # Mock the event loop since we're not in an async context mock_loop = Mock(spec=asyncio.AbstractEventLoop) with patch("asyncio.get_running_loop", return_value=mock_loop): mock_context = ChainlitContext(session=session) token = context_var.set(mock_context) try: yield mock_context finally: context_var.reset(token) ``` ### Key Features - **Event Loop Mocking**: Patches `asyncio.get_running_loop()` to avoid "no running event loop" errors in synchronous tests - **Context Variable Management**: Properly sets and resets `context_var` using tokens - **Session Mocking**: Creates mock sessions with configurable IDs for testing - **Proper Cleanup**: `setup_method()` and `teardown_method()` clear `chat_contexts` dictionary ## Coverage Details - **Total Tests**: 28 - **Synchronous Tests**: All tests are synchronous (no async/await) - **Mocking Strategy**: Uses `Mock` for sessions and messages, `patch` for event loop - **Cross-Platform**: Compatible with Windows and Linux environments ## Testing Approach - **Context Initialization**: Uses custom helper to properly initialize Chainlit context - **Message Mocking**: Creates mock message objects with `type` and `content` attributes - **Session Isolation**: Tests verify that different sessions don't interfere with each other - **State Management**: Proper setup/teardown ensures test isolation ## Related Modules - `chainlit.chat_context`: Message history management - `chainlit.context`: Chainlit context and context variables - `chainlit.message`: Message types and structures Contribution by Gittensor, learn more at https://gittensor.io/ --------- Co-authored-by: Josh Hayes <35790761+hayescode@users.noreply.github.com>
1 parent f57fe97 commit 3a444b1

File tree

1 file changed

+459
-0
lines changed

1 file changed

+459
-0
lines changed

0 commit comments

Comments
 (0)