Test vision asset scopes, camera identity and batch reverse-order undo

This commit is contained in:
wanglei 2026-12-05 22:35:48 +08:00
parent 860602b480
commit 34f329c532
2 changed files with 174 additions and 0 deletions

View File

@ -0,0 +1,75 @@
using PLCSharp.Models;
using PLCSharp.VVMs.Vision;
using System.IO;
namespace PLCSharp.Tests;
public class VisionAssetRenameTests
{
[Fact]
public void CameraAliasKeepsDiscoveryIdentityAndRestoresBothDocuments()
{
var root = Directory.CreateTempSubdirectory();
try
{
using var project = ProjectDirectory.New();
var camera = new PLCSharp.VVMs.Vision.Camera.CameraBase { Name = "CAM" };
var function = new VisionFunction { Name = "Inspect", RecipeID = project.DefaultRecipeId };
var shot = new VisionFlow { Type = VisionFlowType.拍照 };
shot.StringParams["Camera"] = camera.Name;
function.VisionFlows.Add(shot);
project.Data.AddRange(camera, function);
project.Save(root.FullName);
var files = Directory.GetFiles(root.FullName, "*", SearchOption.AllDirectories)
.ToDictionary(path => path, File.ReadAllBytes);
var plan = project.PlanVisionAssetRename("Cameras", camera.ID, "Alias");
project.ApplyRename(plan);
Assert.Equal("CAM", camera.Params.DiscoveryName);
Assert.Equal("Alias", shot.StringParams["Camera"]);
using (var reopened = ProjectDirectory.Open(root.FullName))
{
var persisted = reopened.Data.Cameras.Find(camera.ID);
Assert.Equal("Alias", persisted.Name);
Assert.Equal("CAM", persisted.Params.DiscoveryName);
}
project.ApplyRename(project.PlanUndo(Guid.NewGuid(), plan));
Assert.Null(camera.Params.DiscoveryName);
Assert.Equal("CAM", shot.StringParams["Camera"]);
foreach (var (path, bytes) in files) Assert.Equal(bytes, File.ReadAllBytes(path));
}
finally { root.Delete(true); }
}
[Fact]
public void ImplicitTemplateBelongsToOneFunctionAndUndoRestoresAbsentKey()
{
var root = Directory.CreateTempSubdirectory();
try
{
using var project = ProjectDirectory.New();
var a = new VisionFunction { Name = "A", RecipeID = project.DefaultRecipeId };
var b = new VisionFunction { Name = "B", RecipeID = project.DefaultRecipeId };
foreach (var owner in new[] { a, b })
{
owner.VisionFlows.Add(new VisionFlow { Type = VisionFlowType.ORB匹配 });
project.Data.Add(owner);
}
var image = new LocalImageData { Name = "ORB_Template", FuncID = a.ID };
project.Data.AddRange(image, new LocalImageData { Name = image.Name, FuncID = b.ID },
new LocalImageData { Name = "Existing", FuncID = a.ID });
project.Save(root.FullName);
var path = Path.Combine(root.FullName, "configuration", "vision.json");
var bytes = File.ReadAllBytes(path);
Assert.ThrowsAny<IOException>(() => project.PlanVisionAssetRename("LocalImageDatas", image.ID, "Existing"));
var plan = project.PlanVisionAssetRename("LocalImageDatas", image.ID, "Renamed");
Assert.Equal(a.ID, Assert.Single(plan.VisionReferences).FunctionId);
project.ApplyRename(plan);
Assert.Equal("Renamed", a.VisionFlows[0].StringParams["TemplateName"]);
Assert.False(b.VisionFlows[0].StringParams.ContainsKey("TemplateName"));
project.ApplyRename(project.PlanUndo(Guid.NewGuid(), plan));
Assert.False(a.VisionFlows[0].StringParams.ContainsKey("TemplateName"));
Assert.Equal(bytes, File.ReadAllBytes(path));
}
finally { root.Delete(true); }
}
}

View File

@ -0,0 +1,99 @@
"""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()
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", 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"])}
if kind == "Cameras":
paths.add(hw)
hardware = json.loads(before[hw])
camera, = hardware[kind]
camera["Name"] = new
camera["Params"]["DiscoveryName"] = old
assert json.loads(after[hw]) == hardware
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", 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:]))