Merged
Conversation
hayescode
approved these changes
Nov 20, 2025
# Add Comprehensive Tests for Cache Module
## Overview
This PR adds comprehensive test coverage for the `cache` module,
ensuring robust testing of the `@cache` decorator functionality and
LangChain cache initialization.
## Changes
- **New Test File**: `backend/tests/test_cache.py` with 27 test cases
- **Test Coverage**: Cache decorator behavior, thread safety, LangChain
integration, and edge cases
- **Module Access**: Uses `sys.modules` to access the internal `_cache`
dictionary for test isolation
## Test Suites
### 1. Cache Decorator Tests (14 tests)
- **Basic Functionality** (3 tests)
- Caches function results correctly
- Different arguments create separate cache entries
- Returns cached results on subsequent calls with same arguments
- **Keyword Arguments** (3 tests)
- Works with keyword arguments
- Order-independent kwargs (sorted for cache key)
- Mixed positional and keyword arguments
- **Special Cases** (4 tests)
- Functions with no arguments
- Mutable return values (returns same object reference)
- `None` as argument value
- Preserves original function behavior (including exceptions)
- **Advanced Features** (4 tests)
- Thread-safe cache access with `_cache_lock`
- Different functions with same args have separate cache entries
- Function name included in cache key
- Cache decorator doesn't interfere with function execution
### 2. LangChain Cache Initialization Tests (7 tests)
- **Configuration Handling**
- Cache disabled by `config.project.cache = False`
- Cache disabled by `config.run.no_cache = True`
- No initialization when LangChain not installed
- **LangChain Integration**
- Initializes `SQLiteCache` when LangChain is available
- Uses configured `lc_cache_path` for database location
- Logs info message when creating new cache file
- Skips initialization when `lc_cache_path` is `None`
### 3. Edge Cases Tests (6 tests)
- **Argument Types**
- Unhashable arguments (lists) raise `TypeError`
- String arguments work correctly
- Tuple arguments (hashable) work correctly
- Boolean arguments work correctly
- **Cache State**
- Global cache state persists across function calls
- Cache entries accumulate for different arguments
## Technical Implementation
### Cache Key Generation
```python
cache_key = (
(func.__name__,) + args + tuple((k, v) for k, v in sorted(kwargs.items()))
)
```
- Function name ensures different functions don't collide
- Sorted kwargs ensure order independence
- Tuple structure makes keys hashable
### Thread Safety
```python
with _cache_lock:
if cache_key not in _cache:
_cache[cache_key] = func(*args, **kwargs)
```
- Uses `threading.Lock()` to prevent race conditions
- Ensures only one thread computes result for a given key
- All threads get the same cached result
### Test Isolation
```python
cache_module = sys.modules["chainlit.cache"]
def setup_method(self):
cache_module._cache.clear()
```
- Accesses actual module via `sys.modules` (not the re-exported
function)
- Clears cache before/after each test for isolation
- Prevents test interference
## Coverage Details
- **Total Tests**: 27
- **Cache Decorator**: 14 tests covering caching logic, thread safety,
and edge cases
- **LangChain Init**: 7 tests covering configuration and integration
- **Edge Cases**: 6 tests covering argument types and cache state
- **Mocking Strategy**: Uses `patch` for config, `patch.dict` for
`sys.modules`, `Mock` for LangChain components
## Testing Approach
- **Decorator Testing**: Uses `call_count` to verify functions are
called only when cache misses
- **Thread Safety**: Spawns multiple threads to verify single execution
- **LangChain Mocking**: Patches `importlib.util.find_spec` and mocks
LangChain modules
- **State Verification**: Checks `_cache` dictionary size and contents
- **Exception Handling**: Verifies decorator preserves original function
exceptions
## Related Modules
- `chainlit.cache`: Cache decorator and LangChain cache initialization
- `chainlit.config`: Configuration for cache settings
- `langchain.cache`: SQLiteCache for LangChain LLM caching (optional
dependency)
- `langchain.globals`: Global LLM cache setter (optional dependency)
Contribution by Gittensor, learn more at https://gittensor.io/
… into feat/test_translation
auto-merge was automatically disabled
November 20, 2025 16:20
Head branch was pushed to by a user without write access
Contributor
Author
|
@hayescode |
hayescode
approved these changes
Nov 20, 2025
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Add Comprehensive Tests for Translations Module
Overview
This PR adds comprehensive test coverage for the
translationsmodule, ensuring robust testing of JSON structure comparison and translation file linting functionality.Changes
backend/tests/test_translations.pywith 41 test casesTest Suites
1. JSON Structure Comparison Tests (26 tests)
Basic Comparisons (5 tests)
Nested Structure Tests (8 tests)
Structure Mismatch Tests (2 tests)
Input Validation Tests (3 tests)
ValueErrorwhen truth is not a dictionaryValueErrorwhen to_compare is not a dictionaryValue Type Tests (4 tests)
Edge Cases (4 tests)
2. Translation Linting Tests (6 tests)
Success Cases (1 test)
Error Detection (4 tests)
Output Formatting (1 test)
3. Edge Cases Tests (9 tests)
Special Key Types (3 tests)
-,_,.charactersNesting and Values (3 tests)
Linting Edge Cases (3 tests)
Technical Implementation
Structure Comparison Algorithm
Error Types
Path Notation
'key''parent.child.grandchild'Coverage Details
Testing Approach
StringIOwithpatchto capture print statementsRelated Modules
chainlit.translations: JSON structure comparison and linting utilitiesfrontend/translations/directoryContribution by Gittensor, learn more at https://gittensor.io/