-
add test for chat context (#2677)
发布于
2025-11-20 15:15:05 +00:00 | 120 次提交 在此版本后已推送到 mainAdd Comprehensive Tests for Chat Context Module
Overview
This PR adds comprehensive test coverage for the
chat_contextmodule,
ensuring robust testing of message history management, session
isolation, and OpenAI format conversion functionality.Changes
- New Test File:
backend/tests/test_chat_context.pywith 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
- Converts user messages to
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_contextinstance consistency - Return Value Chaining:
add()returns message for fluent API
Technical Implementation
Context Helper Function
@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_varusing tokens - Session Mocking: Creates mock sessions with configurable IDs for
testing - Proper Cleanup:
setup_method()andteardown_method()clear
chat_contextsdictionary
Coverage Details
- Total Tests: 28
- Synchronous Tests: All tests are synchronous (no async/await)
- Mocking Strategy: Uses
Mockfor 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
typeand
contentattributes - 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 managementchainlit.context: Chainlit context and context variableschainlit.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
下载附件
- New Test File: