fix: 发布一致性校验、日志轮转与构建脚本对齐
- 新增发布校验脚本(buildsh/lib/verify_release.py + release.sh),核对 tag/清单/资产 三者的 sha256 与体积,并复验清单签名;接入 ./build.sh release-verify 与 .gitea/workflows/release-verify.yml(手动触发) - GcLog 改为常驻 StreamWriter + 按天轮转 + 14 天/64MB 保留策略,避免高峰期反复 开关文件句柄;只清理本模块生成的 gc-*.log,不碰用户文件 - 修复 Applier 验签逻辑:无效签名永远拒绝,仅「未签名」在调用方不强制时放行 - 新增应用器测试(GC.Savedog.Tests):整目录替换、.GC/bin 合并、启动失败回滚、 路径穿越防护、验签;接入 pr-check.yml - GC.Tests 增加日志用例(写入/轮转/清理/用户文件保护) - 同步 PowerShell 打包脚本与 buildsh 一致:GCL 命名、单顶层目录、守护进程收进 .GC/bin、启动器与守护进程压缩单文件、不预置 .GC、prune/strip 对齐、签名 keyId 改为 gc-2026-12、新增 release-verify 与应用器测试任务
This commit is contained in:
1 parent
a5fcaeb658
commit
59a66c8fa8
15 files changed
+981
-93
No files matched your search
+124
-12
@@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
|
||||
@@ -15,15 +16,30 @@ namespace GC.Services;
|
||||
/// 中英分开而不是写在一个文件里:用户排查时不用在一行里找自己看得懂的那半句;
|
||||
/// 也给反馈问题时直接发对应语言的文件即可。
|
||||
///
|
||||
/// 写入方式:常驻 <see cref="StreamWriter"/>(<c>AutoFlush</c> 打开,崩溃也不丢最后几行),
|
||||
/// 不再每行 open/append/close 一遍 —— 那条路径每写一行要开两个文件句柄,
|
||||
/// 在下载 / 启动高峰期会明显拖慢调用方。
|
||||
///
|
||||
/// 保留策略:<see cref="RetentionDays"/> 天之前的日志在初始化与跨天滚动时删除;
|
||||
/// 总量超过 <see cref="MaxTotalBytes"/> 时从最旧的开始删。日志目录不会无限长。
|
||||
///
|
||||
/// 日志失败绝不影响主流程(磁盘满、只读目录都只是少一份日志)。
|
||||
/// </summary>
|
||||
public static class GcLog
|
||||
{
|
||||
/// <summary>日志保留天数。</summary>
|
||||
public const int RetentionDays = 14;
|
||||
|
||||
/// <summary>日志目录总量上限(中英两份合计)。</summary>
|
||||
public const long MaxTotalBytes = 64L * 1024 * 1024;
|
||||
|
||||
private static readonly object Gate = new();
|
||||
private const string FilePrefix = "gc-";
|
||||
|
||||
private static string? _dir;
|
||||
private static string _day = "";
|
||||
private static string _zhPath = "";
|
||||
private static string _enPath = "";
|
||||
private static StreamWriter? _zh;
|
||||
private static StreamWriter? _en;
|
||||
|
||||
public static bool Enabled
|
||||
{
|
||||
@@ -45,8 +61,10 @@ public static class GcLog
|
||||
|
||||
lock (Gate)
|
||||
{
|
||||
CloseWriters();
|
||||
_dir = dir;
|
||||
_day = "";
|
||||
PruneOldFiles(dir);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,10 +76,8 @@ public static class GcLog
|
||||
{
|
||||
var now = DateTime.Now;
|
||||
var prefix = $"{now:yyyy-MM-dd HH:mm:ss} [{level}] ";
|
||||
var lineZh = prefix + zh;
|
||||
var lineEn = prefix + en;
|
||||
|
||||
try { Console.WriteLine(lineZh); } catch { /* 无控制台 */ }
|
||||
try { Console.WriteLine(prefix + zh); } catch { /* 无控制台 */ }
|
||||
|
||||
lock (Gate)
|
||||
{
|
||||
@@ -70,25 +86,121 @@ public static class GcLog
|
||||
var day = now.ToString("yyyyMMdd");
|
||||
if (day != _day)
|
||||
{
|
||||
// 跨天换文件;顺便清一次旧日志,长时间挂机的进程也不会攒满磁盘
|
||||
CloseWriters();
|
||||
_day = day;
|
||||
_zhPath = Path.Combine(_dir, $"gc-{day}.log");
|
||||
_enPath = Path.Combine(_dir, $"gc-{day}.en.log");
|
||||
PruneOldFiles(_dir);
|
||||
}
|
||||
|
||||
Append(_zhPath, lineZh);
|
||||
Append(_enPath, lineEn);
|
||||
if (_zh == null)
|
||||
{
|
||||
_zh = OpenWriter(Path.Combine(_dir, $"{FilePrefix}{day}.log"));
|
||||
_en = OpenWriter(Path.Combine(_dir, $"{FilePrefix}{day}.en.log"));
|
||||
}
|
||||
|
||||
Append(_zh, prefix + zh);
|
||||
Append(_en, prefix + en);
|
||||
}
|
||||
}
|
||||
|
||||
private static void Append(string path, string line)
|
||||
private static StreamWriter? OpenWriter(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
File.AppendAllText(path, line + Environment.NewLine, new UTF8Encoding(false));
|
||||
var stream = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
|
||||
return new StreamWriter(stream, new UTF8Encoding(false)) { AutoFlush = true };
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 日志失败不能影响程序
|
||||
// 写不了就不写;下一次跨天会再试一次
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static void Append(StreamWriter? writer, string line)
|
||||
{
|
||||
if (writer == null) return;
|
||||
try
|
||||
{
|
||||
writer.WriteLine(line);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 磁盘满 / 文件被删:关掉写入器,下次跨天重建
|
||||
try { writer.Dispose(); } catch { }
|
||||
if (ReferenceEquals(writer, _zh)) _zh = null; else _en = null;
|
||||
}
|
||||
}
|
||||
|
||||
private static void CloseWriters()
|
||||
{
|
||||
try { _zh?.Dispose(); } catch { }
|
||||
try { _en?.Dispose(); } catch { }
|
||||
_zh = null;
|
||||
_en = null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 清理过期与超量日志。只动本模块自己写的 <c>gc-YYYYMMDD[.en].log</c>,
|
||||
/// 目录里用户放的其他文件一概不碰。
|
||||
/// </summary>
|
||||
private static void PruneOldFiles(string dir)
|
||||
{
|
||||
try
|
||||
{
|
||||
var files = new DirectoryInfo(dir).GetFiles(FilePrefix + "*.log");
|
||||
if (files.Length == 0) return;
|
||||
|
||||
var cutoff = DateTime.Now.Date.AddDays(-RetentionDays);
|
||||
var alive = new System.Collections.Generic.List<FileInfo>(files.Length);
|
||||
foreach (var file in files)
|
||||
{
|
||||
if (!TryReadDate(file.Name, out var date))
|
||||
{
|
||||
// 名字不是我们的格式,忽略(既不删也不计入配额)
|
||||
continue;
|
||||
}
|
||||
|
||||
if (date < cutoff)
|
||||
{
|
||||
try { file.Delete(); } catch { }
|
||||
continue;
|
||||
}
|
||||
|
||||
alive.Add(file);
|
||||
}
|
||||
|
||||
long total = 0;
|
||||
foreach (var file in alive) total += file.Length;
|
||||
if (total <= MaxTotalBytes) return;
|
||||
|
||||
alive.Sort((a, b) => a.LastWriteTimeUtc.CompareTo(b.LastWriteTimeUtc));
|
||||
foreach (var file in alive)
|
||||
{
|
||||
if (total <= MaxTotalBytes) break;
|
||||
try
|
||||
{
|
||||
total -= file.Length;
|
||||
file.Delete();
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 清理失败不影响写日志
|
||||
}
|
||||
}
|
||||
|
||||
private static bool TryReadDate(string name, out DateTime date)
|
||||
{
|
||||
date = default;
|
||||
// gc-20261118.log / gc-20261118.en.log
|
||||
if (!name.StartsWith(FilePrefix, StringComparison.Ordinal)) return false;
|
||||
var rest = name.Substring(FilePrefix.Length);
|
||||
var dot = rest.IndexOf('.');
|
||||
if (dot != 8) return false;
|
||||
return DateTime.TryParseExact(rest.Substring(0, 8), "yyyyMMdd",
|
||||
CultureInfo.InvariantCulture, DateTimeStyles.None, out date);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
using System.Linq;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using GC.Savedog;
|
||||
|
||||
namespace GC.Savedog.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// GC-SAVEDOG 的应用器测试:更新真正落盘的那一段(整目录替换 / .GC/bin 合并 / 失败回滚)。
|
||||
///
|
||||
/// 为什么单独一个工程:<c>GC.Tests</c> 引用的是启动器程序集,而 GC-SAVEDOG 为了保持
|
||||
/// 「安全逻辑只有一份实现」把 <c>GC/src/Security</c> 与 <c>Json.cs</c> 以源码链接的方式
|
||||
/// 编进了自己 —— 两个程序集里存在同名类型。同一个测试工程里同时引用两者会撞类型,
|
||||
/// 所以应用器测试单独放这里,只引用守护进程。
|
||||
///
|
||||
/// 为什么需要这组用例:<c>--update-test</c> 覆盖的是「怎么判断该不该更新」,
|
||||
/// <see cref="Applier"/> 才是会动用户安装目录的代码 —— 它出错就是用户目录被删空。
|
||||
/// 全部在临时目录里跑,不碰真实安装、不联网。
|
||||
/// </summary>
|
||||
internal static class ApplierTests
|
||||
{
|
||||
private static int _failed;
|
||||
private static string _root = "";
|
||||
|
||||
public static int Main()
|
||||
{
|
||||
_root = Path.Combine(Path.GetTempPath(), "gc-applier-" + Guid.NewGuid().ToString("N")[..8]);
|
||||
Directory.CreateDirectory(_root);
|
||||
Console.WriteLine("Applier 测试目录: " + _root);
|
||||
|
||||
try
|
||||
{
|
||||
CaseRefusesTraversalPackageName();
|
||||
CaseRefusesShaMismatch();
|
||||
CaseRefusesSourceTree();
|
||||
CaseDryRunKeepsInstallUntouched();
|
||||
CaseRollbackRestoresOldFiles();
|
||||
CaseSuccessMergesGcBinAndKeepsUserData();
|
||||
}
|
||||
finally
|
||||
{
|
||||
try { Directory.Delete(_root, true); } catch { }
|
||||
}
|
||||
|
||||
Console.WriteLine(_failed == 0
|
||||
? "Applier 测试全部通过"
|
||||
: $"Applier 测试失败 {_failed} 项");
|
||||
return _failed == 0 ? 0 : 1;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 用例
|
||||
|
||||
/// <summary>包名带 ../ 时必须拒绝(路径穿越的第一道闸)。</summary>
|
||||
private static void CaseRefusesTraversalPackageName()
|
||||
{
|
||||
var (install, update) = Sandbox("traversal");
|
||||
WritePackage(update, new Dictionary<string, string>
|
||||
{
|
||||
["GCL-9.9.9-test-amd64.exe"] = "new"
|
||||
});
|
||||
WriteRequest(update, "../evil.exe", sha: null);
|
||||
|
||||
var code = Apply(update, install, dryRun: true);
|
||||
Check("路径穿越的包名被拒绝", code == 3, $"exit={code}(期望 3)");
|
||||
}
|
||||
|
||||
/// <summary>zip 内容与清单 sha256 不符时必须丢弃。</summary>
|
||||
private static void CaseRefusesShaMismatch()
|
||||
{
|
||||
var (install, update) = Sandbox("sha");
|
||||
WritePackage(update, new Dictionary<string, string>
|
||||
{
|
||||
["GCL-9.9.9-test-amd64.exe"] = "new"
|
||||
});
|
||||
WriteRequest(update, "GCL-9.9.9-test-amd64.exe", sha: new string('a', 64));
|
||||
|
||||
var code = Apply(update, install, dryRun: true);
|
||||
Check("sha256 不符的包被丢弃", code == 5, $"exit={code}(期望 5)");
|
||||
}
|
||||
|
||||
/// <summary>安装目录里有 GC.sln 时拒绝替换 —— 防止误在源码树里跑更新。</summary>
|
||||
private static void CaseRefusesSourceTree()
|
||||
{
|
||||
var (install, update) = Sandbox("srctree");
|
||||
File.WriteAllText(Path.Combine(install, "GC.sln"), "fake solution");
|
||||
var zip = WritePackage(update, new Dictionary<string, string>
|
||||
{
|
||||
["GCL-9.9.9-test-amd64.exe"] = "new"
|
||||
});
|
||||
WriteRequest(update, "GCL-9.9.9-test-amd64.exe", Sha256File(zip));
|
||||
|
||||
var code = Apply(update, install, dryRun: false);
|
||||
Check("源码目录被拒绝替换", code == 4, $"exit={code}(期望 4)");
|
||||
Check("源码目录里的文件没被动过",
|
||||
File.ReadAllText(Path.Combine(install, "GC.sln")) == "fake solution",
|
||||
"GC.sln 内容变了");
|
||||
}
|
||||
|
||||
/// <summary>dry-run 只校验不落盘:安装目录必须一个字节都不变。</summary>
|
||||
private static void CaseDryRunKeepsInstallUntouched()
|
||||
{
|
||||
var (install, update) = Sandbox("dryrun");
|
||||
File.WriteAllText(Path.Combine(install, "GCL-1.0.0-test-amd64.exe"), "old");
|
||||
File.WriteAllText(Path.Combine(install, "only-in-old.txt"), "keep me");
|
||||
|
||||
var zip = WritePackage(update, new Dictionary<string, string>
|
||||
{
|
||||
["GCL-9.9.9-test-amd64.exe"] = "new",
|
||||
["GC-UI.exe"] = "ui"
|
||||
});
|
||||
WriteRequest(update, "GCL-9.9.9-test-amd64.exe", Sha256File(zip));
|
||||
|
||||
var code = Apply(update, install, dryRun: true);
|
||||
var names = Directory.GetFileSystemEntries(install).Select(Path.GetFileName).OrderBy(n => n).ToArray();
|
||||
Check("dry-run 返回 0", code == 0, $"exit={code}");
|
||||
Check("dry-run 不改安装目录",
|
||||
names.SequenceEqual(new[] { "GCL-1.0.0-test-amd64.exe", "only-in-old.txt" }),
|
||||
"安装目录变成: " + string.Join(", ", names));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 新版本启动不健康 → 回滚:旧文件原样回来,新包独有的文件被删掉,zip 与申请被清理。
|
||||
/// </summary>
|
||||
private static void CaseRollbackRestoresOldFiles()
|
||||
{
|
||||
var (install, update) = Sandbox("rollback");
|
||||
var oldExe = Path.Combine(install, "GCL-1.0.0-test-amd64.exe");
|
||||
var oldOnly = Path.Combine(install, "only-in-old.txt");
|
||||
File.WriteAllText(oldExe, "old-binary");
|
||||
File.WriteAllText(oldOnly, "old-only");
|
||||
|
||||
// 新版什么都不做直接退出:健康标记不会出现,必然回滚
|
||||
var zip = WritePackage(update, new Dictionary<string, string>
|
||||
{
|
||||
["GCL-9.9.9-test-amd64.exe"] = "#!/bin/sh\nexit 1\n",
|
||||
["only-in-new.txt"] = "new-only"
|
||||
});
|
||||
WriteRequest(update, "GCL-9.9.9-test-amd64.exe", Sha256File(zip));
|
||||
|
||||
var code = Apply(update, install, dryRun: false, timeoutSeconds: 5);
|
||||
Check("启动失败后回滚(exit=8)", code == 8, $"exit={code}(期望 8)");
|
||||
Check("旧启动器被还原",
|
||||
File.Exists(oldExe) && File.ReadAllText(oldExe) == "old-binary",
|
||||
"旧启动器没回来");
|
||||
Check("旧版独有文件被还原",
|
||||
File.Exists(oldOnly) && File.ReadAllText(oldOnly) == "old-only",
|
||||
"旧版独有文件没回来");
|
||||
Check("新包独有文件被删除", !File.Exists(Path.Combine(install, "only-in-new.txt")),
|
||||
"only-in-new.txt 残留");
|
||||
Check("更新包与申请已清理",
|
||||
!File.Exists(Path.Combine(update, "package.zip")) &&
|
||||
!File.Exists(Path.Combine(update, "apply-request.json")),
|
||||
"update 目录里还有残留");
|
||||
}
|
||||
|
||||
/// <summary>正常路径:新文件就位、.GC/bin 被合并、.GC 下的用户数据原地不动。</summary>
|
||||
private static void CaseSuccessMergesGcBinAndKeepsUserData()
|
||||
{
|
||||
var (install, update) = Sandbox("success");
|
||||
var updateDirFull = Path.GetFullPath(update);
|
||||
|
||||
// 用户数据:设置、模型、守护进程源文件
|
||||
Directory.CreateDirectory(Path.Combine(install, ".GC", "config"));
|
||||
Directory.CreateDirectory(Path.Combine(install, ".GC", "model", "earth-rotation"));
|
||||
Directory.CreateDirectory(Path.Combine(install, ".GC", "bin"));
|
||||
File.WriteAllText(Path.Combine(install, ".GC", "config", "settings.json"), "{\"theme\":\"dark\"}");
|
||||
File.WriteAllText(Path.Combine(install, ".GC", "model", "earth-rotation", "a.bin"), "model");
|
||||
File.WriteAllText(Path.Combine(install, ".GC", "bin", "GC-SAVEDOG.exe"), "old-savedog");
|
||||
|
||||
// 假启动器:写健康标记后退出,模拟「新版本起来了」
|
||||
var launcher =
|
||||
"#!/bin/sh\n" +
|
||||
"cat > '" + Path.Combine(updateDirFull, "health.json") + "' <<'JSON'\n" +
|
||||
"{\"version\":\"9.9.9\",\"pid\":4242,\"at\":\"2026-01-01T00:00:00Z\",\"ok\":true}\n" +
|
||||
"JSON\n" +
|
||||
"exit 0\n";
|
||||
|
||||
var zip = WritePackage(update, new Dictionary<string, string>
|
||||
{
|
||||
["GCL-9.9.9-test-amd64.exe"] = launcher,
|
||||
[".GC/bin/GC-SAVEDOG.exe"] = "new-savedog",
|
||||
["GC-UI.exe"] = "ui"
|
||||
});
|
||||
WriteRequest(update, "GCL-9.9.9-test-amd64.exe", Sha256File(zip));
|
||||
|
||||
var code = Apply(update, install, dryRun: false, timeoutSeconds: 10);
|
||||
Check("启动健康后更新成功(exit=0)", code == 0, $"exit={code}");
|
||||
Check("新启动器就位",
|
||||
File.Exists(Path.Combine(install, "GCL-9.9.9-test-amd64.exe")), "新启动器缺失");
|
||||
Check("新前端就位", File.Exists(Path.Combine(install, "GC-UI.exe")), "GC-UI.exe 缺失");
|
||||
Check(".GC/bin 被合并",
|
||||
File.ReadAllText(Path.Combine(install, ".GC", "bin", "GC-SAVEDOG.exe")) == "new-savedog",
|
||||
".GC/bin/GC-SAVEDOG.exe 没被替换");
|
||||
Check("用户设置原样保留",
|
||||
File.ReadAllText(Path.Combine(install, ".GC", "config", "settings.json")) == "{\"theme\":\"dark\"}",
|
||||
"settings.json 被覆盖");
|
||||
Check("模型目录原样保留",
|
||||
File.Exists(Path.Combine(install, ".GC", "model", "earth-rotation", "a.bin")),
|
||||
"模型文件被删除");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 辅助
|
||||
|
||||
private static int Apply(string updateDir, string installDir, bool dryRun, int timeoutSeconds = 10)
|
||||
{
|
||||
var log = new Log(Path.Combine(updateDir, "logs"));
|
||||
var applier = new Applier(new ApplyOptions
|
||||
{
|
||||
UpdateDir = updateDir,
|
||||
InstallDir = installDir,
|
||||
DryRun = dryRun,
|
||||
TimeoutSeconds = timeoutSeconds,
|
||||
RequireSignature = false, // 用例不生成签名清单;验签本身由 --update-test 覆盖
|
||||
Force = false
|
||||
}, log);
|
||||
return applier.Run();
|
||||
}
|
||||
|
||||
private static (string Install, string Update) Sandbox(string name)
|
||||
{
|
||||
var baseDir = Path.Combine(_root, name);
|
||||
var install = Path.Combine(baseDir, "app");
|
||||
var update = Path.Combine(baseDir, "update");
|
||||
Directory.CreateDirectory(install);
|
||||
Directory.CreateDirectory(update);
|
||||
File.WriteAllText(Path.Combine(update, "version.json"), "{\"launcher\":{\"version\":\"9.9.9\"}}");
|
||||
return (install, update);
|
||||
}
|
||||
|
||||
private static string WritePackage(string updateDir, IDictionary<string, string> files)
|
||||
{
|
||||
var zipPath = Path.Combine(updateDir, "package.zip");
|
||||
try { File.Delete(zipPath); } catch { }
|
||||
using (var archive = ZipFile.Open(zipPath, ZipArchiveMode.Create))
|
||||
{
|
||||
foreach (var (name, text) in files)
|
||||
{
|
||||
var entry = archive.CreateEntry(name.Replace('\\', '/'), CompressionLevel.Fastest);
|
||||
using var stream = entry.Open();
|
||||
var bytes = Encoding.UTF8.GetBytes(text);
|
||||
stream.Write(bytes, 0, bytes.Length);
|
||||
}
|
||||
}
|
||||
return zipPath;
|
||||
}
|
||||
|
||||
/// <summary>手写申请文件:不引用 Json 序列化助手(同名类型在两个程序集里都有)。</summary>
|
||||
private static void WriteRequest(string updateDir, string packageName, string? sha)
|
||||
{
|
||||
var zipPath = Path.Combine(updateDir, "package.zip");
|
||||
var size = File.Exists(zipPath) ? new FileInfo(zipPath).Length : 0;
|
||||
var json = new StringBuilder()
|
||||
.Append("{\n")
|
||||
.Append(" \"schema\": 1,\n")
|
||||
.Append(" \"version\": \"9.9.9\",\n")
|
||||
.Append(" \"rid\": \"test-amd64\",\n")
|
||||
.Append(" \"platformLabel\": \"test-amd64\",\n")
|
||||
.Append(" \"packageName\": ").Append(Quote(packageName)).Append(",\n")
|
||||
.Append(" \"payloadDir\": \"payload\",\n")
|
||||
.Append(" \"installRelative\": \"../app\",\n")
|
||||
.Append(" \"manifestPath\": \"version.json\",\n")
|
||||
.Append(" \"packageZip\": \"package.zip\",\n")
|
||||
.Append(" \"packageSha256\": ").Append(sha == null ? "null" : Quote(sha)).Append(",\n")
|
||||
.Append(" \"packageSize\": ").Append(size).Append(",\n")
|
||||
.Append(" \"requireSignature\": false\n")
|
||||
.Append("}\n")
|
||||
.ToString();
|
||||
File.WriteAllText(Path.Combine(updateDir, "apply-request.json"), json);
|
||||
}
|
||||
|
||||
private static string Quote(string value) => "\"" + value.Replace("\\", "\\\\").Replace("\"", "\\\"") + "\"";
|
||||
|
||||
private static string Sha256File(string path)
|
||||
{
|
||||
using var stream = File.OpenRead(path);
|
||||
return Convert.ToHexString(SHA256.HashData(stream)).ToLowerInvariant();
|
||||
}
|
||||
|
||||
private static void Check(string label, bool ok, string detail)
|
||||
{
|
||||
if (ok)
|
||||
{
|
||||
Console.WriteLine(" ✓ " + label);
|
||||
return;
|
||||
}
|
||||
_failed++;
|
||||
Console.WriteLine($" ✗ {label} —— {detail}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!--
|
||||
应用器测试:只引用 GC-SAVEDOG。
|
||||
|
||||
不并入 GC.Tests 的原因见 ApplierTests.cs 顶部注释 —— 守护进程把 GC/src/Security
|
||||
以源码链接编进了自己,与启动器程序集存在同名类型,同一工程内同时引用会撞类型。
|
||||
-->
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<Nullable>enable</Nullable>
|
||||
<RootNamespace>GC.Savedog.Tests</RootNamespace>
|
||||
<AssemblyName>GC.Savedog.Tests</AssemblyName>
|
||||
<InvariantGlobalization>true</InvariantGlobalization>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="../../../../../GC-SAVEDOG/GC-SAVEDOG.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,67 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using GC.Services;
|
||||
|
||||
namespace GC.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// 日志模块的用例:双语写入、跨天文件命名、旧日志清理、不误删用户文件。
|
||||
///
|
||||
/// 这些看起来是小事,但 <c>.GC/logs</c> 会随程序跑很久:写入路径每行开两个文件句柄,
|
||||
/// 或者完全不清理,都会在几个月后变成用户磁盘上的几 GB。用例锁住这两个行为。
|
||||
/// </summary>
|
||||
internal static class LogTests
|
||||
{
|
||||
private static int _failed;
|
||||
|
||||
public static int Run()
|
||||
{
|
||||
var dir = Path.Combine(Path.GetTempPath(), "gc-log-" + Guid.NewGuid().ToString("N")[..8]);
|
||||
Directory.CreateDirectory(dir);
|
||||
try
|
||||
{
|
||||
// 过期日志(2000 年)+ 用户自己的文件
|
||||
var oldZh = Path.Combine(dir, "gc-20000101.log");
|
||||
var oldEn = Path.Combine(dir, "gc-20000101.en.log");
|
||||
var userFile = Path.Combine(dir, "keep-me.txt");
|
||||
File.WriteAllText(oldZh, "old");
|
||||
File.WriteAllText(oldEn, "old");
|
||||
File.WriteAllText(userFile, "user data");
|
||||
|
||||
GcLog.Init(dir);
|
||||
GcLog.Info("测试中文", "test english");
|
||||
|
||||
var day = DateTime.Now.ToString("yyyyMMdd");
|
||||
var zhPath = Path.Combine(dir, $"gc-{day}.log");
|
||||
var enPath = Path.Combine(dir, $"gc-{day}.en.log");
|
||||
|
||||
Check("中文日志写入", File.Exists(zhPath) && File.ReadAllText(zhPath).Contains("测试中文"), "中文日志缺失");
|
||||
Check("英文日志写入", File.Exists(enPath) && File.ReadAllText(enPath).Contains("test english"), "英文日志缺失");
|
||||
Check("过期日志被清理", !File.Exists(oldZh) && !File.Exists(oldEn), "2000 年的日志还在");
|
||||
Check("目录里的用户文件不被误删", File.Exists(userFile), "keep-me.txt 被删了");
|
||||
|
||||
var names = Directory.GetFiles(dir).Select(Path.GetFileName).OrderBy(n => n).ToArray();
|
||||
Check("日志目录只剩当天两份 + 用户文件",
|
||||
names.Length == 3, "目录内容: " + string.Join(", ", names));
|
||||
}
|
||||
finally
|
||||
{
|
||||
try { Directory.Delete(dir, true); } catch { }
|
||||
}
|
||||
|
||||
Console.WriteLine(_failed == 0 ? "日志测试全部通过" : $"日志测试失败 {_failed} 项");
|
||||
return _failed;
|
||||
}
|
||||
|
||||
private static void Check(string label, bool ok, string detail)
|
||||
{
|
||||
if (ok)
|
||||
{
|
||||
Console.WriteLine(" ✓ " + label);
|
||||
return;
|
||||
}
|
||||
_failed++;
|
||||
Console.WriteLine($" ✗ {label} —— {detail}");
|
||||
}
|
||||
}
|
||||
@@ -51,7 +51,9 @@ internal static class Program
|
||||
RenderPages(services);
|
||||
|
||||
Console.WriteLine("截图输出: " + Path.GetFullPath(_outDir));
|
||||
return 0;
|
||||
|
||||
// 日志模块的用例放在渲染之后:它会切换 GcLog 的输出目录
|
||||
return LogTests.Run() == 0 ? 0 : 1;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
Reference in new issue
Block a user