Files
vibemake-pcb-studio/backend/tests/test_codex_entry.py
T
2026-11-10 19:04:27 +08:00

86 lines
5.1 KiB
Python

"""Approval and STEP delivery regressions; never calls a model or edits EDA."""
import sys, tempfile, unittest, zipfile
from pathlib import Path
from unittest.mock import patch
BACKEND=Path(__file__).resolve().parents[1]
sys.path[:0]=[str(BACKEND/'easyeda_backend'),str(BACKEND),str(BACKEND/'api')]
from design_runtime.delivery import normalize_step, inspect_file, freeze
from design_runtime.service import DesignService
from design_runtime.state import DesignError
from app.main import create_app
from app.config import Settings
from fastapi.testclient import TestClient
STEP=b"ISO-10303-21;\nHEADER;ENDSEC;\nDATA;\n#1=CARTESIAN_POINT('',(0.,0.,0.));\n#2=SHAPE_REPRESENTATION('',(#1),#3);\nENDSEC;\nEND-ISO-10303-21;\n"
class EntryTests(unittest.TestCase):
def setUp(self):
self.tmp=tempfile.TemporaryDirectory();self.addCleanup(self.tmp.cleanup);self.root=Path(self.tmp.name)
def test_api_cannot_bypass_review(self):
app=create_app(Settings(self.root,self.root/'unused',mode='real'),start_workers=False)
with TestClient(app) as c:
c.get('/api/v1/session')
response=c.post('/api/v1/commands',headers={'Origin':'http://127.0.0.1:5173'},json={'request_id':'bypass','action':'create','payload':{'description':'LED','selection_policy':'auto'}})
self.assertEqual(response.status_code,422)
self.assertIsNone(app.state.store.claim(False))
def test_core_cannot_bypass_review(self):
service=DesignService(self.root);self.addCleanup(service.close)
with patch.object(service,'_agent') as agent:
result=service.handle({'request_id':'bypass','action':'create','payload':{'description':'LED','selection_policy':'auto'}})
self.assertIn('审核',result['message']);agent.assert_not_called()
def test_step_direct_and_zipped(self):
path=self.root/'board.step';path.write_bytes(STEP);normalize_step(path)
with zipfile.ZipFile(path,'w') as z:z.writestr('board.stp',STEP)
normalize_step(path);self.assertEqual(path.read_bytes(),STEP)
def test_step_rejects_missing_geometry_and_multiple_assemblies(self):
path=self.root/'board.step';path.write_bytes(b'ISO-10303-21;END-ISO-10303-21;')
with self.assertRaises(DesignError):normalize_step(path)
with zipfile.ZipFile(path,'w') as z:
z.writestr('a.step',STEP);z.writestr('b.step',STEP)
with self.assertRaises(DesignError):normalize_step(path)
def test_step_rejects_archive_traversal(self):
path=self.root/'board.step'
with zipfile.ZipFile(path,'w') as z:z.writestr('../board.step',STEP)
with self.assertRaises(DesignError):normalize_step(path)
def test_no_ready_package_without_step(self):
items=[{'kind':k,'path':k} for k in ['native','schematic','pcb','pcb_preview','bom','model','render']]
with self.assertRaisesRegex(DesignError,'Incomplete'):
freeze(self.root,items,{}, {'passed':True})
class LiveRegressionTests(unittest.TestCase):
def test_later_start_event_is_explicit_in_model_context(self):
from unittest.mock import Mock
with tempfile.TemporaryDirectory() as directory:
agent=Mock();agent.call.return_value={'ok':True}
service=DesignService(directory,agent=agent);self.addCleanup(service.close)
task=service._create({'description':'先给方案,不开工'})
service._agent(task,'intake',{}, {},'first')
self.assertNotIn('execution_authorization',agent.call.call_args.args[1])
task.update(accepted_plan={'selection':{'recorded_at':'2026-11-10T05:00:00Z'}},selection_hash='accepted-hash',selected_option='A')
service._agent(task,'design-author',{'contract':{'comment':'先修订方案'}},{},'second')
auth=agent.call.call_args.args[1]['execution_authorization']
self.assertEqual(auth['action'],'user_approved_proposal_and_clicked_start')
self.assertEqual(auth['selection_hash'],'accepted-hash')
def test_empty_snapshot_focuses_schematic_without_exporting_nonexistent_netlist(self):
from design_runtime.eda import EDAController
from unittest.mock import Mock
import subprocess,json
controller=EDAController.__new__(EDAController)
controller.focus=Mock();adapter=Mock();controller.adapter=Mock(return_value=adapter)
def execute(code):
controller.focus.assert_called_once_with({},'schematic')
source='''const eda={sch_PrimitiveComponent:{getAll:async()=>[]},sch_PrimitiveWire:{getAll:async()=>[]},sch_ManufactureData:{getNetlistFile:async()=>{throw Error('must not export empty netlist')}}};
const AsyncFunction=Object.getPrototypeOf(async function(){}).constructor;
new AsyncFunction('eda', CODE)(eda).then(x=>console.log(JSON.stringify(x)));'''.replace('CODE',json.dumps(code))
result=subprocess.run(['node','-e',source],capture_output=True,text=True,check=True)
return json.loads(result.stdout)
adapter.execute.side_effect=execute
self.assertEqual(controller.semantic_snapshot({},'schematic'),{'netlist':{},'parts':[],'wires':[]})
def test_title_block_cannot_be_counted_as_a_real_component(self):
from design_runtime.eda import EDAController
with self.assertRaisesRegex(DesignError,'drawing sheet'):
EDAController.check_script('return {ok:true,parts:await eda.sch_PrimitiveComponent.getAll()};')
EDAController.check_script('return {ok:true,parts:await eda.sch_PrimitiveComponent.getAll("part")};')
if __name__=='__main__':unittest.main()