Merge branch 'dev' into hugo-shipping-notice
This commit is contained in:
commit
472b530be3
397 files changed
+46450
-34171
No files matched your search
@@ -0,0 +1,103 @@
|
||||
"""
|
||||
backend/tests/jobs/test_schedule_queue.py
|
||||
|
||||
用途:验证排程迁出 Web 后的手动入队、Cron 扫描与 Job handler 状态闭环。
|
||||
依赖:通用 app fixture、models.Job/ScheduleRun/ScheduleTask、schedule.queue_service。
|
||||
逻辑:只替换真正的排程执行器,不启动后台线程,断言 API/worker 之间的数据契约。
|
||||
"""
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from app import db
|
||||
from app.jobs.context import JobContext
|
||||
from app.jobs.handlers.schedule_run import run_schedule
|
||||
from app.jobs.types import JobType
|
||||
from app.models import Job, ScheduleRun, ScheduleTask, User
|
||||
from app.services.schedule.queue_service import enqueue_due_schedule_runs, enqueue_manual_schedule_run
|
||||
|
||||
|
||||
def _create_task(*, due: bool = False) -> ScheduleTask:
|
||||
"""创建测试用户与排程;due=True 时令 next_run_at 已到期。"""
|
||||
suffix = str(datetime.utcnow().timestamp()).replace(".", "-")
|
||||
user = User(
|
||||
username=f"schedule-owner-{suffix}",
|
||||
email=f"schedule-owner-{suffix}@example.com",
|
||||
role="admin",
|
||||
status="active",
|
||||
)
|
||||
user.set_password("test")
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
task = ScheduleTask(
|
||||
schedule_no=f"SCH-TEST-{datetime.utcnow().timestamp()}",
|
||||
name="schedule queue test",
|
||||
schedule_type="data_pipeline",
|
||||
owner_user_id=user.id,
|
||||
cron_expr="0 3 * * *",
|
||||
schedule_timezone="Asia/Shanghai",
|
||||
enabled=True,
|
||||
next_run_at=datetime.utcnow() - timedelta(minutes=1) if due else datetime.utcnow() + timedelta(days=1),
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
return task
|
||||
|
||||
|
||||
def test_manual_schedule_run_creates_queued_job(app):
|
||||
"""关键断言:手动触发只写 queued run/job,不在 Web 请求线程执行。"""
|
||||
with app.app_context():
|
||||
task = _create_task()
|
||||
run, job_id, created = enqueue_manual_schedule_run(task.id, triggered_by_user_id=task.owner_user_id)
|
||||
|
||||
job = db.session.get(Job, job_id)
|
||||
assert created is True
|
||||
assert run.status == "queued"
|
||||
assert run.started_at is None
|
||||
assert job is not None
|
||||
assert job.domain == "schedule"
|
||||
assert job.job_type == JobType.SCHEDULE_RUN.value
|
||||
assert job.payload_json["schedule_run_id"] == run.id
|
||||
|
||||
|
||||
def test_due_schedule_scan_is_idempotent(app):
|
||||
"""关键断言:同一到期任务已有 queued run 时不会重复创建,next_run_at 会推进。"""
|
||||
with app.app_context():
|
||||
task = _create_task(due=True)
|
||||
old_next_run = task.next_run_at
|
||||
|
||||
assert enqueue_due_schedule_runs() == 1
|
||||
assert enqueue_due_schedule_runs() == 0
|
||||
|
||||
runs = db.session.query(ScheduleRun).filter_by(schedule_task_id=task.id).all()
|
||||
jobs = db.session.query(Job).filter_by(domain="schedule", job_type=JobType.SCHEDULE_RUN.value).all()
|
||||
db.session.refresh(task)
|
||||
assert len(runs) == 1
|
||||
assert len(jobs) == 1
|
||||
assert task.next_run_at is not None and task.next_run_at > old_next_run
|
||||
|
||||
|
||||
def test_schedule_handler_finishes_generic_job(app, monkeypatch):
|
||||
"""关键断言:worker handler 执行完成后同时收口 ScheduleRun 与通用 Job。"""
|
||||
with app.app_context():
|
||||
task = _create_task()
|
||||
run, job_id, _created = enqueue_manual_schedule_run(task.id, triggered_by_user_id=task.owner_user_id)
|
||||
job = db.session.get(Job, job_id)
|
||||
job.status = "running"
|
||||
job.attempts = 1
|
||||
db.session.commit()
|
||||
|
||||
def _fake_run_task_now(task_arg, *, trigger_type, triggered_by_user_id, run):
|
||||
assert task_arg.id == task.id
|
||||
assert trigger_type == "manual"
|
||||
run.status = "success"
|
||||
run.finished_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
return run
|
||||
|
||||
monkeypatch.setattr("app.services.schedule.scheduler_service.run_task_now", _fake_run_task_now)
|
||||
ctx = JobContext(config={}, logger=app.logger)
|
||||
run_schedule(ctx, {"job_id": job_id, "schedule_run_id": run.id})
|
||||
|
||||
db.session.expire_all()
|
||||
assert db.session.get(ScheduleRun, run.id).status == "success"
|
||||
assert db.session.get(Job, job_id).status == "success"
|
||||
@@ -3,9 +3,9 @@ tests/jobs/test_store.py
|
||||
|
||||
用途:验证 store.claim_next 归一化与空队列行为。
|
||||
"""
|
||||
from app.jobs.store import _normalize_kb_job
|
||||
from app.jobs.store import _normalize_generic_job, _normalize_kb_job
|
||||
from app.jobs.types import JobType
|
||||
from app.models import KbJob
|
||||
from app.models import Job, KbJob
|
||||
|
||||
|
||||
def test_normalize_kb_job_clean(app):
|
||||
@@ -77,3 +77,20 @@ def test_find_shipping_notice_job_id_matches_task_no(app):
|
||||
db.session.commit()
|
||||
|
||||
assert _find_shipping_notice_job_id('ship-a') == target.id
|
||||
|
||||
|
||||
def test_normalize_schedule_generic_job(app):
|
||||
"""断言 schedule 通用 Job 会携带 job_id/run_id 交给 handler。"""
|
||||
with app.app_context():
|
||||
job = Job(
|
||||
id=99,
|
||||
domain='schedule',
|
||||
job_type=JobType.SCHEDULE_RUN.value,
|
||||
status='running',
|
||||
attempts=1,
|
||||
payload_json={'schedule_run_id': 12},
|
||||
)
|
||||
normalized = _normalize_generic_job(job)
|
||||
assert normalized['job_type'] == JobType.SCHEDULE_RUN
|
||||
assert normalized['attempts'] == 1
|
||||
assert normalized['payload'] == {'job_id': 99, 'schedule_run_id': 12}
|
||||
@@ -3,7 +3,7 @@ tests/jobs/test_types.py
|
||||
|
||||
用途:验证 JobType 与 KbJob.job_type 映射。
|
||||
"""
|
||||
from app.jobs.types import JobType, handler_type_for_kb_job, kb_job_type_for_handler
|
||||
from app.jobs.types import QUEUE_KB_JOB_TYPES, JobType, handler_type_for_kb_job, kb_job_type_for_handler
|
||||
|
||||
|
||||
def test_handler_type_for_kb_job_mapping():
|
||||
@@ -18,3 +18,8 @@ def test_kb_job_type_for_handler_mapping():
|
||||
assert kb_job_type_for_handler(JobType.KB_CLEAN) == 'clean'
|
||||
assert kb_job_type_for_handler(JobType.KB_DIFY_SYNC) == 'sync_dify'
|
||||
assert kb_job_type_for_handler(JobType.SHIPPING_NOTICE_RUN) == 'shipping_notice_run'
|
||||
|
||||
|
||||
def test_schedule_queue_type_mapping():
|
||||
"""断言独立 schedule worker 只消费 schedule_run。"""
|
||||
assert QUEUE_KB_JOB_TYPES['schedule'] == frozenset({'schedule_run'})
|
||||
@@ -0,0 +1,751 @@
|
||||
"""
|
||||
tests/services/procurement_contract/test_analyze.py
|
||||
|
||||
用途:采购合同清洗、条款结构化、规则叠加、可读性校验与比对结果字段断言。
|
||||
依赖:procurement_contract.analyze。
|
||||
逻辑:保证缺字占位/乱码不会写入 old_text/new_text;条款 title 供前端展示。
|
||||
"""
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.procurement_contract import analyze, rule_service
|
||||
|
||||
|
||||
def test_readable_text_rejects_pdf_missing_glyph_placeholders():
|
||||
"""缺字占位主导的抽取结果必须判定为不可读。"""
|
||||
assert not analyze._is_readable_extracted_text("□□□□□合同条款□□□□□")
|
||||
|
||||
|
||||
def test_compare_uses_difference_title_instead_of_rule_title():
|
||||
"""对比项标题应描述实际差异类别,不得套用单份审核规则标题。"""
|
||||
result = analyze.analyze_compare(
|
||||
"付款:验收后30日内支付。",
|
||||
"付款:验收后90日内支付。",
|
||||
rules=[
|
||||
{
|
||||
"title": "付款条款",
|
||||
"clause_category": "payment",
|
||||
"keywords": ["付款"],
|
||||
"risk_level": "high",
|
||||
"risk_hint": "付款期限延长",
|
||||
"suggestion": "恢复原付款期限",
|
||||
}
|
||||
],
|
||||
)
|
||||
|
||||
# 断言:规则仅提供风险参考;标题和报告围绕真实付款差异。
|
||||
clause = result["clauses_json"][0]
|
||||
assert clause["title"] == "付款条件变更"
|
||||
assert clause["old_text"] == "付款:验收后30日内支付。"
|
||||
assert clause["new_text"] == "付款:验收后90日内支付。"
|
||||
assert clause["comparison_readable"] is True
|
||||
assert clause["suggestion"] == ""
|
||||
assert clause["negotiation_text"] == ""
|
||||
|
||||
|
||||
def test_compare_classifies_equipment_schedule_as_commercial_without_legal_risk():
|
||||
"""合同号、主体和设备清单变化应保留为商业待确认,不计入法律风险。"""
|
||||
result = analyze.analyze_compare(
|
||||
"采购合同\n合同编号:TMP-001\n设备名称:冲切机\n型号:A1\n数量:1台\n单价:100元",
|
||||
"采购合同\n合同编号:VENDOR-889\n设备名称:冲切机\n型号:B2\n数量:2台\n单价:200元",
|
||||
rules=[],
|
||||
)
|
||||
# 断言:交易基础信息变化供业务确认,不污染高中低风险统计。
|
||||
assert result["clauses_json"][0]["change_class"] in {"metadata", "commercial"}
|
||||
assert result["high_risk_count"] == 0
|
||||
assert result["medium_risk_count"] == 0
|
||||
assert result["low_risk_count"] == 0
|
||||
|
||||
|
||||
def test_compare_ignores_truncated_equipment_table_header_without_values():
|
||||
"""同一设备表仅因 OCR 漏取后半段表头时,不得产生合同内容变更。"""
|
||||
result = analyze.analyze_compare(
|
||||
"序号|设备名称|品牌|型号|数量|单价|总价",
|
||||
"序号|设备名称|品牌",
|
||||
rules=[],
|
||||
)
|
||||
|
||||
# 断言:纯表头没有业务值,短表头又是长表头的有序子集,应计为 OCR 噪声。
|
||||
assert result["clauses_json"] == []
|
||||
assert result["total_change_count"] == 0
|
||||
assert result["summary_json"]["comparison_quality"]["ignored_ocr_noise"] == 1
|
||||
|
||||
|
||||
def test_compare_keeps_equipment_table_value_change_when_header_matches():
|
||||
"""设备表金额、数量等字段值变化必须保留,不能被表头容错规则吞掉。"""
|
||||
result = analyze.analyze_compare(
|
||||
"序号|设备名称|品牌|型号|数量|单价|总价\n1|贴标设备|煜英|非标定制|1|24000|24000",
|
||||
"序号|设备名称|品牌|型号|数量|单价|总价\n1|贴标设备|煜英|非标定制|2|24000|48000",
|
||||
rules=[],
|
||||
)
|
||||
|
||||
# 断言:数量和总价均为业务事实,仍需显示为商业信息变更。
|
||||
assert result["total_change_count"] == 1
|
||||
assert result["clauses_json"][0]["change_class"] == "commercial"
|
||||
|
||||
|
||||
def test_compare_ignores_split_total_row_when_amounts_match_in_both_contracts():
|
||||
"""同一合计行仅因表格列拆分不一致时,不得误报为金额修改。"""
|
||||
result = analyze.analyze_compare(
|
||||
"设备数量:2\n设备总价:¥44,000\n合计|2|¥44,000",
|
||||
"设备数量:2\n设备总价:¥44,000\n合计",
|
||||
rules=[],
|
||||
)
|
||||
|
||||
# 断言:金额事实在双方全文一致,只有合计行列拆分不同,应计为抽取噪声。
|
||||
assert result["clauses_json"] == []
|
||||
assert result["total_change_count"] == 0
|
||||
assert result["summary_json"]["comparison_quality"]["ignored_ocr_noise"] == 1
|
||||
|
||||
|
||||
def test_compare_keeps_split_total_row_when_amount_differs():
|
||||
"""合计金额未在双方全文一致出现时,不能按表格拆列噪声过滤。"""
|
||||
result = analyze.analyze_compare(
|
||||
"设备数量:2\n设备总价:¥44,000\n合计|2|¥44,000",
|
||||
"设备数量:2\n设备总价:¥45,000\n合计",
|
||||
rules=[],
|
||||
)
|
||||
|
||||
# 断言:44,000 与 45,000 不一致,必须保留真实金额差异。
|
||||
assert result["total_change_count"] >= 1
|
||||
|
||||
|
||||
def test_compare_ignores_nonsemantic_markdown_and_ocr_fragments():
|
||||
"""Markdown 标记和单字符 OCR 残片不能成为合同新增项。"""
|
||||
for fragment in ("##", "人>", "乙", "v"):
|
||||
result = analyze.analyze_compare("第一条 合同正文", f"第一条 合同正文\n{fragment}", rules=[])
|
||||
|
||||
# 断言:残片不含独立字段、金额或义务,必须完全排除在差异清单外。
|
||||
assert result["clauses_json"] == []
|
||||
assert result["total_change_count"] == 0
|
||||
|
||||
|
||||
def test_compare_ignores_truncated_duplicate_supplier_name_fragment():
|
||||
"""签章区新增的 OCR 截断供应商名不应被误报为合同新增内容。"""
|
||||
supplier = "如玖军棱科技苏州有限公司"
|
||||
result = analyze.analyze_compare(
|
||||
f"乙方:{supplier}\n第一条 合同正文",
|
||||
f"乙方:{supplier}\n第一条 合同正文\n如兮军棱科技(苏",
|
||||
rules=[],
|
||||
)
|
||||
|
||||
# 断言:共同供应商名只多出一个错字截断片段,应计为 OCR 噪声。
|
||||
assert result["clauses_json"] == []
|
||||
assert result["total_change_count"] == 0
|
||||
assert result["summary_json"]["comparison_quality"]["ignored_ocr_noise"] == 1
|
||||
|
||||
|
||||
def test_supplier_fragment_filter_does_not_hide_actual_supplier_change():
|
||||
"""原回传合同的供应商主体不一致时,即使有短片段也不得作为重复名称过滤。"""
|
||||
assert not analyze._is_truncated_duplicate_supplier_fragment_change(
|
||||
"",
|
||||
"新供应商科技(苏",
|
||||
"乙方:原供应商科技苏州有限公司",
|
||||
"乙方:新供应商科技苏州有限公司\n新供应商科技(苏",
|
||||
)
|
||||
|
||||
def test_compare_keeps_distinct_payment_fragments():
|
||||
"""同一付款主题下不同句子的账期变化应分别保留,避免漏报。"""
|
||||
result = analyze.analyze_compare(
|
||||
"付款:验收后30日支付。\n发票:收到专票后付款。",
|
||||
"付款:验收后90日支付。\n发票:收到专票后60日付款。",
|
||||
rules=[
|
||||
{
|
||||
"title": "付款需绑定验收与发票",
|
||||
"clause_category": "payment",
|
||||
"keywords": ["付款", "验收", "发票"],
|
||||
"risk_level": "high",
|
||||
"risk_hint": "付款条件被放宽",
|
||||
"suggestion": "恢复模板付款条件",
|
||||
}
|
||||
],
|
||||
)
|
||||
assert len(result["clauses_json"]) == 2
|
||||
assert all(row["title"] == "付款条件变更" for row in result["clauses_json"])
|
||||
|
||||
|
||||
def test_compare_classifies_equivalent_clause_numbering_as_format_without_risk():
|
||||
"""中文/阿拉伯数字等价的编号变化只能算格式,不得触发付款高风险规则。"""
|
||||
result = analyze.analyze_compare(
|
||||
"3、付款方式:验收后30日支付。",
|
||||
"三、付款方式:验收后30日支付。",
|
||||
rules=[
|
||||
{
|
||||
"title": "付款需绑定验收与发票",
|
||||
"clause_category": "payment",
|
||||
"keywords": ["付款"],
|
||||
"risk_level": "high",
|
||||
"risk_hint": "付款条件变更",
|
||||
"suggestion": "恢复模板付款条件",
|
||||
}
|
||||
],
|
||||
)
|
||||
# 断言:风险评估建立在语义变化上,而不是原始字符 Diff。
|
||||
assert result["clauses_json"] == []
|
||||
assert result["high_risk_count"] == 0
|
||||
|
||||
|
||||
def test_compare_classifies_price_schedule_as_commercial_without_legal_risk():
|
||||
"""数量和单价修改应归入商业待确认,不默认为法律高风险。"""
|
||||
result = analyze.analyze_compare(
|
||||
"设备名称:空压机。数量:1台。单价:100元。",
|
||||
"设备名称:空压机。数量:2台。单价:200元。",
|
||||
rules=[],
|
||||
)
|
||||
assert result["clauses_json"][0]["change_class"] == "commercial"
|
||||
assert result["clauses_json"][0]["risk_level"] == "ok"
|
||||
|
||||
|
||||
def test_compare_keeps_payment_term_change_as_obligation_risk():
|
||||
"""付款账期放宽改变采购方权利义务,仍应进入风险判断。"""
|
||||
result = analyze.analyze_compare(
|
||||
"付款方式:验收后30日支付。",
|
||||
"付款方式:验收后90日支付。",
|
||||
rules=[
|
||||
{
|
||||
"title": "付款需绑定验收与发票",
|
||||
"clause_category": "payment",
|
||||
"keywords": ["付款"],
|
||||
"risk_level": "high",
|
||||
"risk_hint": "付款条件放宽",
|
||||
"suggestion": "恢复模板付款期限",
|
||||
}
|
||||
],
|
||||
)
|
||||
assert result["clauses_json"][0]["change_class"] == "obligation"
|
||||
assert result["clauses_json"][0]["risk_level"] == "high"
|
||||
|
||||
|
||||
def test_compare_classifies_warranty_period_change_by_changed_field():
|
||||
"""同句包含质保款和支付时,质保期限数字变化仍必须归类为质保差异。"""
|
||||
original = "质保款(总价款的0%)¥0.00元,从验收合格日起算6个月质保期满后,乙方无违约行为后支付。"
|
||||
returned = "质保款(总价款的0%)¥0.00元,从验收合格日起算12个月质保期满后,乙方无违约行为后支付。"
|
||||
result = analyze.analyze_compare(
|
||||
original,
|
||||
returned,
|
||||
rules=[
|
||||
{
|
||||
"title": "付款需绑定验收与发票",
|
||||
"clause_category": "payment",
|
||||
"risk_level": "high",
|
||||
"risk_hint": "付款条件不足",
|
||||
"suggestion": "恢复付款条件",
|
||||
"negotiation_text": "恢复我司付款条款",
|
||||
},
|
||||
{
|
||||
"title": "质保期限要求",
|
||||
"clause_category": "warranty",
|
||||
"risk_level": "medium",
|
||||
},
|
||||
],
|
||||
)
|
||||
# 断言:页面和报告只陈述质保差异,不出现无关付款建议或沟通话术。
|
||||
assert len(result["clauses_json"]) == 1
|
||||
clause = result["clauses_json"][0]
|
||||
assert clause["clause_category"] == "warranty"
|
||||
assert clause["title"] == "质保与售后变更"
|
||||
assert clause["suggestion"] == ""
|
||||
assert clause["negotiation_text"] == ""
|
||||
assert "差异项清单" in result["report_text"]
|
||||
assert "我方原文" in result["report_text"]
|
||||
assert "回传内容" in result["report_text"]
|
||||
assert "6个月" in result["report_text"]
|
||||
assert "12个月" in result["report_text"]
|
||||
assert "付款需绑定验收与发票" not in result["report_text"]
|
||||
assert "沟通话术" not in result["report_text"]
|
||||
|
||||
|
||||
def test_compare_ignores_cleaner_role_markers_and_spacing_only_changes():
|
||||
"""清洗器的模板/合同标记、空白与排版差异不得生成任何变更记录。"""
|
||||
result = analyze.analyze_compare(
|
||||
"template\n2. 本合同之任何增修应以书面为之,并以双方盖公章的方式签订。",
|
||||
"contract\n2.本合同之任何增修应以书面为之,并以双方盖公章的方式签订。",
|
||||
rules=[],
|
||||
)
|
||||
# 断言:以语义归一键比对后,仅表达差异不进入结果列表。
|
||||
assert result["clauses_json"] == []
|
||||
|
||||
|
||||
def test_compare_ignores_standalone_numbering_fragment_insert():
|
||||
"""A detached table or clause serial number must not become a contract-change record."""
|
||||
result = analyze.analyze_compare(
|
||||
"第一条 付款方式:验收后30日内支付。",
|
||||
"第一条 付款方式:验收后30日内支付。\n1",
|
||||
rules=[],
|
||||
)
|
||||
|
||||
# The isolated `1` has no field, amount, unit, or obligation and is counted only as OCR noise.
|
||||
assert result["clauses_json"] == []
|
||||
assert result["total_change_count"] == 0
|
||||
assert result["summary_json"]["comparison_quality"]["ignored_ocr_noise"] == 1
|
||||
|
||||
|
||||
def test_compare_ignores_renumbered_clause_when_body_is_unchanged():
|
||||
"""供应商插入条款540e的重新编号不应使后续所有条款错位成为修改。"""
|
||||
result = analyze.analyze_compare(
|
||||
"11、 违约责任\n乙方违约应承担赔偿责任。",
|
||||
"一、违约责任\n乙方违约应承担赔偿责任。",
|
||||
rules=[],
|
||||
)
|
||||
assert result["clauses_json"] == []
|
||||
|
||||
def test_safe_comparison_text_clears_unreadable_blobs():
|
||||
"""缺字占位 / 私用区主导的片段不得写入对照列。"""
|
||||
assert analyze._safe_comparison_text("□" * 40) == ""
|
||||
assert analyze._safe_comparison_text("\ue000" * 40) == ""
|
||||
assert analyze._safe_comparison_text("付款:验收后30日内支付。") == "付款:验收后30日内支付。"
|
||||
|
||||
|
||||
def test_extract_party_fields_reads_seller_and_contract_no():
|
||||
"""乙方(卖方)与合同编号须从合同抬头抽取为供应商与业务合同号。"""
|
||||
text = (
|
||||
"甲方(买方):苏州和信精密科技有限公司\n"
|
||||
"乙方(卖方):邢台恒阔机械制造有限公司\n"
|
||||
"合同编号:HX-PO-20260709-0002\n"
|
||||
"第一条 甲方向乙方所购买的……"
|
||||
)
|
||||
party = analyze.extract_party_fields(text)
|
||||
# 断言:卖方公司名与合同编号被正确识别
|
||||
assert party["supplier_name"] == "邢台恒阔机械制造有限公司"
|
||||
assert party["contract_no"] == "HX-PO-20260709-0002"
|
||||
|
||||
|
||||
def test_compare_short_circuits_binary_placeholder_text():
|
||||
"""任一侧为 [binary:] 占位时不应产出虚假变更行。"""
|
||||
result = analyze.analyze_compare(
|
||||
"[binary:a.pdf] PDF 文本编码不兼容或未能提取正文;请上传 Word 或可检索文本的 PDF。",
|
||||
"付款:验收后30日内支付。",
|
||||
rules=[],
|
||||
)
|
||||
assert result["clauses_json"] == []
|
||||
assert result["summary_json"]["text_extraction_warning"] == "pdf_unreadable"
|
||||
|
||||
|
||||
def test_split_paragraphs_breaks_single_line_pdf_page_into_clause_units():
|
||||
"""单行 PDF 页须按句拆分,避免一整页落入一个 Diff 单元格。"""
|
||||
parts = analyze._split_paragraphs(
|
||||
"□□□□设备买卖合同。付款:验收后30日内支付。质保期12个月。"
|
||||
)
|
||||
|
||||
# 缺字占位已清洗,各句独立成段。
|
||||
assert parts == ["设备买卖合同。", "付款:验收后30日内支付。", "质保期12个月。"]
|
||||
|
||||
|
||||
def test_clean_contract_text_removes_repeated_header_and_page_number():
|
||||
"""重复页眉和独立页码应删除,正式条款内容必须保留。"""
|
||||
raw = (
|
||||
"采购合同(内部)\n第1页\n第一条 交付期限为30日。\n"
|
||||
"采购合同(内部)\n第2页\n第二条 验收期为10日。\n"
|
||||
"采购合同(内部)\n第3页\n第三条 质保期为12个月。"
|
||||
)
|
||||
cleaned = analyze.clean_contract_text(raw)
|
||||
# 关键断言:重复短页眉被识别为噪音,条款编号及业务数值未被改写。
|
||||
assert "采购合同(内部)" not in cleaned
|
||||
assert "第一条 交付期限为30日。" in cleaned
|
||||
assert "第三条 质保期为12个月。" in cleaned
|
||||
|
||||
|
||||
def test_clean_contract_text_removes_inline_page_number_and_page_image_marker():
|
||||
"""扫描清洗器的分页图片标记及粘在正文中的页码不得进入 Diff。"""
|
||||
cleaned = analyze.clean_contract_text(
|
||||
"![page-image-1]\n付款条款。 第 1页 共 6页 交货条款。"
|
||||
)
|
||||
assert "page-image" not in cleaned
|
||||
assert "第 1页 共 6页" not in cleaned
|
||||
assert "付款条款" in cleaned
|
||||
|
||||
|
||||
def test_clean_contract_text_normalizes_mineru_html_table_without_tag_attributes():
|
||||
"""MinerU 表格应只保留单元格内容,rowspan/colspan 不得进入合同改动对照。"""
|
||||
cleaned = analyze.clean_contract_text(
|
||||
"<table><tr><td rowspan=1 colspan=2>设备名称</td><td colspan=1>数量</td></tr>"
|
||||
"<tr><td rowspan=1 colspan=2>切割机</td><td colspan=1>2</td></tr></table>"
|
||||
)
|
||||
# 关键断言:可比文本保留表格业务值,不携带 MinerU HTML 布局属性。
|
||||
assert cleaned == "设备名称 | 数量\n切割机 | 2"
|
||||
assert "rowspan" not in cleaned
|
||||
assert "<td" not in cleaned
|
||||
|
||||
|
||||
def test_clean_contract_text_removes_duplicate_mineru_signature_party_line():
|
||||
"""签章区乙方名称已在抬头出现时不应形成伪删除条款。"""
|
||||
cleaned = analyze.clean_contract_text(
|
||||
"卖方:宏博气体设备(苏州)有限公司(以下简称乙方)\n"
|
||||
"签署日期:2026年7月1日\n乙方:宏博气体设备(苏州)有限公司"
|
||||
)
|
||||
# 关键断言:卖方抬头保留,签章区重复主体行被剥离。
|
||||
assert cleaned.count("宏博气体设备(苏州)有限公司") == 1
|
||||
|
||||
|
||||
def test_structure_contract_clauses_preserves_order_and_category():
|
||||
"""结构化条款必须保留原顺序、编号,并按领域关键词标注类别。"""
|
||||
clauses = analyze.structure_contract_clauses(
|
||||
"第一条 付款\n甲方验收后30日内支付。\n第二条 验收\n甲方应书面确认验收结果。"
|
||||
)
|
||||
# 断言:Dify 可通过稳定 clause_id 遍历全部条款并引用证据。
|
||||
assert [item["clause_id"] for item in clauses] == ["clause-0001", "clause-0002"]
|
||||
assert clauses[0]["clause_no"] == "第一条"
|
||||
assert clauses[0]["category"] == "payment"
|
||||
assert clauses[1]["category"] == "acceptance"
|
||||
|
||||
|
||||
def test_compare_adds_full_contract_rule_scan_without_inflating_change_count():
|
||||
"""模板无差异时仍应追加缺项红线,但模板变更数保持为零。"""
|
||||
text = "第一条 货物应在30日内交付。"
|
||||
rules = [
|
||||
{
|
||||
"code": "IP_REQUIRED",
|
||||
"title": "知识产权保障",
|
||||
"clause_category": "ip",
|
||||
"keywords": ["知识产权"],
|
||||
"trigger_type": "keyword_missing",
|
||||
"risk_level": "high",
|
||||
"risk_hint": "缺少知识产权保障条款",
|
||||
"suggestion": "补充供应商侵权赔偿责任",
|
||||
}
|
||||
]
|
||||
result = analyze.analyze_compare(text, text, rules=rules)
|
||||
result = analyze.append_solo_rule_findings(result, text, rules=rules)
|
||||
# 断言:规则风险被补齐,但不能把规则风险数误当模板变更数。
|
||||
assert result["total_change_count"] == 0
|
||||
assert result["high_risk_count"] >= 1
|
||||
ip_findings = [item for item in result["clauses_json"] if item["clause_no"] == "IP_REQUIRED"]
|
||||
assert len(ip_findings) == 1
|
||||
assert ip_findings[0]["change_type"] == "rule_scan"
|
||||
|
||||
|
||||
def test_extraction_quality_flags_ocr_noise_without_rejecting_readable_chinese():
|
||||
"""正文可读但数字含圈号/希腊字母时应降级质量,不能当作高可信文本。"""
|
||||
quality = analyze.extraction_quality("付款:¥108,OO0 元,交货期为 2026 年 ⑧ 月 ⑳ 日。")
|
||||
assert quality["level"] in {"medium", "low"}
|
||||
assert quality["warning"] in {"ocr_noise_detected", "text_quality_low"}
|
||||
|
||||
|
||||
def test_compare_ignores_high_similarity_ocr_character_noise():
|
||||
"""标点和单个 OCR 错字且关键数值一致时不应报告为合同修改。"""
|
||||
result = analyze.analyze_compare(
|
||||
"第八条 质保。维修价格需符合市场行情。",
|
||||
"第八条 质保,维修价格需符合市场行情c",
|
||||
rules=[],
|
||||
)
|
||||
assert result["clauses_json"] == []
|
||||
assert result["summary_json"]["comparison_quality"]["ignored_ocr_noise"] == 1
|
||||
|
||||
|
||||
def test_compare_keeps_explicit_numeric_change_despite_high_text_similarity():
|
||||
"""付款期限等明确数字变化不能被 OCR 容错吞掉。"""
|
||||
result = analyze.analyze_compare(
|
||||
"付款方式:验收合格后30日内支付。",
|
||||
"付款方式:验收合格后90日内支付。",
|
||||
rules=[],
|
||||
)
|
||||
assert len(result["clauses_json"]) == 1
|
||||
assert result["clauses_json"][0]["change_class"] == "obligation"
|
||||
|
||||
|
||||
def test_compare_ignores_ocr_corrupted_list_number():
|
||||
"""列表编号 4) 被 OCR 为 0 时不应认定履约义务发生变化。"""
|
||||
result = analyze.analyze_compare(
|
||||
"4) 买方发出的任何合理的延期交货指示;",
|
||||
"0 买方发出的任何合理的延期交货指示;",
|
||||
rules=[],
|
||||
)
|
||||
assert result["clauses_json"] == []
|
||||
|
||||
|
||||
def test_compare_marks_corrupted_percentage_as_needing_confirmation():
|
||||
"""比例数字被识别为普通汉字时不进结果卡,只记入手动复核建议统计。"""
|
||||
result = analyze.analyze_compare(
|
||||
"质保款(总价款的0%)¥0.00元,质保期12个月。",
|
||||
"质保款(总价款的维%)¥0.OO元,质保期12个月。",
|
||||
rules=[],
|
||||
)
|
||||
assert all(row.get("change_type") != "ocr_uncertain" for row in result["clauses_json"])
|
||||
assert result["total_change_count"] == 0
|
||||
quality = result["summary_json"]["comparison_quality"]
|
||||
assert quality["needs_confirmation"] == 0
|
||||
assert quality["confirmation_fragments"] >= 1 or quality["ignored_ocr_noise"] >= 1
|
||||
|
||||
|
||||
def test_compare_ignores_ocr_corrupted_metadata_in_noisy_contract():
|
||||
"""合同号和主体名称的 OCR 乱码不应逐条要求采购确认。"""
|
||||
filler = "设备采购合同约定双方应共同遵守。" * 40
|
||||
result = analyze.analyze_compare(
|
||||
f"合同号:5203-2607090002\n买方:苏州和信精密科技有限公司\n{filler}",
|
||||
f"合同号:羽Os刁GO⒛90002\n买方:苏州和信精密科技有限公司\n{filler}",
|
||||
rules=[],
|
||||
)
|
||||
# 断言:抬头 OCR 噪声被统计但不进入待确认或正式改动。
|
||||
quality = result["summary_json"]["comparison_quality"]
|
||||
assert quality["needs_confirmation"] == 0
|
||||
assert quality["ignored_ocr_noise"] >= 1
|
||||
assert result["total_change_count"] == 0
|
||||
|
||||
|
||||
def test_compare_keeps_readable_contract_number_change_in_noisy_contract():
|
||||
"""清晰可读的合同编号变化仍应作为基础信息改动保留。"""
|
||||
filler = "扫描版本α。设备采购合同约定双方应共同遵守。" * 40
|
||||
result = analyze.analyze_compare(
|
||||
f"合同号:5203-2607090002\n{filler}",
|
||||
f"合同号:5203-2607090003\n{filler}",
|
||||
rules=[],
|
||||
)
|
||||
# 断言:只有含 OCR 可疑字形的抬头差异才忽略,明确数字变化不能被吞掉。
|
||||
changes = [row for row in result["clauses_json"] if row.get("change_type") == "modify"]
|
||||
assert len(changes) == 1
|
||||
assert changes[0].get("validation_status") != "needs_review"
|
||||
assert result["total_change_count"] == 1
|
||||
|
||||
|
||||
def test_compare_groups_multiple_payment_ocr_fragments_into_one_confirmation():
|
||||
"""同一付款主题的多个 OCR 数字异常不进结果卡,只累计确认片段数。"""
|
||||
filler = "扫描版本α。本合同经双方签署后生效并共同遵守。" * 40
|
||||
result = analyze.analyze_compare(
|
||||
f"{filler}\n预付款为总价款的30%。\n验收款于验收后30日内支付。",
|
||||
f"{filler}\n预付款为总价款的3哪%。\n验收款于验收后卫日内支付。",
|
||||
rules=[],
|
||||
)
|
||||
pending = [row for row in result["clauses_json"] if row["change_type"] == "ocr_uncertain"]
|
||||
assert pending == []
|
||||
assert result["summary_json"]["comparison_quality"]["confirmation_fragments"] >= 1
|
||||
assert result["summary_json"]["comparison_quality"]["needs_confirmation"] == 0
|
||||
|
||||
|
||||
def test_compare_ignores_noncritical_ocr_typo_in_noisy_contract():
|
||||
"""非关键普通错字在长篇扫描合同中不应生成待确认项。"""
|
||||
filler = "扫描版本α。设备采购合同约定双方应共同遵守。" * 40
|
||||
result = analyze.analyze_compare(
|
||||
f"{filler}\n包装材料应符合正常运输要求。",
|
||||
f"{filler}\n包装材科应符合正常运输要求。",
|
||||
rules=[],
|
||||
)
|
||||
quality = result["summary_json"]["comparison_quality"]
|
||||
assert quality["needs_confirmation"] == 0
|
||||
assert quality["ignored_ocr_noise"] >= 1
|
||||
|
||||
|
||||
def test_compare_ignores_short_mixed_ocr_garbage_insert():
|
||||
"""正文表格附近的印章/字体乱码不得作为供应商新增条款展示。"""
|
||||
result = analyze.analyze_compare(
|
||||
"专用控制平台 I5 工控 1 套 专用电脑",
|
||||
"专用控制平台 I5 工控 1 套 专用电脑\n1 惠 C 市 WW n3",
|
||||
rules=[],
|
||||
)
|
||||
# 断言:短乱码只计入已忽略噪声,不进入改动项或风险统计。
|
||||
assert result["clauses_json"] == []
|
||||
assert result["total_change_count"] == 0
|
||||
assert result["summary_json"]["comparison_quality"]["ignored_ocr_noise"] == 1
|
||||
|
||||
|
||||
def test_compare_keeps_short_commercial_values_and_contract_terms():
|
||||
"""型号、数量、金额、期限等合法短文本不能被短乱码门禁误删。"""
|
||||
cases = (
|
||||
"型号:BD-BLC1313",
|
||||
"1 台 ABC 3000W",
|
||||
"金额100元",
|
||||
"验收后30天支付",
|
||||
"质保期2年",
|
||||
)
|
||||
for added_text in cases:
|
||||
result = analyze.analyze_compare("设备配置如下", f"设备配置如下\n{added_text}", rules=[])
|
||||
# 断言:每种具有明确业务语义的短新增值均保留一条差异。
|
||||
assert len(result["clauses_json"]) == 1, added_text
|
||||
assert result["clauses_json"][0]["change_type"] == "insert", added_text
|
||||
|
||||
|
||||
def test_compare_labels_added_equipment_schedule_as_returned_contract_schedule():
|
||||
"""新增设备清单应使用事实标题,便于结果卡直接说明回传合同新增了什么类型的内容。"""
|
||||
result = analyze.analyze_compare(
|
||||
"第一条 合同正文",
|
||||
"第一条 合同正文\n设备清单\n设备名称:自动封箱机\n型号:FX-01\n数量:1台",
|
||||
rules=[],
|
||||
)
|
||||
|
||||
clause = result["clauses_json"][0]
|
||||
assert clause["change_type"] == "insert" # 关键断言:仅回传合同含该清单,属于新增而非修改。
|
||||
assert clause["title"] == "回传合同新增清单"
|
||||
assert "设备名称:自动封箱机" in clause["new_text"]
|
||||
|
||||
|
||||
def test_compare_ignores_document_end_marker_fragment():
|
||||
"""“以下无正文”等签章页结束语抽取不完整时不应计为合同修改。"""
|
||||
result = analyze.analyze_compare("(以下无正文)", "(以下", rules=[])
|
||||
assert result["clauses_json"] == []
|
||||
|
||||
|
||||
def test_compare_ignores_signature_block_alignment_noise():
|
||||
"""签章页的主体名称和签署日期错位不应计为条款修改。"""
|
||||
result = analyze.analyze_compare("乙方:供应商有限公司", "签署日期:", rules=[])
|
||||
assert result["clauses_json"] == []
|
||||
|
||||
|
||||
def test_compare_ignores_duplicate_party_name_from_signature_section():
|
||||
"""乙方名称已在抬头出现时,签章区重复行的删除不应成为合同改动。"""
|
||||
template = "卖方:宏博气体设备(苏州)有限公司\n签署日期:2026年7月1日\n乙方:宏博气体设备(苏州)有限公司"
|
||||
contract = "卖方:宏博气体设备(苏州)有限公司\n签署日期:2026年7月1日"
|
||||
result = analyze.analyze_compare(template, contract, rules=[])
|
||||
# 关键断言:主体信息重复仅属签章版式,不进入采购改动项。
|
||||
assert result["clauses_json"] == []
|
||||
|
||||
|
||||
def test_compare_ignores_end_signature_misaligned_to_existing_warranty_summary():
|
||||
"""签署日期与正文已出现的保固摘要错配时,不得伪造质保修改。"""
|
||||
template = "保固售服:整机保修1年,碳分子筛质保3年。\n签署日期:年月日"
|
||||
contract = "保固售服:整机保修1年,碳分子筛质保3年。\n签署日期:年月日\n保固售服:整机保修1年,碳分子筛质保3年。"
|
||||
result = analyze.analyze_compare(template, contract, rules=[])
|
||||
# 关键断言:同一摘要已在正文存在,尾部抽取错位不应产生中风险。
|
||||
assert result["clauses_json"] == []
|
||||
|
||||
|
||||
def test_compare_keeps_liability_change_despite_payment_prefix_and_signature():
|
||||
"""同段付款未变但违约金改写、或同行含签署日期时,必须检出实质变更。"""
|
||||
# 断言:focused 截断不得吞掉同段违约金改动。
|
||||
result = analyze.analyze_compare(
|
||||
"付款:验收后30日支付。\n迟延交货违约金按每日合同价款的千分之五计。",
|
||||
"付款:验收后30日支付。\n迟延交货违约金按每日合同价款的千分之一计。",
|
||||
rules=[],
|
||||
)
|
||||
assert len(result["clauses_json"]) >= 1
|
||||
assert any("千分" in f"{row.get('old_text')}{row.get('new_text')}" for row in result["clauses_json"])
|
||||
lights = {item["key"]: item for item in result["summary_json"]["focus_lights"]}
|
||||
assert lights["liability"]["status"] == "changed"
|
||||
|
||||
# 断言:签章词不得吞掉同段违约金改动。
|
||||
signed = analyze.analyze_compare(
|
||||
"迟延交货违约金按每日合同价款的千分之五计。签署日期:2026年1月1日",
|
||||
"迟延交货违约金按每日合同价款的千分之一计。签署日期:2026年1月1日",
|
||||
rules=[],
|
||||
)
|
||||
assert len(signed["clauses_json"]) >= 1
|
||||
assert signed["clauses_json"][0]["risk_level"] in {"high", "medium"}
|
||||
|
||||
|
||||
def test_compare_detects_chinese_per_mille_change():
|
||||
"""中文「千分之五→千分之一」必须识别为实质数字变更。"""
|
||||
result = analyze.analyze_compare(
|
||||
"乙方逾期交付的,每逾期一日按合同总价千分之五支付违约金。",
|
||||
"乙方逾期交付的,每逾期一日按合同总价千分之一支付违约金。",
|
||||
rules=[],
|
||||
)
|
||||
assert len(result["clauses_json"]) == 1
|
||||
assert result["clauses_json"][0]["change_class"] == "obligation"
|
||||
assert result["clauses_json"][0]["risk_level"] in {"high", "medium"}
|
||||
|
||||
|
||||
def test_compare_jurisdiction_change_is_at_least_medium():
|
||||
"""管辖地由甲方改为乙方时,即使无管理端规则也应达到中高风险。"""
|
||||
result = analyze.analyze_compare(
|
||||
"因本合同而生的争议,双方同意以甲方所在地人民法院作为第一审管辖法院。",
|
||||
"因本合同而生的争议,双方同意以乙方所在地人民法院作为第一审管辖法院。",
|
||||
rules=[],
|
||||
)
|
||||
assert len(result["clauses_json"]) == 1
|
||||
assert result["clauses_json"][0]["change_class"] == "obligation"
|
||||
assert result["clauses_json"][0]["risk_level"] in {"high", "medium"}
|
||||
lights = {item["key"]: item for item in result["summary_json"]["focus_lights"]}
|
||||
assert lights["dispute"]["status"] == "changed"
|
||||
|
||||
|
||||
def test_structure_contract_clauses_recognizes_chinese_list_heading():
|
||||
"""一、二、形式的主条款必须独立切分,不能与合同抬头粘在同一段。"""
|
||||
clauses = analyze.structure_contract_clauses(
|
||||
"设备买卖合同\n一、付款方式\n验收合格后付款。\n二、交货期限\n签约后30日交货。"
|
||||
)
|
||||
numbered = [item for item in clauses if item["clause_no"] in {"一、", "二、"}]
|
||||
assert [item["clause_no"] for item in numbered] == ["一、", "二、"]
|
||||
|
||||
|
||||
def test_solo_policy_flags_missing_procurement_focus_terms():
|
||||
"""卖方自有合同缺少采购五项重点保障时应给出确定性风险项。"""
|
||||
result = analyze.analyze_solo("设备名称:方管矫直机。总价:28000元。", rules=[])
|
||||
codes = {item["clause_no"] for item in result["clauses_json"]}
|
||||
assert {
|
||||
"POLICY_PAYMENT_CONDITIONS",
|
||||
"POLICY_DELIVERY_DEADLINE",
|
||||
"POLICY_WARRANTY_TERM",
|
||||
"POLICY_JURISDICTION",
|
||||
"POLICY_DELAY_PENALTY",
|
||||
}.issubset(codes)
|
||||
|
||||
|
||||
def test_solo_policy_accepts_clear_five_per_mille_delay_penalty():
|
||||
"""每日合同总价千分之五的逾期交付违约金达到采购基线,不应新增该项风险。"""
|
||||
text = (
|
||||
"付款:设备到货并验收合格,收到发票后支付。\n"
|
||||
"交货期限:签约后30个工作日。\n"
|
||||
"质保期:验收合格后12个月。\n"
|
||||
"争议由甲方所在地人民法院管辖。\n"
|
||||
"乙方逾期交付的,每逾期一日按合同总价5‰支付违约金。"
|
||||
)
|
||||
result = analyze.analyze_solo(text, rules=[])
|
||||
codes = {item["clause_no"] for item in result["clauses_json"]}
|
||||
assert "POLICY_DELAY_PENALTY" not in codes
|
||||
|
||||
|
||||
def test_solo_policy_accepts_chinese_five_per_mille_delay_penalty():
|
||||
"""“每延迟一日按千分之五”应识别为达到采购基线。"""
|
||||
text = "乙方迟延履行交货义务时,每延迟一日按设备总价款千分之五支付违约金。"
|
||||
result = analyze.analyze_solo(text, rules=[])
|
||||
codes = {item["clause_no"] for item in result["clauses_json"]}
|
||||
assert "POLICY_DELAY_PENALTY" not in codes
|
||||
|
||||
|
||||
def test_solo_policy_marks_ocr_delivery_date_for_confirmation_not_high_risk():
|
||||
"""交期数字受 OCR 污染时应进入待确认,不能计入高风险。"""
|
||||
text = "交货期限:乙方应于2026年⊥月⒛日前交货。"
|
||||
result = analyze.analyze_solo(text, rules=[])
|
||||
item = next(row for row in result["clauses_json"] if row["clause_no"] == "POLICY_DELIVERY_DEADLINE")
|
||||
assert item["validation_status"] == "needs_review"
|
||||
assert result["high_risk_count"] == 3
|
||||
|
||||
|
||||
def test_compound_payment_rule_requires_acceptance_and_invoice():
|
||||
"""付款组合规则不能因仅出现“付款”一词就判定通过。"""
|
||||
rule = {
|
||||
"code": "payment_acceptance_required",
|
||||
"title": "付款需绑定验收与发票",
|
||||
"clause_category": "payment",
|
||||
"keywords": ["付款", "验收", "发票"],
|
||||
"trigger_type": "keyword_missing",
|
||||
"risk_level": "high",
|
||||
}
|
||||
assert analyze._triggered(rule, "合同约定签约后立即付款。") is True
|
||||
assert analyze._triggered(rule, "货到并验收合格,收到发票后付款。") is False
|
||||
|
||||
|
||||
def test_custom_rule_categories_are_limited_to_supported_result_groups():
|
||||
"""自定义规则只能使用受支持分类,避免自由文本破坏风险聚合和策略去重。"""
|
||||
# 关键断言:标准分类可通过;未知分类必须在保存前被拒绝。
|
||||
assert rule_service._validate_clause_category("PAYMENT") == "payment"
|
||||
try:
|
||||
rule_service._validate_clause_category("free_text_category")
|
||||
except ValidationError:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError("未知条款分类必须被拒绝")
|
||||
|
||||
|
||||
def test_builtin_rule_codes_are_reserved_for_compound_procurement_checks():
|
||||
"""内置编码不能被自定义规则复用,避免关键词配置意外改写付款等组合判断。"""
|
||||
# 关键断言:前端不传 code 创建自定义规则;若旧客户端传入内置编码,服务端必须拒绝。
|
||||
assert "payment_acceptance_required" in rule_service.BUILTIN_RULE_CODES
|
||||
|
||||
|
||||
def test_structure_contract_clauses_uses_heading_and_parent_category():
|
||||
"""交货和保固子条款应继承父级主题,不被正文中的付款或验收词抢占。"""
|
||||
clauses = analyze.structure_contract_clauses(
|
||||
"四、交货\n1.交货期限为30日,买方未付款时顺延。\n九、保固\n1.整机保固从验收合格日起12个月。"
|
||||
)
|
||||
delivery = next(row for row in clauses if "交货期限" in row["text"])
|
||||
warranty = next(row for row in clauses if "整机保固" in row["text"])
|
||||
assert delivery["category"] == "delivery"
|
||||
assert warranty["category"] == "warranty"
|
||||
|
||||
|
||||
def test_compare_keeps_multiple_distinct_payment_changes():
|
||||
"""同一付款类别的预付款比例和付款期限变化必须分别保留。"""
|
||||
result = analyze.analyze_compare(
|
||||
"付款期限:验收后30日支付。\n预付款:签约后支付30%。",
|
||||
"付款期限:验收后90日支付。\n预付款:签约后支付50%。",
|
||||
rules=[],
|
||||
)
|
||||
assert result["total_change_count"] == 2
|
||||
@@ -0,0 +1,157 @@
|
||||
"""
|
||||
backend/tests/services/procurement_contract/test_artifact_archive.py
|
||||
|
||||
用途:验证采购合同审核产物的 MinIO 私有归档、manifest 提交和按需恢复。
|
||||
依赖:procurement_contract.artifact_archive、Flask 最小应用。
|
||||
逻辑:以内存 MinIO 替身覆盖上传和下载,确保只有完整 manifest 才能恢复文件,归档后本地可安全清理。
|
||||
"""
|
||||
|
||||
import io
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
from flask import Flask
|
||||
|
||||
from app.services.procurement_contract import artifact_archive
|
||||
|
||||
|
||||
class _MemoryResponse:
|
||||
"""模拟 MinIO 读取响应,兼容 close/release_conn 生命周期。"""
|
||||
|
||||
def __init__(self, data: bytes):
|
||||
self._stream = io.BytesIO(data)
|
||||
|
||||
def read(self) -> bytes:
|
||||
return self._stream.read()
|
||||
|
||||
def close(self) -> None:
|
||||
self._stream.close()
|
||||
|
||||
def release_conn(self) -> None:
|
||||
return None
|
||||
|
||||
|
||||
class _MemoryMinio:
|
||||
"""最小私有对象存储替身,记录 bucket、对象与最终 manifest 写入顺序。"""
|
||||
|
||||
def __init__(self):
|
||||
self.buckets: set[str] = set()
|
||||
self.objects: dict[tuple[str, str], bytes] = {}
|
||||
self.put_keys: list[str] = []
|
||||
|
||||
def bucket_exists(self, bucket: str) -> bool:
|
||||
return bucket in self.buckets
|
||||
|
||||
def make_bucket(self, bucket: str) -> None:
|
||||
self.buckets.add(bucket)
|
||||
|
||||
def put_object(self, bucket, key, stream, length, content_type):
|
||||
self.objects[(bucket, key)] = stream.read(length)
|
||||
self.put_keys.append(key)
|
||||
|
||||
def get_object(self, bucket: str, key: str) -> _MemoryResponse:
|
||||
return _MemoryResponse(self.objects[(bucket, key)])
|
||||
|
||||
|
||||
class _MissingManifestMinio:
|
||||
"""模拟审核尚未归档时读取 manifest 返回 NoSuchKey。"""
|
||||
|
||||
def get_object(self, _bucket: str, _key: str):
|
||||
"""始终抛出可被归档恢复逻辑识别的缺失对象异常。"""
|
||||
raise _MissingKeyError("manifest not ready")
|
||||
|
||||
|
||||
class _MissingKeyError(Exception):
|
||||
"""提供与 MinIO S3Error 相同的 code 属性,避免单元测试依赖真实服务。"""
|
||||
|
||||
code = "NoSuchKey"
|
||||
|
||||
|
||||
class _MissingTarget:
|
||||
"""模拟审查目录内尚不存在的目标文件。"""
|
||||
|
||||
def __init__(self, root):
|
||||
self.parent = root
|
||||
self.parents = (root,)
|
||||
|
||||
def resolve(self):
|
||||
return self
|
||||
|
||||
def is_file(self) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
class _MissingRoot:
|
||||
"""提供 Path 除法语义,避免该日志专项测试依赖 pytest 临时目录。"""
|
||||
|
||||
def __truediv__(self, _relative):
|
||||
return _MissingTarget(self)
|
||||
|
||||
|
||||
def _archive_app() -> Flask:
|
||||
"""提供合同归档开关和独立存储目录。"""
|
||||
app = Flask(__name__)
|
||||
app.config.update(
|
||||
PROCUREMENT_CONTRACT_STORAGE_ROOT="unused-in-unit-test",
|
||||
PROCUREMENT_CONTRACT_ARCHIVE_ENABLED=True,
|
||||
PROCUREMENT_CONTRACT_ARCHIVE_BUCKET="procurement-contract",
|
||||
PROCUREMENT_CONTRACT_ARCHIVE_CLEANUP_LOCAL=True,
|
||||
MINIO_ENDPOINT="minio:9000",
|
||||
MINIO_ACCESS_KEY="test",
|
||||
MINIO_SECRET_KEY="test",
|
||||
MINIO_SECURE=False,
|
||||
)
|
||||
return app
|
||||
|
||||
|
||||
def test_archive_uploads_all_files_then_manifest_and_restores_missing_file(monkeypatch):
|
||||
"""归档必须先上传文件后提交 manifest,恢复时校验 checksum。"""
|
||||
review_no = "CR-TEST-ARCHIVE"
|
||||
document_data = "付款条件:验收后30日付款。".encode("utf-8")
|
||||
result_data = b'{"total_change_count": 0}'
|
||||
document = SimpleNamespace(
|
||||
relative_to=lambda _root: Path("cleaned/contract/document.md"),
|
||||
read_bytes=lambda: document_data,
|
||||
is_file=lambda: True,
|
||||
name="document.md",
|
||||
)
|
||||
result = SimpleNamespace(
|
||||
relative_to=lambda _root: Path("result/merged_result.json"),
|
||||
read_bytes=lambda: result_data,
|
||||
is_file=lambda: True,
|
||||
name="merged_result.json",
|
||||
)
|
||||
root = SimpleNamespace(is_dir=lambda: True, rglob=lambda _pattern: [document, result])
|
||||
storage = _MemoryMinio()
|
||||
monkeypatch.setattr(artifact_archive, "_archive_client", lambda: storage)
|
||||
monkeypatch.setattr(artifact_archive, "_review_root", lambda _review_no: root)
|
||||
|
||||
with _archive_app().app_context():
|
||||
meta = artifact_archive.archive_review_artifacts(review_no)
|
||||
# 关键断言:manifest 最后写入,只有它代表完整可恢复归档。
|
||||
assert storage.put_keys[-1].endswith("/_manifest.json")
|
||||
assert meta["status"] == "archived"
|
||||
|
||||
assert storage.objects[("procurement-contract", f"reviews/{review_no}/cleaned/contract/document.md")] == document_data
|
||||
|
||||
|
||||
def test_restore_missing_manifest_is_expected_and_does_not_warn(monkeypatch, caplog):
|
||||
"""
|
||||
审核过程中可选 OCR 坐标缺失且 manifest 尚未提交时,应返回 None 而不记录 WARNING。
|
||||
|
||||
关键断言:NoSuchKey 是任务完成归档前的正常状态;网络错误和其他 S3 错误仍由生产代码告警。
|
||||
"""
|
||||
review_no = "CR-TEST-PENDING"
|
||||
root = _MissingRoot()
|
||||
monkeypatch.setattr(artifact_archive, "_archive_client", lambda: _MissingManifestMinio())
|
||||
monkeypatch.setattr(artifact_archive, "_review_root", lambda _review_no: root)
|
||||
monkeypatch.setattr(artifact_archive, "S3Error", _MissingKeyError)
|
||||
|
||||
with _archive_app().app_context(), caplog.at_level("WARNING"):
|
||||
restored = artifact_archive.restore_review_artifact(
|
||||
review_no,
|
||||
"cleaned/template/ocr_layout.json",
|
||||
)
|
||||
|
||||
assert restored is None
|
||||
assert not [record for record in caplog.records if record.levelname == "WARNING"]
|
||||
@@ -0,0 +1,126 @@
|
||||
"""
|
||||
backend/tests/services/procurement_contract/test_comparison_regions.py
|
||||
|
||||
Purpose: Verify comparison-region validation, partitioning, metadata extraction, and attachment summaries.
|
||||
Dependencies: procurement_contract.comparison_regions pure helpers.
|
||||
Flow: Tests model the V4 body/signature/attachment sequence without database or external converters.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.procurement_contract import comparison_regions
|
||||
|
||||
|
||||
def _config():
|
||||
"""Return an isolated V4 config for mutation-safe tests."""
|
||||
return comparison_regions.default_comparison_region_config()
|
||||
|
||||
|
||||
def test_validate_rejects_unknown_attachment_policy():
|
||||
"""An unknown attachment policy must use the unified validation error contract."""
|
||||
config = _config()
|
||||
config["attachment_policy"] = "content_diff"
|
||||
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
comparison_regions.validate_comparison_region_config(config)
|
||||
|
||||
# The assertion protects the stable business error code exposed by Admin API.
|
||||
assert exc_info.value.code == "PROCUREMENT_CONTRACT.INVALID_COMPARISON_REGION_CONFIG"
|
||||
|
||||
|
||||
def test_partition_excludes_header_signature_and_attachment_content():
|
||||
"""Only substantive body text remains after a successful V4 partition."""
|
||||
pages = [
|
||||
"设备买卖合同\n版本:04\n合同号:A-001\n买方:和信公司\n卖方:供应商甲\n兹因甲方向乙方购买设备\n第一条 价格不变。",
|
||||
"第二条 交货期为30日。\n本合同一式两份,由双方各持一份。",
|
||||
"甲方:和信公司 乙方:供应商甲\n盖章\n签署日期:2026年7月24日",
|
||||
"性能需求表\n设备配置内容不参与审核",
|
||||
]
|
||||
text = "\n".join(pages)
|
||||
|
||||
partition = comparison_regions.partition_document(text, pages, _config())
|
||||
|
||||
# Body changes remain reviewable, while seal and attachment text are outside the body scope.
|
||||
assert partition is not None
|
||||
assert "交货期为30日" in partition.body
|
||||
assert "盖章" not in partition.body
|
||||
assert "设备配置内容" not in partition.body
|
||||
assert partition.attachment_pages == 1
|
||||
assert partition.metadata["contract_no"] == "A-001"
|
||||
assert partition.metadata["seller"] == "供应商甲"
|
||||
|
||||
|
||||
def test_partition_requires_both_body_anchors_for_safe_fallback():
|
||||
"""Missing end anchors must return None rather than silently truncating clauses."""
|
||||
pages = ["合同号:A-001\n兹因甲方向乙方购买设备\n第一条 价格不变。"]
|
||||
|
||||
partition = comparison_regions.partition_document(pages[0], pages, _config())
|
||||
|
||||
# None is the explicit signal for review_service to call the legacy full-document diff.
|
||||
assert partition is None
|
||||
|
||||
|
||||
def test_diagnose_partition_reports_missing_page_text_for_scanned_contract():
|
||||
"""A scan with OCR body text but no page text must identify the pagination prerequisite."""
|
||||
text = (
|
||||
"合同号:A-001\n兹因甲方向乙方购买设备\n第一条 价格不变。\n"
|
||||
"本合同一式两份。\n甲方:和信公司\n盖章"
|
||||
)
|
||||
|
||||
diagnostic = comparison_regions.diagnose_partition(text, ["", ""], _config())
|
||||
|
||||
# The reason distinguishes scan pagination loss from a configuration or anchor mismatch.
|
||||
assert diagnostic["page_text_available"] is False
|
||||
assert diagnostic["body_start_anchor"] == "兹因甲方向乙方购买设备"
|
||||
assert diagnostic["body_end_anchor"] == "本合同一式两份"
|
||||
assert diagnostic["fallback_reason"] == "page_text_unavailable"
|
||||
|
||||
|
||||
def test_attachment_comparison_reports_pages_only():
|
||||
"""Attachment summaries contain counts and never expose attachment content."""
|
||||
result = comparison_regions.build_attachment_comparison(0, 2)
|
||||
|
||||
# Added pages are informational and do not have any clause/evidence payload.
|
||||
assert result == {
|
||||
"status": "added",
|
||||
"original_pages": 0,
|
||||
"returned_pages": 2,
|
||||
"added_pages": 2,
|
||||
"removed_pages": 0,
|
||||
}
|
||||
|
||||
|
||||
def test_same_attachment_page_count_ignores_content_changes():
|
||||
"""Different attachment text is intentionally irrelevant when physical page counts match."""
|
||||
result = comparison_regions.build_attachment_comparison(1, 1)
|
||||
|
||||
# No content field exists and equal page counts produce an unchanged informational summary.
|
||||
assert result["status"] == "unchanged"
|
||||
assert result["added_pages"] == 0
|
||||
assert result["removed_pages"] == 0
|
||||
|
||||
|
||||
def test_missing_signature_terms_forces_safe_fallback():
|
||||
"""A body-end phrase alone cannot justify dropping all following text without a signature signal."""
|
||||
pages = [
|
||||
"合同号:A-001\n买方:和信公司\n卖方:供应商甲\n兹因甲方向乙方购买设备\n第一条 价格不变。",
|
||||
"第二条 交货期为30日。\n本合同一式两份,由双方各持一份。\n补充履约条款仍应审核。",
|
||||
]
|
||||
|
||||
partition = comparison_regions.partition_document("\n".join(pages), pages, _config())
|
||||
|
||||
# None ensures the supplemental substantive clause remains in the legacy full-document comparison.
|
||||
assert partition is None
|
||||
|
||||
|
||||
def test_metadata_comparison_is_structured_not_clause_diff():
|
||||
"""Header changes receive field statuses outside the clause schema."""
|
||||
result = comparison_regions.build_metadata_comparison(
|
||||
{"contract_no": "A-001", "seller": "供应商甲"},
|
||||
{"contract_no": "A-002", "seller": "供应商甲"},
|
||||
)
|
||||
|
||||
# Only the changed contract number is marked changed; unchanged parties stay visible for reference.
|
||||
assert result["contract_no"]["status"] == "changed"
|
||||
assert result["seller"]["status"] == "unchanged"
|
||||
@@ -0,0 +1,181 @@
|
||||
"""
|
||||
tests/services/procurement_contract/test_llm_enhancer.py
|
||||
|
||||
用途:采购合同 Dify 新风险结果的证据校验、风险升级和待确认状态断言。
|
||||
依赖:procurement_contract.llm_enhancer。
|
||||
逻辑:直接测试纯合并函数,不访问数据库或真实 Dify,锁住结果治理契约。
|
||||
"""
|
||||
|
||||
from app.services.procurement_contract import llm_enhancer
|
||||
|
||||
|
||||
def _base_result() -> dict:
|
||||
"""构造一个已有中风险规则发现的最小确定性结果。"""
|
||||
return {
|
||||
"summary_json": {"mode": "solo"},
|
||||
"clauses_json": [
|
||||
{
|
||||
"clause_no": "RULE-1",
|
||||
"title": "付款期限",
|
||||
"risk_level": "medium",
|
||||
"detail": "付款条件需要确认",
|
||||
}
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def test_merge_review_output_validates_evidence_and_escalates_existing_risk():
|
||||
"""有效原文证据应成为 confirmed,新模型等级可提高但不能降低已有风险。"""
|
||||
result = llm_enhancer._merge_review_output(
|
||||
_base_result(),
|
||||
{
|
||||
"RULE-1": {
|
||||
"llm_reason": "付款前置条件不足",
|
||||
"llm_model_risk_level": "high",
|
||||
"llm_confidence": 0.9,
|
||||
}
|
||||
},
|
||||
[
|
||||
{
|
||||
"clause_id": "clause-0001",
|
||||
"clause_no": "第八条",
|
||||
"title": "默示验收",
|
||||
"risk_level": "high",
|
||||
"professional_reason": "沉默被视为验收合格",
|
||||
"evidence": "三日内未提出异议视为验收合格",
|
||||
"confidence": 0.88,
|
||||
}
|
||||
],
|
||||
clean_text="第八条 三日内未提出异议视为验收合格。",
|
||||
structured_clauses=[
|
||||
{
|
||||
"clause_id": "clause-0001",
|
||||
"clause_no": "第八条",
|
||||
"category": "acceptance",
|
||||
"text": "第八条 三日内未提出异议视为验收合格。",
|
||||
}
|
||||
],
|
||||
)
|
||||
# 断言:已有规则风险只升不降;新风险证据和条款均有效。
|
||||
assert result["clauses_json"][0]["risk_level"] == "high"
|
||||
assert result["clauses_json"][1]["validation_status"] == "confirmed"
|
||||
|
||||
|
||||
def test_merge_review_output_marks_missing_evidence_for_review():
|
||||
"""模型引用不存在的证据时不得标成已确认结论。"""
|
||||
result = llm_enhancer._merge_review_output(
|
||||
_base_result(),
|
||||
{},
|
||||
[
|
||||
{
|
||||
"clause_no": "第八条",
|
||||
"title": "不存在的免责内容",
|
||||
"risk_level": "high",
|
||||
"professional_reason": "模型候选风险",
|
||||
"evidence": "供应商不承担任何责任",
|
||||
}
|
||||
],
|
||||
clean_text="第八条 双方应按约履行。",
|
||||
structured_clauses=[
|
||||
{
|
||||
"clause_id": "clause-0001",
|
||||
"clause_no": "第八条",
|
||||
"category": "liability",
|
||||
"text": "第八条 双方应按约履行。",
|
||||
}
|
||||
],
|
||||
)
|
||||
# 断言:条款编号存在但证据不在原文中,必须进入待确认状态。
|
||||
assert result["clauses_json"][1]["validation_status"] == "needs_review"
|
||||
assert result["summary_json"]["llm_new_findings"]["needs_review"] == 1
|
||||
|
||||
|
||||
def test_needs_review_llm_finding_is_excluded_from_risk_counts():
|
||||
"""证据未验证的模型候选项只能进入待确认,不得污染高中低风险统计。"""
|
||||
from app.services.procurement_contract import analyze
|
||||
|
||||
result = llm_enhancer._merge_review_output(
|
||||
{"summary_json": {"mode": "solo"}, "clauses_json": []},
|
||||
{},
|
||||
[{
|
||||
"clause_id": "clause-0001",
|
||||
"title": "待确认风险",
|
||||
"risk_level": "high",
|
||||
"evidence": "不存在的原文",
|
||||
}],
|
||||
clean_text="第一条 双方应按约履行。",
|
||||
structured_clauses=[{
|
||||
"clause_id": "clause-0001",
|
||||
"clause_no": "第一条",
|
||||
"category": "other",
|
||||
"text": "第一条 双方应按约履行。",
|
||||
}],
|
||||
)
|
||||
rebuilt = analyze.rebuild_result(result)
|
||||
assert rebuilt["clauses_json"][0]["validation_status"] == "needs_review"
|
||||
assert rebuilt["high_risk_count"] == 0
|
||||
|
||||
|
||||
def test_llm_can_reject_deterministic_false_positive_with_verified_evidence():
|
||||
"""模型仅在真实原文和高置信度同时满足时,才可撤销确定性误报。"""
|
||||
result = llm_enhancer._merge_review_output(
|
||||
_base_result(),
|
||||
{
|
||||
"RULE-1": {
|
||||
"llm_decision": "reject",
|
||||
"llm_evidence": "验收合格并收到发票后90日付款",
|
||||
"llm_reason": "原文已明确付款前置条件",
|
||||
"llm_confidence": 0.92,
|
||||
"llm_model_risk_level": "ok",
|
||||
}
|
||||
},
|
||||
[],
|
||||
clean_text="付款条款:验收合格并收到发票后90日付款。",
|
||||
structured_clauses=[],
|
||||
)
|
||||
assert result["clauses_json"][0]["risk_level"] == "ok"
|
||||
assert result["clauses_json"][0]["validation_status"] == "confirmed"
|
||||
|
||||
|
||||
def test_llm_cannot_reject_finding_without_verified_evidence():
|
||||
"""证据不在合同原文时,reject 不能降低已有确定性风险。"""
|
||||
result = llm_enhancer._merge_review_output(
|
||||
_base_result(),
|
||||
{
|
||||
"RULE-1": {
|
||||
"llm_decision": "reject",
|
||||
"llm_evidence": "不存在的付款原文",
|
||||
"llm_confidence": 0.99,
|
||||
"llm_model_risk_level": "ok",
|
||||
}
|
||||
},
|
||||
[],
|
||||
clean_text="付款条款需要双方确认。",
|
||||
structured_clauses=[],
|
||||
)
|
||||
assert result["clauses_json"][0]["risk_level"] == "medium"
|
||||
|
||||
|
||||
def test_chatflow_provider_override_takes_priority_over_agent_app_type(monkeypatch):
|
||||
"""复用Chatflow时环境变量应覆盖HXOPS Agent页面的Workflow类型。"""
|
||||
class FakeAgent:
|
||||
dify_app_type = "workflow"
|
||||
|
||||
monkeypatch.setattr(llm_enhancer.Config, "PROCUREMENT_CONTRACT_LLM_PROVIDER", "chatflow")
|
||||
# 断言:无需把原会话Chatflow改为Workflow,合同后台调用也会走chat-messages。
|
||||
assert llm_enhancer._review_provider(FakeAgent()) == "chatflow"
|
||||
|
||||
|
||||
def test_chatflow_answer_json_uses_same_review_output_contract():
|
||||
"""Chatflow最终Answer中的JSON应被解析成已有项增强和独立风险。"""
|
||||
enhancements, new_items = llm_enhancer._extract_review_output(
|
||||
{
|
||||
"answer": (
|
||||
'{"items":[{"id":"RULE-1","professional_reason":"付款风险"}],'
|
||||
'"new_items":[{"id":"llm-1","title":"免责条款"}]}'
|
||||
)
|
||||
}
|
||||
)
|
||||
# 断言:Chatflow与Workflow只在传输层不同,最终结构化审核协议保持一致。
|
||||
assert enhancements["RULE-1"]["llm_reason"] == "付款风险"
|
||||
assert new_items[0]["title"] == "免责条款"
|
||||
@@ -0,0 +1,223 @@
|
||||
"""
|
||||
tests/services/procurement_contract/test_pdf_annotation.py
|
||||
|
||||
用途:验证采购合同 PDF 证据锚定、坐标字段和高亮批注输出。
|
||||
依赖:procurement_contract.pdf_annotation、pypdfium2、pypdf。
|
||||
逻辑:覆盖文本型 PDF 精确高亮、纯图片 PDF OCR 行框高亮,以及无坐标时的页级批注降级。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
|
||||
from pypdf import PdfReader, PdfWriter
|
||||
from pypdf.generic import DictionaryObject, DecodedStreamObject, NameObject
|
||||
|
||||
from app.services.procurement_contract import pdf_annotation
|
||||
|
||||
|
||||
def _sample_pdf_bytes() -> bytes:
|
||||
"""用 PDF 标准 Helvetica 字体生成带可搜索文本层的单页测试 PDF。"""
|
||||
writer = PdfWriter()
|
||||
page = writer.add_blank_page(width=595, height=842)
|
||||
font = DictionaryObject(
|
||||
{
|
||||
NameObject("/Type"): NameObject("/Font"),
|
||||
NameObject("/Subtype"): NameObject("/Type1"),
|
||||
NameObject("/BaseFont"): NameObject("/Helvetica"),
|
||||
}
|
||||
)
|
||||
font_ref = writer._add_object(font)
|
||||
page[NameObject("/Resources")] = DictionaryObject(
|
||||
{NameObject("/Font"): DictionaryObject({NameObject("/F1"): font_ref})}
|
||||
)
|
||||
stream = DecodedStreamObject()
|
||||
stream.set_data(b"BT /F1 14 Tf 72 720 Td (Seller delay penalty is 5 per mille per day.) Tj ET")
|
||||
page[NameObject("/Contents")] = writer._add_object(stream)
|
||||
buffer = io.BytesIO()
|
||||
writer.write(buffer)
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def test_anchor_and_annotate_pdf_contract_evidence():
|
||||
"""锚定命中后必须返回第一页坐标,并生成至少一个标准 PDF 高亮批注。"""
|
||||
pdf_bytes = _sample_pdf_bytes()
|
||||
|
||||
item = {
|
||||
"title": "Delay penalty",
|
||||
"risk_level": "high",
|
||||
"detail": "Penalty is below policy baseline.",
|
||||
"evidence": "Seller delay penalty is 5 per mille per day.",
|
||||
}
|
||||
anchor = pdf_annotation.locate_pdf_evidence(pdf_bytes, item)
|
||||
# 断言:原文证据被定位到第一页,且坐标可以直接供 PDF Highlight 使用。
|
||||
assert anchor is not None
|
||||
assert anchor["page_no"] == 1
|
||||
assert anchor["rects"]
|
||||
assert anchor["confidence"] >= 0.82
|
||||
|
||||
item["evidence_anchor"] = anchor
|
||||
annotated = pdf_annotation.build_annotated_pdf_bytes(pdf_bytes, [item])
|
||||
reader = PdfReader(io.BytesIO(annotated))
|
||||
assert len(reader.pages[0].get("/Annots", [])) >= 1
|
||||
|
||||
|
||||
def test_enrich_result_marks_non_pdf_as_unsupported():
|
||||
"""Word 合同不支持 PDF 坐标时只写状态,不影响审核结果。"""
|
||||
result = {"summary_json": {}, "clauses_json": [{"risk_level": "high", "evidence": "sample"}]}
|
||||
enriched = pdf_annotation.enrich_result_with_pdf_anchors(
|
||||
result,
|
||||
filename="contract.docx",
|
||||
pdf_bytes=b"not-a-pdf",
|
||||
)
|
||||
assert enriched["summary_json"]["evidence_anchoring"]["status"] == "unsupported"
|
||||
|
||||
|
||||
def test_annotate_scanned_pdf_from_ocr_page_text():
|
||||
"""扫描 PDF 无文本坐标时,应按 page-image OCR 文本命中页码并添加页级批注。"""
|
||||
pdf_bytes = _sample_pdf_bytes()
|
||||
item = {
|
||||
"title": "Delivery deadline",
|
||||
"risk_level": "high",
|
||||
"detail": "Deadline needs confirmation.",
|
||||
"evidence": "Seller shall deliver before 2026-08-20.",
|
||||
}
|
||||
clean_text = (
|
||||
"![page-image-1]\nOther clauses.\n"
|
||||
"![page-image-2]\nSeller shall deliver before 2026-08-20.\n"
|
||||
)
|
||||
|
||||
anchor = pdf_annotation.locate_ocr_evidence_page(clean_text, item)
|
||||
assert anchor is not None
|
||||
assert anchor["page_no"] == 2
|
||||
assert anchor["rects"] == []
|
||||
assert anchor["method"] == "ocr_page"
|
||||
|
||||
writer = PdfWriter()
|
||||
writer.add_blank_page(width=595, height=842)
|
||||
writer.add_blank_page(width=595, height=842)
|
||||
buffer = io.BytesIO()
|
||||
writer.write(buffer)
|
||||
annotated = pdf_annotation.build_annotated_pdf_bytes(
|
||||
buffer.getvalue(),
|
||||
[item],
|
||||
clean_text=clean_text,
|
||||
)
|
||||
reader = PdfReader(io.BytesIO(annotated))
|
||||
assert not reader.pages[0].get("/Annots", [])
|
||||
assert len(reader.pages[1].get("/Annots", [])) >= 1
|
||||
|
||||
|
||||
def test_annotate_image_only_pdf_from_persisted_ocr_line_boxes():
|
||||
"""纯图片 PDF 应把归一化 OCR 行框转换成 PDF 坐标并写入矩形高亮。"""
|
||||
writer = PdfWriter()
|
||||
writer.add_blank_page(width=600, height=800)
|
||||
buffer = io.BytesIO()
|
||||
writer.write(buffer)
|
||||
item = {
|
||||
"title": "设备使用地变更",
|
||||
"change_type": "modify",
|
||||
"risk_level": "ok",
|
||||
"detail": "设备使用地发生变化。",
|
||||
"old_text": "3.设备使用地:一厂。",
|
||||
"new_text": "3.设备使用地:二厂。",
|
||||
}
|
||||
ocr_layout = {
|
||||
"version": 1,
|
||||
"coordinate_space": "normalized_top_left",
|
||||
"pages": [
|
||||
{
|
||||
"page_no": 1,
|
||||
"lines": [
|
||||
{
|
||||
"text": "3.设备使用地:一厂。",
|
||||
"confidence": 0.98,
|
||||
"polygon": [[0.1, 0.2], [0.5, 0.2], [0.5, 0.24], [0.1, 0.24]],
|
||||
}
|
||||
],
|
||||
}
|
||||
],
|
||||
}
|
||||
|
||||
anchor = pdf_annotation.locate_ocr_layout_evidence(ocr_layout, item)
|
||||
assert anchor is not None
|
||||
assert anchor["page_no"] == 1
|
||||
assert anchor["method"] == "ocr_bbox_exact"
|
||||
assert anchor["ocr_polygons"]
|
||||
|
||||
annotated = pdf_annotation.build_annotated_pdf_bytes(
|
||||
buffer.getvalue(),
|
||||
[item],
|
||||
ocr_layout=ocr_layout,
|
||||
)
|
||||
reader = PdfReader(io.BytesIO(annotated))
|
||||
annotations = reader.pages[0].get("/Annots", [])
|
||||
assert len(annotations) == 1
|
||||
# 关键断言:写入的是矩形 Highlight,而不是只能指示页码的 Text 批注。
|
||||
assert annotations[0].get_object().get("/Subtype") == "/Highlight"
|
||||
|
||||
|
||||
def test_ocr_line_box_anchor_falls_back_to_stable_field_label():
|
||||
"""OCR 把一厂错成二厂时,完整句不一致仍应通过稳定字段名定位同一行。"""
|
||||
item = {
|
||||
"title": "设备使用地变更",
|
||||
"change_type": "modify",
|
||||
"risk_level": "ok",
|
||||
"old_text": "3.设备使用地:一厂。",
|
||||
"new_text": "3.设备使用地:二厂。",
|
||||
}
|
||||
layout = {
|
||||
"pages": [
|
||||
{
|
||||
"page_no": 2,
|
||||
"lines": [
|
||||
{
|
||||
"text": "3.设备使用地:一厂。",
|
||||
"polygon": [[0.1, 0.3], [0.4, 0.3], [0.4, 0.34], [0.1, 0.34]],
|
||||
}
|
||||
],
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
anchor = pdf_annotation.locate_ocr_layout_evidence(layout, item)
|
||||
assert anchor is not None
|
||||
assert anchor["page_no"] == 2
|
||||
assert "设备使用地" in anchor["matched_text"]
|
||||
|
||||
|
||||
def test_enrich_anchors_compare_change_even_when_risk_is_ok(monkeypatch):
|
||||
"""未发现风险的已确认比对改动仍属于标注对象,不能因 risk_level=ok 被跳过。"""
|
||||
expected_anchor = {"page_no": 1, "rects": [[1, 2, 3, 4]], "method": "exact"}
|
||||
monkeypatch.setattr(pdf_annotation, "locate_pdf_evidence", lambda *_args, **_kwargs: expected_anchor)
|
||||
result = {
|
||||
"summary_json": {},
|
||||
"clauses_json": [
|
||||
{
|
||||
"change_type": "modify",
|
||||
"risk_level": "ok",
|
||||
"new_text": "设备使用地:二厂",
|
||||
}
|
||||
],
|
||||
}
|
||||
|
||||
enriched = pdf_annotation.enrich_result_with_pdf_anchors(
|
||||
result,
|
||||
filename="contract.pdf",
|
||||
pdf_bytes=b"test",
|
||||
)
|
||||
assert enriched["clauses_json"][0]["evidence_anchor"] == expected_anchor
|
||||
assert enriched["summary_json"]["evidence_anchoring"]["anchored"] == 1
|
||||
|
||||
|
||||
def test_annotate_returns_original_pdf_when_no_finding_can_be_anchored():
|
||||
"""没有可定位证据时下载仍应成功,返回未加批注的合同副本。"""
|
||||
pdf_bytes = _sample_pdf_bytes()
|
||||
annotated = pdf_annotation.build_annotated_pdf_bytes(
|
||||
pdf_bytes,
|
||||
[{"title": "Unanchored", "risk_level": "medium", "new_text": "合同中不存在的文字"}],
|
||||
)
|
||||
reader = PdfReader(io.BytesIO(annotated))
|
||||
# 关键断言:原页保留,且没有凭空生成批注。
|
||||
assert len(reader.pages) == 1
|
||||
assert not reader.pages[0].get("/Annots", [])
|
||||
@@ -0,0 +1,180 @@
|
||||
"""
|
||||
backend/tests/services/procurement_contract/test_preprocessing.py
|
||||
|
||||
用途:验证采购合同调用 MinerU 的请求协议、Markdown 读取、OCR 坐标产物与故障回退前提。
|
||||
依赖:procurement_contract.preprocessing、Flask 最小应用上下文。
|
||||
逻辑:模拟测试环境 MinerU 和 edkb 产物,确保 PDF 解析结果与纯图片行坐标可审计、可归档。
|
||||
"""
|
||||
|
||||
from io import BytesIO
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from flask import Flask
|
||||
|
||||
from app.services.procurement_contract import preprocessing
|
||||
|
||||
|
||||
class _MineruResponse:
|
||||
"""模拟 requests.Response,仅暴露 MinerU 客户端需要的状态和 JSON 接口。"""
|
||||
|
||||
def __init__(self, payload: dict):
|
||||
self.payload = payload
|
||||
|
||||
def raise_for_status(self) -> None:
|
||||
return None
|
||||
|
||||
def json(self) -> dict:
|
||||
return self.payload
|
||||
|
||||
|
||||
class _SourcePdf:
|
||||
"""模拟待上传的 PDF,避免测试依赖受限的本机临时目录。"""
|
||||
|
||||
name = "seller.pdf"
|
||||
|
||||
def open(self, mode: str):
|
||||
assert mode == "rb"
|
||||
|
||||
class _Handle(BytesIO):
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc, tb):
|
||||
self.close()
|
||||
return False
|
||||
|
||||
return _Handle(b"%PDF-1.4 test")
|
||||
|
||||
|
||||
class _Artifact:
|
||||
"""保存 MinerU 审计产物的内存替身。"""
|
||||
|
||||
def __init__(self, store: dict[str, str], name: str):
|
||||
self.store = store
|
||||
self.name = name
|
||||
|
||||
def write_text(self, content: str, *, encoding: str) -> None:
|
||||
assert encoding == "utf-8"
|
||||
self.store[self.name] = content
|
||||
|
||||
|
||||
class _OutputDir:
|
||||
"""模拟清洗目录,仅记录 MinerU 产生的 JSON 与 Markdown。"""
|
||||
|
||||
def __init__(self):
|
||||
self.files: dict[str, str] = {}
|
||||
|
||||
def __truediv__(self, name: str) -> _Artifact:
|
||||
return _Artifact(self.files, name)
|
||||
|
||||
|
||||
def _mineru_app() -> Flask:
|
||||
"""构造最小配置,隔离 MinerU 单元测试的文件输出目录。"""
|
||||
app = Flask(__name__)
|
||||
app.config.update(
|
||||
PROCUREMENT_CONTRACT_MINERU_API_URL="http://host.docker.internal:8100",
|
||||
PROCUREMENT_CONTRACT_MINERU_BACKEND="pipeline",
|
||||
PROCUREMENT_CONTRACT_MINERU_PARSE_METHOD="auto",
|
||||
PROCUREMENT_CONTRACT_MINERU_CONNECT_TIMEOUT_SECONDS=5,
|
||||
PROCUREMENT_CONTRACT_MINERU_READ_TIMEOUT_SECONDS=300,
|
||||
)
|
||||
return app
|
||||
|
||||
|
||||
def test_mineru_parse_pdf_reads_markdown_and_persists_response(monkeypatch):
|
||||
"""MinerU 成功时必须使用 files 字段,并保存原始响应供问题追溯。"""
|
||||
seen: dict = {}
|
||||
|
||||
def fake_post(url, *, data, files, timeout):
|
||||
seen.update({"url": url, "data": data, "files": files, "timeout": timeout})
|
||||
return _MineruResponse(
|
||||
{
|
||||
"status": "completed",
|
||||
"backend": "pipeline",
|
||||
"version": "3.1.14",
|
||||
"results": {"seller": {"md_content": "## 三、付款方式\n\n预付款为30%。"}},
|
||||
}
|
||||
)
|
||||
|
||||
monkeypatch.setattr(preprocessing.requests, "post", fake_post)
|
||||
source = _SourcePdf()
|
||||
output = _OutputDir()
|
||||
with _mineru_app().app_context():
|
||||
markdown, meta = preprocessing._mineru_parse_pdf(source, output)
|
||||
|
||||
# 关键断言:协议与测试环境 OpenAPI 一致,单文件结果不依赖 results 的文件名键。
|
||||
assert markdown == "## 三、付款方式\n\n预付款为30%。"
|
||||
assert seen["url"] == "http://host.docker.internal:8100/file_parse"
|
||||
assert seen["data"]["lang_list"] == "ch"
|
||||
assert seen["data"]["backend"] == "pipeline"
|
||||
assert seen["files"][0][0] == "files"
|
||||
assert meta == {
|
||||
"provider": "mineru",
|
||||
"backend": "pipeline",
|
||||
"version": "3.1.14",
|
||||
"parse_method": "auto",
|
||||
"result_artifact": "mineru_result.json",
|
||||
}
|
||||
assert output.files["mineru_document.md"] == markdown
|
||||
assert '"status": "completed"' in output.files["mineru_result.json"]
|
||||
|
||||
|
||||
def test_mineru_parse_pdf_rejects_incomplete_task_result(monkeypatch):
|
||||
"""MinerU 未完成或未返回 Markdown 时必须抛错,调用方才能安全回退旧解析器。"""
|
||||
monkeypatch.setattr(
|
||||
preprocessing.requests,
|
||||
"post",
|
||||
lambda *args, **kwargs: _MineruResponse({"status": "failed", "error": "model unavailable"}),
|
||||
)
|
||||
with _mineru_app().app_context(), pytest.raises(RuntimeError, match="did not complete"):
|
||||
preprocessing._mineru_parse_pdf(_SourcePdf(), _OutputDir())
|
||||
|
||||
|
||||
def test_extract_page_texts_uses_mineru_logical_page_when_pdf_has_no_text_layer(monkeypatch):
|
||||
"""Readable MinerU OCR must still let comparison regions find body anchors on scanned PDFs."""
|
||||
monkeypatch.setattr(preprocessing, "_extract_pdf_page_texts", lambda _path: ["", ""])
|
||||
|
||||
pages, warning = preprocessing._extract_page_texts(
|
||||
Path("seller.pdf"),
|
||||
_OutputDir(),
|
||||
"兹因甲方向乙方购买设备\n第一条 价格不变。\n本合同一式两份。\n甲方:和信公司",
|
||||
)
|
||||
|
||||
# The logical page is only an anchor fallback; physical attachment page counts remain unavailable.
|
||||
assert pages == ["兹因甲方向乙方购买设备\n第一条 价格不变。\n本合同一式两份。\n甲方:和信公司"]
|
||||
assert warning == "PDF native page text unavailable; used MinerU logical page for body boundaries"
|
||||
|
||||
|
||||
def test_ocr_layout_from_edkb_keeps_pdf_page_line_polygons(tmp_path):
|
||||
"""edkb 已识别的 PDF 整页行框应直接复用,避免合同预处理重复 OCR。"""
|
||||
raw_layout = tmp_path / "01_raw_layout.json"
|
||||
raw_layout.write_text(
|
||||
"""
|
||||
[
|
||||
{
|
||||
"id": "ocr-pdf-page-2",
|
||||
"page": 2,
|
||||
"type": "ocr_text",
|
||||
"text": "OCR_TEXT: 设备使用地:一厂",
|
||||
"bbox": [0, 0, 1000, 1000],
|
||||
"meta": {
|
||||
"page_image": true,
|
||||
"ocr_lines": [
|
||||
{
|
||||
"text": "设备使用地:一厂",
|
||||
"confidence": 0.98,
|
||||
"polygon": [[0.1, 0.2], [0.4, 0.2], [0.4, 0.24], [0.1, 0.24]]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
""",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
pages = preprocessing._ocr_layout_from_edkb(raw_layout)
|
||||
assert pages[0]["page_no"] == 2
|
||||
assert pages[0]["lines"][0]["text"] == "设备使用地:一厂"
|
||||
assert pages[0]["lines"][0]["polygon"][0] == [0.1, 0.2]
|
||||
@@ -0,0 +1,22 @@
|
||||
"""
|
||||
tests/services/procurement_contract/test_review_service.py
|
||||
|
||||
用途:验证采购合同审核创建阶段的文件输入门禁。
|
||||
依赖:review_service、ValidationError。
|
||||
逻辑:在访问文件资产或数据库前,确保比对模式必须显式提供我方原合同,禁止回退默认模板。
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.procurement_contract import review_service
|
||||
|
||||
|
||||
def test_compare_review_requires_uploaded_original_contract():
|
||||
"""比对模式缺少我方原合同时应立即拒绝,防止静默使用库内默认模板。"""
|
||||
with pytest.raises(ValidationError, match="original_contract_asset_no is required"):
|
||||
review_service.start_review(
|
||||
user_id=1,
|
||||
review_mode="compare",
|
||||
contract_asset_no="FA-SELLER-RETURN",
|
||||
)
|
||||
@@ -0,0 +1,457 @@
|
||||
"""
|
||||
backend/tests/services/procurement_contract/test_visual_ocr_validation.py
|
||||
|
||||
用途:验证混合提取合同的双边同源 OCR 复核只移除地点字段和视觉设备表噪声差异。
|
||||
依赖:visual_ocr_validation;页面定位和 OCR 在单元测试中替换为确定性结果。
|
||||
逻辑:构造 compare 差异 → 模拟文字层/扫描件及页面 OCR → 断言移除、保留和诊断分支。
|
||||
"""
|
||||
|
||||
from app.services.procurement_contract import analyze, visual_ocr_validation
|
||||
|
||||
|
||||
def _compare_result(item: dict) -> dict:
|
||||
"""构造包含一个差异项的最小 compare 结果,便于验证复核后的统计。"""
|
||||
return {
|
||||
"summary_json": {
|
||||
"mode": "compare",
|
||||
"comparison_quality": {"ignored_ocr_noise": 2},
|
||||
"focus_lights": [
|
||||
{
|
||||
"key": "delivery",
|
||||
"label": "交期",
|
||||
"status": "changed",
|
||||
"risk_level": "medium",
|
||||
"change_count": 1,
|
||||
}
|
||||
],
|
||||
},
|
||||
"clauses_json": [item],
|
||||
}
|
||||
|
||||
|
||||
def _location_modify() -> dict:
|
||||
"""返回本次真实问题对应的设备使用地 OCR 差异。"""
|
||||
return {
|
||||
"clause_no": "1",
|
||||
"title": "设备使用地变更",
|
||||
"clause_category": "commercial",
|
||||
"change_type": "modify",
|
||||
"risk_level": "ok",
|
||||
"old_text": "3.设备使用地:一厂。",
|
||||
"new_text": "3.设备使用地:二。",
|
||||
}
|
||||
|
||||
|
||||
def _run(monkeypatch, result: dict, *, original_ocr: str | list[str], returned_ocr: str | list[str]) -> dict:
|
||||
"""
|
||||
固定为文字原合同与扫描回传合同,并注入双方命中页 OCR 行。
|
||||
|
||||
Args:
|
||||
monkeypatch: pytest 补丁工具。
|
||||
result: 待复核的最小 compare 结果。
|
||||
original_ocr: 原合同单行文本或真实分行 OCR 文本。
|
||||
returned_ocr: 回传合同单行文本或真实分行 OCR 文本。
|
||||
|
||||
Returns:
|
||||
执行双边同源 OCR 复核后的结果。
|
||||
"""
|
||||
profiles = iter([
|
||||
{"page_count": 3, "native_text_pages": 3},
|
||||
{"page_count": 3, "native_text_pages": 0},
|
||||
])
|
||||
monkeypatch.setattr(visual_ocr_validation, "_pdf_text_profile", lambda _data: next(profiles))
|
||||
monkeypatch.setattr(visual_ocr_validation, "_locate_page", lambda **_kwargs: 2)
|
||||
|
||||
original_lines = original_ocr if isinstance(original_ocr, list) else [original_ocr]
|
||||
returned_lines = returned_ocr if isinstance(returned_ocr, list) else [returned_ocr]
|
||||
page_results = iter([
|
||||
{2: [{"text": text} for text in original_lines]},
|
||||
{2: [{"text": text} for text in returned_lines]},
|
||||
])
|
||||
monkeypatch.setattr(
|
||||
visual_ocr_validation,
|
||||
"_ocr_pdf_pages",
|
||||
lambda _data, _pages: next(page_results),
|
||||
)
|
||||
return visual_ocr_validation.suppress_mixed_extraction_ocr_noise(
|
||||
result,
|
||||
review_no="CR-TEST",
|
||||
original_filename="original.pdf",
|
||||
original_pdf_bytes=b"original",
|
||||
original_extraction_meta={"mode": "mineru"},
|
||||
original_ocr_layout={},
|
||||
returned_filename="returned.pdf",
|
||||
returned_pdf_bytes=b"returned",
|
||||
returned_extraction_meta={"mode": "edkb_system"},
|
||||
returned_ocr_layout={"pages": []},
|
||||
)
|
||||
|
||||
|
||||
def _ocr_line(text: str, left: float, top: float, right: float, bottom: float) -> dict:
|
||||
"""构造带像素框的 OCR 行,模拟 RapidOCR 表格检测结果。"""
|
||||
return {
|
||||
"text": text,
|
||||
"pixel_polygon": [[left, top], [right, top], [right, bottom], [left, bottom]],
|
||||
}
|
||||
|
||||
|
||||
def _equipment_page_lines(*, model: str = "BC-MD601", quantity: str = "2") -> list[dict]:
|
||||
"""构造含空品牌列的标准设备表,验证后续列不会左移。"""
|
||||
return [
|
||||
_ocr_line("序号", 100, 100, 150, 125),
|
||||
_ocr_line("设备名称", 220, 100, 330, 125),
|
||||
_ocr_line("品牌", 400, 100, 455, 125),
|
||||
_ocr_line("型号", 525, 100, 580, 125),
|
||||
_ocr_line("数量", 670, 100, 725, 125),
|
||||
_ocr_line("单价", 805, 100, 860, 125),
|
||||
_ocr_line("总价", 945, 100, 1000, 125),
|
||||
_ocr_line("1", 115, 150, 130, 175),
|
||||
_ocr_line("半自动拉铆钉机", 205, 150, 350, 175),
|
||||
_ocr_line(model, 500, 150, 610, 175),
|
||||
_ocr_line(quantity, 690, 150, 705, 175),
|
||||
_ocr_line("18,600", 790, 150, 875, 175),
|
||||
_ocr_line("37,200", 930, 150, 1015, 175),
|
||||
_ocr_line("合计", 430, 200, 485, 225),
|
||||
]
|
||||
|
||||
|
||||
def _equipment_result() -> dict:
|
||||
"""构造截图中的型号漏列修改项及其无文本新增伴随项。"""
|
||||
modify = {
|
||||
"clause_no": "1",
|
||||
"title": "合同内容变更",
|
||||
"change_type": "modify",
|
||||
"change_class": "commercial",
|
||||
"risk_level": "ok",
|
||||
"old_text": "1|半自动拉铆钉机|BC-MD601|2|18,600|37,200",
|
||||
"new_text": "1|半自动拉铆钉机|2|18,600|37,200",
|
||||
}
|
||||
insert = {
|
||||
"clause_no": "2",
|
||||
"title": "合同内容变更",
|
||||
"change_type": "insert",
|
||||
"change_class": "commercial",
|
||||
"risk_level": "ok",
|
||||
"old_text": "",
|
||||
"new_text": "",
|
||||
"detail": "供应商回传合同新增了交易条件或清单信息,请以变更对照为准。",
|
||||
}
|
||||
result = _compare_result(modify)
|
||||
result["clauses_json"].append(insert)
|
||||
return result
|
||||
|
||||
|
||||
def _run_equipment(monkeypatch, *, original_lines: list[dict], returned_lines: list[dict]) -> dict:
|
||||
"""注入双方第一页设备表 OCR,执行混合提取视觉复核。"""
|
||||
profiles = iter([
|
||||
{"page_count": 5, "native_text_pages": 5},
|
||||
{"page_count": 6, "native_text_pages": 0},
|
||||
])
|
||||
monkeypatch.setattr(visual_ocr_validation, "_pdf_text_profile", lambda _data: next(profiles))
|
||||
monkeypatch.setattr(visual_ocr_validation, "_table_candidate_pages", lambda **_kwargs: {1})
|
||||
page_results = iter([{1: original_lines}, {1: returned_lines}])
|
||||
monkeypatch.setattr(
|
||||
visual_ocr_validation,
|
||||
"_ocr_pdf_pages",
|
||||
lambda _data, _pages: next(page_results),
|
||||
)
|
||||
return visual_ocr_validation.suppress_mixed_extraction_ocr_noise(
|
||||
_equipment_result(),
|
||||
review_no="CR-TABLE",
|
||||
original_filename="original.pdf",
|
||||
original_pdf_bytes=b"original",
|
||||
original_extraction_meta={"mode": "mineru"},
|
||||
original_ocr_layout={},
|
||||
returned_filename="returned.pdf",
|
||||
returned_pdf_bytes=b"returned",
|
||||
returned_extraction_meta={"mode": "mineru"},
|
||||
returned_ocr_layout={},
|
||||
)
|
||||
|
||||
|
||||
def test_same_visual_ocr_removes_location_noise_and_records_diagnostic(monkeypatch):
|
||||
"""双方视觉 OCR 同为“二”时应移除文本层“一厂 vs 二”的伪差异。"""
|
||||
result = _run(
|
||||
monkeypatch,
|
||||
_compare_result(_location_modify()),
|
||||
original_ocr="3.设备使用地:二。",
|
||||
returned_ocr="3.设备使用地:二。",
|
||||
)
|
||||
result = analyze.rebuild_result(result)
|
||||
|
||||
assert result["clauses_json"] == [] # 关键断言:只移除经双边视觉证明一致的差异。
|
||||
assert result["summary_json"]["total_changes"] == 0
|
||||
assert result["total_change_count"] == 0
|
||||
quality = result["summary_json"]["comparison_quality"]
|
||||
assert quality["ignored_ocr_noise"] == 3
|
||||
assert quality["visual_ocr_rechecks"]["ignored"] == 1
|
||||
assert quality["visual_ocr_rechecks"]["items"][0]["decision"] == "ignored"
|
||||
assert result["summary_json"]["focus_lights"][0]["status"] == "unchanged"
|
||||
|
||||
|
||||
def test_different_visual_ocr_keeps_location_difference(monkeypatch):
|
||||
"""双方视觉 OCR 不一致时必须保留差异,避免复核扩大为内容忽略器。"""
|
||||
result = _run(
|
||||
monkeypatch,
|
||||
_compare_result(_location_modify()),
|
||||
original_ocr="3.设备使用地:一厂。",
|
||||
returned_ocr="3.设备使用地:二厂。",
|
||||
)
|
||||
|
||||
assert result["clauses_json"] == [_location_modify()]
|
||||
diagnostic = result["summary_json"]["comparison_quality"]["visual_ocr_rechecks"]
|
||||
assert diagnostic["ignored"] == 0
|
||||
assert diagnostic["kept"] == 1
|
||||
assert diagnostic["items"][0]["reason"] == "visual_ocr_differs"
|
||||
|
||||
|
||||
def test_same_visual_ocr_removes_high_similarity_noncritical_noise(monkeypatch):
|
||||
"""无标签的少量字符误识别在视觉 OCR 一致时应移除,覆盖截图中的通用文本差异。"""
|
||||
item = {
|
||||
"clause_no": "1",
|
||||
"title": "合同内容变更",
|
||||
"change_type": "modify",
|
||||
"risk_level": "ok",
|
||||
"old_text": "专用控制平台f5工控专用电脑",
|
||||
"new_text": "专用控制平台15工控专用电脑",
|
||||
}
|
||||
result = _run(
|
||||
monkeypatch,
|
||||
_compare_result(item),
|
||||
original_ocr="专用控制平台15工控专用电脑",
|
||||
returned_ocr="专用控制平台15工控专用电脑",
|
||||
)
|
||||
|
||||
assert result["clauses_json"] == [] # 关键断言:视觉文本一致的非关键 OCR 噪声不显示为改动。
|
||||
diagnostic = result["summary_json"]["comparison_quality"]["visual_ocr_rechecks"]
|
||||
assert diagnostic["ignored"] == 1
|
||||
assert diagnostic["items"][0]["validation_type"] == "high_similarity_text"
|
||||
|
||||
|
||||
def test_same_visual_ocr_removes_multiline_warranty_clause_noise(monkeypatch):
|
||||
"""混合 PDF 中质保条款仅因 OCR 断行/漏标点产生差异时,应由双方同源 OCR 复核后移除。"""
|
||||
item = {
|
||||
"clause_no": "9",
|
||||
"title": "质保与售后变更",
|
||||
"change_type": "modify",
|
||||
"change_class": "obligation",
|
||||
"risk_level": "medium",
|
||||
"old_text": "1.乙方自本设备安装并经验收合格之日起,免费提供保固壹年。于保固期间内,如甲方发现设备有瑕疵或不符合验收标准时,乙方应于接到甲方通知后,至迟24小时内,立即派员进行电话、邮件、微信等在线支持或赴现场实地勘查处理,并应于7天内处理完毕。",
|
||||
"new_text": "1.乙方自本设备安装并经验收合格之日起,免费提供保固壹年。于保固期间内,如甲方发现设备有瑕疵或不符合验收标准时,乙方应于接到甲方通知后,至迟 24 小时内,立即派员进行邮件、微信等在线支持或赴现场实地勘查处理,并应于 7 天内处理完毕。",
|
||||
}
|
||||
visual_text = [
|
||||
"1.乙方自本设备安装并经验收合格之日起,免费提供保固壹年。",
|
||||
"于保固期间内,如甲方发现设备有瑕疵或不符合验收标准时,乙方应于接到甲方通知后,",
|
||||
"至迟24小时内,立即派员进行电话、邮件、微信等在线支持或赴现场实地勘查处理,",
|
||||
"并应于7天内处理完毕。",
|
||||
]
|
||||
result = _run(
|
||||
monkeypatch,
|
||||
_compare_result(item),
|
||||
original_ocr=visual_text,
|
||||
returned_ocr=visual_text,
|
||||
)
|
||||
result = analyze.rebuild_result(result)
|
||||
|
||||
assert result["clauses_json"] == []
|
||||
quality = result["summary_json"]["comparison_quality"]
|
||||
assert quality["visual_ocr_rechecks"]["checked"] == 1
|
||||
assert quality["visual_ocr_rechecks"]["items"][0]["reason"] == "same_visual_ocr"
|
||||
|
||||
|
||||
def test_shared_anchor_rebuilds_full_warranty_clause_when_returned_diff_is_truncated(monkeypatch):
|
||||
"""
|
||||
回传抽取乱码只保留条款前缀时,应按双方共同锚点继续拼接后续 OCR 行并移除误报。
|
||||
|
||||
关键断言:模拟测试环境 CR-20260804-5DF6 的真实分行结果,回传 expected_text 在“立即派”后截断,
|
||||
但页面 OCR 后续行仍包含完整售后方式;复核必须重建完整条款,而不是选择短前缀窗口。
|
||||
"""
|
||||
item = {
|
||||
"clause_no": "5",
|
||||
"title": "质保与售后变更",
|
||||
"change_type": "modify",
|
||||
"change_class": "obligation",
|
||||
"risk_level": "medium",
|
||||
"old_text": "3.保固期外,如设备出现故障,乙方也需在接到甲方通知后,至迟24小时内,立即派员进行电话、邮件、微信等在线支持或赴现场实地勘查处理,维修价格需符合市场行情。",
|
||||
"new_text": "3.保固期外,如设备出现故障,乙方也需在接到甲方通知后,至迟24小时内,立即派行邮件缴信士山",
|
||||
}
|
||||
visual_lines = [
|
||||
"3.保固期外,如设备出现故障,乙方也需在接到甲方通知后,",
|
||||
"至迟24小时内,立即派员进行电话、邮件、微信等在线支持",
|
||||
"或赴现场实地勘查处理,维修价格需符合市场行情。",
|
||||
]
|
||||
result = _run(
|
||||
monkeypatch,
|
||||
_compare_result(item),
|
||||
original_ocr=visual_lines,
|
||||
returned_ocr=visual_lines,
|
||||
)
|
||||
|
||||
assert result["clauses_json"] == []
|
||||
diagnostic = result["summary_json"]["comparison_quality"]["visual_ocr_rechecks"]["items"][0]
|
||||
assert diagnostic["reason"] == "same_visual_ocr"
|
||||
assert "电话、邮件、微信" in diagnostic["returned_visual_ocr"]
|
||||
|
||||
|
||||
def test_shared_anchor_keeps_real_multiline_warranty_content_change(monkeypatch):
|
||||
"""
|
||||
共同锚点只能用于完整重建;若回传页面确实删除电话支持,视觉文本不一致时必须保留差异。
|
||||
|
||||
关键断言:即使数字、期限和条款前缀完全一致,也不能把真实的售后服务方式删除当作 OCR 噪声。
|
||||
"""
|
||||
item = {
|
||||
"clause_no": "5",
|
||||
"title": "质保与售后变更",
|
||||
"change_type": "modify",
|
||||
"change_class": "obligation",
|
||||
"risk_level": "medium",
|
||||
"old_text": "3.保固期外,如设备出现故障,乙方也需在接到甲方通知后,至迟24小时内,立即派员进行电话、邮件、微信等在线支持或赴现场实地勘查处理。",
|
||||
"new_text": "3.保固期外,如设备出现故障,乙方也需在接到甲方通知后,至迟24小时内,立即派员进行邮件、微信等在线支持或赴现场实地勘查处理。",
|
||||
}
|
||||
original_lines = [
|
||||
"3.保固期外,如设备出现故障,乙方也需在接到甲方通知后,",
|
||||
"至迟24小时内,立即派员进行电话、邮件、微信等在线支持",
|
||||
"或赴现场实地勘查处理。",
|
||||
]
|
||||
returned_lines = [
|
||||
"3.保固期外,如设备出现故障,乙方也需在接到甲方通知后,",
|
||||
"至迟24小时内,立即派员进行邮件、微信等在线支持",
|
||||
"或赴现场实地勘查处理。",
|
||||
]
|
||||
result = _run(
|
||||
monkeypatch,
|
||||
_compare_result(item),
|
||||
original_ocr=original_lines,
|
||||
returned_ocr=returned_lines,
|
||||
)
|
||||
|
||||
assert result["clauses_json"] == [item]
|
||||
diagnostic = result["summary_json"]["comparison_quality"]["visual_ocr_rechecks"]["items"][0]
|
||||
assert diagnostic["decision"] == "kept"
|
||||
assert diagnostic["reason"] == "visual_ocr_differs"
|
||||
|
||||
|
||||
def test_warranty_deadline_change_is_not_eligible_for_auto_ocr_suppression():
|
||||
"""质保期限等关键数字变化不得因高相似文本而进入自动忽略。"""
|
||||
item = {
|
||||
"change_type": "modify",
|
||||
"old_text": "质保期满12个月后支付",
|
||||
"new_text": "质保期满24个月后支付",
|
||||
}
|
||||
|
||||
assert visual_ocr_validation._eligible_high_similarity_field(item) is False
|
||||
|
||||
|
||||
def test_numeric_field_is_never_auto_ignored(monkeypatch):
|
||||
"""金额等关键数值字段即使双边 OCR 相同,也不得进入地点字段白名单。"""
|
||||
item = {
|
||||
"change_type": "modify",
|
||||
"old_text": "合同总价:10000元",
|
||||
"new_text": "合同总价:20000元",
|
||||
"risk_level": "high",
|
||||
}
|
||||
result = _run(
|
||||
monkeypatch,
|
||||
_compare_result(item),
|
||||
original_ocr="合同总价:20000元",
|
||||
returned_ocr="合同总价:20000元",
|
||||
)
|
||||
|
||||
assert result["clauses_json"] == [item]
|
||||
diagnostic = result["summary_json"]["comparison_quality"]["visual_ocr_rechecks"]
|
||||
assert diagnostic["checked"] == 0
|
||||
assert diagnostic["reason"] == "no_eligible_visual_recheck"
|
||||
|
||||
|
||||
def test_insert_and_delete_are_never_auto_ignored(monkeypatch):
|
||||
"""单侧新增/删除缺少双边对应字段,不执行同源 OCR 自动忽略。"""
|
||||
item = _location_modify()
|
||||
item["change_type"] = "insert"
|
||||
item["old_text"] = ""
|
||||
result = _run(
|
||||
monkeypatch,
|
||||
_compare_result(item),
|
||||
original_ocr="设备使用地:二厂",
|
||||
returned_ocr="设备使用地:二厂",
|
||||
)
|
||||
|
||||
assert result["clauses_json"] == [item]
|
||||
diagnostic = result["summary_json"]["comparison_quality"]["visual_ocr_rechecks"]
|
||||
assert diagnostic["checked"] == 0
|
||||
|
||||
|
||||
def test_page_location_failure_keeps_difference_without_running_ocr(monkeypatch):
|
||||
"""任一侧页码定位失败时保留差异并给出 page_not_located 诊断。"""
|
||||
profiles = iter([
|
||||
{"page_count": 3, "native_text_pages": 3},
|
||||
{"page_count": 3, "native_text_pages": 0},
|
||||
])
|
||||
monkeypatch.setattr(visual_ocr_validation, "_pdf_text_profile", lambda _data: next(profiles))
|
||||
monkeypatch.setattr(visual_ocr_validation, "_locate_page", lambda **_kwargs: None)
|
||||
monkeypatch.setattr(
|
||||
visual_ocr_validation,
|
||||
"_ocr_pdf_pages",
|
||||
lambda *_args, **_kwargs: (_ for _ in ()).throw(AssertionError("OCR must not run")),
|
||||
)
|
||||
result = visual_ocr_validation.suppress_mixed_extraction_ocr_noise(
|
||||
_compare_result(_location_modify()),
|
||||
review_no="CR-TEST",
|
||||
original_filename="original.pdf",
|
||||
original_pdf_bytes=b"original",
|
||||
original_extraction_meta={"mode": "mineru"},
|
||||
original_ocr_layout={},
|
||||
returned_filename="returned.pdf",
|
||||
returned_pdf_bytes=b"returned",
|
||||
returned_extraction_meta={"mode": "edkb_system"},
|
||||
returned_ocr_layout={},
|
||||
)
|
||||
|
||||
assert len(result["clauses_json"]) == 1
|
||||
diagnostic = result["summary_json"]["comparison_quality"]["visual_ocr_rechecks"]
|
||||
assert diagnostic["kept"] == 1
|
||||
assert diagnostic["items"][0]["reason"] == "page_not_located"
|
||||
|
||||
|
||||
def test_same_visual_equipment_table_removes_modify_and_empty_insert(monkeypatch):
|
||||
"""双方视觉设备表一致时,型号漏列修改及同表空新增项应一起移除。"""
|
||||
result = _run_equipment(
|
||||
monkeypatch,
|
||||
original_lines=_equipment_page_lines(),
|
||||
returned_lines=_equipment_page_lines(),
|
||||
)
|
||||
result = analyze.rebuild_result(result)
|
||||
|
||||
assert result["clauses_json"] == [] # 关键断言:表格线性化产生的两个伪差异同时消失。
|
||||
assert result["summary_json"]["total_changes"] == 0
|
||||
diagnostic = result["summary_json"]["comparison_quality"]["visual_ocr_rechecks"]
|
||||
assert diagnostic["ignored"] == 2
|
||||
assert diagnostic["kept"] == 0
|
||||
assert diagnostic["items"][0]["validation_type"] == "equipment_table"
|
||||
assert diagnostic["items"][0]["reason"] == "same_visual_equipment_table"
|
||||
|
||||
|
||||
def test_visual_equipment_table_keeps_real_model_change(monkeypatch):
|
||||
"""型号真实变化会使设备表键不同,修改和新增项均保留。"""
|
||||
result = _run_equipment(
|
||||
monkeypatch,
|
||||
original_lines=_equipment_page_lines(model="BC-MD601"),
|
||||
returned_lines=_equipment_page_lines(model="BC-MD602"),
|
||||
)
|
||||
|
||||
assert len(result["clauses_json"]) == 2
|
||||
diagnostic = result["summary_json"]["comparison_quality"]["visual_ocr_rechecks"]
|
||||
assert diagnostic["ignored"] == 0
|
||||
assert diagnostic["items"][0]["reason"] == "visual_table_differs"
|
||||
|
||||
|
||||
def test_visual_equipment_table_keeps_real_quantity_change(monkeypatch):
|
||||
"""数量真实变化不得被空品牌列容错吞掉。"""
|
||||
result = _run_equipment(
|
||||
monkeypatch,
|
||||
original_lines=_equipment_page_lines(quantity="2"),
|
||||
returned_lines=_equipment_page_lines(quantity="3"),
|
||||
)
|
||||
|
||||
assert len(result["clauses_json"]) == 2
|
||||
diagnostic = result["summary_json"]["comparison_quality"]["visual_ocr_rechecks"]
|
||||
assert diagnostic["items"][0]["reason"] == "visual_table_differs"
|
||||
@@ -8,6 +8,7 @@ tests/test_admin_create_user_casdoor.py
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.auth.jwt import issue_local_access_token
|
||||
from app.models import User
|
||||
from app.api import user as user_api
|
||||
from app.services.auth import casdoor_service
|
||||
@@ -24,6 +25,21 @@ NEW_USER_PAYLOAD = {
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def admin_headers(app):
|
||||
"""为 Casdoor 用户同步接口生成真实 HXOPS 管理员 JWT,避免依赖旧认证请求头。"""
|
||||
app.config['SECRET_KEY'] = 'test-casdoor-sync-secret-at-least-32-bytes'
|
||||
admin = User(username='casdoor-sync-admin', email='casdoor-sync-admin@example.com', role='admin', status='active')
|
||||
admin.set_password('test-admin-password')
|
||||
db.session.add(admin)
|
||||
db.session.commit()
|
||||
token = issue_local_access_token(admin)
|
||||
return {
|
||||
'Authorization': f'Bearer {token}',
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
|
||||
|
||||
def test_admin_create_user_syncs_casdoor(client, admin_headers, monkeypatch):
|
||||
"""
|
||||
Casdoor 已配置时,管理端创建用户应调用 add-user 且本地库成功入库。
|
||||
@@ -51,6 +67,7 @@ def test_admin_create_user_syncs_casdoor(client, admin_headers, monkeypatch):
|
||||
assert casdoor_calls['payload']['email'] == 'casdoor_new@example.com'
|
||||
assert casdoor_calls['payload']['displayName'] == 'Casdoor User'
|
||||
assert casdoor_calls['payload']['phone'] == '13800000099'
|
||||
assert casdoor_calls['payload']['properties'] == {'employee_id': 'EMP-CAS-001'}
|
||||
assert casdoor_calls['payload']['isForbidden'] is False
|
||||
|
||||
user = db.session.query(User).filter_by(username='casdoor_new').first()
|
||||
@@ -240,13 +257,14 @@ def test_admin_update_user_provisions_missing_casdoor_user_with_password(client,
|
||||
client.application.config['CASDOOR_CLIENT_SECRET'] = 'client-secret'
|
||||
client.application.config['CASDOOR_ORGANIZATION'] = 'organization_HX'
|
||||
|
||||
casdoor_calls = {'update_user': 0, 'add_user': 0, 'set_password': 0}
|
||||
casdoor_calls = {'update_user': 0, 'add_user': 0, 'set_password': 0, 'add_payload': None}
|
||||
|
||||
def fake_update_user(_payload):
|
||||
casdoor_calls['update_user'] += 1
|
||||
|
||||
def fake_add_user(_payload):
|
||||
def fake_add_user(payload):
|
||||
casdoor_calls['add_user'] += 1
|
||||
casdoor_calls['add_payload'] = payload
|
||||
|
||||
def fake_set_password(_owner, _name, _old, _new):
|
||||
casdoor_calls['set_password'] += 1
|
||||
@@ -262,7 +280,10 @@ def test_admin_update_user_provisions_missing_casdoor_user_with_password(client,
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert res.status_code == 200
|
||||
assert casdoor_calls == {'update_user': 0, 'add_user': 1, 'set_password': 1}
|
||||
assert casdoor_calls['update_user'] == 0
|
||||
assert casdoor_calls['add_user'] == 1
|
||||
assert casdoor_calls['set_password'] == 1
|
||||
assert casdoor_calls['add_payload']['properties'] == {'employee_id': user.employee_id}
|
||||
|
||||
db.session.refresh(user)
|
||||
assert user.real_name == 'Legacy Updated'
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
"""
|
||||
backend/tests/test_auth_common.py
|
||||
|
||||
用途:验证可复制认证公共模块的身份、配置、Casdoor HTTP 请求和错误安全边界。
|
||||
依赖:pytest、Flask 测试应用、公共 auth common/casdoor 模块。
|
||||
逻辑:不访问 HXOPS User 表,确保公共目录可以脱离业务模型独立工作。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import AppError
|
||||
from app.services.auth.casdoor.client import CasdoorClient, get_casdoor_client
|
||||
from app.services.auth.casdoor.config import CasdoorConfig, casdoor_config_from_flask
|
||||
from app.services.auth.casdoor.errors import raise_auth_error
|
||||
from app.services.auth.casdoor.identity import identity_from_claims
|
||||
from app.services.auth.common import AuthIdentity, IdentityValidationError, identity_key
|
||||
|
||||
|
||||
class FakeResponse:
|
||||
"""提供 CasdoorClient 单测所需的最小 requests.Response 行为。"""
|
||||
|
||||
def __init__(self, data, *, ok=True, status_code=200):
|
||||
self._data = data
|
||||
self.ok = ok
|
||||
self.status_code = status_code
|
||||
|
||||
def json(self):
|
||||
"""返回构造时注入的 JSON 数据。"""
|
||||
return self._data
|
||||
|
||||
def raise_for_status(self):
|
||||
"""模拟 discovery 请求的 HTTP 状态检查。"""
|
||||
if not self.ok:
|
||||
raise RuntimeError(f'HTTP {self.status_code}')
|
||||
|
||||
|
||||
class FakeHttp:
|
||||
"""记录 CasdoorClient 请求,避免单测访问真实 Casdoor。"""
|
||||
|
||||
def __init__(self):
|
||||
self.posts = []
|
||||
self.gets = []
|
||||
|
||||
def get(self, url, **kwargs):
|
||||
"""按 URL 返回 discovery 或 userinfo 测试响应。"""
|
||||
self.gets.append((url, kwargs))
|
||||
if url.endswith('/.well-known/openid-configuration'):
|
||||
return FakeResponse({
|
||||
'token_endpoint': 'https://casdoor.test/token',
|
||||
'userinfo_endpoint': 'https://casdoor.test/userinfo',
|
||||
})
|
||||
return FakeResponse({
|
||||
'iss': 'https://casdoor.test',
|
||||
'sub': 'subject-1',
|
||||
'preferred_username': 'alice',
|
||||
})
|
||||
|
||||
def post(self, url, **kwargs):
|
||||
"""记录 token 请求并返回固定 token 集合。"""
|
||||
self.posts.append((url, kwargs))
|
||||
return FakeResponse({
|
||||
'access_token': 'casdoor-access',
|
||||
'refresh_token': 'casdoor-refresh',
|
||||
'token_type': 'Bearer',
|
||||
'expires_in': 3600,
|
||||
})
|
||||
|
||||
|
||||
def test_identity_key_requires_stable_identity():
|
||||
"""公共身份必须使用 issuer + subject 作为稳定键,不能接受缺失 subject 的资料。"""
|
||||
identity = AuthIdentity(issuer='https://casdoor.test', subject='subject-1', username='alice')
|
||||
assert identity_key(identity) == ('https://casdoor.test', 'subject-1')
|
||||
with pytest.raises(IdentityValidationError):
|
||||
identity_key(AuthIdentity(issuer='https://casdoor.test', subject='', username='alice'))
|
||||
|
||||
|
||||
def test_identity_from_claims_validates_issuer_and_normalizes_fields():
|
||||
"""Casdoor claims 转换后保留稳定身份和可变资料,并拒绝错误 issuer。"""
|
||||
identity = identity_from_claims({
|
||||
'iss': 'https://casdoor.test/',
|
||||
'sub': 'subject-1',
|
||||
'preferred_username': 'alice',
|
||||
'employeeId': 'E1001',
|
||||
'displayName': 'Alice Zhang',
|
||||
'email': 'alice@example.com',
|
||||
'affiliation': 'IT',
|
||||
}, expected_issuer='https://casdoor.test')
|
||||
assert identity.username == 'alice'
|
||||
assert identity.display_name == 'Alice Zhang'
|
||||
assert identity.employee_id == 'E1001'
|
||||
assert identity.department == 'IT'
|
||||
with pytest.raises(IdentityValidationError):
|
||||
identity_from_claims({
|
||||
'iss': 'https://evil.test',
|
||||
'sub': 'subject-1',
|
||||
'preferred_username': 'alice',
|
||||
}, expected_issuer='https://casdoor.test')
|
||||
|
||||
|
||||
def test_identity_from_claims_uses_configured_issuer_when_userinfo_omits_iss():
|
||||
"""Casdoor userinfo 可省略 iss,但服务端可信 issuer 仍必须来自 discovery 对齐配置。"""
|
||||
identity = identity_from_claims({
|
||||
'sub': 'subject-1',
|
||||
'preferred_username': 'alice',
|
||||
}, expected_issuer='https://casdoor.test')
|
||||
assert identity.issuer == 'https://casdoor.test'
|
||||
assert identity.subject == 'subject-1'
|
||||
|
||||
|
||||
def test_identity_from_claims_reads_employee_id_from_casdoor_properties():
|
||||
"""Casdoor 将自定义工号放在 properties 时,公共解析器仍输出 employee_id。"""
|
||||
identity = identity_from_claims({
|
||||
'sub': 'subject-1',
|
||||
'preferred_username': '26040006',
|
||||
'properties': {'employee_id': '26040006'},
|
||||
}, expected_issuer='https://casdoor.test')
|
||||
assert identity.employee_id == '26040006'
|
||||
|
||||
|
||||
def test_casdoor_config_repr_does_not_expose_secret(app):
|
||||
"""配置对象可诊断但不得在 repr 中泄漏 Casdoor client_secret。"""
|
||||
app.config.update(
|
||||
CASDOOR_BASE_URL='https://casdoor.test/',
|
||||
CASDOOR_CLIENT_ID='peer-client',
|
||||
CASDOOR_CLIENT_SECRET='top-secret-value',
|
||||
AUTH_JWT_ISSUER='https://casdoor.test',
|
||||
CASDOOR_SCOPE='openid profile email',
|
||||
CASDOOR_HTTP_TIMEOUT_SECONDS=9,
|
||||
)
|
||||
config = casdoor_config_from_flask()
|
||||
assert config.base_url == 'https://casdoor.test'
|
||||
assert config.timeout_seconds == 9
|
||||
assert 'top-secret-value' not in repr(config)
|
||||
|
||||
|
||||
def test_casdoor_password_client_request_is_framework_independent():
|
||||
"""公共客户端按配置发送 password grant,不依赖 HXOPS User 或数据库。"""
|
||||
http = FakeHttp()
|
||||
client = CasdoorClient(CasdoorConfig(
|
||||
base_url='https://casdoor.test',
|
||||
client_id='peer-client',
|
||||
client_secret='peer-secret',
|
||||
issuer='https://casdoor.test',
|
||||
timeout_seconds=7,
|
||||
), http_session=http)
|
||||
result = client.password_login('alice', 'user-password')
|
||||
assert result.access_token == 'casdoor-access'
|
||||
_, request = http.posts[0]
|
||||
assert request['data']['grant_type'] == 'password'
|
||||
assert request['data']['client_id'] == 'peer-client'
|
||||
assert request['data']['password'] == 'user-password'
|
||||
assert request['timeout'] == 7
|
||||
|
||||
|
||||
def test_flask_casdoor_client_is_reused_until_config_changes(app):
|
||||
"""Flask 适配器复用 discovery 缓存,并在服务配置变化后创建新客户端。"""
|
||||
app.config.update(
|
||||
CASDOOR_BASE_URL='https://casdoor.test',
|
||||
CASDOOR_CLIENT_ID='peer-client-cache',
|
||||
CASDOOR_CLIENT_SECRET='peer-secret-cache',
|
||||
AUTH_JWT_ISSUER='https://casdoor.test',
|
||||
CASDOOR_HTTP_TIMEOUT_SECONDS=8,
|
||||
)
|
||||
first = get_casdoor_client()
|
||||
second = get_casdoor_client()
|
||||
assert first is second
|
||||
|
||||
app.config['CASDOOR_CLIENT_ID'] = 'peer-client-changed'
|
||||
third = get_casdoor_client()
|
||||
assert third is not first
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
('source', 'context', 'code', 'status'),
|
||||
[
|
||||
({'error': 'invalid_grant'}, 'password', 'CASDOOR_INVALID_CREDENTIALS', 401),
|
||||
({'error': 'invalid_client'}, 'password', 'CASDOOR_CONFIG_ERROR', 503),
|
||||
({'error': 'access_denied'}, 'code', 'CASDOOR_ACCESS_DENIED', 403),
|
||||
({'error': 'unsupported_grant_type'}, 'refresh', 'AUTH.CASDOOR_REFRESH_UNSUPPORTED', 400),
|
||||
],
|
||||
)
|
||||
def test_casdoor_error_mapping_is_stable(app, source, context, code, status):
|
||||
"""公共错误映射保持现有 HXOPS 业务码,供平级服务复制后统一处理。"""
|
||||
with pytest.raises(AppError) as captured:
|
||||
raise_auth_error(source, context=context)
|
||||
assert captured.value.code == code
|
||||
assert captured.value.http_status == status
|
||||
@@ -0,0 +1,176 @@
|
||||
"""
|
||||
backend/tests/test_casdoor_api_session.py
|
||||
|
||||
用途:验证 Casdoor 认证成功后返回 HXOPS 本地 API 会话 JWT,并保留稳定 Casdoor 身份引用。
|
||||
依赖:Flask 测试客户端、User 模型、user API 的 Casdoor 调用替身。
|
||||
逻辑:模拟 password grant/userinfo,随后使用返回 token 访问受保护 API,防止登录后首个请求立即 401。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import jwt
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.api import user as user_api
|
||||
from app.core.errors import AppError
|
||||
from app.models import User
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def casdoor_user(app):
|
||||
"""创建能被 Casdoor userinfo 映射的 active HXOPS 用户。"""
|
||||
user = User(
|
||||
username='casdoor-session',
|
||||
employee_id='casdoor-session',
|
||||
email='casdoor-session@example.com',
|
||||
role='user',
|
||||
status='active',
|
||||
)
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
return user
|
||||
|
||||
|
||||
def test_password_login_returns_hxops_api_session(client, app, casdoor_user, monkeypatch):
|
||||
"""密码由 Casdoor 校验,但浏览器使用 HXOPS 签名 JWT 调用本站 API。"""
|
||||
app.config.update(
|
||||
AUTH_LOGIN_MODE='casdoor',
|
||||
AUTH_JWT_ISSUER='https://casdoor.example.com',
|
||||
AUTH_LOCAL_JWT_ISSUER='hxops-backend',
|
||||
AUTH_LOCAL_JWT_AUDIENCE='hxops-frontend',
|
||||
AUTH_ALLOW_LOCAL_JWT=True,
|
||||
SECRET_KEY='test-session-secret',
|
||||
)
|
||||
monkeypatch.setattr(user_api, '_casdoor_password_login', lambda username, password: {
|
||||
'access_token': 'opaque-casdoor-access-token',
|
||||
'refresh_token': 'casdoor-refresh-token',
|
||||
'expires_in': 3600,
|
||||
})
|
||||
monkeypatch.setattr(user_api, '_casdoor_userinfo', lambda token: {
|
||||
'iss': 'https://casdoor.example.com',
|
||||
'sub': 'casdoor-subject-session',
|
||||
'employee_id': casdoor_user.employee_id,
|
||||
'preferred_username': casdoor_user.username,
|
||||
'email': casdoor_user.email,
|
||||
})
|
||||
|
||||
login = client.post('/api/user/casdoor/password-login', json={
|
||||
'username': casdoor_user.username,
|
||||
'password': 'correct-password',
|
||||
})
|
||||
assert login.status_code == 200
|
||||
body = login.get_json()
|
||||
data = body.get('data') if body.get('success') is True else body
|
||||
api_token = data['access_token']
|
||||
assert api_token != 'opaque-casdoor-access-token'
|
||||
|
||||
claims = jwt.decode(
|
||||
api_token,
|
||||
app.config['SECRET_KEY'],
|
||||
algorithms=['HS256'],
|
||||
issuer='hxops-backend',
|
||||
audience='hxops-frontend',
|
||||
)
|
||||
assert claims['casdoor_iss'] == 'https://casdoor.example.com'
|
||||
assert claims['casdoor_sub'] == 'casdoor-subject-session'
|
||||
|
||||
home = client.get('/api/user/home', headers={'Authorization': f'Bearer {api_token}'})
|
||||
assert home.status_code == 200
|
||||
|
||||
|
||||
def test_authorization_code_login_returns_hxops_api_session(client, app, casdoor_user, monkeypatch):
|
||||
"""授权码回调复用统一登录编排,并签发可访问 HXOPS API 的本地 JWT。"""
|
||||
app.config.update(
|
||||
AUTH_JWT_ISSUER='https://casdoor.example.com',
|
||||
AUTH_LOCAL_JWT_ISSUER='hxops-backend',
|
||||
AUTH_LOCAL_JWT_AUDIENCE='hxops-frontend',
|
||||
AUTH_ALLOW_LOCAL_JWT=True,
|
||||
SECRET_KEY='test-code-session-secret-at-least-32-bytes',
|
||||
)
|
||||
monkeypatch.setattr(user_api, '_casdoor_exchange_code', lambda code, redirect_uri: {
|
||||
'access_token': 'code-opaque-casdoor-access-token',
|
||||
'refresh_token': 'code-casdoor-refresh-token',
|
||||
'expires_in': 3600,
|
||||
})
|
||||
monkeypatch.setattr(user_api, '_casdoor_userinfo', lambda token: {
|
||||
'iss': 'https://casdoor.example.com',
|
||||
'sub': 'casdoor-subject-code-session',
|
||||
'employee_id': casdoor_user.employee_id,
|
||||
'preferred_username': casdoor_user.username,
|
||||
'email': casdoor_user.email,
|
||||
})
|
||||
with app.app_context():
|
||||
state = user_api._issue_casdoor_state('https://hxops.example.com/auth/callback')
|
||||
|
||||
login = client.post('/api/user/casdoor/login', json={
|
||||
'code': 'authorization-code',
|
||||
'state': state,
|
||||
})
|
||||
assert login.status_code == 200
|
||||
body = login.get_json()
|
||||
data = body.get('data') if body.get('success') is True else body
|
||||
assert data['refresh_token'] == 'code-casdoor-refresh-token'
|
||||
|
||||
claims = jwt.decode(
|
||||
data['access_token'],
|
||||
app.config['SECRET_KEY'],
|
||||
algorithms=['HS256'],
|
||||
issuer='hxops-backend',
|
||||
audience='hxops-frontend',
|
||||
)
|
||||
assert claims['casdoor_sub'] == 'casdoor-subject-code-session'
|
||||
|
||||
home = client.get('/api/user/home', headers={'Authorization': f"Bearer {data['access_token']}"})
|
||||
assert home.status_code == 200
|
||||
|
||||
|
||||
def test_refresh_returns_new_hxops_api_session(client, app, casdoor_user, monkeypatch):
|
||||
"""Casdoor refresh 成功后重新映射用户并签发新的 HXOPS API 会话。"""
|
||||
app.config.update(
|
||||
AUTH_JWT_ISSUER='https://casdoor.example.com',
|
||||
AUTH_LOCAL_JWT_ISSUER='hxops-backend',
|
||||
AUTH_LOCAL_JWT_AUDIENCE='hxops-frontend',
|
||||
AUTH_ALLOW_LOCAL_JWT=True,
|
||||
SECRET_KEY='test-session-secret-at-least-32-bytes',
|
||||
)
|
||||
monkeypatch.setattr(user_api, '_casdoor_refresh_token', lambda refresh_token: {
|
||||
'access_token': 'next-opaque-casdoor-access-token',
|
||||
'refresh_token': 'next-casdoor-refresh-token',
|
||||
'expires_in': 3600,
|
||||
})
|
||||
monkeypatch.setattr(user_api, '_casdoor_userinfo', lambda token: {
|
||||
'iss': 'https://casdoor.example.com',
|
||||
'sub': 'casdoor-subject-session',
|
||||
'employee_id': casdoor_user.employee_id,
|
||||
'preferred_username': casdoor_user.username,
|
||||
'email': casdoor_user.email,
|
||||
})
|
||||
|
||||
refreshed = client.post('/api/user/casdoor/refresh', json={
|
||||
'refresh_token': 'old-casdoor-refresh-token',
|
||||
})
|
||||
assert refreshed.status_code == 200
|
||||
body = refreshed.get_json()
|
||||
data = body.get('data') if body.get('success') is True else body
|
||||
api_token = data['access_token']
|
||||
assert api_token != 'next-opaque-casdoor-access-token'
|
||||
assert data['refresh_token'] == 'next-casdoor-refresh-token'
|
||||
|
||||
home = client.get('/api/user/home', headers={'Authorization': f'Bearer {api_token}'})
|
||||
assert home.status_code == 200
|
||||
|
||||
|
||||
def test_refresh_preserves_structured_casdoor_error(client, monkeypatch):
|
||||
"""刷新 grant 的稳定 AppError 应原样返回,不能被路由兜底包装成通用 401。"""
|
||||
def unsupported_refresh(_refresh_token):
|
||||
raise AppError(
|
||||
code='AUTH.CASDOOR_REFRESH_UNSUPPORTED',
|
||||
message='Casdoor refresh token is not supported by current application config',
|
||||
http_status=400,
|
||||
)
|
||||
|
||||
monkeypatch.setattr(user_api, '_casdoor_refresh_token', unsupported_refresh)
|
||||
response = client.post('/api/user/casdoor/refresh', json={'refresh_token': 'unsupported-token'})
|
||||
assert response.status_code == 400
|
||||
assert response.get_json()['error']['code'] == 'AUTH.CASDOOR_REFRESH_UNSUPPORTED'
|
||||
@@ -1,6 +1,17 @@
|
||||
"""Casdoor authorize URL: provider_hint and WeCom defaults."""
|
||||
"""
|
||||
backend/tests/test_casdoor_authorize_url.py
|
||||
|
||||
用途:验证 Casdoor 授权地址的 provider、静默登录、编码和配置失败契约。
|
||||
依赖:user API 兼容代理、HXOPS Casdoor 授权地址服务。
|
||||
逻辑:路由测试保留历史 monkeypatch 入口,服务测试锁定可复制的授权地址组装规则。
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
from app.api import user as user_api
|
||||
from app.core.errors import AppError
|
||||
from app.services.auth.hxops.casdoor_authorize import CasdoorAuthorizeOptions, build_casdoor_authorize_payload
|
||||
from app.services.auth.hxops.casdoor_route_adapter import build_authorize_payload, create_login_service
|
||||
|
||||
|
||||
def test_casdoor_authorize_url_wecom_defaults(client, app, monkeypatch):
|
||||
@@ -61,3 +72,106 @@ def test_casdoor_authorize_url_explicit_provider_hint(client, app, monkeypatch):
|
||||
url = res.get_json()['url']
|
||||
assert 'provider_hint=from_query' in url
|
||||
assert 'silentSignin' not in url
|
||||
|
||||
|
||||
def test_authorize_service_encodes_values_and_honors_explicit_silent_signin(app):
|
||||
"""授权地址必须编码 redirect/scope/provider/state,且 query 显式静默开关优先于默认 provider。"""
|
||||
app.config.update(
|
||||
CASDOOR_CLIENT_ID='client id',
|
||||
CASDOOR_REDIRECT_URI='https://fallback.example.com/callback',
|
||||
CASDOOR_SCOPE='openid profile email',
|
||||
CASDOOR_WECOM_SILENT_SIGNIN=False,
|
||||
)
|
||||
payload = build_casdoor_authorize_payload(
|
||||
CasdoorAuthorizeOptions(
|
||||
redirect_uri='https://hxops.example.com/callback?source=admin panel',
|
||||
provider_hint='wecom provider',
|
||||
silent_signin='yes',
|
||||
),
|
||||
oidc_metadata=lambda: {'authorization_endpoint': 'https://casdoor.example.com/authorize'},
|
||||
issue_state=lambda redirect_uri: f'state for {redirect_uri}',
|
||||
)
|
||||
|
||||
assert payload['redirect_uri'] == 'https://hxops.example.com/callback?source=admin panel'
|
||||
assert 'client_id=client%20id' in payload['url']
|
||||
assert 'redirect_uri=https%3A%2F%2Fhxops.example.com%2Fcallback%3Fsource%3Dadmin%20panel' in payload['url']
|
||||
assert 'provider_hint=wecom%20provider' in payload['url']
|
||||
assert 'state=state%20for%20https%3A%2F%2Fhxops.example.com%2Fcallback%3Fsource%3Dadmin%20panel' in payload['url']
|
||||
assert payload['url'].endswith('&silentSignin=1')
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
('metadata', 'client_id', 'redirect_uri', 'message'),
|
||||
[
|
||||
({}, 'client', 'https://hxops.example.com/callback', 'Casdoor authorization endpoint missing'),
|
||||
({'authorization_endpoint': 'https://casdoor.example.com/authorize'}, '', 'https://hxops.example.com/callback', 'Casdoor client config is incomplete'),
|
||||
({'authorization_endpoint': 'https://casdoor.example.com/authorize'}, 'client', '', 'Casdoor client config is incomplete'),
|
||||
],
|
||||
)
|
||||
def test_authorize_service_rejects_missing_required_config(app, metadata, client_id, redirect_uri, message):
|
||||
"""缺少 discovery endpoint、client_id 或 callback 时维持既有稳定 AppError。"""
|
||||
app.config.update(CASDOOR_CLIENT_ID=client_id, CASDOOR_REDIRECT_URI=redirect_uri)
|
||||
|
||||
with pytest.raises(AppError) as captured:
|
||||
build_casdoor_authorize_payload(
|
||||
CasdoorAuthorizeOptions(),
|
||||
oidc_metadata=lambda: metadata,
|
||||
issue_state=lambda _: 'state',
|
||||
)
|
||||
|
||||
assert captured.value.code == 'SYSTEM.INTERNAL_ERROR'
|
||||
assert captured.value.message == message
|
||||
|
||||
|
||||
def test_route_adapter_passes_compatibility_operations_to_authorize_service(app):
|
||||
"""路由适配器必须透传路由层的 discovery/state 替身,避免改变历史 monkeypatch 契约。"""
|
||||
app.config.update(
|
||||
CASDOOR_CLIENT_ID='client',
|
||||
CASDOOR_REDIRECT_URI='https://hxops.example.com/callback',
|
||||
)
|
||||
seen = {}
|
||||
|
||||
def metadata():
|
||||
"""提供可断言的 discovery 数据,验证适配器没有绕过注入操作。"""
|
||||
seen['metadata'] = True
|
||||
return {'authorization_endpoint': 'https://casdoor.example.com/authorize'}
|
||||
|
||||
def issue_state(redirect_uri):
|
||||
"""记录 state 绑定的回调地址,并返回固定 state。"""
|
||||
seen['redirect_uri'] = redirect_uri
|
||||
return 'compatibility-state'
|
||||
|
||||
payload = build_authorize_payload(
|
||||
CasdoorAuthorizeOptions(),
|
||||
oidc_metadata=metadata,
|
||||
issue_state=issue_state,
|
||||
)
|
||||
|
||||
assert seen == {
|
||||
'metadata': True,
|
||||
'redirect_uri': 'https://hxops.example.com/callback',
|
||||
}
|
||||
assert 'state=compatibility-state' in payload['url']
|
||||
|
||||
|
||||
def test_route_adapter_injects_legacy_login_operations():
|
||||
"""登录服务工厂必须采用传入操作,确保路由迁移期间旧替身点仍然有效。"""
|
||||
password_operation = lambda username, password: {}
|
||||
code_operation = lambda code, redirect_uri: {}
|
||||
refresh_operation = lambda refresh_token: {}
|
||||
userinfo_operation = lambda access_token: {}
|
||||
audit_operation = lambda *args, **kwargs: None
|
||||
|
||||
service = create_login_service(
|
||||
write_login_audit=audit_operation,
|
||||
password_operation=password_operation,
|
||||
code_operation=code_operation,
|
||||
refresh_operation=refresh_operation,
|
||||
userinfo_operation=userinfo_operation,
|
||||
)
|
||||
|
||||
assert service._password_login is password_operation
|
||||
assert service._authorization_code_login is code_operation
|
||||
assert service._refresh_token is refresh_operation
|
||||
assert service._userinfo is userinfo_operation
|
||||
assert service._write_login_audit is audit_operation
|
||||
@@ -0,0 +1,53 @@
|
||||
"""
|
||||
backend/tests/test_casdoor_state.py
|
||||
|
||||
用途:验证 Casdoor 授权码回调 state 的格式兼容、签名完整性和有效期边界。
|
||||
依赖:HXOPS Casdoor state 服务;不访问 Flask 路由、数据库或 Casdoor。
|
||||
逻辑:固定密钥和时钟验证 state 可跨实例校验,篡改或过期必须安全失败。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.auth.hxops.casdoor_state import consume_casdoor_state, issue_casdoor_state
|
||||
|
||||
|
||||
def test_casdoor_state_preserves_existing_wire_format_and_redirect_uri():
|
||||
"""新服务签发的 state 保持 v1 前缀,且在同一密钥下可恢复原 redirect_uri。"""
|
||||
state = issue_casdoor_state(
|
||||
'https://hxops.example.com/auth/callback',
|
||||
secret='state-test-secret',
|
||||
now_timestamp=1_700_000_000,
|
||||
nonce_factory=lambda: 'fixed-nonce',
|
||||
)
|
||||
|
||||
assert state.startswith('hxops_casdoor_v1.')
|
||||
assert consume_casdoor_state(
|
||||
state,
|
||||
secret='state-test-secret',
|
||||
now_timestamp=1_700_000_001,
|
||||
) == 'https://hxops.example.com/auth/callback'
|
||||
|
||||
|
||||
def test_casdoor_state_rejects_tampered_signature():
|
||||
"""攻击者篡改 payload 或签名后,服务必须拒绝恢复 callback 地址。"""
|
||||
state = issue_casdoor_state(
|
||||
'https://hxops.example.com/auth/callback',
|
||||
secret='state-test-secret',
|
||||
now_timestamp=1_700_000_000,
|
||||
)
|
||||
prefix, payload, signature = state.split('.')
|
||||
tampered = f'{prefix}.{payload}.{signature[:-1]}x'
|
||||
|
||||
assert consume_casdoor_state(tampered, secret='state-test-secret', now_timestamp=1_700_000_001) is None
|
||||
|
||||
|
||||
def test_casdoor_state_rejects_expired_or_wrong_secret():
|
||||
"""过期 state 或不同实例密钥均不得通过,保持 callback 的 CSRF 防护。"""
|
||||
state = issue_casdoor_state(
|
||||
'https://hxops.example.com/auth/callback',
|
||||
secret='state-test-secret',
|
||||
now_timestamp=1_700_000_000,
|
||||
)
|
||||
|
||||
assert consume_casdoor_state(state, secret='wrong-secret', now_timestamp=1_700_000_001) is None
|
||||
assert consume_casdoor_state(state, secret='state-test-secret', now_timestamp=1_700_000_600) is None
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Tests for Dify sync process_rule selection (Excel custom vs default automatic)."""
|
||||
"""Tests for Dify sync process_rule selection (all document types preserve complete semantic blocks)."""
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.knowledge_cleaning import dify_sync_service as dify_sync_module
|
||||
@@ -10,14 +10,14 @@ def _make_service(monkeypatch, **overrides):
|
||||
'DIFY_API_KEY': 'dataset-test-key',
|
||||
'KB_DIFY_PERMISSION': 'only_me',
|
||||
'KB_DIFY_INDEXING_TECHNIQUE': 'high_quality',
|
||||
'KB_DIFY_SEARCH_METHOD': 'semantic_search',
|
||||
'KB_DIFY_SEARCH_METHOD': 'hybrid_search',
|
||||
'KB_DIFY_DOC_FORM': 'text_model',
|
||||
'KB_DIFY_PROCESS_MODE': 'automatic',
|
||||
'KB_DIFY_PROCESS_MODE': 'custom',
|
||||
'KB_DIFY_PROCESS_MODE_EXCEL': 'custom',
|
||||
'KB_DIFY_SEGMENT_SEPARATOR': '\\n\\n',
|
||||
'KB_DIFY_SEGMENT_SEPARATOR_EXCEL': '\\n\\n',
|
||||
'KB_DIFY_SEGMENT_MAX_TOKENS': '800',
|
||||
'KB_DIFY_SEGMENT_CHUNK_OVERLAP': '50',
|
||||
'KB_DIFY_SEGMENT_MAX_TOKENS': '600',
|
||||
'KB_DIFY_SEGMENT_CHUNK_OVERLAP': '100',
|
||||
'KB_DIFY_REMOVE_URLS': 'false',
|
||||
}
|
||||
settings.update(overrides)
|
||||
@@ -31,15 +31,18 @@ def test_build_process_rule_xlsx_uses_custom_segmentation(monkeypatch):
|
||||
|
||||
assert rule['mode'] == 'custom'
|
||||
assert rule['rules']['segmentation']['separator'] == '\n\n'
|
||||
assert rule['rules']['segmentation']['max_tokens'] == 800
|
||||
assert rule['rules']['segmentation']['chunk_overlap'] == 50
|
||||
# 断言完整行仍由空行隔开,避免表格字段在 Dify 中被拆散。
|
||||
assert rule['rules']['segmentation']['max_tokens'] == 600
|
||||
assert rule['rules']['segmentation']['chunk_overlap'] == 100
|
||||
assert rule['rules']['pre_processing_rules'][1]['enabled'] is False
|
||||
|
||||
|
||||
def test_build_process_rule_docx_defaults_to_automatic(monkeypatch):
|
||||
def test_build_process_rule_docx_uses_custom_semantic_blocks(monkeypatch):
|
||||
service = _make_service(monkeypatch)
|
||||
rule = service._build_process_rule('docx')
|
||||
assert rule == {'mode': 'automatic'}
|
||||
# 断言制度类文档的标题、规则、例外条件保留在同一个检索片段中。
|
||||
assert rule['mode'] == 'custom'
|
||||
assert rule['rules']['segmentation']['separator'] == '\n\n'
|
||||
|
||||
|
||||
def test_create_document_by_text_xlsx_posts_custom_process_rule(monkeypatch):
|
||||
@@ -65,7 +68,7 @@ def test_create_document_by_text_xlsx_posts_custom_process_rule(monkeypatch):
|
||||
process_rule = captured['json']['process_rule']
|
||||
assert process_rule['mode'] == 'custom'
|
||||
assert process_rule['rules']['segmentation']['separator'] == '\n\n'
|
||||
assert process_rule['rules']['segmentation']['max_tokens'] == 800
|
||||
assert process_rule['rules']['segmentation']['max_tokens'] == 600
|
||||
|
||||
|
||||
def test_remove_urls_emails_respects_kb_dify_remove_urls_true(monkeypatch):
|
||||
@@ -78,6 +81,59 @@ def test_remove_urls_emails_respects_kb_dify_remove_urls_true(monkeypatch):
|
||||
assert remove_urls['enabled'] is True
|
||||
|
||||
|
||||
def test_wait_for_document_indexing_rejects_dify_error(monkeypatch):
|
||||
service = _make_service(monkeypatch)
|
||||
|
||||
try:
|
||||
service.wait_for_document_indexing(
|
||||
dataset_id='dataset-001',
|
||||
document_id='document-001',
|
||||
initial_payload={
|
||||
'document': {
|
||||
'id': 'document-001',
|
||||
'indexing_status': 'error',
|
||||
'error': 'embedding credential invalid',
|
||||
},
|
||||
},
|
||||
)
|
||||
except dify_sync_module.KbDifySyncError as exc:
|
||||
# 断言 Dify 的原始原因被保留,供工作台展示而不是误报同步成功。
|
||||
assert 'embedding credential invalid' in str(exc)
|
||||
else:
|
||||
raise AssertionError('Dify indexing error must fail the local sync')
|
||||
|
||||
|
||||
def test_wait_for_document_indexing_accepts_completed_status(monkeypatch):
|
||||
service = _make_service(monkeypatch)
|
||||
result = service.wait_for_document_indexing(
|
||||
dataset_id='dataset-001',
|
||||
document_id='document-001',
|
||||
initial_payload={'document': {'id': 'document-001', 'indexing_status': 'completed'}},
|
||||
)
|
||||
|
||||
# completed 是唯一可将本地同步记录写为 synced 的终态。
|
||||
assert result['indexing_status'] == 'completed'
|
||||
|
||||
|
||||
def test_remote_document_not_available_is_recreated(monkeypatch):
|
||||
"""400 invalid_param 的不可用文档错误必须触发创建新远端文档的恢复流程。"""
|
||||
error = (
|
||||
'Dify API POST /datasets/dataset-001/documents/document-001/update-by-text '
|
||||
'failed: 400 {"code":"invalid_param","message":"Document is not available","status":400}'
|
||||
)
|
||||
|
||||
# 断言该 Dify 版本特有的 400 响应不会被当成不可恢复的同步失败。
|
||||
assert dify_sync_module._is_remote_document_missing(error) is True
|
||||
|
||||
|
||||
def test_remote_document_other_invalid_parameter_is_not_treated_as_missing():
|
||||
"""非文档失效的参数错误仍应原样失败,避免错误地重复创建文档。"""
|
||||
error = 'Dify API POST /datasets/dataset-001/documents/document-001/update-by-text failed: 400 {"code":"invalid_param","message":"Invalid process rule","status":400}'
|
||||
|
||||
# 断言只有精确的“文档不可用”语义才走自动恢复分支。
|
||||
assert dify_sync_module._is_remote_document_missing(error) is False
|
||||
|
||||
|
||||
def test_resolve_source_file_ext_from_filename():
|
||||
class _Version:
|
||||
source_file_ext = None
|
||||
|
||||
@@ -78,6 +78,16 @@ def test_friendly_workflow_failure_message_rewrites_tool_error_with_current_agen
|
||||
assert message == '员工培训查询工具调用失败,请稍后重试;如持续失败请联系管理员。'
|
||||
|
||||
|
||||
def test_friendly_upstream_error_message_identifies_rerank_authorization_failure():
|
||||
"""断言:Dify 重排插件 403 应提示修复模型授权,而非误导为网络超时。"""
|
||||
message = DifyService._friendly_upstream_error_message(
|
||||
400,
|
||||
'PluginInvokeError: 403 Forbidden for url https://api.example/v1/rerank',
|
||||
agent_name='通用入口',
|
||||
)
|
||||
assert message == '通用入口的知识检索重排服务授权失败。请联系管理员在 Dify 中更新 Rerank 模型供应商的 API Key 后重新发布应用。'
|
||||
|
||||
|
||||
def test_persist_stream_chat_record_uses_workflow_finished_tokens(app):
|
||||
"""workflow_finished 首次落库应写入 data.total_tokens。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -18,6 +18,14 @@ def test_word_still_uses_word_timeout(monkeypatch):
|
||||
assert _file_timeout_sec(Path('manual.docx')) == 420
|
||||
|
||||
|
||||
def test_pdf_uses_dedicated_timeout_for_figure_rich_handbooks(monkeypatch):
|
||||
monkeypatch.setenv('EDKB_FILE_TIMEOUT_SEC', '300')
|
||||
monkeypatch.setenv('EDKB_PDF_FILE_TIMEOUT_SEC', '900')
|
||||
|
||||
# 断言大型图文手册不会被通用 300 秒时限提前终止。
|
||||
assert _file_timeout_sec(Path('mechanical-design-handbook.pdf')) == 900
|
||||
|
||||
|
||||
def test_other_formats_use_global_timeout(monkeypatch):
|
||||
monkeypatch.setenv('EDKB_FILE_TIMEOUT_SEC', '180')
|
||||
assert _file_timeout_sec(Path('slides.pptx')) == 180
|
||||
@@ -1527,7 +1527,7 @@ def test_dify_sync_repairs_sync_record_id_sequence_on_pkey_conflict(app, monkeyp
|
||||
monkeypatch.setattr(
|
||||
dify_sync_module.KbDifySyncService,
|
||||
'create_document_by_text',
|
||||
lambda self, dataset_id, name, text, **kwargs: {'document': {'id': 'remote-doc-001', 'name': name}},
|
||||
lambda self, dataset_id, name, text, **kwargs: {'document': {'id': 'remote-doc-001', 'name': name, 'indexing_status': 'completed'}},
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
|
||||
@@ -16,6 +16,13 @@ def test_supports_rejects_leave_process_questions():
|
||||
assert not HRLeaveSQLServerService.supports("年假制度是什么")
|
||||
|
||||
|
||||
def test_supports_rejects_salary_calculation_questions():
|
||||
# 断言:制度扣薪问题必须走 FAQ/Dify,不能触发 HR 假期余额查询。
|
||||
assert not HRLeaveSQLServerService.supports("请病假怎么扣钱")
|
||||
assert not HRLeaveSQLServerService.supports("请假扣多少薪资")
|
||||
assert not HRLeaveSQLServerService.supports("请假扣款计算公式")
|
||||
|
||||
|
||||
def test_supports_other_person_leave_queries_for_guardrail():
|
||||
assert HRLeaveSQLServerService.supports("张三还有多少假期")
|
||||
assert HRLeaveSQLServerService.supports("曹惠鹏还有多少假期")
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
"""
|
||||
backend/tests/test_hxops_user_resolver.py
|
||||
|
||||
用途:验证 Casdoor 身份到 HXOPS 用户的工号优先映射规则。
|
||||
依赖:Flask 测试应用、User、AuthIdentity、HXOPS 用户解析器。
|
||||
逻辑:覆盖工号优先、用户名兼容、邮箱手机号不匹配和双键冲突拒绝。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.models import User
|
||||
from app.services.auth.common import AuthIdentity
|
||||
from app.services.auth.hxops.user_resolver import HxopsIdentityMappingError, resolve_hxops_user
|
||||
|
||||
|
||||
def _identity(*, employee_id: str | None, username: str, email: str | None = None, phone_number: str | None = None) -> AuthIdentity:
|
||||
"""构造最小 Casdoor 统一身份,供映射规则测试复用。"""
|
||||
return AuthIdentity(
|
||||
issuer='https://casdoor.example.com',
|
||||
subject='casdoor-subject',
|
||||
employee_id=employee_id,
|
||||
username=username,
|
||||
email=email,
|
||||
phone_number=phone_number,
|
||||
)
|
||||
|
||||
|
||||
def _user(*, username: str, employee_id: str | None, email: str, phone_number: str | None = None) -> User:
|
||||
"""创建 active HXOPS 用户,确保每个测试自行声明本地身份资料。"""
|
||||
user = User(
|
||||
username=username,
|
||||
employee_id=employee_id,
|
||||
email=email,
|
||||
phone_number=phone_number,
|
||||
role='user',
|
||||
status='active',
|
||||
)
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
return user
|
||||
|
||||
|
||||
def test_resolver_prefers_casdoor_employee_id_over_username(app):
|
||||
"""Casdoor 同时提供工号和用户名时,优先以 employee_id 命中 HXOPS 用户。"""
|
||||
with app.app_context():
|
||||
expected = _user(username='26040006', employee_id='26040006', email='employee@example.com')
|
||||
|
||||
user = resolve_hxops_user(_identity(employee_id='26040006', username='casdoor-display-name'))
|
||||
|
||||
assert user.id == expected.id
|
||||
|
||||
|
||||
def test_resolver_uses_username_as_employee_id_compatibility(app):
|
||||
"""Casdoor 未返回 employee_id 时,当前用户名即工号可匹配本地 employee_id。"""
|
||||
with app.app_context():
|
||||
expected = _user(username='legacy-local-name', employee_id='26040008', email='compat@example.com')
|
||||
|
||||
user = resolve_hxops_user(_identity(employee_id=None, username='26040008'))
|
||||
|
||||
assert user.id == expected.id
|
||||
|
||||
|
||||
def test_resolver_does_not_match_email_or_phone(app):
|
||||
"""邮箱和手机号仅是资料字段,不能作为 Casdoor 登录身份回退键。"""
|
||||
with app.app_context():
|
||||
_user(
|
||||
username='other-employee',
|
||||
employee_id='26040009',
|
||||
email='shared@example.com',
|
||||
phone_number='13800000009',
|
||||
)
|
||||
|
||||
with pytest.raises(HxopsIdentityMappingError) as captured:
|
||||
resolve_hxops_user(_identity(
|
||||
employee_id='missing-employee',
|
||||
username='missing-username',
|
||||
email='shared@example.com',
|
||||
phone_number='13800000009',
|
||||
))
|
||||
|
||||
assert captured.value.code == 'CASDOOR_USER_NOT_FOUND'
|
||||
|
||||
|
||||
def test_resolver_rejects_conflicting_employee_id_and_username(app):
|
||||
"""工号与用户名指向不同本地用户时必须拒绝,避免把 Casdoor 身份关联到错误账号。"""
|
||||
with app.app_context():
|
||||
_user(username='26040010', employee_id='26040010', email='employee-conflict@example.com')
|
||||
_user(username='legacy-conflict', employee_id='26040011', email='username-conflict@example.com')
|
||||
|
||||
with pytest.raises(HxopsIdentityMappingError) as captured:
|
||||
resolve_hxops_user(_identity(employee_id='26040010', username='legacy-conflict'))
|
||||
|
||||
assert captured.value.code == 'CASDOOR_IDENTITY_CONFLICT'
|
||||
|
||||
|
||||
def test_resolver_rejects_disabled_employee(app):
|
||||
"""工号命中 rejected/disabled 用户时保持既有 active 状态校验。"""
|
||||
with app.app_context():
|
||||
user = _user(username='26040012', employee_id='26040012', email='disabled@example.com')
|
||||
user.status = 'rejected'
|
||||
db.session.commit()
|
||||
|
||||
with pytest.raises(HxopsIdentityMappingError) as captured:
|
||||
resolve_hxops_user(_identity(employee_id='26040012', username='26040012'))
|
||||
|
||||
assert captured.value.code == 'ACCOUNT_DISABLED'
|
||||
@@ -0,0 +1,127 @@
|
||||
"""
|
||||
backend/tests/test_integration_source_fallback.py
|
||||
|
||||
用途:验证源文件缺失时 integration 下载与序列化回退到清洗 Markdown。
|
||||
依赖:pytest、kb 模型与 integration 路由。
|
||||
逻辑:模拟磁盘无 source、有 cleaned md,断言 kind=source 仍可读且序列化返回 .md。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from app import db
|
||||
from app.models import KbDifySyncRecord, KbDocument, KbDocumentVersion, KbGroup, User
|
||||
|
||||
|
||||
def _configure(app, tmp_path: Path) -> Path:
|
||||
root = tmp_path / 'kb-storage'
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
app.config.update(
|
||||
SECRET_KEY='test-secret-key-with-sufficient-length-123456',
|
||||
KB_STORAGE_ROOT=str(root),
|
||||
WECOM_PUBLIC_BASE_URL='https://ai.example.com',
|
||||
INTEGRATION_API_KEY='test-integration-key',
|
||||
INTEGRATION_API_MODE='local',
|
||||
)
|
||||
return root
|
||||
|
||||
|
||||
def _ensure_admin() -> User:
|
||||
user = db.session.query(User).filter_by(username='admin').first()
|
||||
if user:
|
||||
return user
|
||||
user = User(username='admin', email='admin@example.com', role='admin', status='active')
|
||||
user.set_password('password123')
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
return user
|
||||
|
||||
|
||||
def _seed_doc_with_missing_source(root: Path) -> tuple[KbDocument, KbDocumentVersion]:
|
||||
"""创建文档:source_file_path 指向不存在文件,cleaned md 真实存在。"""
|
||||
_ensure_admin()
|
||||
group = KbGroup(name='fallback-group', description='t', is_active=True)
|
||||
db.session.add(group)
|
||||
db.session.flush()
|
||||
|
||||
document = KbDocument(
|
||||
group_id=group.id,
|
||||
title='员工入职须知',
|
||||
status='ready',
|
||||
source_type='upload',
|
||||
is_deleted=False,
|
||||
)
|
||||
db.session.add(document)
|
||||
db.session.flush()
|
||||
|
||||
missing_source = root / 'docs' / 'missing-source.pdf'
|
||||
cleaned = root / 'docs' / 'cleaned.md'
|
||||
cleaned.parent.mkdir(parents=True, exist_ok=True)
|
||||
cleaned.write_text('# 入职须知\n\n欢迎加入。', encoding='utf-8')
|
||||
|
||||
version = KbDocumentVersion(
|
||||
document_id=document.id,
|
||||
version_no=1,
|
||||
status='ready',
|
||||
is_current=True,
|
||||
source_file_name='员工入职须知.pdf',
|
||||
source_file_path=str(missing_source),
|
||||
source_file_ext='pdf',
|
||||
source_file_size=12,
|
||||
sha256='abc',
|
||||
cleaned_file_path=str(cleaned),
|
||||
)
|
||||
db.session.add(version)
|
||||
db.session.flush()
|
||||
|
||||
sync = KbDifySyncRecord(
|
||||
group_id=group.id,
|
||||
document_id=document.id,
|
||||
document_version_id=version.id,
|
||||
dataset_id='ds-fallback',
|
||||
remote_document_id='remote-fallback',
|
||||
status='synced',
|
||||
)
|
||||
db.session.add(sync)
|
||||
db.session.commit()
|
||||
return document, version
|
||||
|
||||
|
||||
def test_download_source_falls_back_to_markdown(app, client, tmp_path):
|
||||
"""断言:kind=source 时源文件不存在,仍返回清洗 Markdown 内容。"""
|
||||
root = _configure(app, tmp_path)
|
||||
with app.app_context():
|
||||
document, version = _seed_doc_with_missing_source(root)
|
||||
document_id = document.id
|
||||
version_id = version.id
|
||||
|
||||
response = client.get(
|
||||
f'/api/integration/files/{document_id}/download',
|
||||
headers={'X-Integration-Key': 'test-integration-key'},
|
||||
query_string={'kind': 'source', 'version_id': version_id},
|
||||
)
|
||||
assert response.status_code == 200, response.get_data(as_text=True)
|
||||
body = response.get_data(as_text=True)
|
||||
assert '入职须知' in body
|
||||
assert '欢迎加入' in body
|
||||
|
||||
|
||||
def test_serialize_prefers_markdown_when_source_missing(app, client, tmp_path):
|
||||
"""断言:dify-file 在源文件缺失时返回 kind=md 与 .md 扩展名。"""
|
||||
root = _configure(app, tmp_path)
|
||||
with app.app_context():
|
||||
_seed_doc_with_missing_source(root)
|
||||
|
||||
response = client.get(
|
||||
'/api/integration/dify-file',
|
||||
headers={'X-Integration-Key': 'test-integration-key'},
|
||||
query_string={
|
||||
'dataset_id': 'ds-fallback',
|
||||
'remote_document_id': 'remote-fallback',
|
||||
},
|
||||
)
|
||||
assert response.status_code == 200, response.get_json()
|
||||
payload = response.get_json()
|
||||
assert payload['source_ext'] == 'md'
|
||||
assert str(payload['source_filename']).endswith('.md')
|
||||
assert 'kind=md' in str(payload['source_download_url'])
|
||||
@@ -115,7 +115,7 @@ def test_kb_document_upload_and_sync_flow(app, client, monkeypatch, tmp_path):
|
||||
monkeypatch.setattr(
|
||||
dify_sync_module.KbDifySyncService,
|
||||
'create_document_by_text',
|
||||
lambda self, dataset_id, name, text: {'document': {'id': 'doc_test_001', 'name': name}},
|
||||
lambda self, dataset_id, name, text, **kwargs: {'document': {'id': 'doc_test_001', 'name': name, 'indexing_status': 'completed'}},
|
||||
)
|
||||
|
||||
sync_response = client.post(f'/api/kb/documents/{document_id}/sync', headers=admin_headers)
|
||||
@@ -159,7 +159,7 @@ def test_integration_api_resolves_synced_document(app, client, monkeypatch, tmp_
|
||||
monkeypatch.setattr(
|
||||
dify_sync_module.KbDifySyncService,
|
||||
'create_document_by_text',
|
||||
lambda self, dataset_id, name, text: {'document': {'id': 'doc_integration_001', 'name': name}},
|
||||
lambda self, dataset_id, name, text, **kwargs: {'document': {'id': 'doc_integration_001', 'name': name, 'indexing_status': 'completed'}},
|
||||
)
|
||||
|
||||
sync_response = client.post(f'/api/kb/documents/{document_id}/sync', headers=admin_headers)
|
||||
@@ -232,7 +232,7 @@ def test_sync_recreates_missing_remote_document_for_same_hash(app, client, monke
|
||||
monkeypatch.setattr(
|
||||
dify_sync_module.KbDifySyncService,
|
||||
'create_document_by_text',
|
||||
lambda self, dataset_id, name, text: {'document': {'id': 'doc_old_001', 'name': name}},
|
||||
lambda self, dataset_id, name, text, **kwargs: {'document': {'id': 'doc_old_001', 'name': name, 'indexing_status': 'completed'}},
|
||||
)
|
||||
|
||||
first_sync_response = client.post(f'/api/kb/documents/{document_id}/sync', headers=admin_headers)
|
||||
@@ -252,7 +252,7 @@ def test_sync_recreates_missing_remote_document_for_same_hash(app, client, monke
|
||||
monkeypatch.setattr(
|
||||
dify_sync_module.KbDifySyncService,
|
||||
'create_document_by_text',
|
||||
lambda self, dataset_id, name, text: {'document': {'id': 'doc_new_001', 'name': name}},
|
||||
lambda self, dataset_id, name, text, **kwargs: {'document': {'id': 'doc_new_001', 'name': name, 'indexing_status': 'completed'}},
|
||||
)
|
||||
|
||||
second_sync_response = client.post(f'/api/kb/documents/{document_id}/sync', headers=admin_headers)
|
||||
|
||||
@@ -0,0 +1,316 @@
|
||||
"""
|
||||
backend/tests/test_sso.py
|
||||
|
||||
用途:验证 HXOPS 面向产品内平级服务的 RS256 assertion、应用注册表和 JWKS 契约。
|
||||
依赖:Flask 测试客户端、User、PyJWT、cryptography 与临时 RSA 密钥。
|
||||
逻辑:模拟带 Casdoor 身份引用的 HXOPS 会话,断言 JWT 受众、有效期、身份字段和公钥发布均符合协议。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
import jwt
|
||||
import pytest
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import rsa
|
||||
from flask import g
|
||||
|
||||
from app import db
|
||||
from app.models import User
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def active_user(app):
|
||||
"""创建可签发平级服务登录 assertion 的 active HXOPS 用户。"""
|
||||
user = User(
|
||||
username='sso-user',
|
||||
email='sso-user@example.com',
|
||||
real_name='SSO User',
|
||||
employee_id='E1001',
|
||||
phone_number='13800000001',
|
||||
department='IT',
|
||||
role='user',
|
||||
status='active',
|
||||
)
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
return user
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sso_keys(tmp_path):
|
||||
"""生成仅供当前测试使用的当前私钥、旧公钥文件和公钥对象。"""
|
||||
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
||||
private_key_path = tmp_path / 'hxops-sso-private.pem'
|
||||
private_key_path.write_bytes(private_key.private_bytes(
|
||||
encoding=serialization.Encoding.PEM,
|
||||
format=serialization.PrivateFormat.PKCS8,
|
||||
encryption_algorithm=serialization.NoEncryption(),
|
||||
))
|
||||
old_private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
||||
old_public_key_path = tmp_path / 'hxops-sso-old-public.pem'
|
||||
old_public_key_path.write_bytes(old_private_key.public_key().public_bytes(
|
||||
encoding=serialization.Encoding.PEM,
|
||||
format=serialization.PublicFormat.SubjectPublicKeyInfo,
|
||||
))
|
||||
return private_key_path, private_key.public_key(), old_public_key_path
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sso_config(app, sso_keys):
|
||||
"""启用一个使用测试地址和独立 audience 的产品内平级服务。"""
|
||||
private_key_path, public_key, old_public_key_path = sso_keys
|
||||
app.config.update(
|
||||
SSO_ENABLED=True,
|
||||
ENV_NAME='test',
|
||||
AUTH_JWT_ISSUER='https://casdoor.example.com',
|
||||
SSO_ASSERTION_TTL_SECONDS=60,
|
||||
SSO_ISSUER='http://hxops.test',
|
||||
SSO_SIGNING_ALGORITHM='RS256',
|
||||
SSO_SIGNING_KEY_ID='hxops-sso-test-key',
|
||||
SSO_PRIVATE_KEY_PATH=str(private_key_path),
|
||||
SSO_ADDITIONAL_PUBLIC_KEYS_JSON=json.dumps([{
|
||||
'kid': 'hxops-sso-old-key',
|
||||
'public_key_path': str(old_public_key_path),
|
||||
}]),
|
||||
SSO_APPS_JSON=json.dumps([{
|
||||
'key': 'peer-service',
|
||||
'display_name': 'Peer Service',
|
||||
'login_url': 'http://peer.test/auth/hxops/start',
|
||||
'callback_url': 'http://peer.test/auth/hxops/callback',
|
||||
'audience': 'peer-service',
|
||||
'enabled': True,
|
||||
}]),
|
||||
)
|
||||
return public_key
|
||||
|
||||
|
||||
def _bearer_user(monkeypatch, user, *, claims=None):
|
||||
"""模拟已验证 HXOPS API JWT,并把 Casdoor 稳定身份引用挂到 Flask g。"""
|
||||
resolved_claims = claims if claims is not None else {
|
||||
'casdoor_iss': 'https://casdoor.example.com',
|
||||
'casdoor_sub': 'casdoor-subject-1001',
|
||||
}
|
||||
|
||||
def resolve_user():
|
||||
g.jwt_claims = resolved_claims
|
||||
return user
|
||||
|
||||
monkeypatch.setattr('app.api.sso.get_current_user', resolve_user)
|
||||
|
||||
|
||||
def _data(response):
|
||||
"""兼容是否启用成功 envelope,提取实际 API 数据。"""
|
||||
body = response.get_json()
|
||||
return body.get('data') if body.get('success') is True else body
|
||||
|
||||
|
||||
def _error_code(response):
|
||||
"""从统一错误 envelope 中提取业务错误码。"""
|
||||
return (response.get_json().get('error') or {}).get('code')
|
||||
|
||||
|
||||
def _issue(client, monkeypatch, user, *, state='peer-signed-state'):
|
||||
"""签发一枚测试 assertion,供声明与错误分支测试复用。"""
|
||||
_bearer_user(monkeypatch, user)
|
||||
return client.post(
|
||||
'/api/sso/apps/peer-service/assertions',
|
||||
headers={'Authorization': 'Bearer verified-token'},
|
||||
json={'state': state},
|
||||
)
|
||||
|
||||
|
||||
def test_apps_requires_bearer_header(client, sso_config):
|
||||
"""平级服务目录不接受匿名请求或 legacy 用户头。"""
|
||||
response = client.get('/api/sso/apps')
|
||||
assert response.status_code == 401
|
||||
assert _error_code(response) == 'AUTH.UNAUTHORIZED'
|
||||
|
||||
|
||||
def test_assertion_is_rs256_audience_bound_and_contains_no_permissions(
|
||||
client,
|
||||
active_user,
|
||||
sso_config,
|
||||
monkeypatch,
|
||||
):
|
||||
"""签发结果可被公开密钥验证,且只包含共享身份、不包含 HXOPS 权限。"""
|
||||
response = _issue(client, monkeypatch, active_user)
|
||||
assert response.status_code == 200
|
||||
result = _data(response)
|
||||
assert result['post_url'] == 'http://peer.test/auth/hxops/callback'
|
||||
assert result['state'] == 'peer-signed-state'
|
||||
assert result['expires_in'] == 60
|
||||
|
||||
header = jwt.get_unverified_header(result['assertion'])
|
||||
assert header['alg'] == 'RS256'
|
||||
assert header['kid'] == 'hxops-sso-test-key'
|
||||
claims = jwt.decode(
|
||||
result['assertion'],
|
||||
sso_config,
|
||||
algorithms=['RS256'],
|
||||
issuer='http://hxops.test',
|
||||
audience='peer-service',
|
||||
)
|
||||
|
||||
# 关键断言:稳定 Casdoor 身份进入 token,本地用户主键和业务权限不得泄漏。
|
||||
assert claims['sub'] == 'casdoor-subject-1001'
|
||||
assert claims['identity_issuer'] == 'https://casdoor.example.com'
|
||||
assert claims['preferred_username'] == active_user.username
|
||||
assert claims['name'] == active_user.real_name
|
||||
assert claims['exp'] - claims['iat'] == 60
|
||||
assert claims['nbf'] <= claims['iat']
|
||||
assert claims['jti']
|
||||
assert 'user_id' not in claims
|
||||
assert 'role' not in claims
|
||||
assert 'feature_permissions' not in claims
|
||||
|
||||
|
||||
def test_each_assertion_has_a_unique_jti(client, active_user, sso_config, monkeypatch):
|
||||
"""同一用户连续签发的 assertion 使用不同 jti,便于平级服务按需增加防重放。"""
|
||||
first = _data(_issue(client, monkeypatch, active_user))['assertion']
|
||||
second = _data(_issue(client, monkeypatch, active_user))['assertion']
|
||||
first_claims = jwt.decode(first, sso_config, algorithms=['RS256'], audience='peer-service')
|
||||
second_claims = jwt.decode(second, sso_config, algorithms=['RS256'], audience='peer-service')
|
||||
assert first_claims['jti'] != second_claims['jti']
|
||||
|
||||
|
||||
def test_jwks_publishes_matching_public_key(client, sso_config):
|
||||
"""公开 JWKS 同时发布当前和旧公钥,且响应不包含任何私钥参数。"""
|
||||
response = client.get('/.well-known/jwks.json')
|
||||
assert response.status_code == 200
|
||||
body = _data(response)
|
||||
assert response.headers['Cache-Control'] == 'public, max-age=300'
|
||||
assert len(body['keys']) == 2
|
||||
jwk = next(item for item in body['keys'] if item['kid'] == 'hxops-sso-test-key')
|
||||
old_jwk = next(item for item in body['keys'] if item['kid'] == 'hxops-sso-old-key')
|
||||
assert jwk['kid'] == 'hxops-sso-test-key'
|
||||
assert jwk['alg'] == 'RS256'
|
||||
assert jwk['kty'] == 'RSA'
|
||||
assert jwk['use'] == 'sig'
|
||||
assert jwk['n']
|
||||
assert jwk['e'] == 'AQAB'
|
||||
assert old_jwk['alg'] == 'RS256'
|
||||
assert old_jwk['n'] != jwk['n']
|
||||
assert 'd' not in jwk
|
||||
assert 'p' not in jwk
|
||||
assert 'q' not in jwk
|
||||
|
||||
|
||||
def test_assertion_requires_casdoor_identity(client, active_user, sso_config, monkeypatch):
|
||||
"""缺少 casdoor_iss/casdoor_sub 的 HXOPS 本地登录态不能跨服务签发身份。"""
|
||||
_bearer_user(monkeypatch, active_user, claims={'username': active_user.username})
|
||||
response = client.post(
|
||||
'/api/sso/apps/peer-service/assertions',
|
||||
headers={'Authorization': 'Bearer local-token'},
|
||||
json={'state': 'peer-signed-state'},
|
||||
)
|
||||
assert response.status_code == 403
|
||||
assert _error_code(response) == 'AUTH.SSO_IDENTITY_UNSUPPORTED'
|
||||
|
||||
|
||||
def test_local_issuer_subject_cannot_impersonate_casdoor(
|
||||
client,
|
||||
active_user,
|
||||
sso_config,
|
||||
monkeypatch,
|
||||
):
|
||||
"""HXOPS API JWT 自身的标准 iss/sub 不能冒充 Casdoor 身份引用。"""
|
||||
_bearer_user(monkeypatch, active_user, claims={
|
||||
'iss': 'hxops-backend',
|
||||
'sub': str(active_user.id),
|
||||
})
|
||||
response = client.post(
|
||||
'/api/sso/apps/peer-service/assertions',
|
||||
headers={'Authorization': 'Bearer local-token'},
|
||||
json={'state': 'peer-signed-state'},
|
||||
)
|
||||
assert response.status_code == 403
|
||||
assert _error_code(response) == 'AUTH.SSO_IDENTITY_UNSUPPORTED'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('state', ['', 'x' * 4097])
|
||||
def test_assertion_rejects_invalid_state(client, active_user, sso_config, monkeypatch, state):
|
||||
"""state 必须存在且受长度限制,避免放大请求或意外持久化不可信数据。"""
|
||||
response = _issue(client, monkeypatch, active_user, state=state)
|
||||
assert response.status_code == 400
|
||||
assert _error_code(response) == 'VALIDATION.INVALID_PARAM'
|
||||
|
||||
|
||||
def test_assertion_rejects_unknown_application(client, active_user, sso_config, monkeypatch):
|
||||
"""浏览器不能通过未注册 app key 指定任意 callback 或 audience。"""
|
||||
_bearer_user(monkeypatch, active_user)
|
||||
response = client.post(
|
||||
'/api/sso/apps/not-registered/assertions',
|
||||
headers={'Authorization': 'Bearer verified-token'},
|
||||
json={'state': 'peer-signed-state'},
|
||||
)
|
||||
assert response.status_code == 404
|
||||
assert _error_code(response) == 'AUTH.SSO_APP_NOT_FOUND'
|
||||
|
||||
|
||||
def test_application_registry_rejects_duplicate_audience(client, app, active_user, sso_config, monkeypatch):
|
||||
"""两个平级服务不能共享 audience,避免一个服务接受签给另一个服务的 assertion。"""
|
||||
app.config['SSO_APPS_JSON'] = json.dumps([
|
||||
{
|
||||
'key': 'peer-service-a',
|
||||
'display_name': 'Peer Service A',
|
||||
'login_url': 'http://peer-a.test/auth/hxops/start',
|
||||
'callback_url': 'http://peer-a.test/auth/hxops/callback',
|
||||
'audience': 'shared-audience',
|
||||
},
|
||||
{
|
||||
'key': 'peer-service-b',
|
||||
'display_name': 'Peer Service B',
|
||||
'login_url': 'http://peer-b.test/auth/hxops/start',
|
||||
'callback_url': 'http://peer-b.test/auth/hxops/callback',
|
||||
'audience': 'shared-audience',
|
||||
},
|
||||
])
|
||||
_bearer_user(monkeypatch, active_user)
|
||||
response = client.get('/api/sso/apps', headers={'Authorization': 'Bearer verified-token'})
|
||||
assert response.status_code == 503
|
||||
assert _error_code(response) == 'AUTH.SSO_CONFIG_ERROR'
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
('config_key', 'config_value'),
|
||||
[
|
||||
('SSO_ASSERTION_TTL_SECONDS', 61),
|
||||
('SSO_SIGNING_ALGORITHM', 'HS256'),
|
||||
('SSO_PRIVATE_KEY_PATH', ''),
|
||||
],
|
||||
)
|
||||
def test_assertion_fails_closed_for_invalid_signing_config(
|
||||
client,
|
||||
app,
|
||||
active_user,
|
||||
sso_config,
|
||||
monkeypatch,
|
||||
config_key,
|
||||
config_value,
|
||||
):
|
||||
"""TTL、算法或私钥配置错误时返回 503,不使用普通 API JWT 密钥降级。"""
|
||||
app.config[config_key] = config_value
|
||||
response = _issue(client, monkeypatch, active_user)
|
||||
assert response.status_code == 503
|
||||
assert _error_code(response) == 'AUTH.SSO_CONFIG_ERROR'
|
||||
|
||||
|
||||
def test_jwks_fails_closed_for_duplicate_rotation_key_id(client, app, sso_config):
|
||||
"""旧验证公钥不得复用当前 kid,避免平级服务选择到含义不明确的公钥。"""
|
||||
app.config['SSO_ADDITIONAL_PUBLIC_KEYS_JSON'] = json.dumps([{
|
||||
'kid': 'hxops-sso-test-key',
|
||||
'public_key_path': 'unused',
|
||||
}])
|
||||
response = client.get('/.well-known/jwks.json', headers={'Accept': 'application/json'})
|
||||
assert response.status_code == 503
|
||||
assert _error_code(response) == 'AUTH.SSO_CONFIG_ERROR'
|
||||
|
||||
|
||||
def test_legacy_ticket_and_exchange_routes_are_removed(client, sso_config):
|
||||
"""旧 Redis ticket 协议路由必须彻底下线,避免两个认证契约并存。"""
|
||||
ticket_response = client.post('/api/sso/apps/peer-service/tickets')
|
||||
exchange_response = client.post('/api/sso/exchange')
|
||||
assert ticket_response.status_code == 404
|
||||
assert exchange_response.status_code == 404
|
||||
@@ -192,6 +192,51 @@ def test_local_assistant_message_query_does_not_duplicate_user_bubble(client):
|
||||
assert msgs[-1]['content'] == '已确认,进入下一步。'
|
||||
|
||||
|
||||
def test_local_typed_assistant_message_keeps_query_for_user_bubble_and_title(client):
|
||||
"""结构化结果卡须保留 query:刷新后回放用户提问,会话标题用提问而非 headline。"""
|
||||
headers = get_headers(client)
|
||||
user_question = '请对《邦达激光合同.pdf》进行模板比对'
|
||||
headline = '模板比对完成:高 1 / 中 0 / 低 0,共 1 处变更'
|
||||
|
||||
save_res = client.post('/api/chat/messages/local?agent_id=1', headers=headers, json={
|
||||
'conversation_id': 'conv-contract-review',
|
||||
'role': 'assistant',
|
||||
'type': 'procurement-contract-review',
|
||||
'content': headline,
|
||||
'query': user_question,
|
||||
'payload': {
|
||||
'review_no': 'CR-TEST-001',
|
||||
'contract_file_name': '邦达激光合同.pdf',
|
||||
'high_risk_count': 1,
|
||||
'medium_risk_count': 0,
|
||||
'low_risk_count': 0,
|
||||
},
|
||||
})
|
||||
assert save_res.status_code == 200
|
||||
|
||||
# 断言:历史回放含用户气泡 + 结果卡
|
||||
msg_res = client.get(
|
||||
'/api/chat/messages?conversation_id=conv-contract-review&agent_id=1',
|
||||
headers=headers,
|
||||
)
|
||||
assert msg_res.status_code == 200
|
||||
msgs = msg_res.get_json()
|
||||
assert len(msgs) >= 2
|
||||
assert msgs[0]['role'] == 'user'
|
||||
assert msgs[0]['content'] == user_question
|
||||
assert msgs[-1]['role'] == 'assistant'
|
||||
assert msgs[-1]['type'] == 'procurement-contract-review'
|
||||
|
||||
# 断言:侧栏标题取用户提问,而非审查 headline
|
||||
sessions_res = client.get('/api/chat/sessions?agent_id=1', headers=headers)
|
||||
assert sessions_res.status_code == 200
|
||||
sessions = sessions_res.get_json()
|
||||
target = next((s for s in sessions if s['conversation_id'] == 'conv-contract-review'), None)
|
||||
assert target is not None
|
||||
assert target['title'].startswith('请对《邦达激光合同.pdf》')
|
||||
assert '模板比对完成' not in target['title']
|
||||
|
||||
|
||||
def test_chat_sessions_keep_latest_non_empty_query_as_title(client):
|
||||
headers = get_headers(client)
|
||||
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
"""backend/tests/voucher_check — 立账凭证检核单测包。"""
|
||||
@@ -0,0 +1,30 @@
|
||||
"""
|
||||
backend/tests/voucher_check/test_period_and_incremental.py
|
||||
|
||||
用途:自然月边界与增量跳过决策相关单测。
|
||||
依赖:pytest、erp_repository.current_period_bounds。
|
||||
逻辑:固定时钟注入,验证 Asia/Shanghai 月初/下月边界。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from app.services.voucher_check.erp_repository import current_period_bounds
|
||||
|
||||
|
||||
def test_current_period_bounds_shanghai_august():
|
||||
now = datetime(2026, 8, 15, 10, 0, 0, tzinfo=ZoneInfo("Asia/Shanghai"))
|
||||
period_month, next_month, period_start, next_start = current_period_bounds(now)
|
||||
assert period_month.isoformat() == "2026-08-01"
|
||||
assert next_month.isoformat() == "2026-09-01"
|
||||
assert period_start.isoformat().startswith("2026-08-01T00:00:00")
|
||||
assert next_start.isoformat().startswith("2026-09-01T00:00:00")
|
||||
|
||||
|
||||
def test_current_period_bounds_december_rollover():
|
||||
now = datetime(2026, 12, 31, 23, 30, 0, tzinfo=ZoneInfo("Asia/Shanghai"))
|
||||
period_month, next_month, _, _ = current_period_bounds(now)
|
||||
assert period_month.isoformat() == "2026-12-01"
|
||||
assert next_month.isoformat() == "2027-01-01"
|
||||
@@ -0,0 +1,106 @@
|
||||
"""
|
||||
backend/tests/voucher_check/test_share_and_fingerprint.py
|
||||
|
||||
用途:立账凭证检核目录模板、文件名精确匹配与指纹稳定性单测。
|
||||
依赖:pytest、临时目录、voucher_check 领域模块。
|
||||
逻辑:不连 Oracle/共享盘;覆盖精确匹配、0 字节齐全、子目录不计、指纹变化。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.voucher_check.config import (
|
||||
RequiredFileRule,
|
||||
validate_directory_template,
|
||||
)
|
||||
from app.services.voucher_check.fingerprint import build_material_fingerprint
|
||||
from app.services.voucher_check.share_scanner import (
|
||||
FileMeta,
|
||||
match_required_files,
|
||||
scan_invoice_folder,
|
||||
)
|
||||
|
||||
|
||||
def test_directory_template_rejects_unknown_placeholder():
|
||||
with pytest.raises(ValidationError) as exc:
|
||||
validate_directory_template("{root}/{YYYY}/{MM}/{invoice_no}/{extra}")
|
||||
assert exc.value.code == "VOUCHER_CHECK.CONFIG_INVALID"
|
||||
|
||||
|
||||
def test_exact_filename_match_and_zero_byte_counts():
|
||||
rules = (
|
||||
RequiredFileRule(
|
||||
code="price_check_sheet",
|
||||
name="核价单",
|
||||
required=True,
|
||||
accepted_filenames=("核价单.pdf",),
|
||||
),
|
||||
RequiredFileRule(
|
||||
code="purchase_order",
|
||||
name="采购单",
|
||||
required=True,
|
||||
accepted_filenames=("采购单.pdf",),
|
||||
),
|
||||
)
|
||||
files = [
|
||||
FileMeta(name="核价单.pdf", size=0, mtime_ns=1),
|
||||
FileMeta(name="采购单.pdf", size=10, mtime_ns=2),
|
||||
]
|
||||
matched, missing = match_required_files(files, rules, case_sensitive=True)
|
||||
assert matched["price_check_sheet"] == "核价单.pdf"
|
||||
assert matched["purchase_order"] == "采购单.pdf"
|
||||
assert missing == []
|
||||
|
||||
|
||||
def test_subdir_same_name_does_not_count(tmp_path: Path):
|
||||
"""直接子文件才命中;子目录内同名文件不算。"""
|
||||
from app.services.voucher_check.config import VoucherCheckConfig
|
||||
|
||||
root = tmp_path / "vouche"
|
||||
inv_dir = root / "2026" / "08" / "INV001"
|
||||
inv_dir.mkdir(parents=True)
|
||||
nested = inv_dir / "nested"
|
||||
nested.mkdir()
|
||||
(nested / "核价单.pdf").write_bytes(b"x")
|
||||
(inv_dir / "采购单.pdf").write_bytes(b"y")
|
||||
|
||||
cfg = VoucherCheckConfig(
|
||||
scope_code="HXJM",
|
||||
directory_template="{root}/{YYYY}/{MM}/{invoice_no}",
|
||||
required_files=(
|
||||
RequiredFileRule("price_check_sheet", "核价单", True, ("核价单.pdf",)),
|
||||
RequiredFileRule("purchase_order", "采购单", True, ("采购单.pdf",)),
|
||||
),
|
||||
filename_case_sensitive=True,
|
||||
notify_missing_enabled=False,
|
||||
notify_failure_enabled=False,
|
||||
same_day_dedup_enabled=False,
|
||||
local_root=str(root),
|
||||
share_unc="",
|
||||
healthcheck_relative_path=".hxops-share-ready",
|
||||
erp_dsn="x",
|
||||
erp_username="u",
|
||||
erp_password="p",
|
||||
)
|
||||
result = scan_invoice_folder(
|
||||
cfg,
|
||||
root=str(root),
|
||||
period_month=date(2026, 8, 1),
|
||||
invoice_no="INV001",
|
||||
)
|
||||
assert result.result == "missing"
|
||||
assert any(m["code"] == "price_check_sheet" for m in result.missing_materials)
|
||||
assert result.matched_files.get("purchase_order") == "采购单.pdf"
|
||||
|
||||
|
||||
def test_fingerprint_stable_and_changes_on_mtime():
|
||||
a = build_material_fingerprint([("a.pdf", 1, 100), ("b.pdf", 2, 200)])
|
||||
b = build_material_fingerprint([("b.pdf", 2, 200), ("a.pdf", 1, 100)])
|
||||
assert a == b
|
||||
c = build_material_fingerprint([("a.pdf", 1, 101), ("b.pdf", 2, 200)])
|
||||
assert a != c
|
||||
@@ -0,0 +1,52 @@
|
||||
"""
|
||||
backend/tests/voucher_check/test_tool_auth_and_openapi.py
|
||||
|
||||
用途:立账凭证检核 Tool OpenAPI 静态规格校验(不依赖 Flask venv)。
|
||||
依赖:pytest、openapi_base.json。
|
||||
逻辑:直接读 JSON,校验 operationId 与 securitySchemes。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
_SPEC = (
|
||||
Path(__file__).resolve().parents[2]
|
||||
/ "app"
|
||||
/ "services"
|
||||
/ "voucher_check"
|
||||
/ "openapi_base.json"
|
||||
)
|
||||
|
||||
|
||||
def test_openapi_base_contains_expected_operations():
|
||||
spec = json.loads(_SPEC.read_text(encoding="utf-8"))
|
||||
paths = spec["paths"]
|
||||
assert (
|
||||
paths["/api/accounting-voucher-check/tools/tasks/{task_id}/missing"]["get"]["operationId"]
|
||||
== "list_voucher_missing"
|
||||
)
|
||||
assert (
|
||||
paths["/api/accounting-voucher-check/tools/runs/{run_id}/items"]["get"]["operationId"]
|
||||
== "list_voucher_run_items"
|
||||
)
|
||||
assert (
|
||||
paths["/api/accounting-voucher-check/tools/invoices/{invoice_no}/latest"]["get"]["operationId"]
|
||||
== "get_voucher_invoice_latest"
|
||||
)
|
||||
assert "BearerAuth" in spec["components"]["securitySchemes"]
|
||||
assert "IntegrationKey" in spec["components"]["securitySchemes"]
|
||||
|
||||
|
||||
def test_docs_openapi_export_in_sync():
|
||||
docs = (
|
||||
Path(__file__).resolve().parents[3]
|
||||
/ "docs"
|
||||
/ "openapi"
|
||||
/ "accounting_voucher_check_tools_openapi.json"
|
||||
)
|
||||
assert docs.is_file(), "请运行 python backend/scripts/export_voucher_check_openapi.py"
|
||||
exported = json.loads(docs.read_text(encoding="utf-8"))
|
||||
base = json.loads(_SPEC.read_text(encoding="utf-8"))
|
||||
assert exported["paths"].keys() == base["paths"].keys()
|
||||
Reference in new issue
Block a user