using System.Collections.Concurrent;
using System.Diagnostics;
using System.IO.Compression;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using XFEWorkflow.Abstractions;
using XFEWorkflow.Core.Runtime;
using XFEWorkflow.Infrastructure.Storage;
using XFEWorkflow.Plugins.Standard;
namespace XFEWorkflow.Test;
internal static class TestSupport
{
public static string Root
{
get
{
var directory = new DirectoryInfo(AppContext.BaseDirectory);
while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "XFEWorkflow.slnx"))) directory = directory.Parent;
return directory?.FullName ?? throw new DirectoryNotFoundException("找不到测试仓库");
}
}
public static string FindOutput(string project, string file)
{
var bin = Path.Combine(Root, "XFEWorkflow", project, "bin");
var configuration = AppContext.BaseDirectory.Replace('\\', '/').Contains("/Release/", StringComparison.OrdinalIgnoreCase) ? "Release" : "Debug";
var rid = System.Runtime.InteropServices.RuntimeInformation.RuntimeIdentifier;
var candidates = Directory.EnumerateFiles(bin, file, SearchOption.AllDirectories).Where(path =>
{
var normalized = path.Replace('\\', '/');
return !normalized.Contains("/linux-", StringComparison.OrdinalIgnoreCase) &&
(!normalized.Contains("/win-", StringComparison.OrdinalIgnoreCase) || normalized.Contains("/" + rid + "/", StringComparison.OrdinalIgnoreCase));
}).ToList();
return candidates.OrderByDescending(x => x.Replace('\\', '/').Contains("/" + configuration + "/", StringComparison.OrdinalIgnoreCase)).ThenByDescending(File.GetLastWriteTimeUtc).First();
}
public static WorkflowExecutionContext Context(CapabilityRegistry? registry = null, JsonObject? inputs = null, List<RunEvent>? events = null, string? entryNodeId = null, Func<string, JsonObject, CancellationToken, ValueTask<JsonObject>>? host = null) => new()
{
RunId = Guid.NewGuid().ToString("N"), Inputs = inputs ?? [], Capabilities = registry ?? new(), EntryNodeId = entryNodeId,
Subworkflow = (_, _, _) => throw new NotSupportedException(), Secret = (_, _) => ValueTask.FromResult("mock-managed-secret"),
Host = host ?? ((_, _, _) => throw new NotSupportedException()),
Report = ev => { if (events is not null) lock (events) events.Add(ev); return ValueTask.CompletedTask; }
};
public static WorkflowDefinition Graph(params NodeDefinition[] nodes)
{
var workflow = WorkflowTemplates.CreateGraph(); workflow.Graph.Nodes.InsertRange(1, nodes); workflow.Graph.Edges.Clear();
for (var i = 0; i < workflow.Graph.Nodes.Count - 1; i++) workflow.Graph.Edges.Add(new() { FromNode = workflow.Graph.Nodes[i].Id, ToNode = workflow.Graph.Nodes[i + 1].Id });
return workflow;
}
public static CapabilityRegistry Standard()
{
var registry = new CapabilityRegistry();
foreach (var plugin in new IWorkflowPlugin[] { new HttpPlugin(), new FilePlugin(), new AiPlugin(), new WeComPlugin(), new BrowserPlugin(), new TimerPlugin(), new CommandPlugin() }) plugin.Register(registry);
return registry;
}
public static string Package(string directory, PluginManifest? manifest = null, params (string Path, string Text)[] extra)
{
manifest ??= new HttpPlugin().Manifest;
var output = Path.Combine(directory, Guid.NewGuid().ToString("N") + ".xfeplugin");
using var archive = ZipFile.Open(output, ZipArchiveMode.Create);
using (var writer = new StreamWriter(archive.CreateEntry("plugin.json").Open(), new UTF8Encoding(false))) writer.Write(JsonSerializer.Serialize(manifest, WorkflowJson.Options));
var assembly = manifest.Assembly == "XFEWorkflow.Plugins.WeCom.dll" ? typeof(Plugins.WeCom.WeComPlugin).Assembly : typeof(HttpPlugin).Assembly;
archive.CreateEntryFromFile(assembly.Location, manifest.Assembly);
foreach (var file in extra) using (var writer = new StreamWriter(archive.CreateEntry(file.Path).Open())) writer.Write(file.Text);
return output;
}
public static int Port()
{
var listener = new TcpListener(IPAddress.Loopback, 0); listener.Start(); var port = ((IPEndPoint)listener.LocalEndpoint).Port; listener.Stop(); return port;
}
}
internal sealed class TestWorkspace : IAsyncDisposable
{
public WorkspacePaths Paths { get; } = new(Path.Combine(TestSupport.Root, ".artifacts", "tests", Guid.NewGuid().ToString("N")));
public ClientState State { get; }
public TestWorkspace() => State = new(Paths);
public async ValueTask DisposeAsync()
{
await State.DisposeAsync(); await State.Store.FlushAsync();
var allowed = Path.GetFullPath(Path.Combine(TestSupport.Root, ".artifacts", "tests")) + Path.DirectorySeparatorChar;
if (!Paths.Root.StartsWith(allowed, StringComparison.OrdinalIgnoreCase)) throw new IOException("测试清理越界");
Directory.Delete(Paths.Root, true);
}
}
internal sealed class MockHttpServer : IAsyncDisposable
{
private readonly HttpListener listener = new();
private readonly Task loop;
public string Url { get; } = "http://localhost:" + TestSupport.Port() + "/";
public ConcurrentQueue<(string Path, JsonObject Body)> Requests { get; } = [];
public MockHttpServer()
{
listener.Prefixes.Add(Url); listener.Start();
loop = Task.Run(async () =>
{
try
{
while (true)
{
var request = await listener.GetContextAsync();
using var reader = new StreamReader(request.Request.InputStream);
var text = await reader.ReadToEndAsync();
var body = text.Length == 0 ? new JsonObject() : JsonNode.Parse(text)!.AsObject();
Requests.Enqueue((request.Request.Url!.AbsolutePath, body));
var response = request.Request.Url.AbsolutePath switch
{
"/seed" => """{"title":"本地模拟数据"}""",
"/v1/chat/completions" => """{"choices":[{"message":{"role":"assistant","content":"AI 已处理:本地模拟数据"}}]}""",
"/robot" => """{"errcode":0,"errmsg":"ok"}""",
_ => "{}"
};
request.Response.ContentType = "application/json";
var bytes = Encoding.UTF8.GetBytes(response); await request.Response.OutputStream.WriteAsync(bytes); request.Response.Close();
}
}
catch (Exception ex) when (ex is HttpListenerException or ObjectDisposedException) { }
});
}
public async ValueTask DisposeAsync() { listener.Close(); await loop; }
}
using System.Collections.Concurrent;
using System.Diagnostics;
using System.IO.Compression;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using XFEWorkflow.Abstractions;
using XFEWorkflow.Core.Runtime;
using XFEWorkflow.Infrastructure.Storage;
using XFEWorkflow.Plugins.Standard;
namespace XFEWorkflow.Test;
internal static class TestSupport
{
public static string Root
{
get
{
var directory = new DirectoryInfo(AppContext.BaseDirectory);
while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "XFEWorkflow.slnx"))) directory = directory.Parent;
return directory?.FullName ?? throw new DirectoryNotFoundException("找不到测试仓库");
}
}
public static string FindOutput(string project, string file)
{
var bin = Path.Combine(Root, "XFEWorkflow", project, "bin");
var configuration = AppContext.BaseDirectory.Replace('\\', '/').Contains("/Release/", StringComparison.OrdinalIgnoreCase) ? "Release" : "Debug";
var rid = System.Runtime.InteropServices.RuntimeInformation.RuntimeIdentifier;
var candidates = Directory.EnumerateFiles(bin, file, SearchOption.AllDirectories).Where(path =>
{
var normalized = path.Replace('\\', '/');
return !normalized.Contains("/linux-", StringComparison.OrdinalIgnoreCase) &&
(!normalized.Contains("/win-", StringComparison.OrdinalIgnoreCase) || normalized.Contains("/" + rid + "/", StringComparison.OrdinalIgnoreCase));
}).ToList();
return candidates.OrderByDescending(x => x.Replace('\\', '/').Contains("/" + configuration + "/", StringComparison.OrdinalIgnoreCase)).ThenByDescending(File.GetLastWriteTimeUtc).First();
}
public static WorkflowExecutionContext Context(CapabilityRegistry? registry = null, JsonObject? inputs = null, List<RunEvent>? events = null, string? entryNodeId = null, Func<string, JsonObject, CancellationToken, ValueTask<JsonObject>>? host = null) => new()
{
RunId = Guid.NewGuid().ToString("N"), Inputs = inputs ?? [], Capabilities = registry ?? new(), EntryNodeId = entryNodeId,
Subworkflow = (_, _, _) => throw new NotSupportedException(), Secret = (_, _) => ValueTask.FromResult("mock-managed-secret"),
Host = host ?? ((_, _, _) => throw new NotSupportedException()),
Report = ev => { if (events is not null) lock (events) events.Add(ev); return ValueTask.CompletedTask; }
};
public static WorkflowDefinition Graph(params NodeDefinition[] nodes)
{
var workflow = WorkflowTemplates.CreateGraph(); workflow.Graph.Nodes.InsertRange(1, nodes); workflow.Graph.Edges.Clear();
for (var i = 0; i < workflow.Graph.Nodes.Count - 1; i++) workflow.Graph.Edges.Add(new() { FromNode = workflow.Graph.Nodes[i].Id, ToNode = workflow.Graph.Nodes[i + 1].Id });
return workflow;
}
public static CapabilityRegistry Standard()
{
var registry = new CapabilityRegistry();
foreach (var plugin in new IWorkflowPlugin[] { new HttpPlugin(), new FilePlugin(), new AiPlugin(), new WeComPlugin(), new BrowserPlugin(), new TimerPlugin(), new CommandPlugin() }) plugin.Register(registry);
return registry;
}
public static string Package(string directory, PluginManifest? manifest = null, params (string Path, string Text)[] extra)
{
manifest ??= new HttpPlugin().Manifest;
var output = Path.Combine(directory, Guid.NewGuid().ToString("N") + ".xfeplugin");
using var archive = ZipFile.Open(output, ZipArchiveMode.Create);
using (var writer = new StreamWriter(archive.CreateEntry("plugin.json").Open(), new UTF8Encoding(false))) writer.Write(JsonSerializer.Serialize(manifest, WorkflowJson.Options));
var assembly = manifest.Assembly == "XFEWorkflow.Plugins.WeCom.dll" ? typeof(Plugins.WeCom.WeComPlugin).Assembly : typeof(HttpPlugin).Assembly;
archive.CreateEntryFromFile(assembly.Location, manifest.Assembly);
foreach (var file in extra) using (var writer = new StreamWriter(archive.CreateEntry(file.Path).Open())) writer.Write(file.Text);
return output;
}
public static int Port()
{
var listener = new TcpListener(IPAddress.Loopback, 0); listener.Start(); var port = ((IPEndPoint)listener.LocalEndpoint).Port; listener.Stop(); return port;
}
}
internal sealed class TestWorkspace : IAsyncDisposable
{
public WorkspacePaths Paths { get; } = new(Path.Combine(TestSupport.Root, ".artifacts", "tests", Guid.NewGuid().ToString("N")));
public ClientState State { get; }
public TestWorkspace() => State = new(Paths);
public async ValueTask DisposeAsync()
{
await State.DisposeAsync(); await State.Store.FlushAsync();
var allowed = Path.GetFullPath(Path.Combine(TestSupport.Root, ".artifacts", "tests")) + Path.DirectorySeparatorChar;
if (!Paths.Root.StartsWith(allowed, StringComparison.OrdinalIgnoreCase)) throw new IOException("测试清理越界");
Directory.Delete(Paths.Root, true);
}
}
internal sealed class MockHttpServer : IAsyncDisposable
{
private readonly HttpListener listener = new();
private readonly Task loop;
public string Url { get; } = "http://localhost:" + TestSupport.Port() + "/";
public ConcurrentQueue<(string Path, JsonObject Body)> Requests { get; } = [];
public MockHttpServer()
{
listener.Prefixes.Add(Url); listener.Start();
loop = Task.Run(async () =>
{
try
{
while (true)
{
var request = await listener.GetContextAsync();
using var reader = new StreamReader(request.Request.InputStream);
var text = await reader.ReadToEndAsync();
var body = text.Length == 0 ? new JsonObject() : JsonNode.Parse(text)!.AsObject();
Requests.Enqueue((request.Request.Url!.AbsolutePath, body));
var response = request.Request.Url.AbsolutePath switch
{
"/seed" => """{"title":"本地模拟数据"}""",
"/v1/chat/completions" => """{"choices":[{"message":{"role":"assistant","content":"AI 已处理:本地模拟数据"}}]}""",
"/robot" => """{"errcode":0,"errmsg":"ok"}""",
_ => "{}"
};
request.Response.ContentType = "application/json";
var bytes = Encoding.UTF8.GetBytes(response); await request.Response.OutputStream.WriteAsync(bytes); request.Response.Close();
}
}
catch (Exception ex) when (ex is HttpListenerException or ObjectDisposedException) { }
});
}
public async ValueTask DisposeAsync() { listener.Close(); await loop; }
}