from pathlib import Path import csv,json,platform,datetime,sys HERE=Path(__file__).resolve().parent def clean(value):return str(value or '').strip() def read_csv(root,name): with (root/'input'/f'{name}.csv').open(encoding='utf-8-sig',newline='') as f:return list(csv.DictReader(f)) def hashfile(path): import hashlib return hashlib.sha256(path.read_bytes()).hexdigest() def known(value):return clean(value).lower() not in {"","미확인","unknown"} REPORT_HEADERS=['원본행', '식별번호', '등록 상태'] def compute(root=HERE): source=read_csv(root,'original-example');registered=set();counts={};outstanding=[];issues=[];rows=[] for index,r in enumerate(source,1): rid=clean(r.get('식별번호'));state=clean(r.get('현재 상태')) if not rid:issues.append({'row':index,'issue':'register_id_missing'});rows.append([index,'','등록 식별번호 확인 필요']);continue registered.add(rid);known_state=state if state in {'보관 중','지급 중','회수 대기'} else '상태미확인';counts[known_state]=counts.get(known_state,0)+1 if known_state!='보관 중':outstanding.append(rid) rows.append([index,rid,known_state]) unmatched=[] for r in read_csv(root,'return_events'): rid=clean(r.get('id')) if not rid or rid not in registered:unmatched.append(rid or '[missing_id]') reported=int(read_csv(root,'bad_total')[0]['counted_stored_only']) actual={'registered_count':len(registered),'status_counts':counts,'stored_only_count_error':len(registered)-reported,'unmatched_return_ids':unmatched,'outstanding_ids':outstanding} return actual,rows,{'register_review':issues,'policy':'Blank identifiers do not count as registered items or join to blank return identifiers.'} def run(root=HERE): try:actual,rows,details=compute(root) except ValueError as exc: report={'lab_id':root.name,'status':'INPUT_ERROR','actual':None,'input_error':str(exc),'assertion_count':0} (root/'results.json').write_text(json.dumps(report,ensure_ascii=False,indent=2),encoding='utf-8') (root/'actual.json').write_text('null',encoding='utf-8') with (root/'results.csv').open('w',encoding='utf-8-sig',newline='') as f:csv.writer(f).writerows([['입력 검토 필요'],[str(exc)]]) print(json.dumps(report,ensure_ascii=False));return report expected=json.loads((root/'expected/report.json').read_text(encoding='utf-8')) checks=[{'field':k,'pass':actual.get(k)==v,'actual':actual.get(k),'expected':v} for k,v in expected.items()] passed=all(c['pass'] for c in checks) and set(actual)==set(expected) report={'lab_id':root.name,'synthetic_fixture':True,'environment':{'python':platform.python_version(),'platform':platform.system(),'processor':'Python standard library'},'run_utc':datetime.datetime.now(datetime.timezone.utc).isoformat(),'status':'PASS' if passed else 'FAIL','assertion_count':len(checks),'actual':actual,'assertions':checks,'details':details,'limits':'Synthetic record checks only;not a real building inspection,safety/legal verdict,Excel app test,physical receipt or authenticity verification.'} (root/'results.json').write_text(json.dumps(report,ensure_ascii=False,indent=2),encoding='utf-8') (root/'actual.json').write_text(json.dumps(actual,ensure_ascii=False,indent=2),encoding='utf-8') with (root/'results.csv').open('w',encoding='utf-8-sig',newline='') as f: w=csv.writer(f);w.writerow(REPORT_HEADERS);w.writerows(rows) print(json.dumps(report,ensure_ascii=False,indent=2)) return report if __name__=='__main__': report=run() if report['status']!='PASS':raise SystemExit(1)