dingdanquanliucheng/backend/tests/test_ai.py
2026-06-14 16:20:04 +08:00

112 lines
3.5 KiB
Python

"""AI-001 ~ AI-005: AI 识别测试。
覆盖功能点:
- OCR 识别成功/失败
- 人工修正
- 识别结果确认
- 置信度处理
"""
from __future__ import annotations
import pytest
@pytest.mark.ai
@pytest.mark.p1
class TestAIRecognition:
"""AI-001 ~ AI-002: AI 识别测试。"""
def test_ai_recognition_success(self, client, admin_headers, db_session):
"""AI-001: OCR 识别成功。"""
from backend.app.models.business import AIRecognitionLog
# 模拟识别结果
log = AIRecognitionLog(
biz_type="order",
biz_id=1,
image_url="https://oss.example.com/test.jpg",
raw_result='{"customer_name": "测试客户", "items": []}',
confidence=0.95,
created_by=1,
)
db_session.add(log)
db_session.flush()
# 查询识别记录
saved = db_session.query(AIRecognitionLog).filter(
AIRecognitionLog.biz_type == "order",
AIRecognitionLog.biz_id == 1,
).first()
assert saved is not None
assert float(saved.confidence) == 0.95
def test_ai_recognition_low_confidence(self, client, admin_headers, db_session):
"""AI-005: 置信度过低标记为需人工确认。"""
from backend.app.models.business import AIRecognitionLog
log = AIRecognitionLog(
biz_type="order",
biz_id=2,
image_url="https://oss.example.com/test2.jpg",
raw_result='{"customer_name": "不确定客户"}',
confidence=0.3,
created_by=1,
)
db_session.add(log)
db_session.flush()
saved = db_session.query(AIRecognitionLog).filter(
AIRecognitionLog.biz_id == 2,
).first()
assert saved is not None
assert float(saved.confidence) < 0.5
@pytest.mark.ai
@pytest.mark.p1
class TestAIHumanCorrection:
"""AI-003 ~ AI-004: 人工修正测试。"""
def test_human_correction(self, client, admin_headers, db_session):
"""AI-003: 人工修正保存成功。"""
from backend.app.models.business import AIRecognitionLog
# 创建识别记录
log = AIRecognitionLog(
biz_type="order",
biz_id=3,
image_url="https://oss.example.com/test3.jpg",
raw_result='{"customer_name": "原始识别"}',
confidence=0.8,
created_by=1,
)
db_session.add(log)
db_session.flush()
# 提交人工修正
resp = client.put(f"/api/ai/recognition/{log.id}", headers=admin_headers, json={
"corrected_result": '{"customer_name": "修正后客户", "items": []}',
})
# 如果接口存在,应该成功
if resp.status_code == 200:
data = resp.json()
assert data["data"]["corrected_result"] is not None
@pytest.mark.ai
@pytest.mark.p1
class TestAIPermission:
"""AI 识别权限测试。"""
def test_secretary_can_access_ai(self, client, secretary_headers):
"""秘书可以访问 AI 识别接口。"""
resp = client.get("/api/ai/recognition", headers=secretary_headers)
# 如果接口存在,应该允许
assert resp.status_code in (200, 404)
def test_salesman_cannot_access_ai(self, client, salesman_headers):
"""业务员不能访问 AI 识别接口。"""
resp = client.get("/api/ai/recognition", headers=salesman_headers)
# 如果有权限控制,应该拒绝
assert resp.status_code in (403, 404)