plcsharp/Tests/mcp_rename_editor_smoke.py

155 lines
8.6 KiB
Python

"""Prepare a portable sample copy, open it in PLCSharp and enable AI access, then run verify."""
import argparse
import json
from pathlib import Path
import shutil
import uuid
from mcp_smoke import Client
def prepare(sample, directory):
shutil.copytree(sample, directory)
script, = directory.rglob("*.cs")
source = (
"using PLCSharp.Models;\nusing PLCSharp.Core.Common;\n"
f"public class Extension_{script.stem.replace('-', '')} {{\n"
" public void Run(GlobalModel model, FlowModel flow) {\n"
' _ = model.GetVariable("计数");\n'
' _ = model.GetVariable(flow.Step.ToString());\n'
" }\n}\n"
)
script.write_bytes(source.encode("utf-8"))
def prepare_workflow(sample, directory):
shutil.copytree(sample, directory)
target_script, = directory.rglob("*.cs")
manifest = target_script.parent.parent / "recipe.json"
recipe = json.loads(manifest.read_bytes())
target, = recipe["workflows"]
caller = dict(target, id=str(uuid.uuid4()), name="调度", automaticExecution=False)
recipe["workflows"].append(caller)
manifest.write_text(json.dumps(recipe, ensure_ascii=False, indent=2), encoding="utf-8")
source = (
"using PLCSharp.Models;\nusing PLCSharp.Core.Common;\n"
f"public class Extension_{caller['id'].replace('-', '')} {{\n"
" public void Run(GlobalModel model, FlowModel flow) {\n"
f' _ = model.GetTask("{target["name"]}");\n'
' _ = model.GetTask(flow.Step.ToString());\n'
" }\n}\n"
)
target_script.with_name(caller["id"] + ".cs").write_bytes(source.encode("utf-8"))
def prepare_point(sample, directory):
shutil.copytree(sample, directory)
caller, = (p for p in directory.rglob("*.cs") if 'GetTask("搬运")' in p.read_text(encoding="utf-8"))
source = caller.read_text(encoding="utf-8").replace("using PLCSharp.Models;", "using PLCSharp.Models; using System.Linq;")
source = source.replace('_ = model.GetTask("搬运");',
'_ = model.ControllersModel.AxisPoints.FirstOrDefault(p => p.Name == "定位");')
source = source.replace('_ = model.GetTask(flow.Step.ToString());',
'_ = model.ControllersModel.AxisPoints.FirstOrDefault(p => p.Name == flow.Step.ToString());')
caller.write_bytes(source.encode("utf-8"))
def prepare_vision(sample, directory):
shutil.copytree(sample, directory)
caller, = (p for p in directory.rglob("*.cs") if 'p.Name == "定位"' in p.read_text(encoding="utf-8"))
source = caller.read_text(encoding="utf-8")
source = source.replace('model.ControllersModel.AxisPoints.FirstOrDefault(p => p.Name == "定位")',
'model.GetVisionFunction("检查")')
source = source.replace('model.ControllersModel.AxisPoints.FirstOrDefault(p => p.Name == flow.Step.ToString())',
'model.GetVisionFunction(flow.Step.ToString())')
caller.write_bytes(source.encode("utf-8"))
def prepare_axis(sample, directory):
shutil.copytree(sample, directory)
caller, = (p for p in directory.rglob("*.cs") if 'GetVisionFunction("检查")' in p.read_text(encoding="utf-8"))
source = caller.read_text(encoding="utf-8")
source = source.replace('model.GetVisionFunction("检查")', 'model.ControllersModel.Axes.FirstOrDefault(a => a.Name == "X")')
source = source.replace('model.GetVisionFunction(flow.Step.ToString())',
'model.ControllersModel.Axes.FirstOrDefault(a => a.Name == flow.Step.ToString())')
caller.write_bytes(source.encode("utf-8"))
def verify(exe, directory, workflow=False, point=False, vision=False, axis=False):
before = {p: p.read_bytes() for p in directory.rglob("*") if p.is_file()}
client = Client(exe, directory, "--allow-write")
try:
summary = client.call("get_project_summary")
assert summary["source"] == "editor"
recipe = summary["DefaultRecipeId"]
kind, old, new, tool, lookup = (
("Workflows", "搬运", "工件搬运", "preview_workflow_rename", "GetTask") if workflow else
("Variables", "计数", "完成计数", "preview_variable_rename", "GetVariable"))
if point:
kind, old, new, tool = "AxisPoints", "定位", "装配定位", "preview_point_rename"
if vision:
kind, old, new = "VisionFunctions", "检查", "装配检查"
tool, lookup = "preview_vision_function_rename", "GetVisionFunction"
if axis:
kind, old, new, tool = "Axes", "X", "横移轴", "preview_axis_rename"
items = client.call("list_objects", kind=kind, **({} if axis else {"recipeId": recipe}))["items"]
target, = (item for item in items if item["name"] == old)
if axis or point:
denied = client.request("tools/call", {"name": "preview_object_rename", "arguments":
{"kind": kind, "id": target["id"], "newName": new}})
assert denied["isError"] and all(p.read_bytes() == data for p, data in before.items())
return
draft = client.call(tool, id=target["id"], newName=new, **({"kind": kind} if point else {}))
plan = draft["Rename"]
script, = plan["Scripts"]
manual, = plan["ManualReferences"]
assert draft["Status"] == "pending" and script["Review"]["Compiled"]
assert manual["confidence"] == "dynamic" and manual["line"] == 6
replacement = f'p.Name == "{new}"' if point else f'{lookup}("{new}")'
if axis:
replacement = f'a.Name == "{new}"'
assert {(ref["Table"], ref["Field"]) for ref in plan["PointReferences"]} == {
("AxisPoints", "AxisXName"), ("InterpolationGroups", "AxisXName")}
if point:
link, = plan["MatrixReferences"]
assert link["Table"] == "Matrices" and link["Field"] == "StartName"
assert replacement in script["After"] and manual["expression"] in script["After"]
print(json.dumps({"source": summary["source"], "dynamic": manual, "compiled": True}, ensure_ascii=False), flush=True)
assert all(p.read_bytes() == old for p, old in before.items())
saved = client.call("apply_changes", confirmed=True, draftId=draft["DraftId"])
assert saved["Status"] == "saved"
assert client.call("get_object", kind=kind, id=target["id"])["Name"] == new
assert client.call("get_object", kind="Workflows", id=script["Id"])["Code"] == script["After"]
if point:
assert client.call("get_object", kind="Matrices", id=link["Id"])["StartName"] == new
metadata = draft["Path"]
changed = {directory / metadata, directory / script["Path"]}
if axis:
changed.add(directory / "configuration/points.json")
for ref in plan["PointReferences"]:
assert client.call("get_object", kind=ref["Table"], id=ref["Id"])[ref["Field"]] == new
assert {p for p, old in before.items() if p.read_bytes() != old} == changed
undo = client.call("preview_undo", draftId=draft["DraftId"])
assert undo["Rename"]["Compiled"] and undo["Rename"]["UndoOf"] == draft["DraftId"]
assert client.call("apply_changes", confirmed=True, draftId=undo["DraftId"])["Status"] == "saved"
assert client.call("get_change_status", draftId=draft["DraftId"])["Status"] == "undone"
assert client.call("get_object", kind=kind, id=target["id"])["Name"] == old
assert client.call("get_object", kind="Workflows", id=script["Id"])["Code"] == script["Before"]
assert before == {p: p.read_bytes() for p in directory.rglob("*") if p.is_file()}
print(f"PASS: live editor rename, confirmation, undo and byte-for-byte restore of {len(before)} files.")
finally:
client.close()
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("mode", choices=["prepare", "verify", "prepare-workflow", "verify-workflow", "prepare-point", "verify-point", "prepare-vision", "verify-vision", "prepare-axis", "verify-axis"])
parser.add_argument("source", type=Path, help="Sample directory for prepare, MCP executable for verify")
parser.add_argument("project", type=Path)
args = parser.parse_args()
if args.mode.startswith("prepare"):
{"prepare": prepare, "prepare-workflow": prepare_workflow, "prepare-point": prepare_point, "prepare-vision": prepare_vision, "prepare-axis": prepare_axis}[args.mode](args.source, args.project)
else:
verify(args.source, args.project, workflow=args.mode == "verify-workflow", point=args.mode == "verify-point",
vision=args.mode == "verify-vision", axis=args.mode == "verify-axis")