Files

83 lines
5.0 KiB
Python

import asyncio
import base64
import json
from pathlib import Path
import re
import tempfile
import unittest
from unittest.mock import patch
import zipfile
from codex_pcb.checks import classify_diagnostics, evaluate_verification
from codex_pcb import eda
from codex_pcb.exports import extract_archive, convert_schematic
from codex_pcb.delivery import inspect
class WarningGate(unittest.TestCase):
def test_native_warning_false_is_accepted_and_retained(self):
warning={'type':'warn','rule':'ATTRMATCHCODE','primitives':[{'id':x} for x in ['JP1','JP2','J4','J5','J6']]}
r=evaluate_verification(dict(schPassed=False,pcbPassed=True,schErrors=[warning],pcbErrors=[],schematicParts=104,pcbParts=104))
self.assertTrue(r['accepted']);self.assertEqual(r['warnings']['schematic'],[warning])
def test_error_unknown_missing_and_inconsistent_results_block(self):
for rows,ok in [([{'type':'error'}],True),([{'type':'warn'},{'rule':'UNKNOWN'}],False),([],False),(None,True),([],None),([{'type':'warn','list':[{'type':'error'}]}],True)]:
with self.subTest(rows=rows,ok=ok):self.assertFalse(classify_diagnostics(rows,ok)['passed'])
def test_nested_warning_and_mixed_errors(self):
self.assertTrue(classify_diagnostics([{'type':'warning','list':[{'rule':'LIB'}]}],False)['passed'])
self.assertFalse(classify_diagnostics([{'type':'warn'},{'type':'error'}],False)['passed'])
def test_missing_geometry_still_blocks_but_step_appearance_does_not(self):
with tempfile.TemporaryDirectory(dir=Path(__file__).parent) as tmp:
p=Path(tmp)/'assembly.step'
p.write_text("ISO-10303-21;\nHEADER;ENDSEC;DATA;#1=CARTESIAN_POINT('',(0.,0.,0.));#2=SHAPE_REPRESENTATION('',(#1),#3);ENDSEC;END-ISO-10303-21;")
self.assertTrue(inspect(p,'step')['warnings'])
p.write_text('not a model'*30)
with self.assertRaises(ValueError):inspect(p,'step')
class ExportSafety(unittest.TestCase):
def test_zip_escape_rejected(self):
with tempfile.TemporaryDirectory(dir=Path(__file__).parent) as tmp:
root=Path(tmp);p=root/'evil.zip'
with zipfile.ZipFile(p,'w') as z:z.writestr('../escape','no')
with self.assertRaises(ValueError):extract_archive(p,root/'output')
self.assertFalse((root/'escape').exists())
def test_svg_pages_converted_to_multipage_pdf(self):
from pypdf import PdfReader
with tempfile.TemporaryDirectory(dir=Path(__file__).parent) as tmp:
root=Path(tmp);p=root/'pages.zip'
with zipfile.ZipFile(p,'w') as z:
for n in range(2):z.writestr(f'page-{n}.svg','<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><text x="10" y="20">R1 GND</text></svg>')
pdf,pages=convert_schematic(p,root/'output')
self.assertEqual(len(PdfReader(pdf).pages),2)
class ChunkTransport(unittest.IsolatedAsyncioTestCase):
async def test_large_transfer_and_truncation_preserve_existing_file(self):
for truncated in [False,True]:
with tempfile.TemporaryDirectory(dir=Path(__file__).parent) as tmp:
folder=Path(tmp);dst=folder/'artifacts/large.bin';dst.parent.mkdir();dst.write_bytes(b'previous')
payload=bytes([37])*(9*1024*1024+17);calls=[]
async def invoke(args,code=None,timeout=210):
calls.append(code)
if 'const __files=[]' in code:return {'result':True,'files':[{'name':'large.bin','bytes':len(payload),'index':0}]}
if code.startswith('delete '):return True
begin,end=map(int,re.search(r'f.slice\((\d+),(\d+)\)',code).groups())
data=payload[begin:end]
if truncated and begin:data=data[:-1]
return {'base64':base64.b64encode(data).decode()}
async def lock():return (folder/'lock').open('a+')
t={'approval':{'hash':'test'},'state':'running','eda_session':'test'}
with patch.object(eda,'workspace',return_value=folder),patch.object(eda,'event'),patch.object(eda,'host_lock',side_effect=lock),patch.object(eda,'cli',side_effect=invoke),patch.object(eda,'EDA_LOCK',asyncio.Lock()):
if truncated:
with self.assertRaisesRegex(ValueError,'Truncated'):await eda.execute(t,'return true')
self.assertEqual(dst.read_bytes(),b'previous')
else:
await eda.execute(t,'return true');self.assertEqual(dst.read_bytes(),payload)
self.assertTrue(calls[-1].startswith('delete '));self.assertFalse(list(dst.parent.glob('*.partial')))
class ResumedToolCompatibility(unittest.IsolatedAsyncioTestCase):
async def test_old_eda_tool_dispatches_shared_preparation(self):
from unittest.mock import AsyncMock
from codex_pcb import app
task={'state':'running','approval':{'hash':'x'}}
prepared={'files':[{'kind':'step','path':'artifacts/board.step'}]}
with patch.object(app,'event'),patch.object(app,'frozen'),patch.object(app,'prepare_delivery',new_callable=AsyncMock,return_value=prepared) as prepare,patch.object(app,'execute',new_callable=AsyncMock) as execute:
result=await app.handle(task,'item/tool/call',{'tool':'pcb_eda','callId':'test','arguments':{'label':'Common delivery','code':json.dumps({'pcb_backend_tool':'prepare_delivery','schematic_id':'sch','pcb_id':'pcb'})}})
self.assertTrue(result['success']);prepare.assert_awaited_once_with(task,'sch','pcb');execute.assert_not_called()