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>
This commit is contained in:
1 parent
830b33c4b3
commit
656f596d7e
51 files changed
+3690
No files matched your search
@@ -0,0 +1 @@
|
||||
# Tests package
|
||||
@@ -0,0 +1,36 @@
|
||||
"""Pytest configuration and fixtures."""
|
||||
import asyncio
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
from typing import AsyncGenerator
|
||||
from sqlalchemy.ext.asyncio import (
|
||||
AsyncSession,
|
||||
create_async_engine,
|
||||
async_sessionmaker,
|
||||
)
|
||||
|
||||
from app.core.database import Base
|
||||
from app.models.user import User
|
||||
from app.models.law import Law, LawArticle
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def db_session(tmp_path) -> AsyncGenerator[AsyncSession, None]:
|
||||
"""Create a test database session."""
|
||||
db_file = tmp_path / "test.db"
|
||||
engine = create_async_engine(
|
||||
f"sqlite+aiosqlite:///{db_file}",
|
||||
echo=False,
|
||||
)
|
||||
|
||||
async with engine.begin() as conn:
|
||||
await conn.run_sync(Base.metadata.create_all)
|
||||
|
||||
async_session = async_sessionmaker(
|
||||
engine, class_=AsyncSession, expire_on_commit=False
|
||||
)
|
||||
|
||||
async with async_session() as session:
|
||||
yield session
|
||||
|
||||
await engine.dispose()
|
||||
@@ -0,0 +1 @@
|
||||
# Unit tests package
|
||||
@@ -0,0 +1,60 @@
|
||||
"""Unit tests for core configuration."""
|
||||
import pytest
|
||||
from app.core.config import Settings
|
||||
|
||||
|
||||
class TestSettings:
|
||||
"""Test cases for Settings configuration."""
|
||||
|
||||
def test_default_settings(self):
|
||||
"""Test default configuration values."""
|
||||
settings = Settings()
|
||||
|
||||
assert settings.APP_NAME == "AI Legal Assistant"
|
||||
assert settings.APP_VERSION == "1.0.0"
|
||||
assert settings.DEBUG is False
|
||||
assert settings.DATABASE_URL == "sqlite+aiosqlite:///./data/legal_assistant.db"
|
||||
|
||||
def test_custom_settings_from_env(self, monkeypatch):
|
||||
"""Test configuration from environment variables."""
|
||||
monkeypatch.setenv("DEBUG", "true")
|
||||
monkeypatch.setenv("DATABASE_URL", "sqlite+aiosqlite:///./test.db")
|
||||
monkeypatch.setenv("LLM_API_KEY", "test-key")
|
||||
|
||||
settings = Settings()
|
||||
|
||||
assert settings.DEBUG is True
|
||||
assert settings.DATABASE_URL == "sqlite+aiosqlite:///./test.db"
|
||||
assert settings.LLM_API_KEY == "test-key"
|
||||
|
||||
def test_llm_settings(self, monkeypatch):
|
||||
"""Test LLM configuration."""
|
||||
monkeypatch.setenv("LLM_API_BASE", "https://api.example.com/v1")
|
||||
monkeypatch.setenv("LLM_MODEL", "gpt-4")
|
||||
|
||||
settings = Settings()
|
||||
|
||||
assert settings.LLM_API_BASE == "https://api.example.com/v1"
|
||||
assert settings.LLM_MODEL == "gpt-4"
|
||||
|
||||
def test_embedding_settings(self, monkeypatch):
|
||||
"""Test embedding configuration."""
|
||||
monkeypatch.setenv("EMBEDDING_MODEL", "text-embedding-3-small")
|
||||
monkeypatch.setenv("EMBEDDING_DIMENSION", "1536")
|
||||
|
||||
settings = Settings()
|
||||
|
||||
assert settings.EMBEDDING_MODEL == "text-embedding-3-small"
|
||||
assert settings.EMBEDDING_DIMENSION == 1536
|
||||
|
||||
def test_jwt_settings(self, monkeypatch):
|
||||
"""Test JWT configuration."""
|
||||
monkeypatch.setenv("JWT_SECRET_KEY", "test-secret-key")
|
||||
monkeypatch.setenv("JWT_ALGORITHM", "HS256")
|
||||
monkeypatch.setenv("JWT_ACCESS_TOKEN_EXPIRE_MINUTES", "60")
|
||||
|
||||
settings = Settings()
|
||||
|
||||
assert settings.JWT_SECRET_KEY == "test-secret-key"
|
||||
assert settings.JWT_ALGORITHM == "HS256"
|
||||
assert settings.JWT_ACCESS_TOKEN_EXPIRE_MINUTES == 60
|
||||
@@ -0,0 +1,100 @@
|
||||
"""Unit tests for Contract service."""
|
||||
import pytest
|
||||
from datetime import date
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models.contract import ContractStatus
|
||||
from app.services.contract_service import ContractService, ContractTemplateService
|
||||
|
||||
|
||||
class TestContractService:
|
||||
"""Test cases for Contract service."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_contract(self, db_session: AsyncSession):
|
||||
"""Test creating a contract."""
|
||||
service = ContractService(db_session)
|
||||
|
||||
contract = await service.create_contract(
|
||||
title="测试合同",
|
||||
party_a="甲方",
|
||||
party_b="乙方",
|
||||
content="合同内容",
|
||||
created_by=1,
|
||||
)
|
||||
|
||||
assert contract.id is not None
|
||||
assert contract.title == "测试合同"
|
||||
assert contract.status == ContractStatus.DRAFT
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_contract_by_id(self, db_session: AsyncSession):
|
||||
"""Test getting a contract by ID."""
|
||||
service = ContractService(db_session)
|
||||
|
||||
created = await service.create_contract(
|
||||
title="测试合同",
|
||||
party_a="甲方",
|
||||
party_b="乙方",
|
||||
content="合同内容",
|
||||
created_by=1,
|
||||
)
|
||||
|
||||
contract = await service.get_contract_by_id(created.id)
|
||||
|
||||
assert contract is not None
|
||||
assert contract.title == "测试合同"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_submit_for_approval(self, db_session: AsyncSession):
|
||||
"""Test submitting a contract for approval."""
|
||||
service = ContractService(db_session)
|
||||
|
||||
contract = await service.create_contract(
|
||||
title="测试合同",
|
||||
party_a="甲方",
|
||||
party_b="乙方",
|
||||
content="合同内容",
|
||||
created_by=1,
|
||||
)
|
||||
|
||||
updated = await service.submit_for_approval(contract.id)
|
||||
|
||||
assert updated.status == ContractStatus.PENDING_APPROVAL
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_approve_contract(self, db_session: AsyncSession):
|
||||
"""Test approving a contract."""
|
||||
service = ContractService(db_session)
|
||||
|
||||
contract = await service.create_contract(
|
||||
title="测试合同",
|
||||
party_a="甲方",
|
||||
party_b="乙方",
|
||||
content="合同内容",
|
||||
created_by=1,
|
||||
)
|
||||
|
||||
approval = await service.approve_contract(contract.id, 1, "同意")
|
||||
|
||||
assert approval.status == ContractStatus.APPROVED
|
||||
|
||||
|
||||
class TestContractTemplateService:
|
||||
"""Test cases for ContractTemplate service."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_template(self, db_session: AsyncSession):
|
||||
"""Test creating a contract template."""
|
||||
service = ContractTemplateService(db_session)
|
||||
|
||||
template = await service.create_template(
|
||||
name="测试模板",
|
||||
content="模板内容",
|
||||
created_by=1,
|
||||
contract_type="销售合同",
|
||||
)
|
||||
|
||||
assert template.id is not None
|
||||
assert template.name == "测试模板"
|
||||
@@ -0,0 +1,51 @@
|
||||
"""Unit tests for database configuration."""
|
||||
import pytest
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker
|
||||
from sqlalchemy import text
|
||||
|
||||
from app.core.database import Base, get_db, init_db
|
||||
|
||||
|
||||
class TestDatabase:
|
||||
"""Test cases for database configuration."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_tables(self, tmp_path):
|
||||
"""Test creating database tables."""
|
||||
db_path = tmp_path / "test.db"
|
||||
engine = create_async_engine(
|
||||
f"sqlite+aiosqlite:///{db_path}",
|
||||
echo=False
|
||||
)
|
||||
|
||||
async with engine.begin() as conn:
|
||||
await conn.run_sync(Base.metadata.create_all)
|
||||
|
||||
# Verify tables exist
|
||||
async with engine.begin() as conn:
|
||||
result = await conn.execute(text(
|
||||
"SELECT name FROM sqlite_master WHERE type='table'"
|
||||
))
|
||||
tables = [row[0] for row in result.fetchall()]
|
||||
# At minimum, alembic_version table should exist after migration
|
||||
# For now, just verify the connection works
|
||||
assert len(tables) >= 0
|
||||
|
||||
await engine.dispose()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_db_session(self, tmp_path):
|
||||
"""Test getting database session."""
|
||||
db_path = tmp_path / "test.db"
|
||||
engine = create_async_engine(
|
||||
f"sqlite+aiosqlite:///{db_path}",
|
||||
echo=False
|
||||
)
|
||||
async_session = async_sessionmaker(
|
||||
engine, class_=AsyncSession, expire_on_commit=False
|
||||
)
|
||||
|
||||
async with async_session() as session:
|
||||
assert isinstance(session, AsyncSession)
|
||||
|
||||
await engine.dispose()
|
||||
@@ -0,0 +1,70 @@
|
||||
"""Unit tests for Law model."""
|
||||
import pytest
|
||||
from datetime import date
|
||||
|
||||
from app.models.law import Law, LawArticle, LawType, LawStatus
|
||||
|
||||
|
||||
class TestLawModel:
|
||||
"""Test cases for Law model."""
|
||||
|
||||
def test_law_creation(self):
|
||||
"""Test creating a law instance."""
|
||||
law = Law(
|
||||
title="中华人民共和国民法典",
|
||||
law_type=LawType.LAW,
|
||||
promulgation_date=date(2020, 5, 28),
|
||||
effective_date=date(2021, 1, 1),
|
||||
status=LawStatus.EFFECTIVE,
|
||||
issuing_authority="全国人民代表大会",
|
||||
content="民法典全文...",
|
||||
)
|
||||
|
||||
assert law.title == "中华人民共和国民法典"
|
||||
assert law.law_type == LawType.LAW
|
||||
assert law.promulgation_date == date(2020, 5, 28)
|
||||
assert law.effective_date == date(2021, 1, 1)
|
||||
assert law.status == LawStatus.EFFECTIVE
|
||||
assert law.issuing_authority == "全国人民代表大会"
|
||||
|
||||
def test_law_type_enum(self):
|
||||
"""Test law type enum values."""
|
||||
assert LawType.LAW.value == "law"
|
||||
assert LawType.REGULATION.value == "regulation"
|
||||
assert LawType.RULE.value == "rule"
|
||||
assert LawType.JUDICIAL_INTERPRETATION.value == "judicial_interpretation"
|
||||
|
||||
def test_law_status_enum(self):
|
||||
"""Test law status enum values."""
|
||||
assert LawStatus.EFFECTIVE.value == "effective"
|
||||
assert LawStatus.REVOKED.value == "revoked"
|
||||
assert LawStatus.AMENDED.value == "amended"
|
||||
|
||||
def test_law_default_values(self):
|
||||
"""Test law default values."""
|
||||
law = Law(
|
||||
title="测试法规",
|
||||
law_type=LawType.REGULATION,
|
||||
promulgation_date=date(2024, 1, 1),
|
||||
effective_date=date(2024, 2, 1),
|
||||
issuing_authority="测试机关",
|
||||
content="测试内容",
|
||||
)
|
||||
|
||||
assert law.status == LawStatus.EFFECTIVE
|
||||
|
||||
|
||||
class TestLawArticleModel:
|
||||
"""Test cases for LawArticle model."""
|
||||
|
||||
def test_article_creation(self):
|
||||
"""Test creating a law article instance."""
|
||||
article = LawArticle(
|
||||
law_id=1,
|
||||
article_number="第一条",
|
||||
content="为了保护民事主体的合法权益...",
|
||||
)
|
||||
|
||||
assert article.law_id == 1
|
||||
assert article.article_number == "第一条"
|
||||
assert "民事主体" in article.content
|
||||
@@ -0,0 +1,144 @@
|
||||
"""Unit tests for Law service."""
|
||||
import pytest
|
||||
from datetime import date
|
||||
from unittest.mock import AsyncMock, patch, MagicMock
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models.law import Law, LawArticle, LawType, LawStatus
|
||||
from app.services.law_service import LawService
|
||||
|
||||
|
||||
class TestLawService:
|
||||
"""Test cases for Law service."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_law(self, db_session: AsyncSession):
|
||||
"""Test creating a law."""
|
||||
service = LawService(db_session)
|
||||
|
||||
law = await service.create_law(
|
||||
title="测试法律",
|
||||
law_type=LawType.LAW,
|
||||
promulgation_date=date(2024, 1, 1),
|
||||
effective_date=date(2024, 2, 1),
|
||||
issuing_authority="测试机关",
|
||||
content="测试内容",
|
||||
)
|
||||
|
||||
assert law.id is not None
|
||||
assert law.title == "测试法律"
|
||||
assert law.law_type == LawType.LAW
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_law_by_id(self, db_session: AsyncSession):
|
||||
"""Test getting a law by ID."""
|
||||
service = LawService(db_session)
|
||||
|
||||
# Create a law first
|
||||
created = await service.create_law(
|
||||
title="测试法律",
|
||||
law_type=LawType.LAW,
|
||||
promulgation_date=date(2024, 1, 1),
|
||||
effective_date=date(2024, 2, 1),
|
||||
issuing_authority="测试机关",
|
||||
content="测试内容",
|
||||
)
|
||||
|
||||
# Get the law
|
||||
law = await service.get_law_by_id(created.id)
|
||||
|
||||
assert law is not None
|
||||
assert law.title == "测试法律"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_laws_list(self, db_session: AsyncSession):
|
||||
"""Test getting list of laws."""
|
||||
service = LawService(db_session)
|
||||
|
||||
# Create multiple laws
|
||||
for i in range(3):
|
||||
await service.create_law(
|
||||
title=f"测试法律{i}",
|
||||
law_type=LawType.LAW,
|
||||
promulgation_date=date(2024, 1, 1),
|
||||
effective_date=date(2024, 2, 1),
|
||||
issuing_authority="测试机关",
|
||||
content=f"测试内容{i}",
|
||||
)
|
||||
|
||||
laws = await service.get_laws_list(skip=0, limit=10)
|
||||
|
||||
assert len(laws) == 3
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_update_law(self, db_session: AsyncSession):
|
||||
"""Test updating a law."""
|
||||
service = LawService(db_session)
|
||||
|
||||
# Create a law
|
||||
law = await service.create_law(
|
||||
title="原标题",
|
||||
law_type=LawType.LAW,
|
||||
promulgation_date=date(2024, 1, 1),
|
||||
effective_date=date(2024, 2, 1),
|
||||
issuing_authority="测试机关",
|
||||
content="原内容",
|
||||
)
|
||||
|
||||
# Update the law
|
||||
updated = await service.update_law(law.id, title="新标题")
|
||||
|
||||
assert updated.title == "新标题"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_delete_law(self, db_session: AsyncSession):
|
||||
"""Test deleting a law."""
|
||||
service = LawService(db_session)
|
||||
|
||||
# Create a law
|
||||
law = await service.create_law(
|
||||
title="待删除法律",
|
||||
law_type=LawType.LAW,
|
||||
promulgation_date=date(2024, 1, 1),
|
||||
effective_date=date(2024, 2, 1),
|
||||
issuing_authority="测试机关",
|
||||
content="测试内容",
|
||||
)
|
||||
|
||||
# Delete the law
|
||||
result = await service.delete_law(law.id)
|
||||
|
||||
assert result is True
|
||||
|
||||
# Verify it's deleted
|
||||
deleted = await service.get_law_by_id(law.id)
|
||||
assert deleted is None
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_search_laws_by_keyword(self, db_session: AsyncSession):
|
||||
"""Test searching laws by keyword."""
|
||||
service = LawService(db_session)
|
||||
|
||||
# Create laws with different content
|
||||
await service.create_law(
|
||||
title="民法典",
|
||||
law_type=LawType.LAW,
|
||||
promulgation_date=date(2024, 1, 1),
|
||||
effective_date=date(2024, 2, 1),
|
||||
issuing_authority="全国人大",
|
||||
content="民法典全文内容",
|
||||
)
|
||||
await service.create_law(
|
||||
title="刑法",
|
||||
law_type=LawType.LAW,
|
||||
promulgation_date=date(2024, 1, 1),
|
||||
effective_date=date(2024, 2, 1),
|
||||
issuing_authority="全国人大",
|
||||
content="刑法全文内容",
|
||||
)
|
||||
|
||||
results = await service.search_laws_by_keyword("民法")
|
||||
|
||||
assert len(results) >= 1
|
||||
assert any("民法典" in law.title for law in results)
|
||||
@@ -0,0 +1,82 @@
|
||||
"""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
|
||||
@@ -0,0 +1,115 @@
|
||||
"""Unit tests for remaining models and services."""
|
||||
import pytest
|
||||
from datetime import date, datetime
|
||||
|
||||
from app.models.analysis import LegalAnalysis, Case, AnalysisStatus
|
||||
from app.models.case import CaseReview, ReviewStatus, ReviewType
|
||||
from app.models.contract import Contract, ContractTemplate, ContractStatus
|
||||
from app.models.signature import SignatureRequest, Signature, SignatureStatus
|
||||
|
||||
|
||||
class TestAnalysisModel:
|
||||
"""Test cases for Analysis model."""
|
||||
|
||||
def test_legal_analysis_creation(self):
|
||||
"""Test creating a legal analysis instance."""
|
||||
analysis = LegalAnalysis(
|
||||
user_id=1,
|
||||
title="合同纠纷分析",
|
||||
case_description="甲方未按合同约定支付货款...",
|
||||
)
|
||||
|
||||
assert analysis.user_id == 1
|
||||
assert analysis.title == "合同纠纷分析"
|
||||
assert analysis.status == AnalysisStatus.DRAFT
|
||||
|
||||
def test_case_creation(self):
|
||||
"""Test creating a case instance."""
|
||||
case = Case(
|
||||
title="买卖合同纠纷案",
|
||||
case_number="(2024)京01民初1号",
|
||||
court="北京市第一中级人民法院",
|
||||
case_type="买卖合同纠纷",
|
||||
)
|
||||
|
||||
assert case.title == "买卖合同纠纷案"
|
||||
assert case.case_number == "(2024)京01民初1号"
|
||||
|
||||
|
||||
class TestCaseReviewModel:
|
||||
"""Test cases for CaseReview model."""
|
||||
|
||||
def test_case_review_creation(self):
|
||||
"""Test creating a case review instance."""
|
||||
review = CaseReview(
|
||||
case_id=1,
|
||||
reviewer_id=1,
|
||||
review_type=ReviewType.INITIAL,
|
||||
opinion="同意立案",
|
||||
score=90,
|
||||
)
|
||||
|
||||
assert review.case_id == 1
|
||||
assert review.review_type == ReviewType.INITIAL
|
||||
assert review.status == ReviewStatus.PENDING
|
||||
|
||||
|
||||
class TestContractModel:
|
||||
"""Test cases for Contract model."""
|
||||
|
||||
def test_contract_creation(self):
|
||||
"""Test creating a contract instance."""
|
||||
contract = Contract(
|
||||
title="销售合同",
|
||||
party_a="甲方公司",
|
||||
party_b="乙方公司",
|
||||
content="合同内容...",
|
||||
created_by=1,
|
||||
)
|
||||
|
||||
assert contract.title == "销售合同"
|
||||
assert contract.party_a == "甲方公司"
|
||||
assert contract.status == ContractStatus.DRAFT
|
||||
|
||||
def test_contract_template_creation(self):
|
||||
"""Test creating a contract template instance."""
|
||||
template = ContractTemplate(
|
||||
name="标准销售合同模板",
|
||||
content="模板内容...",
|
||||
created_by=1,
|
||||
contract_type="销售合同",
|
||||
)
|
||||
|
||||
assert template.name == "标准销售合同模板"
|
||||
assert template.contract_type == "销售合同"
|
||||
|
||||
|
||||
class TestSignatureModel:
|
||||
"""Test cases for Signature model."""
|
||||
|
||||
def test_signature_request_creation(self):
|
||||
"""Test creating a signature request instance."""
|
||||
request = SignatureRequest(
|
||||
contract_id=1,
|
||||
requester_id=1,
|
||||
signer_name="张三",
|
||||
signer_email="zhangsan@example.com",
|
||||
token="abc123token",
|
||||
expires_at=datetime.utcnow(),
|
||||
)
|
||||
|
||||
assert request.contract_id == 1
|
||||
assert request.signer_name == "张三"
|
||||
assert request.status == SignatureStatus.PENDING
|
||||
|
||||
def test_signature_creation(self):
|
||||
"""Test creating a signature instance."""
|
||||
signature = Signature(
|
||||
request_id=1,
|
||||
signer_name="张三",
|
||||
signature_data="base64encodedimage",
|
||||
verification_hash="hash123",
|
||||
)
|
||||
|
||||
assert signature.request_id == 1
|
||||
assert signature.signer_name == "张三"
|
||||
@@ -0,0 +1,84 @@
|
||||
"""Unit tests for security module."""
|
||||
import pytest
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from app.core.security import (
|
||||
get_password_hash,
|
||||
verify_password,
|
||||
create_access_token,
|
||||
decode_access_token,
|
||||
)
|
||||
|
||||
|
||||
class TestPasswordHashing:
|
||||
"""Test cases for password hashing."""
|
||||
|
||||
def test_password_hash(self):
|
||||
"""Test password hashing."""
|
||||
password = "test_password_123"
|
||||
hashed = get_password_hash(password)
|
||||
|
||||
assert hashed != password
|
||||
assert len(hashed) > 0
|
||||
assert hashed.startswith("$2b$")
|
||||
|
||||
def test_verify_password_correct(self):
|
||||
"""Test verifying correct password."""
|
||||
password = "test_password_123"
|
||||
hashed = get_password_hash(password)
|
||||
|
||||
assert verify_password(password, hashed) is True
|
||||
|
||||
def test_verify_password_incorrect(self):
|
||||
"""Test verifying incorrect password."""
|
||||
password = "test_password_123"
|
||||
hashed = get_password_hash(password)
|
||||
|
||||
assert verify_password("wrong_password", hashed) is False
|
||||
|
||||
def test_different_passwords_different_hashes(self):
|
||||
"""Test that same password produces different hashes."""
|
||||
password = "test_password_123"
|
||||
hash1 = get_password_hash(password)
|
||||
hash2 = get_password_hash(password)
|
||||
|
||||
assert hash1 != hash2
|
||||
|
||||
|
||||
class TestJWTTokens:
|
||||
"""Test cases for JWT token handling."""
|
||||
|
||||
def test_create_access_token(self):
|
||||
"""Test creating access token."""
|
||||
data = {"sub": "user123", "role": "lawyer"}
|
||||
token = create_access_token(data)
|
||||
|
||||
assert token is not None
|
||||
assert isinstance(token, str)
|
||||
assert len(token) > 0
|
||||
|
||||
def test_decode_access_token(self):
|
||||
"""Test decoding access token."""
|
||||
data = {"sub": "user123", "role": "lawyer"}
|
||||
token = create_access_token(data)
|
||||
|
||||
decoded = decode_access_token(token)
|
||||
|
||||
assert decoded is not None
|
||||
assert decoded["sub"] == "user123"
|
||||
assert decoded["role"] == "lawyer"
|
||||
|
||||
def test_decode_invalid_token(self):
|
||||
"""Test decoding invalid token."""
|
||||
decoded = decode_access_token("invalid.token.here")
|
||||
|
||||
assert decoded is None
|
||||
|
||||
def test_token_contains_exp(self):
|
||||
"""Test that token contains expiration."""
|
||||
data = {"sub": "user123"}
|
||||
token = create_access_token(data)
|
||||
|
||||
decoded = decode_access_token(token)
|
||||
|
||||
assert "exp" in decoded
|
||||
@@ -0,0 +1,88 @@
|
||||
"""Unit tests for Signature service."""
|
||||
import pytest
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models.signature import SignatureStatus
|
||||
from app.models.contract import Contract
|
||||
from app.services.signature_service import SignatureService
|
||||
from app.services.contract_service import ContractService
|
||||
|
||||
|
||||
class TestSignatureService:
|
||||
"""Test cases for Signature service."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_generate_token(self, db_session: AsyncSession):
|
||||
"""Test token generation."""
|
||||
service = SignatureService(db_session)
|
||||
|
||||
token = service.generate_token()
|
||||
|
||||
assert token is not None
|
||||
assert len(token) > 20
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_generate_verification_hash(self, db_session: AsyncSession):
|
||||
"""Test verification hash generation."""
|
||||
service = SignatureService(db_session)
|
||||
|
||||
hash1 = service.generate_verification_hash("test content")
|
||||
hash2 = service.generate_verification_hash("test content")
|
||||
hash3 = service.generate_verification_hash("different content")
|
||||
|
||||
assert hash1 == hash2
|
||||
assert hash1 != hash3
|
||||
assert len(hash1) == 64 # SHA-256 hex length
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_signature_request(self, db_session: AsyncSession):
|
||||
"""Test creating a signature request."""
|
||||
# First create a contract
|
||||
contract_service = ContractService(db_session)
|
||||
contract = await contract_service.create_contract(
|
||||
title="测试合同",
|
||||
party_a="甲方",
|
||||
party_b="乙方",
|
||||
content="合同内容",
|
||||
created_by=1,
|
||||
)
|
||||
|
||||
service = SignatureService(db_session)
|
||||
request = await service.create_signature_request(
|
||||
contract_id=contract.id,
|
||||
requester_id=1,
|
||||
signer_name="张三",
|
||||
signer_email="zhangsan@example.com",
|
||||
)
|
||||
|
||||
assert request.id is not None
|
||||
assert request.signer_name == "张三"
|
||||
assert request.status == SignatureStatus.PENDING
|
||||
assert request.token is not None
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_is_request_valid(self, db_session: AsyncSession):
|
||||
"""Test checking if request is valid."""
|
||||
# Create a contract first
|
||||
contract_service = ContractService(db_session)
|
||||
contract = await contract_service.create_contract(
|
||||
title="测试合同",
|
||||
party_a="甲方",
|
||||
party_b="乙方",
|
||||
content="合同内容",
|
||||
created_by=1,
|
||||
)
|
||||
|
||||
service = SignatureService(db_session)
|
||||
request = await service.create_signature_request(
|
||||
contract_id=contract.id,
|
||||
requester_id=1,
|
||||
signer_name="张三",
|
||||
signer_email="zhangsan@example.com",
|
||||
expire_hours=72,
|
||||
)
|
||||
|
||||
is_valid = await service.is_request_valid(request)
|
||||
assert is_valid is True
|
||||
@@ -0,0 +1,52 @@
|
||||
"""Unit tests for User model."""
|
||||
import pytest
|
||||
from datetime import datetime
|
||||
|
||||
from app.models.user import User, UserRole
|
||||
|
||||
|
||||
class TestUserModel:
|
||||
"""Test cases for User model."""
|
||||
|
||||
def test_user_creation(self):
|
||||
"""Test creating a user instance."""
|
||||
user = User(
|
||||
username="testuser",
|
||||
email="test@example.com",
|
||||
hashed_password="hashed_password",
|
||||
role=UserRole.LAWYER,
|
||||
)
|
||||
|
||||
assert user.username == "testuser"
|
||||
assert user.email == "test@example.com"
|
||||
assert user.hashed_password == "hashed_password"
|
||||
assert user.role == UserRole.LAWYER
|
||||
assert user.is_active is True
|
||||
|
||||
def test_user_role_enum(self):
|
||||
"""Test user role enum values."""
|
||||
assert UserRole.ADMIN.value == "admin"
|
||||
assert UserRole.LAWYER.value == "lawyer"
|
||||
assert UserRole.REVIEWER.value == "reviewer"
|
||||
assert UserRole.CLIENT.value == "client"
|
||||
|
||||
def test_user_default_values(self):
|
||||
"""Test user default values."""
|
||||
user = User(
|
||||
username="testuser",
|
||||
email="test@example.com",
|
||||
hashed_password="hashed_password",
|
||||
)
|
||||
|
||||
assert user.role == UserRole.CLIENT
|
||||
assert user.is_active is True
|
||||
|
||||
def test_user_repr(self):
|
||||
"""Test user string representation."""
|
||||
user = User(
|
||||
username="testuser",
|
||||
email="test@example.com",
|
||||
hashed_password="hashed_password",
|
||||
)
|
||||
|
||||
assert "testuser" in repr(user)
|
||||
@@ -0,0 +1,81 @@
|
||||
"""Unit tests for Vector service."""
|
||||
import pytest
|
||||
import numpy as np
|
||||
from unittest.mock import AsyncMock, patch, MagicMock
|
||||
|
||||
from app.services.vector_service import VectorService
|
||||
|
||||
|
||||
class TestVectorService:
|
||||
"""Test cases for Vector service."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_embedding_no_api_key(self):
|
||||
"""Test getting embedding without API key returns mock."""
|
||||
service = VectorService()
|
||||
service.api_key = None # Ensure no API key
|
||||
|
||||
embedding = await service.get_embedding("测试文本")
|
||||
|
||||
# Should return mock embedding
|
||||
assert len(embedding) == service.dimension
|
||||
assert all(x == 0.0 for x in embedding)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_embedding_with_api_key(self):
|
||||
"""Test getting embedding with API key."""
|
||||
service = VectorService()
|
||||
service.api_key = "test-key"
|
||||
|
||||
with patch('httpx.AsyncClient') as mock_client:
|
||||
mock_response = MagicMock()
|
||||
mock_response.json.return_value = {
|
||||
"data": [{"embedding": [0.1] * 1536}]
|
||||
}
|
||||
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
|
||||
|
||||
embedding = await service.get_embedding("测试文本")
|
||||
|
||||
assert len(embedding) == 1536
|
||||
assert all(x == 0.1 for x in embedding)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cosine_similarity(self):
|
||||
"""Test cosine similarity calculation."""
|
||||
service = VectorService()
|
||||
|
||||
vec1 = [1.0, 0.0, 0.0]
|
||||
vec2 = [1.0, 0.0, 0.0]
|
||||
vec3 = [0.0, 1.0, 0.0]
|
||||
|
||||
# Same vectors should have similarity 1.0
|
||||
sim1 = service.cosine_similarity(vec1, vec2)
|
||||
assert abs(sim1 - 1.0) < 0.001
|
||||
|
||||
# Orthogonal vectors should have similarity 0.0
|
||||
sim2 = service.cosine_similarity(vec1, vec3)
|
||||
assert abs(sim2 - 0.0) < 0.001
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_search_similar(self):
|
||||
"""Test searching similar vectors."""
|
||||
service = VectorService()
|
||||
|
||||
# Mock vectors: first is similar, second is different
|
||||
stored_vectors = [
|
||||
{"id": 1, "embedding": [1.0, 0.0, 0.0]},
|
||||
{"id": 2, "embedding": [0.0, 1.0, 0.0]},
|
||||
]
|
||||
|
||||
query_vec = [0.9, 0.1, 0.0]
|
||||
|
||||
results = service.search_similar(query_vec, stored_vectors, top_k=2)
|
||||
|
||||
assert len(results) == 2
|
||||
assert results[0]["id"] == 1 # Most similar should be first
|
||||
Reference in new issue
Block a user