借助网络配置,控制Modbus工具的日志显示,避免卡死界面
智能大石头 authored at 2021-12-11 22:09:19
8.63 KiB
XCoder
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input.Platform;
using Avalonia.VisualTree;
using NewLife.XCoder.Controls;
using NewLife.XCoder.Shell;
using Xunit;

namespace XCoder.App.UiTests;

/// <summary>工具页面的响应式布局测试</summary>
/// <remarks>
/// 工具页曾用固定高度的文本框与左对齐的窄容器,窗口最大化后内容不跟随放大。
/// 这里在无头环境中以两种尺寸走布局,确保页面铺满宽度、可伸缩的文本框/日志视图随窗口变高,
/// 同时覆盖磁盘星图的驱动器快捷入口。
/// </remarks>
public class ToolLayoutTests
{
    private static Task RunOnUi(Action action) => UiSession.Run(action);

    private static Task RunOnUi(Func<Task> action) => UiSession.Run(action);

    private sealed record LayoutResult(Double Width, Double Height, Double TextHeight, Boolean ChecksGrowth);

    private static LayoutResult Measure(Type viewType, Double width, Double height) => Measure((Control)Activator.CreateInstance(viewType)!, width, height);

    private static LayoutResult Measure(Control instance, Double width, Double height)
    {
        var source = instance as Window;
        var view = source?.Content as Control ?? instance;
        if (source != null) source.Content = null;

        var window = new Window { Width = width, Height = height, Content = view };
        window.Show();
        try
        {
            var pageRoot = view is UserControl ? view.FindControl<Control>("PageRoot") : null;
            var root = pageRoot ?? view;
            var textHeight = view.GetVisualDescendants()
                .OfType<Control>()
                .Where(e => e is LogView || (e is TextBox box && box.AcceptsReturn))
                .Select(e => e.Bounds.Height)
                .DefaultIfEmpty(0)
                .Max();

            // 未采用统一页容器的 UserControl(仍在迁移中)只断言铺满,伸缩断言由迁移后的页容器承担
            return new LayoutResult(root.Bounds.Width, root.Bounds.Height, textHeight, view is not UserControl || pageRoot != null);
        }
        finally
        {
            window.Close();
            try { source?.Close(); } catch { }
        }
    }

    [Fact]
    [DisplayName("全部工具页铺满窗口,可伸缩区域的文本框随高度放大")]
    public async Task AllToolViews_Stretch()
    {
        await RunOnUi(() =>
        {
            var failures = new List<String>();
            var views = ToolRegistry.Tools
                .Where(e => e.ViewType != null)
                .ToList();

            Assert.NotEmpty(views);

            foreach (var tool in views)
            {
                try
                {
                    var large = Measure(tool.ViewType!, 1600, 1000);
                    if (large.Width <= 1500) failures.Add($"{tool.Key}: 页面宽度未铺满({large.Width:F0})");
                    if (large.Height <= 900) failures.Add($"{tool.Key}: 页面高度未铺满({large.Height:F0})");

                    if (large.ChecksGrowth && large.TextHeight > 0)
                    {
                        var small = Measure(tool.ViewType!, 900, 600);
                        if (large.TextHeight <= small.TextHeight + 50)
                            failures.Add($"{tool.Key}: 文本框未随窗口放大({small.TextHeight:F0} -> {large.TextHeight:F0})");
                    }
                }
                catch (Exception ex)
                {
                    failures.Add($"{tool.Key}: {ex.GetType().Name} {ex.Message}");
                }
            }

            Assert.True(failures.Count == 0, "以下工具布局未通过:" + Environment.NewLine + String.Join(Environment.NewLine, failures));
        });
    }

    [Fact]
    [DisplayName("加密解密纵向流水线铺满窗口且输入框随高度增长")]
    public async Task CryptoPipeline_Stretches()
    {
        await RunOnUi(() =>
        {
            var type = typeof(NewLife.XCoder.Tools.Crypto.CryptoToolView);
            var large = Measure(type, 1600, 1000);
            var small = Measure(type, 900, 600);

            Assert.True(large.Width > 1500, $"页面宽度未铺满:{large.Width}");
            Assert.True(large.Height > 900, $"页面高度未铺满:{large.Height}");
            Assert.True(large.TextHeight > small.TextHeight + 50, $"输入框未随窗口放大:{small.TextHeight} -> {large.TextHeight}");
        });
    }

