XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFEWorkflow

【WinUI】XFE基于windows的工作流

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Text.Json.Nodes;
using XFEExtension.NetCore.XUnit.Assertions;
using XFEExtension.NetCore.XUnit.Attributes;
using XFEWorkflow.Abstractions;
using XFEWorkflow.Core.Runtime;
using XFEWorkflow.Infrastructure.Compilation;

namespace XFEWorkflow.Test;

[TestFixture]
public class EngineTests
{
    [Test]
    public async Task StartPreservesWorkflowInputsAndDataEdges()
    {
        using var compiler = new CodeCompiler();
        var workflow = TestSupport.Graph(); var start = workflow.Graph.Nodes[0]; var end = workflow.Graph.Nodes[^1];
        workflow.Graph.Edges.Add(new() { FromNode = start.Id, FromPort = "inputs", ToNode = end.Id, ToPort = "result", Kind = PortKind.Data });
        var result = await new WorkflowEngine(compiler, CoreCapabilities.Catalog()).ExecuteAsync(workflow, TestSupport.Context(inputs: new() { ["message"] = "中文输入" }), default);
        Assert.Equal("中文输入", result["result"]!["message"]!.GetValue<string>());
    }
    [TestCase(true, "yes")]
    [TestCase(false, "no")]
    public async Task BranchExecutesExactlyOnePath(bool condition, string expected)
    {
        using var compiler = new CodeCompiler();
        var decision = new NodeDefinition { CapabilityId = "core.if", Parameters = new() { ["left"] = condition, ["right"] = true } };
        var yes = new NodeDefinition { CapabilityId = "core.set", Parameters = new() { ["name"] = "answer", ["value"] = "yes" } };
        var no = new NodeDefinition { CapabilityId = "core.set", Parameters = new() { ["name"] = "answer", ["value"] = "no" } };
        var workflow = TestSupport.Graph(decision, yes, no); workflow.Graph.Edges.Clear();
        workflow.Graph.Edges = [new() { FromNode = workflow.Graph.Nodes[0].Id, ToNode = decision.Id },
            new() { FromNode = decision.Id, FromPort = "true", ToNode = yes.Id }, new() { FromNode = decision.Id, FromPort = "false", ToNode = no.Id }];
        var context = TestSupport.Context(); await new WorkflowEngine(compiler, CoreCapabilities.Catalog()).ExecuteAsync(workflow, context, default);
        Assert.Equal(expected, context.Variables.String("answer"));
    }
    [Test]
    public async Task SwitchUsesDeclaredCase()
    {
        using var compiler = new CodeCompiler();
        var choice = new NodeDefinition { CapabilityId = "core.switch", Parameters = new() { ["value"] = "b", ["cases"] = new JsonArray("a", "b") } };
        var result = new NodeDefinition { CapabilityId = "core.set", Parameters = new() { ["name"] = "selected", ["value"] = "b" } };
        var workflow = TestSupport.Graph(choice, result); workflow.Graph.Edges[1].FromPort = "b";
        var context = TestSupport.Context(); await new WorkflowEngine(compiler, CoreCapabilities.Catalog()).ExecuteAsync(workflow, context, default);
        Assert.Equal("b", context.Variables.String("selected"));
    }
    [Test]
    public async Task ForEachRestoresLoopScope()
    {
        using var compiler = new CodeCompiler();
        var body = TestSupport.Graph(new NodeDefinition { CapabilityId = "core.set", Parameters = new() { ["name"] = "last", ["value"] = new JsonObject { ["$var"] = "item" } } });
        var each = new NodeDefinition { CapabilityId = "core.foreach", Parameters = new() { ["items"] = new JsonArray(1, 2, 3) }, Children = new() { ["body"] = body.Graph } };
        var context = TestSupport.Context(); context.Variables["item"] = "outer";
        await new WorkflowEngine(compiler, CoreCapabilities.Catalog()).ExecuteAsync(TestSupport.Graph(each), context, default);
        Assert.Equal("outer", context.Variables.String("item")); Assert.Equal(3, context.Variables.Integer("last")); Assert.False(context.Variables.ContainsKey("index"));
    }
    [Test]
    public async Task WhileResolvesConditionAfterEachIteration()
    {
        using var compiler = new CodeCompiler();
        var increment = new NodeDefinition { CapabilityId = "core.csharp", Code = """context.Variables["n"] = context.Variables["n"]!.GetValue<int>() + 1; return new JsonObject();""" };
        var loop = new NodeDefinition { CapabilityId = "core.while", Parameters = new() { ["left"] = new JsonObject { ["$var"] = "n" }, ["operator"] = "lt", ["right"] = 3 }, Children = new() { ["body"] = TestSupport.Graph(increment).Graph } };
        var context = TestSupport.Context(); context.Variables["n"] = 0;
        await new WorkflowEngine(compiler, CoreCapabilities.Catalog()).ExecuteAsync(TestSupport.Graph(loop), context, default); Assert.Equal(3, context.Variables.Integer("n"));
    }
    [Test]
    public async Task ParallelIsolatesVariablesAndJoins()
    {
        using var compiler = new CodeCompiler();
        GraphDefinition Branch(int value) => TestSupport.Graph(new NodeDefinition { CapabilityId = "core.set", Parameters = new() { ["name"] = "same", ["value"] = value } }).Graph;
        var parallel = new NodeDefinition { CapabilityId = "core.parallel", Children = new() { ["left"] = Branch(1), ["right"] = Branch(2) } };
        var join = new NodeDefinition { CapabilityId = "core.join" }; var context = TestSupport.Context(); context.Variables["same"] = 0;
        await new WorkflowEngine(compiler, CoreCapabilities.Catalog()).ExecuteAsync(TestSupport.Graph(parallel, join), context, default);
        Assert.Equal(0, context.Variables.Integer("same")); Assert.Equal(2, context.NodeOutputs[parallel.Id]["branches"]!.AsObject().Count); Assert.True(context.NodeOutputs.ContainsKey(join.Id));
    }
    [Test]
    public async Task TryCatchRunsFinally()
    {
        using var compiler = new CodeCompiler();
        var failure = new NodeDefinition { CapabilityId = "core.csharp", Code = """throw new InvalidOperationException("fixture-error");""" };
        var caught = new NodeDefinition { CapabilityId = "core.log", Parameters = new() { ["message"] = new JsonObject { ["$var"] = "error" } } };
        var final = new NodeDefinition { CapabilityId = "core.set", Parameters = new() { ["name"] = "finally", ["value"] = true } };
        var node = new NodeDefinition { CapabilityId = "core.try", Children = new() { ["try"] = TestSupport.Graph(failure).Graph, ["catch"] = TestSupport.Graph(caught).Graph, ["finally"] = TestSupport.Graph(final).Graph } };
        List<RunEvent> events = []; var context = TestSupport.Context(events: events);
        await new WorkflowEngine(compiler, CoreCapabilities.Catalog()).ExecuteAsync(TestSupport.Graph(node), context, default);
        Assert.True(context.Variables.Boolean("finally")); Assert.True(events.Any(x => x.Kind == RunEventKind.Log && x.Message.Contains("fixture-error")));
    }
    [Test]
    public async Task TimeoutPointsAtFailingNode()
    {
        using var compiler = new CodeCompiler();
        var delay = new NodeDefinition { CapabilityId = "core.delay", TimeoutSeconds = 1, Parameters = new() { ["milliseconds"] = 10_000 } };
        Func<Task> run = async () => await new WorkflowEngine(compiler, CoreCapabilities.Catalog()).ExecuteAsync(TestSupport.Graph(delay), TestSupport.Context(), default);
        var error = await Assert.ThrowsAsync<WorkflowExecutionException>(run); Assert.Equal(delay.Id, error.NodeId); Assert.Contains("超时", error.Message);
    }
    [Test]
    public async Task CancellationIsNotCaughtByTry()
    {
        using var compiler = new CodeCompiler(); using var cancellation = new CancellationTokenSource(100);
        var delay = new NodeDefinition { CapabilityId = "core.delay", Parameters = new() { ["milliseconds"] = 10_000 } };
        var node = new NodeDefinition { CapabilityId = "core.try", Children = new() { ["try"] = TestSupport.Graph(delay).Graph, ["catch"] = WorkflowTemplates.EmptyGraph() } };
        Func<Task> run = async () => await new WorkflowEngine(compiler, CoreCapabilities.Catalog()).ExecuteAsync(TestSupport.Graph(node), TestSupport.Context(), cancellation.Token);
        await Assert.ThrowsAsync<OperationCanceledException>(run);
    }
    [Test]
    public void InvalidGraphReportsMissingPluginAndCycles()
    {
        var missing = new NodeDefinition { CapabilityId = "missing.plugin.action" }; var graph = TestSupport.Graph(missing);
        Assert.True(GraphValidator.Validate(graph, CoreCapabilities.Catalog()).Any(x => x.NodeId == missing.Id));
        graph = TestSupport.Graph(new NodeDefinition { CapabilityId = "core.log" });
        graph.Graph.Edges.Add(new() { FromNode = graph.Graph.Nodes[1].Id, ToNode = graph.Graph.Nodes[1].Id });
        Assert.True(GraphValidator.Validate(graph, CoreCapabilities.Catalog()).Any(x => x.Message.Contains("环")));
    }
    [Test]
    public void IncompatibleDataPortIsRejected()
    {
        var workflow = TestSupport.Graph(new NodeDefinition { CapabilityId = "core.delay" });
        workflow.Graph.Edges.Add(new() { FromNode = workflow.Graph.Nodes[0].Id, FromPort = "inputs", ToNode = workflow.Graph.Nodes[1].Id, ToPort = "milliseconds", Kind = PortKind.Data });
        Assert.True(GraphValidator.Validate(workflow, CoreCapabilities.Catalog()).Any(x => x.Message.Contains("类型不兼容")));
    }
}

[TestFixture]
public class CompilerTests
{
    [Test]
    public async Task CompilesSdkWithoutInstalledSdkDependency()
    {
        using var compiler = new CodeCompiler();
        var result = await compiler.ExecuteAsync(WorkflowTemplates.WorkflowCode, false, "fixture.cs", TestSupport.Context(), default); Assert.Equal("运行成功", result.String("message"));
    }
    [Test]
    public async Task DiagnosticsKeepNodeLineNumbers()
    {
        using var compiler = new CodeCompiler();
        var diagnostics = await compiler.AnalyzeAsync("unknown();\nreturn new JsonObject();", true, "节点.cs");
        Assert.True(diagnostics.Any(x => x.IsError && x.Line == 1 && x.File == "节点.cs"));
    }
    [Test]
    public async Task CompletionIncludesSdkMethods()
    {
        using var compiler = new CodeCompiler(); var text = "context.";
        var items = await compiler.CompleteAsync(text, true, text.Length); Assert.True(items.Any(x => x.Label == "InvokeAsync"));
    }
}