File size: 4,994 Bytes
4437ddb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 | import json
from pathlib import Path
import sys
from threading import Thread
from urllib.error import HTTPError
from urllib.request import Request, urlopen
import pytest
project = Path(__file__).resolve().parents[1]
sys.path.insert(0,str(project/"tools" if (project/"tools").is_dir() else project))
from build_data import ROOT, build
from evidence_model import PortableModel
from methods import annotated_rates, compare, match_exclusion, review_gate, valid_span
from service import ThreadingHTTPServer, handler
def test_pair_rules_counts_and_unresolved_bounds():
rows,pairs,splits=build()
report=compare(pairs)
assert report["eligible_pairs"]==20
assert report["complete_pairs"]==16
assert report["gap_bounds"]==pytest.approx([.4,.6])
assert report["left"]["presented_as_fact"]==12
assert report["right"]["presented_as_fact"]==4
assert report["exclusions"]["not_a_factual_comparison"]==1
assert len(report["exclusions"])==5
assert len({row["event_id"] for row in rows})==20
assert all(row["split"]==splits[row["event_id"]] and valid_span(row,row["reference_span"]) for row in rows)
with pytest.raises(ValueError, match="Duplicate pair ID"):
compare([pairs[0],pairs[0]])
assert match_exclusion(pairs[0]["left"],{**pairs[0]["right"],"published_at":"2024-02-31T12:00:00Z"})=="timestamp_missing_or_invalid"
assert compare([])["gap_bounds"] is None
def test_independent_review_and_reproduction_gate():
row={"unit_id":"r1","origin":"authentic","source_url":"https://example.com/record",
"source_sha256":"1"*64,"rights_basis":"example documentation","label":"asserted","text":"One claim.",
"reference_span":{"segment":"passage","start":0,"end":10,"quote":"One claim."},
"reviews":[{"reviewer_id":"one","origin":"human","independent":True,"label":"asserted"},
{"reviewer_id":"two","origin":"human","independent":True,"label":"attributed"}]}
digest="0"*64
approvals=[{"role":role,"reviewer_id":name,"artifact_sha256":digest,"recorded_at":"2026-11-27",
"origin":"human","decision":"approve","independent":True}
for role,name in [("methods_reviewer","three"),("independent_reproduction_engineer","four")]]
assert "adjudication_required:r1" in review_gate([row],approvals,digest)["failures"]
row["adjudication"]={"reviewer_id":"five","label":"asserted","rationale":"fixture rationale"}
assert review_gate([row],approvals,digest)["ready_for_human_reviewed_release"]
assert not review_gate([row],approvals,"2"*64)["ready_for_human_reviewed_release"]
assert not review_gate([{**row,"origin":"fictional"}],approvals,digest)["ready_for_human_reviewed_release"]
assert not review_gate([row],[*approvals[:1],{**approvals[1],"reviewer_id":"three"}],digest)["ready_for_human_reviewed_release"]
assert not review_gate([],[],digest)["ready_for_human_reviewed_release"]
def test_annotation_rates_keep_unknown_denominator():
rate=annotated_rates([{"eligible":True,"status":"reviewed","loaded_wording":True,"frames":["human_impact"]},
{"eligible":True,"status":"unresolved"},{"eligible":False,"status":"unresolved"}])
assert rate["eligible"]==2 and rate["unresolved"]==1
assert rate["loaded_wording_rate"]==[.5,1]
assert rate["frame_prevalence"]["causal_responsibility"]==[0,.5]
def test_loopback_predict_scorecard_unqualified_text():
model=PortableModel(ROOT/"work"/"model.json")
rows,pairs,_=build()
selected=next(row for row in rows if row["family"]=="context_flip" and row["label"]=="attributed")
with ThreadingHTTPServer(("127.0.0.1",0),handler(model)) as server:
thread=Thread(target=server.serve_forever,daemon=True)
thread.start()
base=f"http://127.0.0.1:{server.server_port}"
def post(endpoint,value):
req=Request(base+endpoint,json.dumps(value).encode(),{"Content-Type":"application/json"})
with urlopen(req,timeout=10) as response:
assert response.headers["Cache-Control"]=="no-store"
return json.load(response)
try:
assert json.load(urlopen(base+"/health",timeout=10))["status"]=="ok"
result=post("/v1/predict",{"claim_type":"budget","text":selected["text"],"context":selected["context"]})
assert result["decision"]=="attributed" and valid_span(selected,result["evidence"])
assert post("/v1/predict",{"claim_type":"normative_position","text":"I oppose the policy."})["status"]=="out_of_scope"
assert post("/v1/predict",{"claim_type":"budget","text":"𐄂"})["status"]=="abstained"
assert post("/v1/scorecard",{"pairs":pairs})["eligible_pairs"]==20
with pytest.raises(HTTPError) as error:
post("/v1/predict",{"claim_type":"budget","text":"x"*6001})
assert error.value.code==400
finally:
server.shutdown()
thread.join()
|