    [Fact]
    [DisplayName("磁盘星图列出磁盘卷并生成树图")]
    public async Task FolderStat_ShowsVolumes()
    {
        await RunOnUi(() =>
        {
            var view = new NewLife.XCoder.Tools.Folder.FolderStatToolView();
            var result = Measure(view, 1600, 1000);

            Assert.True(result.Width > 1500, $"页面宽度未铺满:{result.Width}");
            Assert.True(result.Height > 900, $"页面高度未铺满:{result.Height}");

            var map = view.FindControl<NewLife.XCoder.Tools.Folder.TreemapControl>("Map");
            Assert.NotNull(map);
            Assert.NotEmpty(map!.Items);
            Assert.NotEmpty(map.Tiles);
        });
    }

    [Fact]
    [DisplayName("删除确认默认隐藏并提供状态说明")]
    public async Task FolderStat_DeleteOverlayHidden()
    {
        await RunOnUi(() =>
        {
            var view = new NewLife.XCoder.Tools.Folder.FolderStatToolView();
            _ = Measure(view, 1600, 1000);

            var overlay = view.FindControl<Border>("DeleteOverlay");
            Assert.NotNull(overlay);
            Assert.False(overlay!.IsVisible);

            var hint = view.FindControl<TextBlock>("StateHintText");
            Assert.NotNull(hint);
            Assert.False(String.IsNullOrWhiteSpace(hint!.Text));

            var queue = view.FindControl<TextBlock>("DeleteQueueText");
            Assert.NotNull(queue);
            Assert.False(queue!.IsVisible);

            var cleanup = view.FindControl<Border>("CleanupOverlay");
            Assert.NotNull(cleanup);
            Assert.False(cleanup!.IsVisible);
            Assert.NotNull(view.FindControl<StackPanel>("CleanupPanel"));
        });
    }

    [Fact]
    [DisplayName("复制路径写入剪贴板并给出提示")]
    public async Task FolderStat_CopyPath_WritesClipboard()
    {
        await RunOnUi(async () =>
        {
            var view = new NewLife.XCoder.Tools.Folder.FolderStatToolView();
            var window = new Window { Width = 1200, Height = 800, Content = view };
            window.Show();
            try
            {
                var clipboard = TopLevel.GetTopLevel(view)?.Clipboard;
                Assert.NotNull(clipboard);

                var method = typeof(NewLife.XCoder.Tools.Folder.FolderStatToolView)
                    .GetMethod("CopyTextAsync", BindingFlags.Instance | BindingFlags.NonPublic);
                Assert.NotNull(method);

                var path = "D:\\probe-path";
                var task = (Task)method!.Invoke(view, [path])!;
                await task;

                Assert.Equal(path, await clipboard!.TryGetTextAsync());

                var toast = view.FindControl<Border>("Toast");
                var text = view.FindControl<TextBlock>("ToastText");
                Assert.True(toast!.IsVisible);
                Assert.Contains("probe-path", text!.Text);
            }
            finally
            {
                window.Close();
            }
        });
    }

    [Fact]
    [DisplayName("树图命中测试返回对应磁盘块")]
    public async Task Treemap_HitTest()
    {
        await RunOnUi(() =>
        {
            var control = new NewLife.XCoder.Tools.Folder.TreemapControl();
            var window = new Window { Width = 600, Height = 400, Content = control };
            window.Show();
            try
            {
                var tree = new NewLife.XCoder.Tools.Folder.DiskScanner().BuildTree(
                [
                    new NewLife.XCoder.Tools.Folder.FolderDrive("C:\\", "C", 300, 100, true),
                    new NewLife.XCoder.Tools.Folder.FolderDrive("D:\\", "D", 100, 20, true),
                ]);
                control.SetLevel(tree, tree.Children);

                Assert.Equal(2, control.Tiles.Count);
                var largest = control.Tiles.OrderByDescending(e => e.Bounds.Width * e.Bounds.Height).First();
                var hit = control.HitTest(largest.Bounds.Center);

                Assert.NotNull(hit);
                Assert.Equal("C:\\", hit!.FullPath);
            }
            finally
            {
                window.Close();
            }
        });
    }
}