plcsharp/Tests/mcp_object_edit_smoke.py

99 lines
4.9 KiB
Python

"""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:]))