using PLCSharp.Models; using System.IO; using System.Text; using System.Text.Json.Nodes; namespace PLCSharp.Tests; public class ProjectBatchTests { [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 Files() => Directory.GetFiles(dir.FullName, "*", SearchOption.AllDirectories).ToDictionary(f => f, File.ReadAllBytes); void Same(Dictionary 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(() => Call("apply", new() { ["draftId"] = (string)invalid["DraftId"]! })); Same(original); var stale = Call("previewBatch", args); File.AppendAllText(path, " "); var external = Files(); Assert.ThrowsAny(() => Call("apply", new() { ["draftId"] = (string)stale["DraftId"]! })); Same(external); } finally { dir.Delete(true); } } }