plcsharp/Tests/PLCSharp.Tests/WorkflowScriptChangeTests.cs

55 lines
2.7 KiB
C#

using PLCSharp.Models;
using PLCSharp.VVMs.Workflows;
using System.IO;
using System.Text.Json.Nodes;
namespace PLCSharp.Tests;
public class WorkflowScriptChangeTests
{
[Fact]
public void SaveRequiresValidReviewedSourceApprovalAndAnUnchangedBase()
{
var folder = Directory.CreateTempSubdirectory();
try
{
using var project = ProjectDirectory.New();
var flow = new Workflow { Name = "测试", Code = "// before" };
project.Flows(project.DefaultRecipeId).Add(flow);
project.Save(folder.FullName);
string path = Directory.GetFiles(folder.FullName, "*.cs", SearchOption.AllDirectories).Single();
string valid = $"public class Extension_{flow.ID:N} {{ public void Run(PLCSharp.Models.GlobalModel m, PLCSharp.Core.Common.FlowModel f) {{ }} }}";
var changes = new ProjectChanges();
JsonNode Preview(string source) => changes.Execute(project, "previewScript",
new() { ["id"] = flow.ID.ToString(), ["code"] = source }, false);
JsonNode Apply(JsonNode draft, Func<ProjectChange, bool>? approve, bool write = true) =>
changes.Execute(project, "apply", new() { ["draftId"] = (string?)draft["DraftId"] }, write, approve!);
var invalid = Preview("bad source");
Assert.Equal("invalid", (string?)invalid["Status"]);
Assert.Throws<InvalidOperationException>(() => Apply(invalid, _ => throw new Exception("Unexpected confirmation")));
var draft = Preview(valid);
Assert.Throws<InvalidOperationException>(() => Apply(draft, _ => true, false));
Assert.Throws<InvalidOperationException>(() => Apply(draft, null));
Assert.Equal("rejected", (string?)Apply(draft, _ => false)["Status"]);
Assert.Equal("// before", File.ReadAllText(path));
var stale = Preview(valid);
File.WriteAllText(path, "// external");
Assert.ThrowsAny<IOException>(() => Apply(stale, _ => true));
Assert.Equal("// external", File.ReadAllText(path));
File.WriteAllText(path, "// before");
var pending = Preview(valid);
flow.Code = "// editor";
Assert.ThrowsAny<IOException>(() => Apply(pending, _ => true));
flow.Code = "// before";
var final = Preview(valid);
Assert.Equal("saved", (string?)Apply(final, _ => true)["Status"]);
Assert.Equal("saved", (string?)Apply(final, _ => throw new Exception("Duplicate confirmation"))["Status"]);
Assert.Equal(valid, File.ReadAllText(path));
Assert.Equal(valid, flow.Code);
Assert.False(flow.IsCompiled);
}
finally { folder.Delete(true); }
}
}