借助网络配置,控制Modbus工具的日志显示,避免卡死界面
智能大石头 authored at 2021-12-11 22:09:19
7.39 KiB
XCoder
using System;
using System.ComponentModel;
using NewLife.XCoder.Services;
using NewLife.XCoder.Tools.Voice;
using Xunit;

namespace XCoder.App.Tests;

/// <summary>在线更新检查测试</summary>
public class UpdateCheckerTests
{
    [Fact]
    [DisplayName("JSON 清单解析出版本、地址与说明")]
    public void Parse_Json()
    {
        var manifest = UpdateChecker.Parse("""{"version":"8.2.2026.1201","url":"https://x/a.zip","notes":"修复若干问题","force":true}""");

        Assert.NotNull(manifest);
        Assert.Equal("8.2.2026.1201", manifest!.Version);
        Assert.Equal("https://x/a.zip", manifest.Url);
        Assert.Equal("修复若干问题", manifest.Notes);
        Assert.True(manifest.Force);
    }

    [Fact]
    [DisplayName("纯文本清单取首行有效内容")]
    public void Parse_PlainText()
    {
        var manifest = UpdateChecker.Parse("# 注释行\n8.2.2026.1201 https://x/a.zip 新增 SQL 工作台");

        Assert.NotNull(manifest);
        Assert.Equal("8.2.2026.1201", manifest!.Version);
        Assert.Equal("https://x/a.zip", manifest.Url);
        Assert.Contains("SQL", manifest.Notes);
        Assert.False(manifest.Force);
    }

    [Theory]
    [DisplayName("空内容/非法 JSON/缺少版本返回空")]
    [InlineData("")]
    [InlineData("   ")]
    [InlineData("{bad json}")]
    [InlineData("""{"url":"https://x"}""")]
    public void Parse_Invalid(String text)
    {
        Assert.Null(UpdateChecker.Parse(text));
    }

    [Theory]
    [DisplayName("版本比较按段数值判断")]
    [InlineData("8.2.2026.1111", "8.2.2026.1201", true)]
    [InlineData("8.2.2026.1201", "8.2.2026.1111", false)]
    [InlineData("8.2.2026.1111", "8.2.2026.1111", false)]
    [InlineData("8.2.2026.1111-beta0906", "8.2.2026.1111", false)]
    [InlineData("9.0", "10.0", true)]
    [InlineData("", "8.2", true)]
    [InlineData("8.2", "", false)]
    public void IsNewer_Works(String current, String latest, Boolean expected)
    {
        Assert.Equal(expected, UpdateChecker.IsNewer(current, latest));
    }

    [Fact]
    [DisplayName("无法解析的地址返回空而不抛异常")]
    public async System.Threading.Tasks.Task FetchAsync_InvalidUrl_ReturnsNull()
    {
        var manifest = await UpdateChecker.FetchAsync("http://127.0.0.1:1/not-exist.json", 2);

        Assert.Null(manifest);
    }

    [Fact]
    [DisplayName("可从本地 HTTP 服务下载更新包并按 URL 末段命名")]
    public async System.Threading.Tasks.Task DownloadAsync_Works()
    {
        // 用 TcpListener 起一个极简 HTTP 服务,避免依赖外部网络
        var listener = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Loopback, 0);
        listener.Start();
        var port = ((System.Net.IPEndPoint)listener.LocalEndpoint).Port;
        var payload = System.Text.Encoding.UTF8.GetBytes("fake-zip-content");

        var server = System.Threading.Tasks.Task.Run(async () =>
        {
            using var client = await listener.AcceptTcpClientAsync();
            using var stream = client.GetStream();
            var buffer = new Byte[1024];
            await stream.ReadAsync(buffer);

            var header = System.Text.Encoding.ASCII.GetBytes(
                "HTTP/1.1 200 OK\r\nContent-Type: application/zip\r\nContent-Length: " + payload.Length + "\r\nConnection: close\r\n\r\n");
            await stream.WriteAsync(header);
            await stream.WriteAsync(payload);
            await stream.FlushAsync();
        });

