plcsharp/Tests/PLCSharp.Tests/ProjectBatchTests.cs

103 lines
5.0 KiB
C#

using PLCSharp.Models;
using System.IO;
using System.Text;
using System.Text.Json.Nodes;
namespace PLCSharp.Tests;
public class ProjectBatchTests
{
[Theory]
[InlineData("Recipes")]
[InlineData("Axes")]
[InlineData("RobotPoints")]
[InlineData("Cameras")]
[InlineData("InterpolationPoints")]
public void ProtectedNamesCannotBeRenamedThroughSingleOrBatchTools(string kind)
{
var dir = Directory.CreateTempSubdirectory();
try
{
using var p = ProjectDirectory.New();
p.Save(dir.FullName);
var changes = new ProjectChanges();
var args = new JsonObject { ["action"] = "rename", ["kind"] = kind, ["id"] = p.DefaultRecipeId.ToString(), ["newName"] = "改名" };
Assert.Contains("不能修改", Assert.Throws<ArgumentException>(() => changes.Execute(p, "previewObjectRename", args, false)).Message);
Assert.Contains("不能修改", Assert.Throws<ArgumentException>(() => changes.Execute(p, "previewBatch",
new() { ["operations"] = new JsonArray(args.DeepClone()) }, false)).Message);
Assert.Equal("First", p.Recipes.Single().Name);
}
finally { dir.Delete(true); }
}
[Fact]
public void ScriptMayReadButCannotAssignExistingRecipeName()
{
var id = Guid.NewGuid();
string Source(string statement) => $"using PLCSharp.Models; using PLCSharp.Core.Common; public class Extension_{id:N} {{ public void Run(GlobalModel model, FlowModel flow) {{ {statement} }} }}";
Assert.True(WorkflowScriptReview.Create(id, "", Source("_ = model.CurrentRecipe.Name;")).Compiled);
var review = WorkflowScriptReview.Create(id, "", Source("model.CurrentRecipe.Name = \"其他\";"));
Assert.Contains(review.Diagnostics, d => d.Code == "PLC002");
Assert.False(review.Compiled);
}
[Fact]
public void BatchIsReviewedOnceAndRestoresOriginalBytes()
{
var dir = Directory.CreateTempSubdirectory();
try
{
using (var fresh = ProjectDirectory.New()) fresh.Save(dir.FullName);
var path = Path.Combine(dir.FullName, "project.json");
File.WriteAllText(path, File.ReadAllText(path), new UTF8Encoding(true));
using var p = ProjectDirectory.Open(dir.FullName);
var changes = new ProjectChanges();
var confirmations = 0;
JsonNode Call(string op, JsonObject args, bool accept = true) =>
changes.Execute(p, op, args, true, draft => { confirmations++; return accept; });
Dictionary<string, byte[]> Files() => Directory.GetFiles(dir.FullName, "*", SearchOption.AllDirectories).ToDictionary(f => f, File.ReadAllBytes);
void Same(Dictionary<string, byte[]> original)
{
var now = Files();
Assert.Equal(original.Keys.Order(), now.Keys.Order());
foreach (var (file, bytes) in original) Assert.Equal(bytes, now[file]);
}
var original = Files();
var args = JsonNode.Parse("""
{"operations":[{"action":"create","kind":"Recipes","alias":"r","properties":{"Name":"试产"}},
{"action":"create","kind":"Workflows","alias":"w","properties":{"RecipeID":"$r","Name":"检测"}},
{"action":"update","kind":"Workflows","id":"$w","properties":{"Comment":"验收"}}]}
""")!.AsObject();
var batch = Call("previewBatch", args);
Same(original);
Assert.Equal(0, confirmations);
var key = new JsonObject { ["draftId"] = (string)batch["DraftId"]! };
Assert.Equal("rejected", (string)Call("apply", key, false)["Status"]!);
Same(original);
key["draftId"] = (string)Call("previewBatch", args)["DraftId"]!;
Assert.Equal("saved", (string)Call("apply", key)["Status"]!);
Call("apply", key);
Assert.Equal(2, confirmations);
using (var copy = ProjectDirectory.Open(dir.FullName))
Assert.Equal("验收", copy.Flows(copy.Recipes.Single(r => r.Name == "试产").ID).Single().Comment);
var undo = Call("previewUndo", key);
Call("apply", new() { ["draftId"] = (string)undo["DraftId"]! });
Assert.Equal(3, confirmations);
Same(original);
var bad = args.DeepClone().AsObject();
bad["operations"]![2]!["properties"] = new JsonObject { ["Code"] = "bad C#" };
var invalid = Call("previewBatch", bad);
Assert.Equal("invalid", (string)invalid["Status"]!);
Assert.Throws<InvalidOperationException>(() => Call("apply", new() { ["draftId"] = (string)invalid["DraftId"]! }));
Same(original);
var stale = Call("previewBatch", args);
File.AppendAllText(path, " ");
var external = Files();
Assert.ThrowsAny<IOException>(() => Call("apply", new() { ["draftId"] = (string)stale["DraftId"]! }));
Same(external);
}
finally { dir.Delete(true); }
}
}