from pathlib import Path import csv,json,datetime as _clock,platform,copy BASE=Path(__file__).resolve().parent NORMALIZE_FIELDS={'example.csv': ['번호', '위치', '기기', '온도단위', '문상태']} LIMITS_TEXT='합성 입력만 사용하며 실제 현장·안전·법률·성능 판정을 수행하지 않습니다.' REPORT_FILE='result.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,platform,datetime HERE=Path(__file__).resolve().parent source=read_judged('example.csv') from decimal import Decimal keys=['위치','기기','온도단위','문상태'];groups={} for r in source:groups.setdefault(tuple(r[k] for k in keys),[]).append(r) out=[] for key,items in groups.items(): temps=[Decimal(r['온도']) for r in items];hums=[Decimal(r['상대습도']) for r in items] out.append({'그룹':' / '.join(key),'기록수':len(items),'온도평균':str(sum(temps)/len(temps)),'상대습도평균':str(sum(hums)/len(hums)),'번호':','.join(r['번호'] for r in items)}) actual={'결과':out,'분리그룹수':len(groups),'같은조건반복번호':[r['번호'] for r in source if tuple(r[k] for k in keys)==('회의실 중앙','H01','C','닫힘')],'임의전체평균계산':False} 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)