        var dir = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "xcoder-dl-" + Guid.NewGuid().ToString("N"));
        try
        {
            var path = await UpdateChecker.DownloadAsync($"http://127.0.0.1:{port}/pkg/XCoder-9.9.zip", null, dir, 10);

            Assert.True(System.IO.File.Exists(path));
            Assert.EndsWith("XCoder-9.9.zip", path);
            Assert.Equal("fake-zip-content", await System.IO.File.ReadAllTextAsync(path));
        }
        finally
        {
            listener.Stop();
            try { await server.WaitAsync(TimeSpan.FromSeconds(3)); } catch { }
            if (System.IO.Directory.Exists(dir)) System.IO.Directory.Delete(dir, true);
        }
    }

    [Fact]
    [DisplayName("下载空地址抛参数异常")]
    public async System.Threading.Tasks.Task DownloadAsync_EmptyUrl_Throws()
    {
        await Assert.ThrowsAsync<ArgumentException>(() => UpdateChecker.DownloadAsync(""));
    }

    [Fact]
    [DisplayName("只有 exe/msi 才算可直接运行的安装包")]
    public void IsInstallerFile_Cases()
    {
        var dir = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "xcoder-inst-" + Guid.NewGuid().ToString("N"));
        System.IO.Directory.CreateDirectory(dir);

        try
        {
            var exe = System.IO.Path.Combine(dir, "setup.exe");
            var msi = System.IO.Path.Combine(dir, "setup.MSI");
            var zip = System.IO.Path.Combine(dir, "pkg.zip");

            foreach (var file in new[] { exe, msi, zip }) System.IO.File.WriteAllText(file, "x");

            Assert.True(UpdateChecker.IsInstallerFile(exe));
            Assert.True(UpdateChecker.IsInstallerFile(msi));
            Assert.False(UpdateChecker.IsInstallerFile(zip));
            Assert.False(UpdateChecker.IsInstallerFile(System.IO.Path.Combine(dir, "missing.exe")));
            Assert.False(UpdateChecker.IsInstallerFile(null));
            Assert.False(UpdateChecker.IsInstallerFile(""));
        }
        finally
        {
            System.IO.Directory.Delete(dir, true);
        }
    }
}

/// <summary>语音命令构建测试</summary>
public class SpeechCommandBuilderTests
{
    [Fact]
    [DisplayName("三平台各自生成朗读命令")]
    public void Build_PerPlatform()
    {
        var win = SpeechCommandBuilder.Build(true, false, "测试");
        var linux = SpeechCommandBuilder.Build(false, false, "测试");
        var mac = SpeechCommandBuilder.Build(false, true, "测试");

        Assert.Contains("System.Speech", win);
        Assert.Contains("espeak", linux);
        Assert.StartsWith("say ", mac);
        Assert.Contains("测试", linux);
    }

    [Fact]
    [DisplayName("导出音频时命令带输出文件参数")]
    public void Build_WithOutputFile()
    {
        var linux = SpeechCommandBuilder.Build(false, false, "测试", "/tmp/a.wav");
        var mac = SpeechCommandBuilder.Build(false, true, "测试", "/tmp/a.aiff");

        Assert.Contains("-w \"/tmp/a.wav\"", linux);
        Assert.Contains("-o \"/tmp/a.aiff\"", mac);
    }

    [Fact]
    [DisplayName("引号被转义,换行折叠为空格")]
    public void Build_EscapesText()
    {
        var linux = SpeechCommandBuilder.Build(false, false, "他说\"你好\"\n第二行");

        Assert.Contains("\\\"你好\\\"", linux);
        Assert.DoesNotContain("\n", linux);
    }

    [Theory]
    [DisplayName("空文本构建朗读命令抛出异常")]
    [InlineData(null)]
    [InlineData("")]
    [InlineData("   ")]
    public void Build_EmptyText_Throws(String? text)
    {
        Assert.Throws<ArgumentException>(() => SpeechCommandBuilder.Build(false, false, text!));
    }

    [Fact]
    [DisplayName("探测命令按平台区分")]
    public void BuildProbe_PerPlatform()
    {
        Assert.Contains("System.Speech", SpeechCommandBuilder.BuildProbe(true, false));
        Assert.Equal("say -v ?", SpeechCommandBuilder.BuildProbe(false, true));
        Assert.Contains("espeak", SpeechCommandBuilder.BuildProbe(false, false));
    }
}