from __future__ import annotations import json import os from pathlib import Path import subprocess import pytest ROOT = Path(__file__).resolve().parents[2] COMMON = ROOT / "integration" / "dxdesigner795" / "BridgeCommon.vbs" PROBE = ROOT / "integration" / "dxdesigner795" / "PartReplaceProbe.vbs" def _vbs_string(value: str) -> str: return '"' + value.replace('"', '""') + '"' def test_bridge_common_json_roundtrip_preserves_unicode(tmp_path: Path) -> None: # Catches signed AscW values being truncated into unrelated ASCII escapes. output_path = tmp_path / "unicode.json" wrapper = tmp_path / "unicode.vbs" wrapper.write_text( fr'''Option Explicit Dim Fso Dim CommonSource Dim Value Set Fso = CreateObject("Scripting.FileSystemObject") CommonSource = Fso.OpenTextFile({_vbs_string(str(COMMON))}, 1, False, 0).ReadAll ExecuteGlobal CommonSource Value = ChrW(&H6D4B) & ChrW(&H8BD5) & ChrW(-10179) & ChrW(-8576) DxWriteUtf8Atomic {_vbs_string(str(output_path))}, _ "{{""value"":""" & DxJsonEscape(Value) & """}}" ''', encoding="ascii", ) completed = subprocess.run( ["cscript", "//nologo", str(wrapper)], cwd=ROOT, check=False, capture_output=True, text=True, encoding="utf-8", errors="replace", ) assert completed.returncode == 0, completed.stdout + completed.stderr assert json.loads(output_path.read_bytes()) == {"value": "\u6d4b\u8bd5\U0001f680"} def _run_probe( tmp_path: Path, request: dict[str, object], *, fail_routes: bool = False, attribute_mode: str = "normal", ) -> tuple[bytes, dict[str, object]]: request_text = json.dumps(request, sort_keys=True, separators=(",", ":")) + "\n" return _run_probe_raw( tmp_path, request_text, fail_routes=fail_routes, attribute_mode=attribute_mode, ) def _run_probe_raw( tmp_path: Path, request_text: str, *, fail_routes: bool = False, attribute_mode: str = "normal", ) -> tuple[bytes, dict[str, object]]: run_dir = tmp_path / "run" run_dir.mkdir(exist_ok=True) request_path = run_dir / "request.json" request_path.write_text(request_text, encoding="utf-8", newline="") wrapper = tmp_path / "run_probe.vbs" wrapper.write_text( fr'''Option Explicit Dim RouteCalls Dim FailRoutes Dim AttributeMode Sub FailRouteIfRequested(ByVal Number, ByVal Source, ByVal Description) If FailRoutes Then Err.Raise Number, Source, Description End Sub Class FakeScripting Public Function GetEnvVariable(ByVal Name) If Name = "DXTOOLS_HOME" Then GetEnvVariable = {_vbs_string(str(tmp_path))} Else GetEnvVariable = "" End If End Function End Class Class FakeAttribute Public Name Public Value Public TextString Public Color Public Font Public Size Public Orientation Public Origin Public Visible Public Parent Private Location Public Sub SetLocation(ByVal X, ByVal Y) Set Location = New FakeLocation Location.X = X Location.Y = Y End Sub Public Function GetLocation Select Case AttributeMode Case "location_unsupported_x" Set GetLocation = New FakeUnsupportedXLocation GetLocation.Y = Location.Y Case "location_read_error_y" Set GetLocation = New FakeReadErrorYLocation GetLocation.X = Location.X Case Else Set GetLocation = Location End Select End Function End Class Class FakeFailingAttribute Public Name Public Value Public Color Public Font Public Size Public Orientation Public Origin Public Visible Public Parent Private Location Public Sub SetLocation(ByVal X, ByVal Y) Set Location = New FakeLocation Location.X = X Location.Y = Y End Sub Public Property Get TextString Err.Raise 53001, "FakeFailingAttribute.TextString", "text unavailable" End Property Public Function GetLocation Set GetLocation = Location End Function End Class Class FakeLocation Public X Public Y End Class Class FakeUnsupportedXLocation Public Y Public Property Get X Err.Raise 438, "FakeUnsupportedXLocation.X", "x unsupported" End Property End Class Class FakeReadErrorYLocation Public X Public Property Get Y Err.Raise 53003, "FakeReadErrorYLocation.Y", "y unavailable" End Property End Class Class FakeParameterOwner End Class Class FakeAttributeCollection Private ValuesByKey Private Sub Class_Initialize() Set ValuesByKey = CreateObject("Scripting.Dictionary") End Sub Public Sub Add(ByRef Value, ByVal Key) ValuesByKey.Add CStr(Key), Value End Sub Public Property Get Item(ByVal Key) Set Item = ValuesByKey.Item(CStr(Key)) End Property Public Property Get Items If AttributeMode = "keyed_only" Or _ AttributeMode = "mixed_collection_errors" Then Err.Raise 438, "FakeAttributeCollection.Items", "items unsupported" End If Items = ValuesByKey.Items End Property End Class Class FakeGate Public Name Public UnitNumber End Class Class FakePin Public Number Public Name Public X Public Y Public NetIdentity End Class Class FakeComponent Public LogicalIdentity Public PartNumber Public RefDes Public Hierarchy Public Units Public Gates Public SymbolName Public OriginX Public OriginY Public X Public Y Public Rotation Public Mirrored Public Pins Public Nets Private AttributeItems Private AttributeAccessCount Public Property Let Attributes(ByVal Value) AttributeItems = Value End Property Public Property Set Attributes(ByVal Value) Set AttributeItems = Value End Property Public Property Get Attributes If AttributeMode = "key_source_mixed" Then AttributeAccessCount = AttributeAccessCount + 1 If AttributeAccessCount = 3 Then Err.Raise 53005, "FakeComponent.Attributes", _ "key source object read failure" End If If AttributeAccessCount = 4 Then Err.Raise 438, "FakeComponent.Attributes", _ "key source variant unsupported" End If End If If AttributeMode = "mixed_collection_errors" Then AttributeAccessCount = AttributeAccessCount + 1 If AttributeAccessCount Mod 2 = 1 Then Err.Raise 53004, "FakeComponent.Attributes", _ "attributes transient read failure" End If End If If AttributeMode = "attributes_unsupported" Then Err.Raise 438, "FakeComponent.Attributes", "attributes unsupported" End If If AttributeMode = "attributes_read_error" Then Err.Raise 53002, "FakeComponent.Attributes", "attributes unavailable" End If If IsObject(AttributeItems) Then Set Attributes = AttributeItems Else Attributes = AttributeItems End If End Property End Class Class FakeFailingComponent Public LogicalIdentity Public PartNumber Public RefDes Public Hierarchy Public Units Public Gates Public SymbolName Public OriginX Public OriginY Public X Public Y Public Rotation Public Mirrored Public Nets Private AttributeItems Private AttributeAccessCount Public Property Let Attributes(ByVal Value) AttributeItems = Value End Property Public Property Set Attributes(ByVal Value) Set AttributeItems = Value End Property Public Property Get Attributes If AttributeMode = "key_source_mixed" Then AttributeAccessCount = AttributeAccessCount + 1 If AttributeAccessCount = 3 Then Err.Raise 53005, "FakeFailingComponent.Attributes", _ "key source object read failure" End If If AttributeAccessCount = 4 Then Err.Raise 438, "FakeFailingComponent.Attributes", _ "key source variant unsupported" End If End If If AttributeMode = "mixed_collection_errors" Then AttributeAccessCount = AttributeAccessCount + 1 If AttributeAccessCount Mod 2 = 1 Then Err.Raise 53004, "FakeFailingComponent.Attributes", _ "attributes transient read failure" End If End If If AttributeMode = "attributes_unsupported" Then Err.Raise 438, "FakeFailingComponent.Attributes", "attributes unsupported" End If If AttributeMode = "attributes_read_error" Then Err.Raise 53002, "FakeFailingComponent.Attributes", "attributes unavailable" End If If IsObject(AttributeItems) Then Set Attributes = AttributeItems Else Attributes = AttributeItems End If End Property Public Property Get Pins Err.Raise 51001, "FakeFailingComponent.Pins", "pins unavailable" End Property End Class Class FakeApplication Public Version Public Build Public ProjectPath Public Modified Private ComponentItems Private Sub Class_Initialize() Dim Values(1) Dim ComponentOne Dim ComponentTwo Dim AttributesOne Dim AttributesTwo Dim GatesOne(1) Dim GatesTwo(0) Dim PinsOne(1) Dim NetsOne(1) Dim NetsTwo(0) Dim Item Dim Owner Version = "7.9.5" Build = "7.9.5.1234" ProjectPath = "C:\fixture\disposable\design.prj" Modified = False Set ComponentOne = New FakeComponent ComponentOne.LogicalIdentity = "/TOP/R1" ComponentOne.PartNumber = "OLD-1" ComponentOne.RefDes = "R1" ComponentOne.Hierarchy = "/TOP" ComponentOne.Units = 2 Set Item = New FakeGate Item.Name = "A" Item.UnitNumber = 1 Set GatesOne(0) = Item Set Item = New FakeGate Item.Name = "B" Item.UnitNumber = 2 Set GatesOne(1) = Item ComponentOne.Gates = GatesOne ComponentOne.SymbolName = "RES" ComponentOne.OriginX = 1.25 ComponentOne.OriginY = 2.5 ComponentOne.X = 12.5 ComponentOne.Y = -7.25 ComponentOne.Rotation = 90 ComponentOne.Mirrored = False Set AttributesOne = New FakeAttributeCollection Set Owner = New FakeParameterOwner Set Item = New FakeAttribute Item.Name = "Tolerance" Item.Value = "5%" Item.TextString = "5 percent" Item.Color = "red" Item.Font = "Arial" Item.Size = 10 Item.Orientation = 90 Item.Origin = "lower_left" Item.Visible = True Set Item.Parent = Owner Item.SetLocation 101.5, -24.25 AttributesOne.Add Item, "Tolerance" Set Item = New FakeAttribute Item.Name = ChrW(&H63CF) & ChrW(&H8FF0) Item.Value = ChrW(&H6D4B) & ChrW(&H8BD5) Item.TextString = "description text" Item.Color = "blue" Item.Font = "Arial" Item.Size = 8 Item.Orientation = 0 Item.Origin = "upper_right" Item.Visible = False Set Item.Parent = Owner Item.SetLocation 102, -25 AttributesOne.Add Item, "Description" Set ComponentOne.Attributes = AttributesOne Set Item = New FakePin Item.Number = "1" Item.Name = "A" Item.X = 12.5 Item.Y = -7.0 Item.NetIdentity = "NET-1" Set PinsOne(0) = Item Set Item = New FakePin Item.Number = "2" Item.Name = "B" Item.X = 12.5 Item.Y = -7.5 Item.NetIdentity = ChrW(&H7F51) & ChrW(&H7EDC) & "-2" Set PinsOne(1) = Item ComponentOne.Pins = PinsOne NetsOne(0) = "NET-1" NetsOne(1) = ChrW(&H7F51) & ChrW(&H7EDC) & "-2" ComponentOne.Nets = NetsOne Set ComponentTwo = New FakeFailingComponent ComponentTwo.LogicalIdentity = "/TOP/U1" ComponentTwo.PartNumber = ChrW(&H5668) & ChrW(&H4EF6) & "-2" ComponentTwo.RefDes = "U1" ComponentTwo.Hierarchy = "/TOP" ComponentTwo.Units = 1 Set Item = New FakeGate Item.Name = "MAIN" Item.UnitNumber = 1 Set GatesTwo(0) = Item ComponentTwo.Gates = GatesTwo ComponentTwo.SymbolName = "IC" ComponentTwo.OriginX = 20 ComponentTwo.OriginY = 30 ComponentTwo.X = 22 ComponentTwo.Y = 33 ComponentTwo.Rotation = 0 ComponentTwo.Mirrored = True Set AttributesTwo = New FakeAttributeCollection Set Owner = New FakeParameterOwner Set Item = New FakeFailingAttribute Item.Name = "Value" Item.Value = "MCU" Item.Color = "green" Item.Font = "Courier" Item.Size = 12 Item.Orientation = 180 Item.Origin = "center" Item.Visible = True Set Item.Parent = Owner Item.SetLocation 202, 88.5 AttributesTwo.Add Item, "Value" Set Item = New FakeAttribute Item.Name = "Part Number" Item.Value = "0010" Item.TextString = "0603" Item.Color = "green" Item.Font = "Courier" Item.Size = 12 Item.Orientation = 180 Item.Origin = "center" Item.Visible = True Set Item.Parent = Owner Item.SetLocation 203, 88.5 AttributesTwo.Add Item, "Part Number" Set ComponentTwo.Attributes = AttributesTwo NetsTwo(0) = "BUS-1" ComponentTwo.Nets = NetsTwo Set Values(0) = ComponentOne Set Values(1) = ComponentTwo ComponentItems = Values End Sub Public Property Get DesignComponents DesignComponents = ComponentItems End Property Public Function OpenReplacePartDialog RouteCalls = RouteCalls & "native_replace_part|" FailRouteIfRequested 52002, "FakeApplication.OpenReplacePartDialog", _ "native replace unavailable" OpenReplacePartDialog = True End Function Public Property Get ReplacePartCompleted RouteCalls = RouteCalls & "completion_observation|" FailRouteIfRequested 52003, "FakeApplication.ReplacePartCompleted", _ "completion unavailable" ReplacePartCompleted = True End Property Public Function Undo RouteCalls = RouteCalls & "undo|" FailRouteIfRequested 52004, "FakeApplication.Undo", "undo unavailable" Undo = True End Function Public Function Save RouteCalls = RouteCalls & "save|" FailRouteIfRequested 52005, "FakeApplication.Save", "save unavailable" Save = True End Function Public Function OpenProject RouteCalls = RouteCalls & "open_project|" FailRouteIfRequested 52006, "FakeApplication.OpenProject", _ "open unavailable" OpenProject = True End Function Public Function CloseProject RouteCalls = RouteCalls & "close_project|" FailRouteIfRequested 52007, "FakeApplication.CloseProject", _ "close unavailable" CloseProject = True End Function Public Function RunPackager RouteCalls = RouteCalls & "packager|" FailRouteIfRequested 52008, "FakeApplication.RunPackager", _ "packager unavailable" RunPackager = True End Function Public Function RunERC RouteCalls = RouteCalls & "erc|" FailRouteIfRequested 52009, "FakeApplication.RunERC", "erc unavailable" RunERC = True End Function Public Function RunNetlist RouteCalls = RouteCalls & "netlist|" FailRouteIfRequested 52010, "FakeApplication.RunNetlist", _ "netlist unavailable" RunNetlist = True End Function Public Function CComp RouteCalls = RouteCalls & "ccomp_research|" FailRouteIfRequested 52011, "FakeApplication.CComp", _ "ccomp unavailable" CComp = True End Function End Class Class FakeActiveView Public Name Private Sub Class_Initialize() Name = "Sheet1" End Sub Public Function SelectExactSet RouteCalls = RouteCalls & "exact_set_selection|" FailRouteIfRequested 52001, "FakeActiveView.SelectExactSet", _ "selection unavailable" SelectExactSet = True End Function End Class Dim Fso Dim CommonSource Dim ProbeSource Dim Scripting Dim Application Dim ActiveView Set Fso = CreateObject("Scripting.FileSystemObject") CommonSource = Fso.OpenTextFile({_vbs_string(str(COMMON))}, 1, False, 0).ReadAll ExecuteGlobal CommonSource ProbeSource = Fso.OpenTextFile({_vbs_string(str(PROBE))}, 1, False, 0).ReadAll ExecuteGlobal ProbeSource Set Scripting = New FakeScripting Set Application = New FakeApplication Set ActiveView = New FakeActiveView RouteCalls = "" FailRoutes = {str(fail_routes)} AttributeMode = {_vbs_string(attribute_mode)} DxRunPartReplaceProbe "run\request.json", "run\profile.json" DxWriteUtf8Atomic {_vbs_string(str(run_dir / "route_calls.txt"))}, RouteCalls ''', encoding="ascii", ) completed = subprocess.run( ["cscript", "//nologo", str(wrapper)], cwd=ROOT, check=False, capture_output=True, text=True, encoding="utf-8", errors="replace", env={**os.environ, "PYTHONPATH": str(ROOT / "src")}, ) assert completed.returncode == 0, completed.stdout + completed.stderr profile_bytes = (run_dir / "profile.json").read_bytes() return profile_bytes, json.loads(profile_bytes) def test_probe_accepts_only_exact_canonical_versioned_request(tmp_path: Path) -> None: # Catches authorization being granted by a substring match instead of the complete schema. _, profile = _run_probe_raw( tmp_path, '{"disposable_project_marker":true,"format_version":1,' '"operator_confirmation":true}\n', ) assert profile["safety"] == { "disposable_project_marker": True, "mutating_probe_attempted": False, "mutating_probe_authorized": True, "operator_confirmation": True, "request_valid": True, } @pytest.mark.parametrize( "request_text", ( 'junk{"disposable_project_marker":true,"format_version":1,' '"operator_confirmation":true}\n', '{"disposable_project_marker":true,"format_version":1,' '"operator_confirmation":true}\njunk', '{"disposable_project_marker":true,"disposable_project_marker":true,' '"format_version":1,"operator_confirmation":true}\n', '{"disposable_project_marker":true,"extra":false,"format_version":1,' '"operator_confirmation":true}\n', '{"disposable_project_marker":"true","format_version":1,' '"operator_confirmation":true}\n', '{"format_version":1,"operator_confirmation":true}\n', '{"disposable_project_marker":TRUE,"format_version":1,' '"operator_confirmation":true}\n', ), ) def test_probe_rejects_noncanonical_authorization_requests( tmp_path: Path, request_text: str, ) -> None: # Catches junk, duplicates, extra fields, missing fields, and alternate truthy types. _, profile = _run_probe_raw(tmp_path, request_text) assert profile["safety"] == { "disposable_project_marker": False, "mutating_probe_attempted": False, "mutating_probe_authorized": False, "operator_confirmation": False, "request_valid": False, } def test_probe_source_is_ascii_and_does_not_enable_unsafe_replace() -> None: # Safety lint: catches prohibited attachment and mutation routes entering VBS source. text = PROBE.read_text(encoding="ascii") assert "ChangeComponentPreserveRefdes" not in text assert "SendKeys" not in text assert "GetObject" not in text assert "ViewDraw.Application" not in text assert ".ChangeComponent " not in text assert "Scripting.GetEnvVariable(\"DXTOOLS_HOME\")" in text assert '"production_replace_route":"native_replace_part"' in text def test_bridge_common_source_is_ascii_and_has_narrow_error_scopes() -> None: # Safety lint only; functional helper behavior is covered by the cscript test. text = COMMON.read_text(encoding="ascii") assert "ADODB.Stream" in text if "On Error Resume Next" in text: assert "Err.Number" in text assert "On Error GoTo 0" in text def test_probe_emits_deterministic_versioned_profile_from_injected_context( tmp_path: Path, ) -> None: # Catches profile output losing build/project identity, interface coverage, or stable ordering. request = { "format_version": 1, "disposable_project_marker": True, "operator_confirmation": True, } first_bytes, first = _run_probe(tmp_path, request) second_bytes, second = _run_probe(tmp_path, request) assert first_bytes == second_bytes assert first == second assert first["format_version"] == 1 assert first["dxdesigner"] == {"build": "7.9.5.1234", "version": "7.9.5"} assert first["project"] == { "active_view": "Sheet1", "dirty": False, "identity": r"C:\fixture\disposable\design.prj", } assert first["enumeration"] == { "available": True, "component_count": 2, "route": "Application.DesignComponents", } assert set(first["interfaces"]) == { "attributes", "hierarchy", "logical_identity", "mirror", "nets", "origin_x", "origin_y", "part_number", "parameter_probe", "pins", "gates", "position_x", "position_y", "refdes", "rotation", "symbol_identity", "units", } assert first["interfaces"]["part_number"]["available"] is True assert first["interfaces"]["parameter_probe"] == { "available": True, "route": "component.Attributes", } assert first["interfaces"]["pins"]["available"] is False assert first["production_replace_route"] == "native_replace_part" assert first["live_acceptance"] == { "checked": False, "reason": "live_795_host_not_exercised", } def test_probe_serializes_exact_component_values_and_per_attempt_errors( tmp_path: Path, ) -> None: # Catches successful component reads being discarded or fallback errors being overwritten. _, profile = _run_probe( tmp_path, { "format_version": 1, "disposable_project_marker": False, "operator_confirmation": False, }, ) components = profile["components"] assert [component["logical_identity"] for component in components] == [ "/TOP/R1", "/TOP/U1", ] first = components[0] assert first["hierarchy"] == "/TOP" assert first["part_number"] == "OLD-1" assert first["refdes"] == "R1" assert first["units"] == 2 assert first["gates"] == [ {"name": "A", "unit_number": 1}, {"name": "B", "unit_number": 2}, ] assert first["symbol_identity"] == "RES" assert first["origin"] == {"x": 1.25, "y": 2.5} assert first["position"] == {"x": 12.5, "y": -7.25} assert first["rotation"] == 90 assert first["mirror"] is False assert first["attributes"] == [ {"name": "Tolerance", "value": "5%"}, {"name": "\u63cf\u8ff0", "value": "\u6d4b\u8bd5"}, ] assert first["pins"] == [ {"name": "A", "net_identity": "NET-1", "number": "1", "x": 12.5, "y": -7}, { "name": "B", "net_identity": "\u7f51\u7edc-2", "number": "2", "x": 12.5, "y": -7.5, }, ] assert first["nets"] == ["NET-1", "\u7f51\u7edc-2"] second = components[1] assert second["part_number"] == "\u5668\u4ef6-2" assert second["pins"] is None pin_errors = [ error for error in second["api_errors"] if ".Pins." in error["operation"] ] assert [error["operation"] for error in pin_errors] == [ "component[1].Pins.object", "component[1].Pins.variant", ] assert [error["number"] for error in pin_errors] == [51001, 51001] assert [error["source"] for error in pin_errors] == [ "FakeFailingComponent.Pins", "FakeFailingComponent.Pins", ] assert [error["description"] for error in pin_errors] == [ "pins unavailable", "pins unavailable", ] assert profile["interfaces"]["pins"]["available"] is False def test_probe_records_read_only_attribute_presentation_routes_and_key_queries( tmp_path: Path, ) -> None: # Catches parameter text coordinates being conflated with component placement, # and keeps unsupported routes separate from read failures. _, profile = _run_probe( tmp_path, { "format_version": 1, "disposable_project_marker": False, "operator_confirmation": False, }, ) first_attributes = profile["components"][0]["attributes"] assert first_attributes == [ {"name": "Tolerance", "value": "5%"}, {"name": "\u63cf\u8ff0", "value": "\u6d4b\u8bd5"}, ] first_probe = profile["components"][0]["parameter_probe"] assert first_probe["enumeration"] == { "count": 2, "route": "component.Attributes", "status": "supported", } tolerance = next( item for item in first_probe["instances"] if item["name"] == {"status": "supported", "value": "Tolerance"} ) assert tolerance["value"] == {"status": "supported", "value": "5%"} assert tolerance["text_string"] == { "status": "supported", "value": "5 percent", } assert tolerance["text_location"] == { "status": "supported", "x": 101.5, "y": -24.25, } assert tolerance["presentation"] == { "color": {"status": "supported", "value": "red"}, "font": {"status": "supported", "value": "Arial"}, "orientation": {"status": "supported", "value": 90}, "origin": {"status": "supported", "value": "lower_left"}, "size": {"status": "supported", "value": 10}, "visible": {"status": "supported", "value": True}, } assert tolerance["parent_type"] == { "status": "supported", "value": "FakeParameterOwner", } second_probe = profile["components"][1]["parameter_probe"] assert { key: {field: query[field] for field in ("exists", "item_type", "status")} for key, query in second_probe["key_queries"].items() } == { "Part Label": {"exists": False, "item_type": None, "status": "unsupported"}, "Part Number": { "exists": True, "item_type": "FakeAttribute", "status": "supported", }, "Value": { "exists": True, "item_type": "FakeFailingAttribute", "status": "supported", }, "Value1": {"exists": False, "item_type": None, "status": "unsupported"}, } value_attribute = next( item for item in second_probe["instances"] if item["name"] == {"status": "supported", "value": "Value"} ) assert value_attribute["text_string"] == {"status": "read_error", "value": None} assert { "description": "text unavailable", "number": 53001, "operation": "component[1].Attributes[0].TextString", "source": "FakeFailingAttribute.TextString", } in profile["api_errors"] missing_key_errors = [ error for error in profile["api_errors"] if error["operation"] == "component[1].Attributes.key[Value1]" ] assert len(missing_key_errors) == 1 assert missing_key_errors[0]["number"] != 0 assert missing_key_errors[0]["description"] @pytest.mark.parametrize( ("attribute_mode", "status", "error_number"), ( ("attributes_unsupported", "unsupported", 438), ("attributes_read_error", "read_error", 53002), ), ) def test_parameter_probe_classifies_attribute_enumeration_failures_and_keeps_keys( tmp_path: Path, attribute_mode: str, status: str, error_number: int, ) -> None: # Catches an unavailable Attributes collection becoming a generic read error, # or suppressing the required four key capability results. _, profile = _run_probe( tmp_path, { "format_version": 1, "disposable_project_marker": False, "operator_confirmation": False, }, attribute_mode=attribute_mode, ) probe = profile["components"][0]["parameter_probe"] assert probe["enumeration"] == { "count": 0, "route": "component.Attributes", "status": status, } assert probe["instances"] == [] assert probe["key_queries"] == { key: {"exists": False, "item_type": None, "status": status} for key in ("Value", "Value1", "Part Number", "Part Label") } assert any( error["number"] == error_number and error["operation"] == "component[0].Attributes.object" for error in profile["api_errors"] ) @pytest.mark.parametrize( ("attribute_mode", "status", "operation", "error_number"), ( ("location_unsupported_x", "unsupported", "GetLocation.X", 438), ("location_read_error_y", "read_error", "GetLocation.Y", 53003), ), ) def test_parameter_probe_aggregates_text_location_field_statuses( tmp_path: Path, attribute_mode: str, status: str, operation: str, error_number: int, ) -> None: # Catches a supported GetLocation call hiding an unsupported or failed axis. _, profile = _run_probe( tmp_path, { "format_version": 1, "disposable_project_marker": False, "operator_confirmation": False, }, attribute_mode=attribute_mode, ) tolerance = next( item for item in profile["components"][0]["parameter_probe"]["instances"] if item["name"]["value"] == "Tolerance" ) assert tolerance["text_location"]["status"] == status assert any( error["number"] == error_number and error["operation"].endswith(operation) for error in profile["api_errors"] ) def test_parameter_probe_preserves_bstr_numeric_text_and_key_read_evidence( tmp_path: Path, ) -> None: # Catches BSTR values losing leading zeros and key probes proving only existence. _, profile = _run_probe( tmp_path, { "format_version": 1, "disposable_project_marker": False, "operator_confirmation": False, }, ) query = profile["components"][1]["parameter_probe"]["key_queries"]["Part Number"] assert query["status"] == "supported" assert query["instance"]["name"] == { "status": "supported", "value": "Part Number", } assert query["instance"]["value"] == {"status": "supported", "value": "0010"} assert query["instance"]["text_string"] == { "status": "supported", "value": "0603", } def test_parameter_probe_queries_keys_when_attributes_are_keyed_only( tmp_path: Path, ) -> None: # Catches an enumeration fallback failure suppressing usable Item(key) routes. _, profile = _run_probe( tmp_path, { "format_version": 1, "disposable_project_marker": False, "operator_confirmation": False, }, attribute_mode="keyed_only", ) probe = profile["components"][1]["parameter_probe"] assert probe["enumeration"]["status"] == "unsupported" assert probe["instances"] == [] assert probe["key_queries"]["Value"]["instance"]["value"] == { "status": "supported", "value": "MCU", } assert probe["key_queries"]["Part Number"]["instance"]["text_string"] == { "status": "supported", "value": "0603", } assert probe["key_queries"]["Value1"] == { "exists": False, "item_type": None, "status": "unsupported", } assert probe["key_queries"]["Part Label"] == { "exists": False, "item_type": None, "status": "unsupported", } def test_parameter_probe_retains_read_error_over_later_unsupported_collection_error( tmp_path: Path, ) -> None: # Catches the initial COM read failure being overwritten by an .Items fallback error. _, profile = _run_probe( tmp_path, { "format_version": 1, "disposable_project_marker": False, "operator_confirmation": False, }, attribute_mode="mixed_collection_errors", ) probe = profile["components"][0]["parameter_probe"] assert probe["enumeration"]["status"] == "read_error" assert set(probe["key_queries"]) == {"Value", "Value1", "Part Number", "Part Label"} errors = [ error for error in profile["api_errors"] if error["operation"].startswith("component[0].Attributes") ] assert [error["number"] for error in errors][:2] == [53004, 438] def test_parameter_probe_records_both_key_source_attempt_errors( tmp_path: Path, ) -> None: # Catches an object-read failure being replaced by the variant fallback error. _, profile = _run_probe( tmp_path, { "format_version": 1, "disposable_project_marker": False, "operator_confirmation": False, }, attribute_mode="key_source_mixed", ) probe = profile["components"][0]["parameter_probe"] assert probe["enumeration"]["status"] == "supported" assert probe["key_queries"] == { key: {"exists": False, "item_type": None, "status": "read_error"} for key in ("Value", "Value1", "Part Number", "Part Label") } key_source_errors = [ error for error in profile["api_errors"] if error["operation"].startswith("component[0].Attributes.key_source") ] assert key_source_errors == [ { "description": "key source object read failure", "number": 53005, "operation": "component[0].Attributes.key_source.object", "source": "FakeComponent.Attributes", }, { "description": "key source variant unsupported", "number": 438, "operation": "component[0].Attributes.key_source.variant", "source": "FakeComponent.Attributes", }, ] def test_authorized_probe_keeps_candidate_routes_read_only( tmp_path: Path, ) -> None: # Catches a disposable authorization accidentally enabling a mutating probe call. _, profile = _run_probe( tmp_path, { "format_version": 1, "disposable_project_marker": True, "operator_confirmation": True, }, ) assert (tmp_path / "run" / "route_calls.txt").read_text(encoding="utf-8-sig") == ( "completion_observation|" ) for name, route in profile["routes"].items(): if name == "completion_observation": assert route["attempted"] is True assert route["available"] is True assert route["attempts"][0]["error"] is None else: assert route["attempted"] is False, name assert route["available"] is False, name assert profile["production_replace_route"] == "native_replace_part" assert profile["routes"]["ccomp_research"]["production_enabled"] is False def test_unauthorized_probe_runs_only_read_only_route_candidates(tmp_path: Path) -> None: # Catches a possibly mutating API call occurring without both authorization fields. _, profile = _run_probe( tmp_path, { "format_version": 1, "disposable_project_marker": False, "operator_confirmation": True, }, ) assert (tmp_path / "run" / "route_calls.txt").read_text(encoding="utf-8-sig") == ( "completion_observation|" ) assert profile["routes"]["completion_observation"]["attempted"] is True assert profile["routes"]["completion_observation"]["available"] is True for name, route in profile["routes"].items(): if name != "completion_observation": assert route["attempted"] is False, name assert route["available"] is False, name def test_probe_retains_read_only_route_errors_in_attempt_order(tmp_path: Path) -> None: # Catches a read-only route failure being hidden while mutation candidates stay dormant. _, profile = _run_probe( tmp_path, { "format_version": 1, "disposable_project_marker": True, "operator_confirmation": True, }, fail_routes=True, ) expected_names = list(profile["routes"]) assert list(profile["routes"]) == expected_names route_errors = [ error for error in profile["api_errors"] if error["operation"].startswith("route.") ] assert [error["number"] for error in route_errors] == [52003] for name in expected_names: route = profile["routes"][name] if name == "completion_observation": assert route["attempted"] is True assert route["available"] is False assert route["attempts"][0]["error"] == route_errors[0] else: assert route["attempted"] is False assert route["available"] is False assert route["attempts"][0]["error"] is None assert profile["routes"]["ccomp_research"]["production_enabled"] is False def test_probe_records_route_fallbacks_and_exact_api_errors(tmp_path: Path) -> None: # Catches an unavailable route being silently enabled or an API error losing evidence. _, profile = _run_probe( tmp_path, { "format_version": 1, "disposable_project_marker": False, "operator_confirmation": True, }, ) assert profile["safety"] == { "disposable_project_marker": False, "mutating_probe_attempted": False, "mutating_probe_authorized": False, "operator_confirmation": True, "request_valid": True, } assert profile["routes"]["native_replace_part"]["attempted"] is False assert profile["routes"]["native_replace_part"]["available"] is False assert profile["routes"]["native_replace_part"]["manual_fallback"] == ( "operator_open_native_replace_part" ) assert profile["routes"]["ccomp_research"]["production_enabled"] is False assert profile["routes"]["ccomp_research"]["attempted"] is False assert { "description": "pins unavailable", "number": 51001, "operation": "component[1].Pins.variant", "source": "FakeFailingComponent.Pins", } in profile["api_errors"]