using System.Text.Json; using System.Text.Json.Nodes; using XFEExtension.NetCore.XFEConsole; using XFEExtension.NetCore.XUnit.Assertions; using XFEExtension.NetCore.XUnit.Attributes; using XFEWorkflow.Abstractions; using XFEWorkflow.Core.Runtime; using XFEWorkflow.Infrastructure.Compilation; using XFEWorkflow.Infrastructure.Execution; using XFEWorkflow.Infrastructure.Plugins; using XFEWorkflow.Infrastructure.Storage; namespace XFEWorkflow.Test; [TestFixture] public sealed class LogExportTests { private static WorkflowLogEntry Entry(string message) => new() { LogText = message, WorkflowId = "workflow", WorkflowName = "日志测试", RunId = "run", NodeId = "log", NodeName = "输出节点", Category = "工作流运行", Trigger = "手动", Level = LogLevel.Info }; [Test] public void ExportRedactsManagedSecretsInTextJsonAndMetadataWithoutChangingEntries() { const string secret = "密钥\"\\\nvalue"; var redactor = new SecretRedactor(); redactor.Add(secret); var entry = Entry("中文日志 " + secret); entry.WorkflowName = "名称 " + secret; entry.Diagnostic = new("诊断 " + secret, entry.NodeId); var text = WorkflowLogExporter.Format([entry], "log", redactor); Assert.Contains("中文日志 ***", text); Assert.Contains("来源=名称 *** / 输出节点", text); Assert.Contains("运行=run", text); Assert.Contains("节点=log", text); Assert.False(text.Contains(secret)); var json = WorkflowLogExporter.Format([entry], "json", redactor); var exported = JsonSerializer.Deserialize>(json, WorkflowJson.Options)!.Single(); Assert.Equal("中文日志 ***", exported.LogText); Assert.Equal("名称 ***", exported.WorkflowName); Assert.Equal("诊断 ***", exported.Diagnostic!.Message); Assert.Equal(entry.RunId, exported.RunId); Assert.Equal("中文日志 " + secret, entry.LogText); Assert.Equal("诊断 " + secret, entry.Diagnostic.Message); Assert.Equal("", WorkflowLogExporter.Format([], "log", redactor)); Assert.Equal(0, JsonNode.Parse(WorkflowLogExporter.Format([], "json", redactor))!.AsArray().Count); } [Test] public async Task FileExportOverwritesAndConcurrentAppendsPreserveEveryRecordInUtf8() { await using var workspace = new TestWorkspace(); var redactor = new SecretRedactor(); var path = Path.Combine(workspace.Paths.Root, "exports", "运行.log"); var first = await WorkflowLogExporter.ExportAsync(path, [Entry("旧日志")], "log", false, redactor); Assert.Equal(Path.GetFullPath(path), first.String("path")); Assert.Equal(1, first.Integer("count")); await WorkflowLogExporter.ExportAsync(path, [Entry("新日志")], "log", false, redactor); await Task.WhenAll(Enumerable.Range(0, 20).Select(i => WorkflowLogExporter.ExportAsync(path, [Entry("追加序号=" + i.ToString("D2"))], "log", true, redactor))); var lines = await File.ReadAllLinesAsync(path); Assert.Equal(21, lines.Length); Assert.True(lines[0].Contains("新日志")); Assert.False(lines.Any(x => x.Contains("旧日志"))); for (var i = 0; i < 20; i++) Assert.Equal(1, lines.Count(x => x.Contains("追加序号=" + i.ToString("D2")))); var bytes = await File.ReadAllBytesAsync(path); Assert.False(bytes.Take(3).SequenceEqual(new byte[] { 0xef, 0xbb, 0xbf })); Assert.False(Directory.EnumerateFiles(Path.GetDirectoryName(path)!, "*.tmp").Any()); } [Test] public async Task InvalidOrCancelledExportPreservesTheExistingFile() { await using var workspace = new TestWorkspace(); var redactor = new SecretRedactor(); var path = Path.Combine(workspace.Paths.Root, "existing.json"); await File.WriteAllTextAsync(path, "keep"); await Assert.ThrowsAsync(() => WorkflowLogExporter.ExportAsync(path, [], "json", true, redactor)); await Assert.ThrowsAsync(() => WorkflowLogExporter.ExportAsync(path, [], "unknown", false, redactor)); await Assert.ThrowsAsync(() => WorkflowLogExporter.ExportAsync(" ", [], "log", false, redactor)); using var cancel = new CancellationTokenSource(); cancel.Cancel(); await Assert.ThrowsAsync(() => WorkflowLogExporter.ExportAsync(path, [Entry("cancelled")], "json", false, redactor, cancel.Token)); Assert.Equal("keep", await File.ReadAllTextAsync(path)); } [Test] public async Task LogExportNodeRunsThroughRealRunnerAndReturnsTypedFileAndCount() { await using var workspace = new TestWorkspace(); var redactor = new SecretRedactor(); redactor.Add("managed-secret"); await using var coordinator = new RunCoordinator(workspace.Paths, new PluginManager(workspace.Paths, workspace.State), new CredentialVault(workspace.State), redactor, TestSupport.FindOutput("XFEWorkflow.Runner", "XFEWorkflow.Runner.exe")); foreach (var format in new[] { "log", "json" }) { var path = Path.Combine(workspace.Paths.Root, "exports", "runner." + format); var log = new NodeDefinition { CapabilityId = "core.log", Name = "输出中文", Parameters = new() { ["message"] = "收到消息 managed-secret" } }; var export = new NodeDefinition { CapabilityId = "core.log.export", Name = "保存日志", Parameters = new() { ["path"] = path, ["format"] = format } }; var workflow = TestSupport.Graph(log, export, new() { CapabilityId = "core.log", Parameters = new() { ["message"] = "导出之后" } }); workflow.Graph.Nodes[^1].Parameters["result"] = new JsonObject { ["file"] = new JsonObject { ["$node"] = export.Id + ".path" }, ["count"] = new JsonObject { ["$node"] = export.Id + ".count" } }; if (format == "json") { GraphCodeGenerator.Update(workflow, true); workflow.Kind = WorkflowKind.CSharp; } var run = await coordinator.RunAsync(workflow).WaitAsync(TimeSpan.FromSeconds(20)); Assert.Equal(RunStatus.Succeeded, run.Status, run.Error); Assert.True(File.Exists(path)); Assert.Equal(Path.GetFullPath(path), run.Outputs["result"]!["file"]!.GetValue()); var text = await File.ReadAllTextAsync(path); Assert.False(text.Contains("managed-secret")); Assert.False(text.Contains("导出之后")); var count = run.Outputs["result"]!["count"]!.GetValue(); Assert.True(count > 0); if (format == "json") { var entries = JsonSerializer.Deserialize>(text, WorkflowJson.Options)!; Assert.Equal(count, entries.Count); Assert.True(entries.All(e => e.RunId == run.Id && e.WorkflowId == workflow.Id)); Assert.True(entries.Any(e => e.NodeName == "输出中文" && e.LogText == "收到消息 ***")); Assert.False(entries.Any(e => e.Id.EndsWith("/finished", StringComparison.Ordinal))); } else { Assert.Contains("收到消息 ***", text); Assert.Equal(count, (await File.ReadAllLinesAsync(path)).Length); } } var catalog = CoreCapabilities.Catalog(); Assert.Equal("日志操作", catalog["core.log"].Category); Assert.Equal("日志操作", catalog["core.log.export"].Category); Assert.Equal(WorkflowValueType.String, catalog["core.log.export"].Outputs.Single(p => p.Name == "path").Type); Assert.Equal(WorkflowValueType.Number, catalog["core.log.export"].Outputs.Single(p => p.Name == "count").Type); } }