from pathlib import Path import csv,json,datetime as _clock,platform,copy BASE=Path(__file__).resolve().parent NORMALIZE_FIELDS={'fixture.csv': ['fixture', 'cap', 'voltage', 'approved_sku'], 'candidates.csv': ['sku', 'cap', 'voltage', 'doc']} LIMITS_TEXT='제품·기구·규격·승인 목록은 전부 가상입니다. P01 판정도 설치 가능·전기 안전·실제 호환의 인증이 아닙니다. 램프 분리·교체·배선 작업은 수행하지 않습니다.' REPORT_FILE='decisions.csv' def compute(overrides=None): judgement_notes={} def read_judged(name): if overrides is not None and name in overrides:raw=copy.deepcopy(overrides[name]) else: with (BASE/name).open(encoding='utf-8-sig',newline='')as f:raw=list(csv.DictReader(f)) fields=NORMALIZE_FIELDS.get(name,[]) return [dict(row,**{key:row.get(key,'').strip()for key in fields})for row in raw] from pathlib import Path import csv,json,datetime,platform,math HERE=Path(__file__).resolve().parent def minute(t): h,m=map(int,t.split(':'));return h*60+m def span(start,end):return set(range(minute(start),minute(end))) LIMITS='제품·기구·규격·승인 목록은 전부 가상입니다. P01 판정도 설치 가능·전기 안전·실제 호환의 인증이 아닙니다. 램프 분리·교체·배선 작업은 수행하지 않습니다.' f=read_judged('fixture.csv')[0];checks=[] for r in read_judged('candidates.csv'): reasons=[] if not r['sku']:reasons.append('sku_missing') if not r['cap'] or not f['cap']:reasons.append('cap_unconfirmed') elif r['cap']!=f['cap']:reasons.append('cap_mismatch') if not r['voltage'] or not f['voltage']:reasons.append('voltage_unconfirmed') elif r['voltage']!=f['voltage']:reasons.append('voltage_mismatch') if int(r['diameter_mm'])>int(f['max_diameter_mm']):reasons.append('diameter_exceeds_fixture') if not r['doc']:reasons.append('document_missing') if r['sku']!=f['approved_sku'] and not reasons:reasons.append('approval_not_confirmed') checks.append({'sku':r['sku'],'comparison':'listed_candidate'if not reasons else'review','reasons':reasons}) actual={'checks':checks,'equal_lumens_count':sum(r['lumens']=='800'for r in read_judged('candidates.csv')),'listed_candidate':[r['sku']for r in checks if r['comparison']=='listed_candidate']} if 'REPORT_HEADERS'in locals():headers=REPORT_HEADERS;output_rows=report elif '결과'in actual: output=actual['결과'];headers=list(output[0])if output else['결과'];output_rows=[[('예'if v is True else'아니오'if v is False else''if v is None else v)for v in row.values()]for row in output] else: headers=['검사항목','실제 결과'];output_rows=[[k,json.dumps(v,ensure_ascii=False)if isinstance(v,(list,dict))else v]for k,v in actual.items()] return actual,headers,output_rows,judgement_notes def at_path(value,path): for token in path: if isinstance(token,dict):value=next(x for x in value if all(x.get(k)==v for k,v in token.items())) else:value=value[token] return value def compare(value,op,expected): if op=='eq':return value==expected if op=='contains':return expected in value if op=='not_contains':return expected not in value raise ValueError('Unknown assertion operator') actual,headers,rows,notes=compute() expected=json.loads((BASE/'expected.json').read_text(encoding='utf-8')) base_checks=[{'field':k,'actual':actual.get(k),'expected':v,'pass':actual.get(k)==v,'passed':actual.get(k)==v}for k,v in expected.items()] fixture_inputs=json.loads((BASE/'boundary-inputs.json').read_text(encoding='utf-8')) fixture_expected=json.loads((BASE/'boundary-expected.json').read_text(encoding='utf-8')) boundary_results=[] for fixture in fixture_inputs: value,_,_,case_notes=compute(fixture['files']);oracle=fixture_expected[fixture['id']];assertions=[] if oracle.get('baseline_equivalent'): assertions=[{'path':[k],'actual':value.get(k),'expected':v,'pass':value.get(k)==v}for k,v in expected.items()] else: for assertion in oracle['assertions']: found=at_path(value,assertion['path']);ok=compare(found,assertion['op'],assertion['expected']) assertions.append(dict(assertion,actual=found,pass_=ok)) for assertion in assertions:assertion['pass']=assertion.pop('pass_') boundary_results.append({'id':fixture['id'],'description':fixture['description'],'actual':value,'judgement_notes':case_notes,'assertions':assertions,'pass':all(x['pass']for x in assertions)}) passed=all(x['pass']for x in base_checks)and all(x['pass']for x in boundary_results) report={'status':'PASS'if passed else'FAIL','synthetic_fixture':True,'executed_at_utc':_clock.datetime.now(_clock.timezone.utc).isoformat(),'python':platform.python_version(),'actual':actual,'judgement_notes':notes,'assertions':base_checks,'checks':base_checks,'regression_status':'PASS'if all(x['pass']for x in boundary_results)else'FAIL','regression_cases':boundary_results,'limits':LIMITS_TEXT} (BASE/'results.json').write_text(json.dumps(report,ensure_ascii=False,indent=2),encoding='utf-8') (BASE/'regression-results.json').write_text(json.dumps(boundary_results,ensure_ascii=False,indent=2),encoding='utf-8') with (BASE/REPORT_FILE).open('w',encoding='utf-8-sig',newline='')as f: writer=csv.writer(f);writer.writerow(headers);writer.writerows(rows) print(json.dumps({'status':report['status'],'baseline_fields':len(base_checks),'boundary_cases':len(boundary_results),'actual':actual},ensure_ascii=False)) if not passed:raise SystemExit(1)