"""Verify three vision asset renames and reverse-order undo in one live PLCSharp editor.""" import json import shutil import sys from pathlib import Path from mcp_smoke import Client ASSETS = (("Cameras", "CAM1", "检测相机"), ("ImageDatas", "模板", "全局模板"), ("LocalImageDatas", "局部", "局部模板")) STEPS = (((0, "Camera"),), ((1, "Image"), (4, "Image")), ((3, "Image"), (6, "Image"), (23, "Image"), (33, "TemplateName"), (40, "TemplateName"), (42, "TemplateName"))) def prepare(sample, root): shutil.copytree(sample, root) vision = root / "configuration/vision.json" data = json.loads(vision.read_bytes()) function, = data["VisionFunctions"] for (_, old, _), steps in zip(ASSETS, STEPS): for kind, key in steps: function["VisionFlows"].append(dict(Type=kind, Comment=old, StringParams={key: old}, DoubleParams={}, LongParams={}, IntParams={}, BoolParams={})) vision.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8") caller, = (p for p in root.rglob("*.cs") if "Controller.DI.FirstOrDefault" in p.read_text(encoding="utf-8")) source = caller.read_text(encoding="utf-8") lines = [ 'model.VisionsModel.Cameras.FirstOrDefault(c => c.Name == "CAM1")', 'model.VisionsModel.Cameras.FirstOrDefault(c => c.Name == flow.Step.ToString())', 'model.GetImageData("模板")', 'model.GetImageData(flow.Step.ToString())', 'model.GetVisionFunction("检查").LocalImageDatas.FirstOrDefault(c => c.Name == "局部")', 'model.GetVisionFunction("检查").LocalImageDatas.FirstOrDefault(c => c.Name == flow.Step.ToString())', ] pos = source.rindex(" }") caller.write_bytes((source[:pos] + "".join(f" _ = {line};\n" for line in lines) + source[pos:]).encode()) def verify(exe, root): def snapshot(): return {p.relative_to(root): p.read_bytes() for p in root.rglob("*") if p.is_file()} original = snapshot() hw = Path("configuration/hardware.json") client = Client(exe, root, "--allow-write") try: assert client.call("get_project_summary")["source"] == "editor" history, manual = [], [] for (kind, old, new), steps in zip(ASSETS, STEPS): item, = (r for r in client.call("list_objects", kind=kind)["items"] if r["name"] == old) before = snapshot() if kind == "Cameras": result = client.request("tools/call", {"name": "preview_vision_asset_rename", "arguments": {"kind": kind, "id": item["id"], "newName": new}}) assert result["isError"] and before == snapshot() continue draft = client.call("preview_vision_asset_rename", kind=kind, id=item["id"], newName=new) plan = draft["Rename"] assert len(plan["VisionReferences"]) == len(steps), plan edit, = plan["Scripts"] hit, = plan["ManualReferences"] manual.append((kind, hit["Name"], hit["line"], hit["expression"])) assert plan["Compiled"] and hit["confidence"] == "dynamic" and before == snapshot() assert edit["After"] == edit["Before"].replace(f'"{old}"', f'"{new}"') print("PREVIEW", draft["DraftId"], manual[-1], flush=True) assert client.call("apply_changes", confirmed=True, draftId=draft["DraftId"])["Status"] == "saved" assert client.call("get_object", kind=kind, id=item["id"])["Name"] == new assert client.call("get_object", kind="Workflows", id=edit["Id"])["Code"] == edit["After"] after = snapshot() assert set(after) == set(before) vision = Path("configuration/vision.json") paths = {vision, Path(edit["Path"])} assert {p for p in before if after[p] != before[p]} == paths expected = json.loads(before[vision]) if kind != "Cameras": next(r for r in expected[kind] if r["ID"].lower() == item["id"].lower())["Name"] = new function, = expected["VisionFunctions"] for typ, key in steps: step, = (s for s in function["VisionFlows"] if s["Type"] == typ) step["StringParams"][key] = new assert json.loads(after[vision]) == expected history.append((draft["DraftId"], before, kind, item["id"], old)) for draft_id, before, kind, object_id, old in reversed(history): undo = client.call("preview_undo", draftId=draft_id) assert undo["Rename"]["Compiled"] and undo["Rename"]["UndoOf"] == draft_id assert client.call("apply_changes", confirmed=True, draftId=undo["DraftId"])["Status"] == "saved" assert client.call("get_change_status", draftId=draft_id)["Status"] == "undone" assert client.call("get_object", kind=kind, id=object_id)["Name"] == old assert before == snapshot() assert original == snapshot() print("PASS", len(original), "files;", sum(map(len, original.values())), "bytes;", manual) finally: client.close() if __name__ == "__main__": {"verify": verify, "prepare": prepare}[sys.argv[1]](*map(Path, sys.argv[2:]))