Files
o2o-plagiarism-ai/tests/test_case_matching_views.py
T
HyeongBaeYangandClaude Opus 5.5 03d500d67c fix: assign case code to partial verbatim copies with exact-span evidence
원고 일부만 그대로 옮기면 전체 유사도가 중간이라 주 태그가 비어 case_id 가
null 로 내려갔다. 35자 이상 연속 일치로 채택된 매칭은 복제권·인용 누락을
주 태그로 붙여 M1 으로 분류한다.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-21 08:38:46 +09:00

168 lines
8.9 KiB
Python

from datetime import datetime, timezone
from pathlib import Path
from fastapi import FastAPI
from fastapi.testclient import TestClient
from app.api.schemas import (BatchStatusResponse, CaseCandidate, DetectResponse,
EvidenceSpan, ExtractedElements, LegalRiskSignal, MatchResult)
from app.engine.taxonomy import load_taxonomy
def response(audience):
return DetectResponse(
audience=audience, doc_id="test", is_infringement=True, confidence=.9,
extracted_elements=ExtractedElements(), engine_version="test-engine",
taxonomy_version="cases_1.3", analyzed_at=datetime.now(timezone.utc),
ccl_basis="A6 판례 2006나16757",
legal_risk=LegalRiskSignal(
status="review_required", similarity_evidence="A6",
protected_expression="not_reviewed", access_evidence="not_provided",
precedent_ids=["2006나16757"], judgment_summary="A6 2006나16757",
supporting_reasons=["A6 2006나16757"], disclaimer="검토 필요"),
matches=[MatchResult(source_doc="source", similarity=.9, case_id="A6",
case_title="case", evidence_spans=[EvidenceSpan(start=0,end=3,matched="일치문")],
case_candidates=[CaseCandidate(case_id="A6",title="case",
handling="technical_detection", representative_precedents=["2006나16757"])])],
)
def test_author_http_and_batch_serialization():
app = FastAPI()
@app.get('/detect', response_model=DetectResponse)
def detect():
return response('author')
@app.get('/batch', response_model=BatchStatusResponse)
def batch():
return BatchStatusResponse(job_id='job',status='completed',total=1,processed=1,
created_at=datetime.now(timezone.utc),results=[response('author')])
with TestClient(app) as client:
direct=client.get('/detect').json()
nested=client.get('/batch').json()['results'][0]
for body in (direct,nested):
assert 'A6' not in str(body) and '2006나16757' not in str(body)
assert 'case_id' not in body['matches'][0]
assert 'legal_risk' not in body
assert body['matches'][0]['evidence_spans'][0]['start']==0
assert body['request_id'] and body['taxonomy_version']=='cases_1.3'
assert body['ccl_basis']=='확인이 필요한 부분이 있습니다.'
def test_admin_preserves_candidates_and_unknown_verdict():
body=response('admin').model_dump()
assert body['matches'][0]['case_id']=='A6'
assert body['matches'][0]['case_candidates'][0]['representative_precedents']==['2006나16757']
assert body['matches'][0]['publication_verdict'] is None
assert body['matches'][0]['publication_verdict_status']=='source_pending'
assert response('admin').request_id != response('admin').request_id
def test_taxonomy_verdicts_come_from_v3_checklist():
tax=load_taxonomy(Path('data/taxonomy'))
assert len(tax.cases)==18
verdicts={c.case_id: c.publication_verdict for c in tax.cases}
assert verdicts['M1']=='조건부' and verdicts['M2']=='조건부(동의 확보)'
assert all(verdicts.values())
def test_real_detector_forwards_audience_for_direct_batch_and_review(tmp_path):
from app.main import app
text = Path('data/reference/ref-0001__어린왕자.txt').read_text()
from scripts.run_precision_eval import build_corpus
from app.engine.persistent_index import PersistentCorpusIndex
from app.engine.detector import PlagiarismDetector
from app.core.config import get_settings
db = tmp_path / 'corpus.sqlite3'
index = tmp_path / 'index'
build_corpus([{'author':'reference','segment_id':'ref-1','text':text}], db)
PersistentCorpusIndex(db, index).sync()
settings = get_settings().model_copy(update={
'use_persistent_index':True,'corpus_db_path':str(db),
'persistent_index_dir':str(index)})
with TestClient(app) as client:
app.state.detector = PlagiarismDetector(settings)
payload={'doc_id':'audience-test','text':text,'options':{'audience':'author','threshold':0}}
direct=client.post('/v1/plagiarism/detect',json=payload)
assert direct.status_code==200
body=direct.json()
assert body['audience']=='author' and body['matches']
assert all('case_candidates' not in m for m in body['matches'])
batch=client.post('/v1/plagiarism/batch',json={
'items':[{'doc_id':'batch-author','text':text}],
'options':{'audience':'author','threshold':0}})
result=client.get('/v1/plagiarism/batch/'+batch.json()['job_id']).json()
assert result['status']=='completed'
assert result['results'][0]['audience']=='author'
assert 'legal_risk' not in result['results'][0]
review=client.post('/v1/plagiarism/review',json=payload).json()
assert review['legal_judgment']['precedent_ids']==[]
assert review['legal_judgment']['label']=='확인이 필요한 부분'
admin=client.post('/v1/plagiarism/detect',json={
'doc_id':'admin-test','text':text,'options':{'threshold':0}}).json()
assert admin['audience']=='admin' and 'legal_risk' in admin
assert any(m['case_candidates'] for m in admin['matches'])
verdicts={c.case_id: c.publication_verdict
for c in load_taxonomy(Path('data/taxonomy')).cases}
for m in admin['matches']:
for c in m['case_candidates']:
assert c['publication_verdict']==verdicts[c['case_id']]
assert c['reason'].startswith('엔진 주 태그') and c['matched_tags']
assert all(m['publication_verdict_status']=='review_required'
for m in admin['matches'] if m['case_candidates'])
def test_author_no_match_message_and_invalid_audience():
import pytest
from pydantic import ValidationError
from app.api.schemas import DetectOptions
result = response('author').model_copy(update={'matches': []})
assert result.model_dump()['ccl_basis'] == '등록된 비교 자료에서 일치 구간을 찾지 못했습니다.'
with pytest.raises(ValidationError):
DetectOptions(audience='public')
def test_case_reason_explains_tags_ties_and_draft_mapping():
from app.engine.detector import PlagiarismDetector
from app.engine.similarity import SimilarityHit
tax = load_taxonomy(Path('data/taxonomy'))
hit = SimilarityHit(doc_id='d', title='t', score=.9, text_sim=.45, lemma_sim=.3,
element_sim={'characters': .35}, evidence=[])
tie = tax.find_cases(['reproduction'])
m1, m10 = tie
reason = PlagiarismDetector._case_reason(m1, ['reproduction'], hit, tie)
assert '복제권' in reason and 'M1(남의 글을 옮겨 실었다)' in reason
assert 'text=0.45' in reason and 'M1, M10 중 하나로' in reason
assert '판단할 것: Q3' in reason and '추정치' not in reason
assert '추정치' in PlagiarismDetector._case_reason(m10, ['reproduction'], hit, tie)
def test_partial_verbatim_copy_gets_case_code(tmp_path):
"""원고 일부만 그대로 옮긴 경우 전체 유사도가 중간이라도 분류 코드가 비면 안 된다.
35자 이상 연속 일치로 채택된 매칭인데 주 태그가 없어 case_id 가 null 로
내려가던 문제의 회귀 테스트. 원문·원고는 모두 가짜 문장이다.
"""
from app.api.schemas import DetectRequest
from app.core.config import get_settings
from app.engine.detector import PlagiarismDetector
from app.engine.persistent_index import PersistentCorpusIndex
from scripts.run_precision_eval import build_corpus
source = ("나는 바닷가 작은 마을에서 태어났다. 아버지는 새벽마다 배를 타고 나가셨고 어머니는 "
"시장에서 생선을 파셨다. 열 살 무렵 처음으로 아버지의 배에 올랐던 날, 바다 위로 "
"떠오르던 해를 보며 나도 언젠가 저 수평선 너머로 가겠다고 다짐했다. 중학교를 마치고 "
"도시로 올라와 인쇄소에서 일을 배웠다. 밤마다 활자를 정리하며 책 냄새를 맡는 것이 "
"그렇게 좋을 수가 없었다.")
query = ("어린 시절 이야기를 조금 적어 본다. 열 살 무렵 처음으로 아버지의 배에 올랐던 날, "
"바다 위로 떠오르던 해를 보며 나도 언젠가 저 수평선 너머로 가겠다고 다짐했다. "
"그 뒤로 나는 늘 바다를 그리워하며 살았다.")
db, index = tmp_path / 'corpus.sqlite3', tmp_path / 'index'
build_corpus([{'author': 'sample', 'segment_id': 'sample-src-001', 'text': source}], db)
PersistentCorpusIndex(db, index).sync()
det = PlagiarismDetector(get_settings().model_copy(update={
'use_persistent_index': True, 'corpus_db_path': str(db),
'persistent_index_dir': str(index)}))
match = det.detect_request(DetectRequest(doc_id='q', text=query)).matches[0]
assert 'exact_span' in match.match_reasons
assert match.case_id == 'M1'
assert [c.case_id for c in match.case_candidates] == ['M1']