diff --git a/Tests/PLCSharp.Tests/ObjectEditTests.cs b/Tests/PLCSharp.Tests/ObjectEditTests.cs index 59fd220..f0f738a 100644 --- a/Tests/PLCSharp.Tests/ObjectEditTests.cs +++ b/Tests/PLCSharp.Tests/ObjectEditTests.cs @@ -6,6 +6,55 @@ namespace PLCSharp.Tests; public class ObjectEditTests { + [Fact] + public void ReviewingDeletionDoesNotTouchFilesAndCancellationPreservesReferences() + { + var dir = Directory.CreateTempSubdirectory(); + try + { + using var p = ProjectDirectory.New(); + var channel = new PLCSharp.VVMs.MotionController.DI { Name = "Clamp", Number = 5 }; + var cylinder = new PLCSharp.VVMs.Cylinders.Cylinder { Name = "Cylinder", InA = "Clamp" }; + p.Data.AddRange(channel, cylinder); + var script = new PLCSharp.VVMs.Workflows.Workflow { Name = "Cycle", RecipeID = p.DefaultRecipeId }; + script.Code = $$""" + using PLCSharp.Models; + using PLCSharp.Core.Common; + using System.Linq; + public class Extension_{{script.ID:N}} { + public void Run(GlobalModel model, FlowModel flow) { + _ = model.ControllersModel.Controller.DI.FirstOrDefault(c => c.Name == "Clamp"); + _ = model.ControllersModel.Controller.DI.FirstOrDefault(c => c.Name == flow.Step.ToString()); + } + } + """; + p.Flows(p.DefaultRecipeId).Add(script); + p.Save(dir.FullName); + var files = Directory.GetFiles(dir.FullName, "*", SearchOption.AllDirectories).ToDictionary(path => path, File.ReadAllBytes); + var changes = new ProjectChanges(); + var request = new JsonObject { ["kind"] = "DI", ["action"] = "delete", ["id"] = channel.ID.ToString() }; + var draft = changes.Execute(p, "previewObjectEdit", request, false); + var review = draft["Edit"]!; + Assert.True((bool)review["Compiled"]!); + Assert.Single(review["WorkflowReferences"]!.AsArray()); + Assert.Equal("InA", (string?)Assert.Single(review["ConfigReferences"]!.AsArray())!["field"]); + Assert.Single(review["ManualReferences"]!.AsArray()); + var args = new JsonObject { ["draftId"] = (string?)draft["DraftId"] }; + Assert.Throws(() => changes.Execute(p, "apply", args, false, _ => true)); + Assert.Equal("rejected", (string?)changes.Execute(p, "apply", args, true, _ => false)["Status"]); + foreach (var (path, bytes) in files) Assert.Equal(bytes, File.ReadAllBytes(path)); + var stale = p.PlanObjectEdit("delete", "DI", channel.ID, null); + p.ApplyObjectEdit(p.PlanObjectEdit("update", "Cylinders", cylinder.ID, new() { ["Comment"] = "reviewed" })); + Assert.ThrowsAny(() => p.ApplyObjectEdit(stale)); + Assert.NotNull(p.Data.DI.Find(channel.ID)); + Assert.Throws(() => p.PlanObjectEdit("create", "DI", null, new() { ["Name"] = "Other", ["Number"] = 5 })); + Assert.Throws(() => p.PlanObjectEdit("update", "Cylinders", cylinder.ID, new() { ["InB"] = "Unknown" })); + Assert.Throws(() => p.PlanObjectEdit("create", "Variables", null, + new() { ["Name"] = "Counter", ["RecipeID"] = p.DefaultRecipeId.ToString(), ["DefaultValueStr"] = "invalid" })); + } + finally { dir.Delete(true); } + } + [Fact] public void EverySupportedTableCreatesUpdatesDeletesAndUndoesEachSnapshot() { diff --git a/Tests/mcp_object_edit_smoke.py b/Tests/mcp_object_edit_smoke.py new file mode 100644 index 0000000..9748e89 --- /dev/null +++ b/Tests/mcp_object_edit_smoke.py @@ -0,0 +1,98 @@ +"""Verify reviewed create/update/delete in one live PLCSharp editor and reverse all nine saves.""" +import json +from pathlib import Path +import shutil +import sys + +from mcp_smoke import Client + + +CASES = ( + ("Variables", "验收变量", {"DefaultValueStr": "7"}, {"DefaultValueStr": "12"}), + ("AxisPoints", "验收点", {"AxisXName": "X", "X": 2}, {"X": 8}), + ("DI", "验收输入", {"Number": 231, "LineNumber": "QA"}, {"LineNumber": "QA2"}), +) + + +def prepare(source, root): + shutil.copytree(source, root) + for name, table, field, target in (("points", "Matrices", "XEndName", "验收点"), ("hardware", "Cylinders", "InB", "验收输入")): + path = root / "configuration" / (name + ".json") + doc = json.loads(path.read_bytes()) + doc[table][0][field] = target + path.write_text(json.dumps(doc, ensure_ascii=False, indent=2), encoding="utf-8") + caller, = (p for p in root.rglob("*.cs") if "model.VisionsModel.Cameras" in p.read_text(encoding="utf-8")) + code = caller.read_text(encoding="utf-8") + index = code.rindex(" }") + refs = """ + _ = model.GetVariable("验收变量"); + _ = model.GetVariable(flow.Step.ToString()); + _ = model.ControllersModel.AxisPoints.FirstOrDefault(p => p.Name == "验收点"); + _ = model.ControllersModel.AxisPoints.FirstOrDefault(p => p.Name == flow.Step.ToString()); + _ = model.ControllersModel.Controller.DI.FirstOrDefault(p => p.Name == "验收输入"); +""" + caller.write_bytes((code[:index] + refs + code[index:]).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() + client = Client(exe, root, "--allow-write") + try: + summary = client.call("get_project_summary") + assert summary["source"] == "editor" + recipe = summary["currentRecipeId"] + created, history = {}, [] + for action in ("create", "update", "delete"): + for kind, name, initial, patch in CASES: + before = snapshot() + if action == "create": + fields = dict(initial, Name=name) + if kind != "DI": + fields["RecipeID"] = recipe + args = {"properties": fields} + else: + args = {"id": created[kind]} + if action == "update": + args["properties"] = patch + draft = client.call("preview_object_edit", action=action, kind=kind, **args) + edit = draft["Edit"] + assert draft["Status"] == "pending" and edit["Compiled"] and len(edit["Workflows"]) == (2 if kind == "Variables" else 1) + assert before == snapshot() and edit["WorkflowReferences"] and edit["ManualReferences"] + if action == "delete": + print("IMPACT", kind, [(r["Name"], r["path"], r["line"], r["expression"]) for r in edit["ManualReferences"]], + [(r["table"], r["field"]) for r in edit["ConfigReferences"]], flush=True) + if kind in {"DI", "AxisPoints"}: + assert edit["ConfigReferences"] + print(action, kind, name, flush=True) + assert client.call("apply_changes", draftId=draft["DraftId"])["Status"] == "saved" + created[kind] = edit["Id"] + after = snapshot() + assert after.keys() == before.keys() + assert {p for p in before if after[p] != before[p]} == {Path(edit["Path"])} + rows = json.loads(after[Path(edit["Path"])])[kind] + matching = [r for r in rows if r["ID"].lower() == edit["Id"].lower()] + assert matching == ([] if action == "delete" else [edit["After"]]) + if action != "delete": + obj = client.call("get_object", kind=kind, id=edit["Id"]) + assert obj["Name"] == name + for field, expected in (patch if action == "update" else initial).items(): + assert obj[field] == expected + history.append((draft["DraftId"], before)) + for draft_id, before in reversed(history): + undo = client.call("preview_undo", draftId=draft_id) + assert undo["Edit"]["Compiled"] and undo["Edit"]["UndoOf"] == draft_id + print("UNDO", undo["Edit"]["Kind"], undo["Edit"]["Action"], flush=True) + assert client.call("apply_changes", draftId=undo["DraftId"])["Status"] == "saved" + assert client.call("get_change_status", draftId=draft_id)["Status"] == "undone" + assert before == snapshot() + assert snapshot() == original + print("PASS", len(history), "saves and undos;", len(original), "files;", sum(map(len, original.values())), "bytes") + finally: + client.close() + + +if __name__ == "__main__": + {"prepare": prepare, "verify": verify}[sys.argv[1]](*map(Path, sys.argv[2:]))