ai-legal-assistant/backend/tests/unit/test_llm_service.py
root 656f596d7e feat: implement AI legal assistant system MVP
Core modules:
- Laws: CRUD, search, AI-powered QA
- Analysis: legal research and case management
- Contracts: lifecycle management with templates
- Signatures: electronic signature workflow

Infrastructure:
- FastAPI + SQLite + async SQLAlchemy
- Docker deployment support
- 54 unit tests passing

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-01 03:34:44 +08:00

83 lines
2.8 KiB
Python

"""Unit tests for LLM service."""
import pytest
from unittest.mock import AsyncMock, patch, MagicMock
from app.services.llm_service import LLMService
class TestLLMService:
"""Test cases for LLM service."""
@pytest.mark.asyncio
async def test_chat_completion_no_api_key(self):
"""Test chat completion without API key returns mock."""
service = LLMService()
service.api_key = None # Ensure no API key
response = await service.chat_completion(
messages=[{"role": "user", "content": "你好"}]
)
# Should return mock response
assert "模拟" in response or "法律" in response
@pytest.mark.asyncio
async def test_chat_completion_with_api_key(self):
"""Test chat completion with API key."""
service = LLMService()
service.api_key = "test-key"
with patch('httpx.AsyncClient') as mock_client:
mock_response = MagicMock()
mock_response.json.return_value = {
"choices": [{
"message": {
"role": "assistant",
"content": "这是测试回复"
}
}]
}
mock_response.raise_for_status = MagicMock()
mock_client_instance = MagicMock()
mock_client_instance.post = AsyncMock(return_value=mock_response)
mock_client_instance.__aenter__ = AsyncMock(return_value=mock_client_instance)
mock_client_instance.__aexit__ = AsyncMock(return_value=None)
mock_client.return_value = mock_client_instance
response = await service.chat_completion(
messages=[{"role": "user", "content": "你好"}]
)
assert "这是测试回复" in response
@pytest.mark.asyncio
async def test_legal_qa(self):
"""Test legal QA."""
service = LLMService()
with patch.object(service, 'chat_completion') as mock_chat:
mock_chat.return_value = "根据《民法典》第一条规定..."
response = await service.legal_qa(
question="民法典的立法目的是什么?",
context="《民法典》第一条 为了保护民事主体的合法权益..."
)
assert "民法典" in response
@pytest.mark.asyncio
async def test_analyze_legal_issue(self):
"""Test legal issue analysis."""
service = LLMService()
with patch.object(service, 'chat_completion') as mock_chat:
mock_chat.return_value = "分析结果:该问题涉及..."
response = await service.analyze_legal_issue(
issue_description="甲方未按合同约定支付货款",
relevant_laws=["《民法典》第五百零九条"]
)
assert "分析结果" in response