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

XFEWorkflow

【WinUI】XFE基于windows的工作流

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Diagnostics;
using System.IO.Compression;
using System.Text;
using System.Text.Json;
using Microsoft.UI.Xaml.Automation;
using Microsoft.UI.Xaml.Media;
using XFEWorkflow.Abstractions;
using XFEWorkflow.Controls;
using XFEWorkflow.Core.Runtime;
using XFEWorkflow.Infrastructure.Storage;
using XFEWorkflow.Space.Contracts;
using XFEWorkflow.ViewModels;
using XFEWorkflow.Views;

namespace XFEWorkflow.Services;

internal static partial class UiSmokeTest
{
    private static async Task SmokeSpaceAsync(string output, bool nativeInput = true)
    {
        Directory.CreateDirectory(output);
        var directory = new DirectoryInfo(AppContext.BaseDirectory);
        while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "XFEWorkflow.slnx"))) directory = directory.Parent;
        var repository = directory?.FullName ?? throw new DirectoryNotFoundException("找不到 Space 服务端");
        var serverDll = Path.Combine(repository, "XFEWorkflow", "XFEWorkflow.Space.Server", "bin", "x64", "Release", "net10.0", "XFEWorkflow.Space.Server.dll");
        var services = AppServices.Current; var shell = AppShellPage.Current!; var navigation = shell.ViewModel.NavigationViewService;
        var frame = (Frame)shell.FindName("navigationFrame"); var root = (FrameworkElement)App.MainWindow.Content;
        var size = App.MainWindow.AppWindow.Size; var theme = root.RequestedTheme; var address = services.State.SpaceAddress;
        var serverRoot = Path.Combine(output, "space-server"); var logs = new StringBuilder();
        const string password = "space-native-fixture-password";
        Process StartServer(bool initialize, string url)
        {
            var info = new ProcessStartInfo("dotnet") { UseShellExecute = false, CreateNoWindow = true, WindowStyle = ProcessWindowStyle.Hidden, RedirectStandardOutput = true, RedirectStandardError = true, RedirectStandardInput = initialize };
            info.ArgumentList.Add(serverDll); info.ArgumentList.Add("--data=" + serverRoot);
            if (initialize) { info.ArgumentList.Add("--init-admin"); info.ArgumentList.Add("--account=administrator"); }
            else info.ArgumentList.Add("--url=" + url);
            var process = Process.Start(info)!;
            process.OutputDataReceived += (_, e) => { if (e.Data is not null) lock (logs) logs.AppendLine(e.Data); };
            process.ErrorDataReceived += (_, e) => { if (e.Data is not null) lock (logs) logs.AppendLine(e.Data); };
            process.BeginOutputReadLine(); process.BeginErrorReadLine(); return process;
        }
        var portSource = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Loopback, 0); portSource.Start(); var port = ((System.Net.IPEndPoint)portSource.LocalEndpoint).Port; portSource.Stop();
        var url = $"http://localhost:{port}/";
        Process? server = null;
        try
        {
            using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(40));
            using (var initialization = StartServer(true, url))
            {
                await initialization.StandardInput.WriteLineAsync(password); initialization.StandardInput.Close();
                try { await initialization.WaitForExitAsync(deadline.Token); }
                finally { if (!initialization.HasExited) initialization.Kill(true); }
                if (initialization.ExitCode != 0) throw new InvalidOperationException("Space 验收管理员初始化失败:" + logs);
            }
            server = StartServer(false, url); services.State.SpaceAddress = url + "space/v1/"; services.Space.Reconnect();
            while (true)
            {
                try { await services.Space.RequestAsync("health", ct: deadline.Token); break; }
                catch (Exception) when (!deadline.IsCancellationRequested) { await Task.Delay(80, deadline.Token); }
            }
            await services.Space.LoginAsync("administrator", password, deadline.Token);
            var original = services.Plugins.Installed.First(p => p.Manifest.Id == "xfe.http"); var manifest = WorkflowJson.Clone(original.Manifest); manifest.Version = "100.0.0";
            var package = Path.Combine(services.Paths.Temp, "space-ui-plugin.xfeplugin");
            try
            {
                using (var zip = ZipFile.Open(package, ZipArchiveMode.Create))
                { using (var writer = new StreamWriter(zip.CreateEntry("plugin.json").Open())) writer.Write(JsonSerializer.Serialize(manifest, WorkflowJson.Options)); zip.CreateEntryFromFile(Path.Combine(original.Directory, manifest.Assembly), manifest.Assembly); }
                var publication = await services.Space.UploadAsync(package, ct: deadline.Token);
                await services.Space.RequestAsync("reviews/decide", new() { ["id"] = publication.Id, ["decision"] = "publish" }, deadline.Token);
            }
            finally { if (File.Exists(package)) File.Delete(package); }
            await services.Space.RequestAsync("register", new() { ["account"] = "space-author", ["password"] = password, ["nickname"] = "工作流分享作者" }, deadline.Token);
            await services.Space.LoginAsync("space-author", password, deadline.Token);
            var flow = WorkflowTemplates.Welcome(); flow.Name = "Space 连线与文本示例😀"; flow.Description = "工作流上传、审核与依赖下载验收";
            if (!nativeInput) flow.Name += " · 只读预览验收";
            var loop = new NodeDefinition { CapabilityId = "core.foreach", Name = "预览遍历子图", X = 1000, Y = 120, Parameters = new() { ["items"] = new System.Text.Json.Nodes.JsonArray("a") }, Children = new() { ["body"] = WorkflowTemplates.EmptyGraph() } };
            var end = flow.Graph.Nodes.Single(n => n.CapabilityId == "core.end"); end.X = 1440;
            flow.Graph.Edges.Single(e => e.ToNode == end.Id).ToNode = loop.Id; flow.Graph.Nodes.Add(loop); flow.Graph.Edges.Add(new() { FromNode = loop.Id, ToNode = end.Id });
            flow.PluginVersions[manifest.Id] = manifest.Version; flow.Enabled = false; await services.Workflows.SaveAsync(flow);
            shell.ShowBrowser(false); shell.SetNavigationOpenForSmoke(false);
            var scale = root.XamlRoot.RasterizationScale; App.MainWindow.AppWindow.Resize(new((int)(1440 * scale), (int)(960 * scale))); root.RequestedTheme = ElementTheme.Dark;
            navigation.NavigateTo<SpacePage>(); await WaitManagementAsync(() => frame.Content is SpacePage && Descendants<GridView>(frame).Any(v => v.Items.Count == 1));
            var page = (SpacePage)frame.Content;
            Button Button(string id) => Descendants<Button>(page).Single(b => AutomationProperties.GetAutomationId(b) == id);
            var tabs = Descendants<Pivot>(page).Single();
            var catalog = Descendants<GridView>(page).Single();
            var kind = Descendants<ComboBox>(page).Single(c => AutomationProperties.GetAutomationId(c) == "SpaceResourceKind");
            var search = Descendants<TextBox>(page).Single(c => AutomationProperties.GetAutomationId(c) == "SpaceSearch");
            ContentDialog? Dialog() => VisualTreeHelper.GetOpenPopupsForXamlRoot(root.XamlRoot).SelectMany(p => Descendants<ContentDialog>(p.Child)).FirstOrDefault();
            async Task AcceptDialogAsync()
            {
                await WaitManagementAsync(() => Dialog() is not null); var dialog = Dialog()!;
                await InvokeButtonAsync(Descendants<Button>(dialog).First(b => b.Name == "PrimaryButton" || b.Content as string == dialog.PrimaryButtonText));
                await WaitManagementAsync(() => Dialog() is null);
            }
            if (tabs.Items.Count != 3 || Descendants<NavigationViewItem>(shell).Count(n => n.Content as string == "Space") != 1) throw new InvalidOperationException("Space 未独立导航或普通作者能看到审核中心");
            if (Button("SpacePrevious").IsEnabled || Button("SpaceNext").IsEnabled) throw new InvalidOperationException("Space 只有一页时翻页按钮仍可用");
            foreach (var id in new[] { "SpaceUploadPlugin", "SpaceUploadWorkflow", "SpaceDownloadPlugin" }) if (!Button(id).IsEnabled) throw new InvalidOperationException("Space 操作不可用:" + id);
            await CaptureWindowAsync(Path.Combine(output, "space-plugins-dark.png"));
            await InvokeButtonAsync(Button("SpaceUploadWorkflow")); await WaitManagementAsync(() => Dialog() is not null);
            var uploadDialog = Dialog()!; Descendants<ComboBox>(uploadDialog).Single().SelectedItem = Descendants<ComboBox>(uploadDialog).Single().Items.OfType<WorkflowDefinition>().Single(w => w.Id == flow.Id);
            Descendants<TextBox>(uploadDialog).Single(t => AutomationProperties.GetAutomationId(t) == "SpaceWorkflowVersion").Text = "2.0.0";
            await CaptureWindowAsync(Path.Combine(output, "space-workflow-upload.png")); await AcceptDialogAsync();
            await WaitManagementAsync(() => (tabs.SelectedItem as PivotItem)?.Tag as string == "mine" && kind.SelectedIndex == 1 && catalog.Items.OfType<SpaceCardModel>().Any(c => c.ResourceId == flow.Id && c.Status == PublicationStatus.Pending));
            if (Descendants<Button>(page).Any(b => AutomationProperties.GetAutomationId(b) == "SpaceDownloadWorkflow")) throw new InvalidOperationException("待审核工作流允许下载");
            await CaptureWindowAsync(Path.Combine(output, "space-my-workflow-pending.png"));
            await services.Space.LoginAsync("administrator", password, deadline.Token); await WaitManagementAsync(() => tabs.Items.Count == 4);
            tabs.SelectedItem = tabs.Items.OfType<PivotItem>().Single(t => t.Tag as string == "review");
            await WaitManagementAsync(() => Descendants<Button>(page).Any(b => AutomationProperties.GetAutomationId(b) == "SpaceApprove"));
            await InvokeButtonAsync(Button("SpaceApprove")); await AcceptDialogAsync();
            await WaitManagementAsync(() => catalog.Items.OfType<SpaceCardModel>().Any(c => c.ResourceId == flow.Id && c.Status == PublicationStatus.Published));
            await CaptureWindowAsync(Path.Combine(output, "space-workflow-review.png"));
            for (var i = 0; i < 25; i++)
            {
                var paging = WorkflowTemplates.CreateGraph(); paging.Name = "分页验收 " + (i + 1);
                var published = await services.Space.UploadWorkflowAsync(paging, "1.0.0", ct: deadline.Token);
                await services.Space.RequestAsync("reviews/decide", new() { ["kind"] = "workflow", ["id"] = published.Id, ["decision"] = "publish" }, deadline.Token);
            }
            tabs.SelectedItem = tabs.Items.OfType<PivotItem>().Single(t => t.Tag as string == "workflows");
            await WaitManagementAsync(() => catalog.Items.Count == 24 && Button("SpaceNext").IsEnabled);
            await InvokeButtonAsync(Button("SpaceNext")); await WaitManagementAsync(() => catalog.Items.Count == 2 && !Button("SpaceNext").IsEnabled && Button("SpacePrevious").IsEnabled);
            await InvokeButtonAsync(Button("SpacePrevious")); await WaitManagementAsync(() => catalog.Items.Count == 24 && Button("SpaceNext").IsEnabled && !Button("SpacePrevious").IsEnabled);
            search.Text = "不存在的工作流"; await InvokeButtonAsync(Button("SearchSpace")); await WaitManagementAsync(() => catalog.Items.Count == 0);
            search.Text = flow.Id; await InvokeButtonAsync(Button("SearchSpace")); await WaitManagementAsync(() => catalog.Items.Count == 1);
            await InvokeButtonAsync(Button("SpaceAllVersions"));
            if (Descendants<ComboBox>(page).Single(c => AutomationProperties.GetAutomationId(c) == "SpaceVersions").Items.Count != 1) throw new InvalidOperationException("工作流版本列表不正确");
            var workflowCount = (await services.Workflows.ListAsync()).Count; var pluginCount = services.Plugins.Installed.Count;
            await InvokeButtonAsync(Button("SpacePreviewWorkflow")); await WaitManagementAsync(() => Dialog() is not null && Descendants<WorkflowPreviewControl>(Dialog()!).Any());
            var previewDialog = Dialog()!; var preview = Descendants<WorkflowPreviewControl>(previewDialog).Single();
            var graphSnapshot = JsonSerializer.Serialize(preview.Canvas.Graph, WorkflowJson.Options);
            if (!preview.Canvas.IsReadOnly || !preview.Code.IsReadOnly || !preview.Code.Text.Contains("core.log") || !preview.Code.Text.Contains("GraphDefinition")) throw new InvalidOperationException("Space 图形或对应代码不是只读真实预览");
            preview.Canvas.AddNode(CoreCapabilities.Catalog()["core.log"]); preview.Canvas.Disconnect(preview.Canvas.Graph.Edges[0].Id); preview.Canvas.ToggleBreakpoint(preview.Canvas.Graph.Nodes[0].Id); preview.Canvas.Delete();
            if (graphSnapshot != JsonSerializer.Serialize(preview.Canvas.Graph, WorkflowJson.Options)) throw new InvalidOperationException("只读预览允许修改图形");
            var previewScopes = Descendants<ComboBox>(preview).Single(); if (previewScopes.Items.Count != 2) throw new InvalidOperationException("Space 未显示结构化子图");
            previewScopes.SelectedIndex = 1; await Task.Delay(100); if (preview.Canvas.Graph.Nodes.Count != 2) throw new InvalidOperationException("子图切换没有显示真实流程"); previewScopes.SelectedIndex = 0;
            var previewTabs = Descendants<TabView>(preview).Single(); previewTabs.SelectedIndex = 1; await preview.Code.Ready.WaitAsync(TimeSpan.FromSeconds(12));
            await Task.Delay(180);
            await AtomicJson.WriteAsync(Path.Combine(output, "space-preview-code-layout.json"), new { previewWidth = preview.ActualWidth, previewHeight = preview.ActualHeight, tabsWidth = previewTabs.ActualWidth, tabsHeight = previewTabs.ActualHeight, codeWidth = preview.Code.ActualWidth, codeHeight = preview.Code.ActualHeight, selectedIndex = previewTabs.SelectedIndex, selected = (previewTabs.SelectedItem as TabViewItem)?.Header });
            await WaitManagementAsync(() => preview.Code.ActualWidth > 100 && preview.Code.ActualHeight > 100); await Task.Delay(150);
            if (await preview.Code.ProbeAsync("editor.getOption(monaco.editor.EditorOption.readOnly)") != "true") throw new InvalidOperationException("Monaco 预览仍可输入代码");
            await preview.Code.CaptureAsync(Path.Combine(output, "space-preview-code.png")); previewTabs.SelectedIndex = 2;
            await WaitManagementAsync(() => Descendants<TextBlock>(preview).Any(t => t.Text.Contains(manifest.Name) && t.Text.Contains(manifest.Version)));
            if (!Descendants<TextBlock>(preview).Any(t => t.Text.Contains(manifest.Name) && t.Text.Contains(manifest.Version))) throw new InvalidOperationException("Space 预览缺少插件名称与锁定版本");
            await CaptureElementAsync(previewDialog, Path.Combine(output, "space-preview-plugins.png")); previewDialog.Hide(); await WaitManagementAsync(() => Dialog() is null);
            // Capture an island popup only after its interactive scenarios;
            // RenderTargetBitmap can invalidate its native child layout.
            await WaitManagementAsync(() => Button("SpacePreviewWorkflow").IsEnabled); await InvokeButtonAsync(Button("SpacePreviewWorkflow"));
            await WaitManagementAsync(() => Dialog() is not null && Descendants<WorkflowPreviewControl>(Dialog()!).Any());
            var graphDialog = Dialog()!; Descendants<WorkflowPreviewControl>(graphDialog).Single().Canvas.CenterView(true); await Task.Delay(180);
            await CaptureElementAsync(graphDialog, Path.Combine(output, "space-preview-graph.png")); graphDialog.Hide(); await WaitManagementAsync(() => Dialog() is null);
            if ((await services.Workflows.ListAsync()).Count != workflowCount || services.Plugins.Installed.Count != pluginCount) throw new InvalidOperationException("预览触发了安装或导入");
            await InvokeButtonAsync(Button("SpaceDownloadWorkflow")); await WaitManagementAsync(() => Descendants<Button>(page).Any(b => AutomationProperties.GetAutomationId(b) == "SpaceOpenImportedWorkflow"));
            var imported = (await services.Workflows.ListAsync()).Single(w => w.Name == flow.Name && w.Id != flow.Id);
            if (imported.Enabled == true || services.Runs.IsRunning(imported.Id) || !services.Plugins.Installed.Any(p => p.Manifest.Id == manifest.Id && p.Manifest.Version == manifest.Version && p.Enabled)) throw new InvalidOperationException("工作流导入激活状态或插件依赖安装不正确");
            if (!Descendants<TextBlock>(page).Any(t => t.Text.Contains(manifest.Id + "  " + manifest.Version + " · 已安装并启用"))) throw new InvalidOperationException("依赖安装后 Space 详情未刷新");
            var panels = Descendants<DetailsWorkspace>(page).Single(); var before = panels.Details.ActualWidth;
            if (nativeInput)
            {
                App.MainWindow.Activate(); SetForegroundWindow(WinRT.Interop.WindowNative.GetWindowHandle(App.MainWindow)); await Task.Delay(180); await DragElementAsync(panels.Splitter, -36, 0);
                if (Math.Abs(panels.Details.ActualWidth - before - 36) > 4) throw new InvalidOperationException("Space 详情面板无法拖动调整");
            }
            await CaptureWindowAsync(Path.Combine(output, "space-workflows-dark.png"));
            root.RequestedTheme = ElementTheme.Light; await Task.Delay(150); await CaptureWindowAsync(Path.Combine(output, "space-workflows-light.png"));
            App.MainWindow.AppWindow.Resize(new((int)(760 * scale), (int)(940 * scale))); await Task.Delay(300);
            if (panels.Splitter.Orientation != Orientation.Horizontal || panels.Details.ActualHeight < 140 || panels.Master.ActualHeight < 100) throw new InvalidOperationException("Space 窄窗口布局不可用");
            await CaptureWindowAsync(Path.Combine(output, "space-workflows-narrow.png"));
            await AtomicJson.WriteAsync(Path.Combine(output, "space-publication-evidence.json"), new { sourceId = flow.Id, importedId = imported.Id, imported.Enabled, pluginId = manifest.Id, pluginVersion = manifest.Version, authorTabs = 3, administratorTabs = tabs.Items.Count, splitterBefore = before, splitterAfter = panels.Details.ActualWidth });
        }
        finally
        {
            navigation.NavigateTo<MainPage>(); await services.Space.LogoutAsync(); services.State.SpaceAddress = address; services.Space.Reconnect();
            root.RequestedTheme = theme; App.MainWindow.AppWindow.Resize(size);
            if (server is not null) { if (!server.HasExited) { server.Kill(true); await server.WaitForExitAsync(); } server.Dispose(); }
            await File.WriteAllTextAsync(Path.Combine(output, "space-server-console.txt"), logs.ToString());
        }
    }
}