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

namespace XCoder.App.Tests;

/// <summary>磁盘清理服务测试:只清理临时测试目录,不触碰真实回收站</summary>
public class CleanupServiceTests : IDisposable
{
    private readonly String _root = Path.Combine(Path.GetTempPath(), "xcoder-cleanup-test-" + Guid.NewGuid().ToString("N"));

    public CleanupServiceTests() => Directory.CreateDirectory(_root);

    public void Dispose()
    {
        try { if (Directory.Exists(_root)) Directory.Delete(_root, true); } catch { }
    }

    [Fact]
    [DisplayName("可清理项包含回收站与临时目录")]
    public void CreateTargets_ContainsRecycleAndTemp()
    {
        var targets = CleanupService.CreateTargets();

        Assert.Contains(targets, e => e.Kind == CleanupKind.RecycleBin);
        Assert.Contains(targets, e => e.Kind == CleanupKind.Temp);
        Assert.All(targets, e => Assert.False(String.IsNullOrWhiteSpace(e.Name)));
    }

    [Fact]
    [DisplayName("临时目录统计后清理内容但保留目录")]
    public async Task MeasureAndClearTemp_RemovesContents()
    {
        var sub = Path.Combine(_root, "sub");
        Directory.CreateDirectory(sub);
        File.WriteAllBytes(Path.Combine(_root, "a.bin"), new Byte[100]);
        File.WriteAllBytes(Path.Combine(sub, "b.bin"), new Byte[50]);

        var target = new CleanupTarget
        {
            Key = "temp:test",
            Name = "临时测试",
            Path = _root,
            Kind = CleanupKind.Temp,
        };

        await CleanupService.MeasureAsync(target);

        Assert.True(target.Measured);
        Assert.Equal(150, target.Size);
        Assert.Equal(2, target.Files);
        Assert.True(target.CanClear);

        var result = await CleanupService.ClearAsync(target);

        Assert.Equal(150, result.FreedSize);
        Assert.Equal(0, result.Failed);
        Assert.True(Directory.Exists(_root));
        Assert.Empty(Directory.EnumerateFileSystemEntries(_root));
        Assert.Equal(0, target.Size);
        Assert.False(target.CanClear);
    }

    [Fact]
    [DisplayName("不存在的临时目录按空处理")]
    public async Task Measure_MissingDirectory()
    {
        var target = new CleanupTarget
        {
            Key = "temp:missing",
            Name = "不存在的目录",
            Path = Path.Combine(_root, "missing"),
            Kind = CleanupKind.Temp,
        };

        await CleanupService.MeasureAsync(target);

        Assert.True(target.Measured);
        Assert.Equal(0, target.Size);
        Assert.False(target.CanClear);
        Assert.NotEmpty(target.Hint);
    }

    [Theory]
    [DisplayName("轮转日志归档识别")]
    [InlineData("syslog.1", true)]
    [InlineData("daemon.log.3", true)]
    [InlineData("dpkg.log.2.gz", true)]
    [InlineData("kern.log.gz", true)]
    [InlineData("messages.xz", true)]
    [InlineData("boot.log.old", true)]
    [InlineData("syslog", false)]
    [InlineData("auth.log", false)]
    [InlineData("lastlog", false)]
    [InlineData("app.log", false)]
    [InlineData("", false)]
    public void IsLogArchive_DetectsRotatedFiles(String name, Boolean expected)
        => Assert.Equal(expected, CleanupService.IsLogArchive(name));

    [Theory]
    [DisplayName("journal 占用输出解析")]
    [InlineData("Archived and active journals take up 147.3M in the file system.", 147.3 * 1024 * 1024)]
    [InlineData("Archived and active journals take up 1.5G in the file system.", 1.5 * 1024 * 1024 * 1024)]
    [InlineData("Archived and active journals take up 0B in the file system.", 0)]
    public void ParseJournalDiskUsage_ReadsSize(String output, Double expected)
        => Assert.Equal((Int64)expected, CleanupService.ParseJournalDiskUsage(output));

    [Fact]
    [DisplayName("无法解析的 journal 输出返回 -1")]
    public void ParseJournalDiskUsage_UnknownOutput()
    {
        Assert.Equal(-1, CleanupService.ParseJournalDiskUsage(""));
        Assert.Equal(-1, CleanupService.ParseJournalDiskUsage("journalctl: command not found"));
    }

    [Fact]
    [DisplayName("日志归档只清理轮转文件,正在写入的日志保留")]
    public async Task MeasureAndClearLogArchives_KeepsActiveLog()
    {
        var sub = Path.Combine(_root, "old");
        Directory.CreateDirectory(sub);
        File.WriteAllBytes(Path.Combine(_root, "app.log"), new Byte[10]);
        File.WriteAllBytes(Path.Combine(_root, "app.log.1"), new Byte[20]);
        File.WriteAllBytes(Path.Combine(_root, "app.log.2.gz"), new Byte[30]);
        File.WriteAllBytes(Path.Combine(sub, "worker.log.old"), new Byte[40]);

        var target = new CleanupTarget
        {
            Key = "log:archive",
            Name = "日志归档",
            Path = _root,
            Kind = CleanupKind.LogArchive,
        };

        await CleanupService.MeasureAsync(target);

        Assert.True(target.Measured);
        Assert.Equal(90, target.Size);
        Assert.Equal(3, target.Files);
        Assert.True(target.CanClear);

        var result = await CleanupService.ClearAsync(target);

        Assert.Equal(90, result.FreedSize);
        Assert.Equal(0, result.Failed);
        Assert.True(File.Exists(Path.Combine(_root, "app.log")));
        Assert.False(File.Exists(Path.Combine(_root, "app.log.1")));
        Assert.False(File.Exists(Path.Combine(sub, "worker.log.old")));
        Assert.Equal(0, target.Size);
        Assert.False(target.CanClear);
    }

    [Fact]
    [DisplayName("可清理项键值唯一")]
    public void CreateTargets_KeysAreUnique()
    {
        var targets = CleanupService.CreateTargets();

        Assert.Equal(targets.Count, targets.Select(e => e.Key).Distinct().Count());
    }
}