Triforce v0.5.2

The new launcher (Windows and Linux: the game's own look, music and settings, saves and mods pages, smaller updates in parts), benchmark mode (Find my best settings: the game tours four places by itself and writes its results), Quit and Restart in the pause menu under Mods, Squadala! in the Mods menu, battle music above 60 fps, menu text, the controller in the menus with the game in the background, the whole GameBanana list, RX 580 and RX 5000/6000 shader fixes, the pipeline cache kept through an update, async present black flashes, and faster builds.
This commit is contained in:
ruckus7382sfgsgdf
2026-11-19 10:52:50 -06:00
parent a750a21025
commit fb26495475
167 changed files with 21552 additions and 293 deletions

View File

@@ -0,0 +1,322 @@
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Text;
using Triforce.Logic;
namespace Triforce.LogicTests;
sealed class TestFailed : Exception { public TestFailed(string m) : base(m) { } }
static class T
{
public static void Check(bool ok, string what) { if (!ok) throw new TestFailed(what); }
public static void Equal<TV>(TV expected, TV actual, string what)
{
if (!EqualityComparer<TV>.Default.Equals(expected, actual)) throw new TestFailed(what + ": expected [" + expected + "], got [" + actual + "]");
}
public static TE Throws<TE>(Action a, string what) where TE : Exception
{
try { a(); }
catch (TE e) { return e; }
catch (Exception e) { throw new TestFailed(what + ": threw " + e.GetType().Name + " (" + e.Message + ") instead of " + typeof(TE).Name); }
throw new TestFailed(what + ": did not throw " + typeof(TE).Name);
}
public static async Task<TE> ThrowsAsync<TE>(Func<Task> a, string what) where TE : Exception
{
try { await a(); }
catch (TE e) { return e; }
catch (Exception e) { throw new TestFailed(what + ": threw " + e.GetType().Name + " (" + e.Message + ") instead of " + typeof(TE).Name); }
throw new TestFailed(what + ": did not throw " + typeof(TE).Name);
}
static readonly string Base = Path.Combine(Path.GetTempPath(), "triforce-logictests-" + Environment.ProcessId);
static int n;
/// <summary>A fresh TRIFORCE_TEST_ROOT folder.</summary>
public static string NewRoot(string name)
{
var root = Path.Combine(Base, Interlocked.Increment(ref n).ToString("00") + "-" + name);
Directory.CreateDirectory(root);
return root;
}
public static void CleanUp()
{
try { if (Directory.Exists(Base)) Directory.Delete(Base, true); } catch (Exception) { }
}
/// <summary>A context whose test root is root, as if the launcher ran as &lt;root&gt;\Programs\Triforce\TriforceSetup.exe (so
/// nothing is written beside the test program itself).</summary>
public static TriforceContext Ctx(string root, string? self = null, Dictionary<string, string?>? env = null)
{
var e = new Dictionary<string, string?>(env ?? new()) { ["TRIFORCE_TEST_ROOT"] = root };
return TriforceContext.Create(e, self ?? Path.Combine(root, "Programs", "Triforce", BuildInfo.SetupAsset));
}
/// <summary>This test program's files (its apphost, dlls, runtimeconfig): copied where a fake python or a fake new launcher
/// must run; exeName names the copy of the apphost.</summary>
public static void CopySelf(string folder, string exeName)
{
Directory.CreateDirectory(folder);
var dir = AppContext.BaseDirectory;
File.Copy(Environment.ProcessPath!, Path.Combine(folder, exeName), true);
foreach (var f in Directory.GetFiles(dir))
{
var name = Path.GetFileName(f);
if (name.EndsWith(".dll") || name.EndsWith(".runtimeconfig.json") || name.EndsWith(".deps.json"))
File.Copy(f, Path.Combine(folder, name), true);
}
}
/// <summary>The bytes of this program's apphost: served as the new TriforceSetup.exe.</summary>
public static byte[] SelfBytes => File.ReadAllBytes(Environment.ProcessPath!);
}
/// <summary>A small HTTP/1.1 server on 127.0.0.1 for the release check and the downloads: GET only, a strong ETag, Range
/// ("bytes=N-") answered with 206 and If-Range honoured, 404 for anything it does not have. (TcpListener, not HttpListener: no URL
/// reservation is needed for a user without admin rights.)</summary>
sealed class FakeServer : IDisposable
{
readonly TcpListener listener;
readonly Dictionary<string, (byte[] Body, string Type, int Status)> routes = new();
readonly CancellationTokenSource stop = new();
public int Requests;
public readonly List<string> Seen = new();
public FakeServer()
{
listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
_ = Task.Run(Loop);
}
public string Url => "http://127.0.0.1:" + ((IPEndPoint)listener.LocalEndpoint).Port;
public void Add(string path, byte[] body, string type = "application/octet-stream", int status = 200)
{
lock (routes) routes[path] = (body, type, status);
}
public void Add(string path, string text, string type = "application/json", int status = 200) => Add(path, Encoding.UTF8.GetBytes(text), type, status);
async Task Loop()
{
while (!stop.IsCancellationRequested)
{
TcpClient c;
try { c = await listener.AcceptTcpClientAsync(stop.Token); } catch (Exception) { return; }
_ = Task.Run(() => Serve(c));
}
}
async Task Serve(TcpClient c)
{
using (c)
try
{
var s = c.GetStream();
var head = new StringBuilder();
var buf = new byte[1];
while (!head.ToString().EndsWith("\r\n\r\n"))
{
if (await s.ReadAsync(buf) == 0) return;
head.Append((char)buf[0]);
}
var lines = head.ToString().Split("\r\n");
var path = lines[0].Split(' ')[1];
Interlocked.Increment(ref Requests);
lock (Seen) Seen.Add(path);
long from = -1;
string? ifRange = null;
foreach (var l in lines.Skip(1))
{
if (l.StartsWith("Range: bytes=", StringComparison.OrdinalIgnoreCase)) from = long.Parse(l.Substring(13).TrimEnd('-'));
if (l.StartsWith("If-Range: ", StringComparison.OrdinalIgnoreCase)) ifRange = l.Substring(10);
}
(byte[] Body, string Type, int Status) r;
bool found;
lock (routes) found = routes.TryGetValue(path, out r);
if (!found) r = (Encoding.UTF8.GetBytes("not found"), "text/plain", 404);
var etag = "\"v" + r.Body.Length + "\"";
var body = r.Body;
var status = r.Status;
var extra = "ETag: " + etag + "\r\n";
if (from > 0 && status == 200 && (ifRange == null || ifRange == etag))
{
if (from >= body.Length) { status = 416; body = Array.Empty<byte>(); }
else
{
extra += "Content-Range: bytes " + from + "-" + (r.Body.Length - 1) + "/" + r.Body.Length + "\r\n";
body = r.Body.AsSpan((int)from).ToArray();
status = 206;
}
}
var text = status switch { 200 => "OK", 206 => "Partial Content", 404 => "Not Found", 416 => "Range Not Satisfiable", _ => "Status" };
var header = "HTTP/1.1 " + status + " " + text + "\r\nContent-Type: " + r.Type + "\r\nContent-Length: " + body.Length + "\r\n" + extra + "Connection: close\r\n\r\n";
await s.WriteAsync(Encoding.ASCII.GetBytes(header));
await s.WriteAsync(body);
await s.FlushAsync();
}
catch (Exception) { }
}
public void Dispose()
{
stop.Cancel();
listener.Stop();
}
}
/// <summary>The fakes this program plays when a test starts it as another program.</summary>
static class Fakes
{
/// <summary>A stand-in game for the benchmark (copied in as Triforce.exe: "image.bin --romfs .. --user .."): the title's fps
/// lines, a save that loads after three A presses, "!cheat 1000+n" teleports, and per place fps / 1% low lines; each 5 s
/// window of the real game is TRIFORCE_FAKE_WINDOW_MS here (default 400). Frame rates: by place, x1.4 with an upscaler on in
/// the options file beside the exe, and the cap there. It writes a save into --user, to show the benchmark's copy takes it.</summary>
/// <summary>The stand-in game's benchmark mode: "bench:" progress lines, then the results file (as host/ writes it), then
/// it ends. Frame rates by scene, x1.4 with an upscaler on in the options file beside the exe. TRIFORCE_FAKE_WINDOW_MS paces it.</summary>
static int FakeBenchmark(string results, string? user)
{
var ic = System.Globalization.CultureInfo.InvariantCulture;
var win = int.TryParse(Environment.GetEnvironmentVariable("TRIFORCE_FAKE_WINDOW_MS"), out var w) ? w : 400;
var opts = Triforce.Logic.BenchIni.Read(Path.Combine(AppContext.BaseDirectory, "triforce_options.ini"));
var up = opts.TryGetValue("dlss", out var u) && u != 0 ? 1.4 : 1.0;
Console.Error.WriteLine("bench: Loading your newest save"); Thread.Sleep(win * 3);
if (user != null) { Directory.CreateDirectory(Path.Combine(user, "save")); File.WriteAllText(Path.Combine(user, "save", "written-by-the-game.txt"), "x"); }
var scenes = new[] { ("Hyrule Field", 92.0), ("Castle Town Market", 71.0), ("Kokiri Forest", 118.0), ("Lake Hylia", 133.0) };
var json = new System.Text.StringBuilder("{\"version\":1,\"stopped\":false,\"gpu\":\"Stand-in GPU\",\"scenes\":[");
for (var i = 0; i < scenes.Length; i++)
{
var (name, fps) = scenes[i];
Console.Error.WriteLine($"bench: Going to {name}"); Thread.Sleep(win);
Console.Error.WriteLine($"bench: Scene {i + 1} of {scenes.Length} · {name}"); Thread.Sleep(win * 3);
var f = fps * up; var ft = Enumerable.Range(0, 120).Select(k => 1000 / f * (1 + 0.08 * Math.Sin(k / 5.0) + (k % 37 == 0 ? 0.6 : 0)));
json.Append(string.Create(ic, $"{(i > 0 ? "," : "")}{{\"name\":\"{name}\",\"avg\":{f:0.0},\"low1\":{f * 0.84:0.0},\"low01\":{f * 0.7:0.0},\"frames\":{(int)(f * 15)},\"seconds\":15,\"frametimes_ms\":[{string.Join(",", ft.Select(x => x.ToString("0.00", ic)))}]}}"));
}
json.Append("]}");
File.WriteAllText(results + ".new", json.ToString()); File.Move(results + ".new", results, true);
Console.Error.WriteLine("bench: Finished"); Thread.Sleep(win);
return 0;
}
public static int FakeGame(string[] a)
{
string? Arg(string name) { var i = Array.IndexOf(a, name); return i >= 0 && i + 1 < a.Length ? a[i + 1] : null; }
if (Environment.GetEnvironmentVariable("HOS_BENCHMARK") is { Length: > 0 } results) return FakeBenchmark(results, Arg("--user"));
var input = Environment.GetEnvironmentVariable("HOS_INPUT_LIVE");
var win = int.TryParse(Environment.GetEnvironmentVariable("TRIFORCE_FAKE_WINDOW_MS"), out var w) ? w : 400;
var ini = Path.Combine(AppContext.BaseDirectory, "triforce_options.ini");
var opts = Triforce.Logic.BenchIni.Read(ini);
var up = opts.TryGetValue("dlss", out var u) && u != 0 ? 1.4 : 1.0;
var capFps = (opts.TryGetValue("frame_rate_cap", out var c) ? c : 0) switch { 0 => 60, 1 => 90, 2 => 120, 3 => 144, 4 => 165, _ => 240 };
var place = new Dictionary<int, double> { [1000] = 118, [1001] = 92, [1003] = 71, [1007] = 133 };
double baseFps = 80; var presses = 0; var loaded = false; long frames = 0; int readAt = 0;
var user = Arg("--user");
for (var t = 0; t < 100000; t++)
{
Thread.Sleep(win);
if (input != null && File.Exists(input))
{
var all = File.ReadAllText(input);
foreach (var line in all[readAt..].Split('\n', StringSplitOptions.RemoveEmptyEntries))
{
if (line.StartsWith("!cheat "))
{
var id = int.Parse(line[7..].Trim());
Console.Error.WriteLine($"cheats: teleport ... to {id} at ...: request sent, result 0x0");
if (place.TryGetValue(id, out var f)) baseFps = f;
}
else presses += line.Split(',').Count(x => x.EndsWith(":A"));
}
readAt = all.Length;
}
if (!loaded && presses >= 3) { loaded = true; if (user != null) { Directory.CreateDirectory(Path.Combine(user, "save")); File.WriteAllText(Path.Combine(user, "save", "written-by-the-game.txt"), "x"); } }
var fps = Math.Min(capFps, (loaded ? baseFps * up : 60) + Math.Sin(t) * 3);
frames += (long)(fps * 5);
var ic = System.Globalization.CultureInfo.InvariantCulture;
Console.Error.WriteLine(string.Create(ic, $"vi: {frames} frames presented ({fps:0.0} fps over the last 5.0 s, interval 1)"));
Console.Error.WriteLine(string.Create(ic, $"vi: 1% low {fps * 0.86:0.0} fps over the last 5.0 s ({(int)(fps * 5)} frames)"));
if (loaded) Console.Error.WriteLine(string.Create(ic, $"vk: {frames} presents, {fps:0.0} fps; a frame: 2600 draws"));
Console.Error.Flush();
}
return 0;
}
/// <summary>make_game.py's lines as a build prints them (formats from nx2/make_game.py say(), build.py's @@plan/@@file/@@eta, and
/// the game's own "@@stage shaders" from gpu/vk/vk_main.cpp), {OUT} the game folder.</summary>
public const string Transcript = """
the Windows SDK is here: C:\Program Files (x86)\Windows Kits\10
@@stage read Reading your game files
@@progress 0.000
@@progress 0.500
@@progress 1.000
@@stage lift Translating the game to PC code
lift: 30211 functions
@@progress 0.300
@@stage compile Compiling
@@plan 12 579
@@file code_hot_0.c 41.2 new
@@file code_1.c 0.0 cached
@@file code_2.c 3.5 again
@@eta 300
@@progress 0.400
compiled in 790s
@@stage finish Putting the game folder together
the build took 0:41:00, compiled in 0:30:00 (the last one 0:45:00)
@@times 2460 1800 2700
the build's steps: before the game files 0:41, read 1:32, lift 2:10, compile 7:42, finish 1:17
@@stage shaders Preparing shaders
@@progress 0.500
@@progress 1.000
@@done {OUT}
""";
/// <summary>"python -I make_game.py ...": --check answers ok; a build plays the transcript and makes the folder (Triforce.exe
/// and triforce_version.txt), "@@error" for an --out with FAIL in it, and sits in its first stage for one with SLOW in it.</summary>
public static int MakeGame(string[] a)
{
string? Arg(string name) { var i = Array.IndexOf(a, name); return i >= 0 && i + 1 < a.Length ? a[i + 1] : null; }
if (a.Contains("--check"))
{
Console.WriteLine("@@check ok This is the version Triforce supports (build e0f3ccfa).");
return 0;
}
var outDir = Arg("--out") ?? Arg("--update") ?? "out";
File.WriteAllText(Path.Combine(Path.GetDirectoryName(Arg("--work") ?? ".")!, "fake-make-game-args.txt"), string.Join("\n", a));
foreach (var raw in Transcript.Split('\n'))
{
var line = raw.TrimEnd('\r').Replace("{OUT}", outDir);
if (line.StartsWith("@@done"))
{
Directory.CreateDirectory(outDir);
File.WriteAllText(Path.Combine(outDir, "Triforce.exe"), "fake game");
File.WriteAllText(Path.Combine(outDir, "triforce_version.txt"), "version=v9.9.9\nbuilder=" + Environment.GetEnvironmentVariable("HOOKSHOT_BUILDER_EXE") + "\n");
}
Console.WriteLine(line);
Console.Out.Flush();
Thread.Sleep(int.TryParse(Environment.GetEnvironmentVariable("TRIFORCE_FAKE_LINE_MS"), out var ms) ? ms : 15);
if (line.StartsWith("@@stage read") && outDir.Contains("SLOW")) { Thread.Sleep(60000); return 9; }
if (line.StartsWith("@@stage compile") && outDir.Contains("FAIL"))
{
Console.Error.WriteLine("clang: error: no space left on device");
Console.WriteLine("@@error The disk is full.");
return 1;
}
}
return 0;
}
/// <summary>A new TriforceSetup.exe started by a self-update: "up" gives the sign its window is up and ends well, "fail" ends with
/// an error before it. Its arguments go to &lt;root&gt;\child-args.txt.</summary>
public static int NewSetup(string mode, string[] args)
{
var root = Environment.GetEnvironmentVariable("TRIFORCE_TEST_ROOT")!;
File.WriteAllText(Path.Combine(root, "child-args.txt"), string.Join("|", args));
if (mode == "fail") return 3;
var ctx = TriforceContext.Create();
Startup.SignalUp(ctx);
Thread.Sleep(300);
return 0;
}
}

View File

@@ -0,0 +1,32 @@
// Triforce.Logic's tests. Run: dotnet run --project LogicTests (exit code 0 = every test passed). Each test makes its own
// TRIFORCE_TEST_ROOT folder under %TEMP%; nothing outside those folders is written.
using System.Diagnostics;
using Triforce.LogicTests;
if (args.Length >= 2 && args[0] == "-I" && args[1].EndsWith("make_game.py", StringComparison.Ordinal)) return Fakes.MakeGame(args.Skip(2).ToArray());
if (args.Contains("--romfs") && args.Contains("--user")) return Fakes.FakeGame(args);
if (Environment.GetEnvironmentVariable("LOGICTESTS_CHILD") is { Length: > 0 } mode && args.Contains("--relaunched")) return Fakes.NewSetup(mode, args);
var only = args.Length > 0 ? args[0] : null;
var tests = Tests.All().Concat(Tests.GameOptionsTests()).Where(t => only == null || t.Name.Contains(only, StringComparison.OrdinalIgnoreCase)).ToList();
int passed = 0, failed = 0;
foreach (var (name, run) in tests)
{
var sw = Stopwatch.StartNew();
try
{
await run();
passed++;
Console.WriteLine("PASS " + name + " (" + sw.ElapsedMilliseconds + " ms)");
}
catch (Exception e)
{
failed++;
Console.WriteLine("FAIL " + name + ": " + (e is TestFailed ? e.Message : e.ToString()));
}
}
Console.WriteLine();
Console.WriteLine(passed + " passed, " + failed + " failed");
Environment.SetEnvironmentVariable("LOGICTESTS_CHILD", null);
if (failed == 0) T.CleanUp();
return failed == 0 ? 0 : 1;

View File

@@ -0,0 +1,262 @@
using System.Diagnostics;
using System.Text.Json.Nodes;
using Triforce.Logic;
using static Triforce.LogicTests.T;
namespace Triforce.LogicTests;
static partial class Tests
{
const string TestGame = @"D:\src\triforce-test-game";
const string Nup = @"D:\NX2navi-dump\The Legend of Zelda Ocarina of Time [0400486024dec000][v131072].nup";
static void Protocol()
{
var t0 = new DateTime(2026, 11, 19, 10, 0, 0, DateTimeKind.Utc);
var now = t0;
var tr = new BuildTracker(() => now);
var changes = new List<string>();
tr.StageChanged += (was, to) => changes.Add((was ?? "-") + ">" + to);
var events = new List<BuildEvent>();
tr.Event += events.Add;
foreach (var raw in Fakes.Transcript.Split('\n'))
{
now = now.AddSeconds(10);
tr.Feed(raw.TrimEnd('\r').Replace("{OUT}", @"C:\Games\Triforce"));
}
tr.End();
Equal("->read|read>lift|lift>compile|compile>finish|finish>shaders", string.Join("|", changes), "the stages in order");
Equal<(int, int)?>((12, 579), tr.Plan, "@@plan");
Equal(2, tr.FilesBuilt, "@@file new + again");
Equal(300, events.OfType<BuildEvent.Eta>().Single().Seconds, "@@eta");
Equal<int?>(null, tr.EtaSeconds, "the eta cleared when the compile ended");
Equal(2460, tr.Times!.TotalSeconds, "@@times total");
Equal<int?>(2700, tr.Times.PreviousSeconds, "@@times previous");
Equal(@"C:\Games\Triforce", tr.DoneFolder, "@@done");
Equal(92.0, tr.ReportedSteps!["read"], "make_game's own step times");
Equal(77.0, tr.ReportedSteps["finish"], "finish 1:17");
Equal(40.0, tr.StageSeconds["read"], "read: four lines of 10 s");
Check(tr.StageSeconds.ContainsKey("shaders"), "the last stage's time at the end");
Equal(1.0, tr.StageProgress, "shader progress");
Check(events.OfType<BuildEvent.Plain>().Any(p => p.Line.StartsWith("lift: ")), "plain lines are Plain");
Equal(new BuildEvent.Check(false, "This is build deadbeef. Triforce supports build e0f3ccfa."),
BuildProtocol.Parse("@@check bad This is build deadbeef. Triforce supports build e0f3ccfa."), "@@check bad");
Equal(new BuildEvent.Error("The builder stopped on an error it did not expect: x"), BuildProtocol.Parse("@@error The builder stopped on an error it did not expect: x"), "@@error");
Equal(new BuildEvent.Times(10, 5, null), BuildProtocol.Parse("@@times 10 5 -1"), "@@times without a previous build");
Check(BuildProtocol.Parse("the shaders were not prepared now (\"Prepare shaders now\" is unticked): the game prepares them at its first start") is BuildEvent.NotPrepared, "NOT_PREPARED");
Equal(new BuildEvent.Progress(0.25), BuildProtocol.Parse("@@progress 0.250"), "progress, invariant culture");
Check(BuildProtocol.Parse("@@progress x") is BuildEvent.Plain, "a bad number is a plain line");
Equal(3723.0, BuildProtocol.ParseSteps("compile 1:02:03")["compile"], "h:mm:ss");
}
static void Estimates()
{
var root = NewRoot("estimates");
var none = BuildEstimator.Estimate(BuildHistory.Load(Path.Combine(root, "nothing")), false, 8, GpuVendor.Nvidia);
Check(!none.Measured, "no history: a stated range");
Equal(TimeSpan.FromSeconds(1890), none.Of("compile")!.Low, "compile's share of the 8-thread range");
Check(none.Text.Contains(" to "), "a range in words: " + none.Text);
var amd = BuildEstimator.Estimate(BuildHistory.Load(root), false, 16, GpuVendor.Amd);
Equal(TimeSpan.FromMinutes(120), amd.Of("shaders")!.High, "AMD's shader step up to 2 hours");
File.WriteAllText(Path.Combine(root, "build_times.json"), new JsonObject
{
["format"] = 1,
["builds"] = new JsonArray(new JsonObject { ["when"] = "2026-11-18 21:00:00", ["kind"] = "build", ["modules"] = 579, ["compiled"] = 579, ["compile_seconds"] = 1800.0, ["total_seconds"] = 2400.0 }),
["seconds"] = new JsonObject(),
}.ToJsonString());
var h = BuildHistory.Load(root);
Equal(1, h.Builds.Count, "build_times.json read");
var est = BuildEstimator.Estimate(h, false, 8, GpuVendor.Nvidia);
Check(est.Measured, "measured from build_times.json");
Equal(TimeSpan.FromSeconds(1800), est.Of("compile")!.Low, "the compile's own time");
Equal(100, (int)Math.Round(est.Of("read")!.Low.TotalSeconds), "the rest split by the stages' weights (600 s * 5/30)");
BuildHistory.RecordStages(root, "build", new Dictionary<string, double> { ["read"] = 90, ["lift"] = 130, ["compile"] = 1500, ["finish"] = 70, ["shaders"] = 600 });
var est2 = BuildEstimator.Estimate(BuildHistory.Load(root), false, 8, GpuVendor.Nvidia);
Equal(TimeSpan.FromSeconds(1500), est2.Of("compile")!.Low, "the stage record wins");
Equal(TimeSpan.FromSeconds(600), est2.Of("shaders")!.High, "the shader step measured too");
Equal("About 40 minutes", est2.Text, "one time in words");
var tr = new BuildTracker();
tr.Feed("@@stage compile Compiling");
tr.Feed("@@eta 300");
var left = BuildClock.Remaining(est2, tr);
Equal(TimeSpan.FromSeconds(300 + 70 + 600), left, "time left: the compile's eta, then finish and shaders");
Equal("About 16 minutes left", BuildClock.LeftText(left), "in words");
Equal("Almost done", BuildClock.LeftText(TimeSpan.FromSeconds(20)), "under a minute");
Equal("1 h 5 min", BuildClock.Span(TimeSpan.FromMinutes(65)), "span");
}
/// <summary>A test root with fake tools: tools\nx2\make_game.py, and this program as tools\python\python.exe.</summary>
static TriforceContext FakeTools(string root)
{
var ctx = Ctx(root);
Directory.CreateDirectory(Path.Combine(ctx.ToolsFolder, "nx2"));
File.WriteAllText(Path.Combine(ctx.ToolsFolder, "nx2", "make_game.py"), "# fake: the test program plays it");
File.WriteAllText(Path.Combine(ctx.ToolsFolder, "version.txt"), "v9.9.9\n");
CopySelf(Path.Combine(ctx.ToolsFolder, "python"), "python.exe");
return ctx;
}
static GameSource FakeSource(string root)
{
var src = Path.Combine(root, "dump");
Directory.CreateDirectory(Path.Combine(src, "romfs"));
Directory.CreateDirectory(Path.Combine(src, "exefs"));
var main = new byte[0x60];
"NSO0"u8.CopyTo(main);
Convert.FromHexString("e0f3ccfaf50065ae").CopyTo(main, 0x40);
File.WriteAllBytes(Path.Combine(src, "exefs", "main"), main);
return GameIntake.Normalize(src)!;
}
static async Task RunnerDone()
{
var root = NewRoot("runner");
var ctx = FakeTools(root);
var notes = new List<LauncherNotification>();
ctx.Platform.NotificationRequested += (_, n) => notes.Add(n);
var src = FakeSource(root);
var outDir = Path.Combine(root, "Games", "Triforce");
var runner = new BuildRunner(ctx);
var stages = new List<string>();
runner.StageChanged += (_, to) => stages.Add(to);
var lines = 0;
runner.Line += _ => Interlocked.Increment(ref lines);
var r = await runner.RunAsync(BuildRequest.New(src, outDir, "de"));
Check(r.Success, "the build ended well: " + r.Failure + " / " + runner.Details);
Equal(outDir, r.Folder, "@@done's folder");
Equal("read,lift,compile,finish,shaders", string.Join(",", stages), "stage events");
Equal(outDir, ctx.Settings.GameFolder, "GameFolder kept");
Equal(outDir + "|", ctx.Settings.ModsBuilt, "the mods marked as built (none)");
Check(notes.Count == 1, "a notification for the App");
var args = File.ReadAllText(Path.Combine(root, "fake-make-game-args.txt")).Split('\n');
Equal("--romfs|" + src.Romfs + "|--exefs|" + src.Exefs + "|--out|" + outDir + "|--language|de|--fsr|--work|" + Path.Combine(root, "build"), string.Join("|", args), "make_game's arguments");
Check(File.ReadAllText(Path.Combine(outDir, "triforce_version.txt")).Contains("builder=" + ctx.BuilderExe), "HOOKSHOT_BUILDER_EXE passed");
Check(File.ReadAllText(runner.LogFile).Contains("@@progress 0.500"), "the log file keeps every line");
Check(!runner.Details.Contains("@@progress"), "the details leave progress out");
Check(File.Exists(Path.Combine(ctx.WorkFolder, BuildHistory.StagesFile)), "stage times recorded");
Equal(2460, r.Times!.TotalSeconds, "times");
Check(lines > 20, "lines came");
// (an update of the folder: --update, kind update)
var u = await new BuildRunner(ctx).RunAsync(BuildRequest.Update(outDir));
Check(u.Success, "the update ended well: " + u.Failure);
Equal("--update|" + outDir + "|--fsr|--work|" + Path.Combine(root, "build"), string.Join("|", File.ReadAllText(Path.Combine(root, "fake-make-game-args.txt")).Split('\n')), "update arguments");
Check(BuildHistory.Load(ctx.WorkFolder).Stages.Any(s => s.Kind == "update"), "an update's times kept as an update's");
// (DLSS chosen: the licence's flags; the update of a folder built with DLSS keeps it)
Directory.CreateDirectory(Path.Combine(outDir, "ngx"));
File.WriteAllText(Path.Combine(outDir, "ngx", "nvngx_dlss.dll"), "");
Check(new Dlss(ctx).ForBuild(outDir) && ctx.Settings.Dlss, "a folder built with DLSS is updated with it, and the choice kept");
Check(BuildRunner.Arguments(ctx, BuildRequest.Update(outDir), true).Contains("--accept-nvidia-license"), "the licence flag");
}
static async Task RunnerStop()
{
var root = NewRoot("runnerstop");
var ctx = FakeTools(root);
var runner = new BuildRunner(ctx);
var reading = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
runner.StageChanged += (_, to) => { if (to == "read") reading.TrySetResult(); };
var sw = Stopwatch.StartNew();
var run = runner.RunAsync(BuildRequest.New(FakeSource(root), Path.Combine(root, "Games", "SLOW"), "en-US"));
await Task.WhenAny(reading.Task, Task.Delay(20000));
Check(reading.Task.IsCompleted, "the build reached its first stage");
Check(runner.Running, "running");
runner.Stop();
var r = await run;
Check(r.Cancelled && r.Failure == "cancelled" && !r.Success, "stopped: " + r.Failure);
Equal("read", r.StoppedAt, "stopped in its first stage");
Check(sw.Elapsed < TimeSpan.FromSeconds(30), "stopped at once, not after the fake's minute");
var left = Process.GetProcessesByName("python").Where(p => { try { return p.MainModule!.FileName.StartsWith(root, StringComparison.OrdinalIgnoreCase); } catch (Exception) { return false; } });
Check(!left.Any(), "no fake make_game left running");
}
static async Task RunnerFail()
{
var root = NewRoot("runnerfail");
var ctx = FakeTools(root);
var runner = new BuildRunner(ctx);
var r = await runner.RunAsync(BuildRequest.New(FakeSource(root), Path.Combine(root, "Games", "FAIL"), "en-US"));
Check(!r.Success && !r.Cancelled, "failed");
Equal("The disk is full.", r.Failure, "@@error's text");
Equal("compile", r.StoppedAt, "where");
Check(runner.Details.Contains("clang: error"), "stderr in the details");
var report = Report.ForBuild(ctx, r, runner.Details, "v9.9.9");
Check(report.Contains("The build stopped at \"Compiling\"") && report.Contains("---- the build's last lines ----"), "the report");
var elsewhere = await new BuildRunner(ctx).RunAsync(BuildRequest.New(FakeSource(root), Path.Combine(Path.GetTempPath(), "not-in-root"), "en-US"));
Equal(ctx.TestOnly, elsewhere.Failure, "a test run builds only inside its root");
var noTools = await new BuildRunner(Ctx(NewRoot("runner-notools"))).RunAsync(BuildRequest.Update(Path.Combine(root, "x")));
Check(noTools.Failure!.Contains("tools"), "no tools: said");
}
static void GameFolder()
{
var ctx = Ctx(NewRoot("game"));
var game = new Game(ctx);
Equal(Path.Combine(TestGame, "Triforce.exe"), game.FindExe(TestGame), "Triforce.exe");
var info = game.Describe(TestGame);
Equal("v0.1.0", info.Version, "triforce_version.txt");
Check(info.Kept, "keeps .triforce_exefs and romfs");
Check(!info.Dlss, "no DLSS");
Check(info.Language == null || Languages.Find(info.Language) != null, "language.txt");
Check(!game.IsRunning(TestGame), "not running (test root: only programs inside it count)");
Equal(null, game.Play(TestGame), "Play refused outside the test root");
Equal(null, game.FindExe(Path.Combine(TestGame, "romfs")), "no game in romfs");
}
static void Intake()
{
var root = NewRoot("intake");
var s = GameIntake.Normalize(TestGame)!;
Equal(SourceKind.Folders, s.Kind, "a built game folder is a source");
Equal(Path.Combine(TestGame, ".triforce_exefs"), s.Exefs, "its kept exefs");
var q = GameIntake.Quick(s);
Check(q.Ok && q.BuildId!.StartsWith("e0f3ccfa") && q.Final, "the supported build, read without tools: " + q.Text);
var viaRomfs = GameIntake.Normalize(Path.Combine(TestGame, "romfs"))!;
Equal(s.Exefs, viaRomfs.Exefs, "the romfs folder finds its exefs");
var n = GameIntake.Normalize(Nup)!;
Equal(SourceKind.Nup, n.Kind, ".nup");
var nq = GameIntake.Quick(n);
Check(nq.Ok && nq.Titles!.Any(t => t.Id == "0400486024dec000"), "the .nup's header reads: " + nq.Text);
Check(!nq.Final, "a .nup still needs the tools' check");
Equal(131072u, nq.Titles![0].Version, "the newest title first (v131072, the file name says)");
// (NX2navi's packed romfs)
var navi = Path.Combine(root, "navi");
Directory.CreateDirectory(Path.Combine(navi, "romfs"));
Directory.CreateDirectory(Path.Combine(navi, "exefs"));
File.WriteAllText(Path.Combine(navi, "romfs", "romfs.bin"), "packed");
File.Copy(Path.Combine(TestGame, ".triforce_exefs", "main"), Path.Combine(navi, "exefs", "main"));
Equal(GameIntake.PackedRomfs, GameIntake.Quick(GameIntake.Normalize(navi)!).Text, "packed romfs refused");
// (another build)
var other = Path.Combine(root, "other");
Directory.CreateDirectory(Path.Combine(other, "romfs"));
Directory.CreateDirectory(Path.Combine(other, "exefs"));
var main = new byte[0x60];
"NSO0"u8.CopyTo(main);
Convert.FromHexString("deadbeef").CopyTo(main, 0x40);
File.WriteAllBytes(Path.Combine(other, "exefs", "main"), main);
var oq = GameIntake.Quick(GameIntake.Normalize(other)!);
Equal("This is build deadbeef. Triforce supports build e0f3ccfa.", oq.Text, "the wrong version, in make_game's words");
Check(GameIntake.IsWrongVersion(oq.Text), "said as the wrong version");
var half = GameIntake.Normalize(Path.Combine(other, "romfs"))!;
Check(half.Complete, "romfs with its exefs beside it");
var lonely = Path.Combine(root, "lonely", "romfs");
Directory.CreateDirectory(lonely);
var l = GameIntake.Normalize(lonely)!;
Equal("exefs", l.Missing, "the exefs is still to be chosen");
Equal(null, GameIntake.Normalize(Path.Combine(root, "nothing-here")), "nothing");
var notNup = Path.Combine(root, "x.nup");
File.WriteAllText(notNup, "not a package at all, longer than the header is......................................................................................................................");
Check(!GameIntake.Quick(GameIntake.Normalize(notNup)!).Ok, "a file that is no .nup");
var space = new GameIntake(Ctx(root)).Space(root);
Check(space.Free > 0 && space.Text.StartsWith("Takes 60 GB while building, about 24 GB after."), space.Text);
}
static async Task IntakeCheck()
{
var root = NewRoot("intakecheck");
var noTools = await new GameIntake(Ctx(NewRoot("intake-notools"))).CheckAsync(GameIntake.Normalize(TestGame)!);
Check(noTools.ToolsMissing && !noTools.Ok, "no tools: said so");
var ctx = FakeTools(root);
var r = await new GameIntake(ctx).CheckAsync(GameIntake.Normalize(TestGame)!);
Check(r.Ok && r.BuildId == "e0f3ccfa", "make_game --check's @@check ok: " + r.Text);
}
}

View File

@@ -0,0 +1,246 @@
using System.Text;
using Triforce.Logic;
using static Triforce.LogicTests.T;
namespace Triforce.LogicTests;
static partial class Tests
{
public static IEnumerable<(string Name, Func<Task> Run)> All()
{
(string, Func<Task>) Sync(string n, Action a) => (n, () => { a(); return Task.CompletedTask; });
yield return Sync("settings: registry.txt round trip", SettingsTestRoot);
yield return Sync("settings: builder.ini round trip (Linux store)", SettingsIni);
yield return Sync("startup: argument parsing", StartArgsParsing);
yield return Sync("startup: lock name algorithm", LockName);
yield return Sync("startup: installed run, old exe removed, second start defers", StartupInstalled);
yield return Sync("startup: not installed shows Install; uninstall refused while open", StartupNotInstalled);
yield return Sync("install + uninstall in a test root", InstallUninstall);
yield return ("release: check, parse, notes against a fake server", ReleaseCheck);
yield return ("release: download with size check and resume", DownloadResume);
yield return ("release: self-swap, new launcher up", SelfSwapUp);
yield return ("release: self-swap, new launcher fails, rolled back", SelfSwapFails);
yield return Sync("release: decide what the start does", Decide);
yield return Sync("tools: unpack the whole zip, refuse unsafe names", ToolsUnpack);
yield return Sync("tools: base list and parts", ToolsParts);
yield return ("tools: update from the fake server with progress", ToolsUpdate);
yield return Sync("build: @@ protocol from a recorded transcript", Protocol);
yield return Sync("build: estimates from history and without", Estimates);
yield return ("build: runner with a fake make_game (done, args, log, times)", RunnerDone);
yield return ("build: runner stop kills the tree", RunnerStop);
yield return ("build: runner failure and test-root refusal", RunnerFail);
yield return Sync("game: the built test game folder", GameFolder);
yield return Sync("intake: folders, .nup header, packed romfs, space", Intake);
yield return ("intake: make_game --check (fake)", IntakeCheck);
yield return Sync("saves: slots of lab-game-merge98 (read only)", SavesListing);
yield return ("saves: find, import, export with backups", SavesCopy);
yield return Sync("mods: list, order, on/off, remove, rebuild mark", ModsFolder);
yield return Sync("mods: add archives and their safety checks", ModsArchives);
yield return ("mods: GameBanana install into the mods folder (fake server)", GameBananaInstall);
yield return ("mods: GameBanana live list (read only)", GameBananaLive);
yield return Sync("mods: GameBanana page parsing and plain text", GameBananaParse);
yield return Sync("linux: release keys, modes, parts list", LinuxLogic);
yield return Sync("steam: add, set, remove in a fake Steam folder", SteamShortcut);
yield return Sync("report: names out", ReportNames);
yield return Sync("languages", LanguagesTest);
}
// ---- settings ----
static void SettingsTestRoot()
{
var root = NewRoot("settings");
var ctx = Ctx(root);
ctx.Settings.GameFolder = @"D:\Games\Triforce";
ctx.Settings.Language = "de";
ctx.Settings.Dlss = true;
ctx.Settings.Set("Language", "fr");
ctx.Platform.Settings.SetUninstall("InstallLocation", root);
ctx.Platform.Settings.SetUninstallNumber("NoModify", 1);
var again = Ctx(root);
Equal(@"D:\Games\Triforce", again.Settings.GameFolder, "GameFolder read back");
Equal("fr", again.Settings.Language, "the last value for a name wins");
Check(again.Settings.Dlss, "Dlss read back");
Equal(40, again.Settings.MusicVolume, "music volume default");
again.Settings.MusicVolume = 250;
Equal(100, Ctx(root).Settings.MusicVolume, "volume clamped");
var lines = File.ReadAllLines(Path.Combine(root, "registry.txt"));
Check(lines.Contains(@"Software\Triforce\GameFolder=D:\Games\Triforce"), "the old Setup's line format: " + string.Join(" / ", lines));
Check(lines.Contains(@"Software\Microsoft\Windows\CurrentVersion\Uninstall\Triforce\NoModify=1"), "uninstall entry lines");
Equal(1, lines.Count(l => l.StartsWith(@"Software\Triforce\Language=")), "one line per name after a write");
again.Platform.Settings.RemoveAll();
Equal(null, Ctx(root).Settings.Language, "settings removed");
Equal(root, Ctx(root).Platform.Settings.GetUninstall("InstallLocation"), "uninstall entry kept until removed");
var snap = Ctx(root);
snap.NoWrites = true;
snap.Settings.Language = "ja";
Equal(null, Ctx(root).Settings.Language, "NoWrites writes nothing");
}
static void SettingsIni()
{
var root = NewRoot("ini");
var file = Path.Combine(root, "triforce", "builder.ini");
Directory.CreateDirectory(Path.GetDirectoryName(file)!);
File.WriteAllText(file, "kind=nup\nnup=/home/a/oot.nup\nout=/home/a/Games/Old\nlanguage=en-US\nprepare=1\nout=/home/a/Games/Triforce\n");
var s = new IniSettingsStore(file);
Equal("/home/a/Games/Triforce", s.Get(SettingNames.GameFolder), "GameFolder is the last out= line (hookshot-launch)");
s.Set(SettingNames.Language, "ja");
s.Set(SettingNames.Dlss, "1");
s.Set(SettingNames.SetupSkip, "v0.5.2");
var text = File.ReadAllText(file);
Check(text.Contains("kind=nup\n") && text.Contains("prepare=1\n") && text.Contains("nup=/home/a/oot.nup\n"), "the Tk builder's keys kept: " + text);
Check(text.Contains("language=ja\n") && text.Contains("dlss=1\n") && text.Contains("SetupSkip=v0.5.2\n"), "written under the shared names: " + text);
Equal(1, text.Split('\n').Count(l => l.StartsWith("out=")), "one out= line after a rewrite");
Throws<ArgumentException>(() => s.Set("x", "a\nb"), "a line break is refused");
}
// ---- startup ----
static void StartArgsParsing()
{
var a = StartArgs.Parse(new[] { "--relaunched", "--merge" });
Check(a.Relaunched && a.Merge && a.UpdateFolder == null, "--relaunched --merge");
a = StartArgs.Parse(new[] { "--update", @"C:\Games\Triforce", "--relaunched" });
Check(a.UpdateFolder == @"C:\Games\Triforce" && a.Merge && a.Relaunched, "--update sets merge");
a = StartArgs.Parse(new[] { "--update", @"C:\Games\Triforce", "--tag", "v0.5.2" });
Equal("v0.5.2", a.Tag, "--tag from the game");
// (a folder ending in a backslash, quoted on a command line: \" escapes the quote)
a = StartArgs.Parse(new[] { "--update", "C:\\Games\\Triforce\" --tag v0.5.2" });
Equal(@"C:\Games\Triforce\", a.UpdateFolder, "the folder repaired");
Equal("v0.5.2", a.Tag, "and the tag after it");
a = StartArgs.Parse(new[] { "--uninstall", "--quiet", "--something-new", "x" });
Check(a.Uninstall && a.Quiet && a.Unknown.Contains("--something-new"), "unknown arguments kept aside, not fatal");
a = StartArgs.Parse(new[] { "--launch", "/home/a/Games/Triforce" });
Equal("/home/a/Games/Triforce", a.LaunchFolder, "Linux --launch");
a = StartArgs.Parse(new[] { "--update", "/g", "--tag", "v1", "--fetched" });
Check(a.Fetched && a.UpdateFolder == "/g" && a.Tag == "v1", "Linux --update --tag --fetched");
a = StartArgs.Parse(new[] { "--install-to", @"D:\T", "--no-desktop" });
Check(a.InstallTo == @"D:\T" && a.NoDesktop && !a.NoStartMenu, "--install-to");
Equal("--relaunched|--merge", string.Join("|", new StartArgs { Merge = true }.PassOn(true)), "self-update passes --relaunched --merge");
Equal("--update|C:\\G|--relaunched", string.Join("|", new StartArgs { Merge = true, UpdateFolder = @"C:\G" }.PassOn(true)), "with the game's folder");
Equal("--merge", string.Join("|", new StartArgs { Merge = true }.PassOn(false)), "install relaunch");
}
static void LockName()
{
var a = @"C:\Users\you\AppData\Local\Programs\Triforce";
var name = InstanceLock.Name(a, null);
Equal(@"Local\TriforceSetup-8f6ec578ae853054-C--USERS-YOU-APPDATA-LOCAL-PROGRAMS-TRIFORCE", name, "FNV-1a 64 + tail, as the old Setup (PowerShell reference)");
Equal(name, InstanceLock.Name(a.ToLowerInvariant() + @"\", null), "case and a trailing slash");
Equal(name, InstanceLock.Name(@"C:\Users\you\AppData\Local\Programs\Other\..\Triforce", null), "another way to the same folder");
Check(name != InstanceLock.Name(a, @"E:\scratch\root"), "a test root names another lock");
Equal(name + "-up", InstanceLock.UpName(a, null), "the handover sign");
var tail = InstanceLock.Name(@"C:\" + new string('x', 400), null);
Check(tail.Length < 200 && tail.EndsWith(new string('X', 60)), "the tail is the last 60 characters");
}
static void StartupInstalled()
{
var root = NewRoot("startup");
var dir = Path.Combine(root, "Programs", "Triforce");
Directory.CreateDirectory(dir);
var exe = Path.Combine(dir, BuildInfo.SetupAsset);
File.WriteAllText(exe, "installed");
File.WriteAllText(Path.Combine(dir, "TriforceSetup.old.exe"), "replaced one");
var ctx = Ctx(root, exe);
ctx.Platform.Settings.SetUninstall("InstallLocation", dir);
Check(ctx.RunningInstalled, "running installed");
var r = Startup.Run(ctx, new[] { "--relaunched", "--merge" });
try
{
Equal(StartScreen.Check, r.Screen, "an installed run checks for updates");
Check(r.Args.Merge && r.SignalUpWhenShown, "merge carried, up sign asked");
Check(!File.Exists(Path.Combine(dir, "TriforceSetup.old.exe")), "TriforceSetup.old.exe removed");
Check(r.Lock is { Held: true }, "the lock held");
var second = Startup.Run(Ctx(root, exe), Array.Empty<string>());
Equal(StartScreen.Exit, second.Screen, "a second start ends");
Equal(0, second.ExitCode, "after asking the first to the front");
var un = Startup.Run(Ctx(root, exe), new[] { "--uninstall", "--quiet" });
Check(un.Screen == StartScreen.Exit && un.ExitCode == 1 && un.Message == null, "uninstall refused while open, quietly");
}
finally { r.Lock?.Dispose(); }
var after = Startup.Run(Ctx(root, exe), Array.Empty<string>());
try { Equal(StartScreen.Check, after.Screen, "the lock is free again after Release"); }
finally { after.Lock?.Dispose(); }
}
static void StartupNotInstalled()
{
var root = NewRoot("notinstalled");
var ctx = Ctx(root, Path.Combine(root, "Downloads", BuildInfo.SetupAsset));
var r = Startup.Run(ctx, Array.Empty<string>());
try { Equal(StartScreen.Install, r.Screen, "a download that is not installed shows Install"); }
finally { r.Lock?.Dispose(); }
var u = Startup.Run(ctx, new[] { "--uninstall" });
try { Equal(StartScreen.Uninstall, u.Screen, "uninstall goes on when nothing is open"); }
finally { u.Lock?.Dispose(); }
// (installed elsewhere, started from a download: the download becomes the installed launcher; here that copy cannot start,
// so this one carries on)
var dir = Path.Combine(root, "Programs", "Triforce");
var self = Path.Combine(root, "Downloads", BuildInfo.SetupAsset);
Directory.CreateDirectory(dir);
Directory.CreateDirectory(Path.GetDirectoryName(self)!);
File.WriteAllText(self, "downloaded copy, no program");
File.WriteAllText(Path.Combine(dir, BuildInfo.SetupAsset), "installed copy");
var c2 = Ctx(root, self);
c2.Platform.Settings.SetUninstall("InstallLocation", dir);
var r2 = Startup.Run(c2, new[] { "--merge" });
try
{
Equal("downloaded copy, no program", File.ReadAllText(Path.Combine(dir, BuildInfo.SetupAsset)), "the download was copied over the installed copy");
Equal(StartScreen.Check, r2.Screen, "and, the installed copy not starting, this one carries on");
}
finally { r2.Lock?.Dispose(); }
}
static void InstallUninstall()
{
var root = NewRoot("install");
var self = Path.Combine(root, "Downloads", BuildInfo.SetupAsset);
Directory.CreateDirectory(Path.GetDirectoryName(self)!);
File.WriteAllText(self, "launcher bytes");
var ctx = Ctx(root, self);
var inst = new Installer(ctx);
Equal(Path.Combine(root, "Programs", "Triforce"), inst.DefaultDir, "default install folder under the test root's LocalAppData");
var exe = inst.Run(inst.DefaultDir, desktop: true, startMenu: true);
Equal("launcher bytes", File.ReadAllText(exe), "copied");
Equal(inst.DefaultDir, ctx.InstalledDir, "registered (InstallLocation)");
Equal("\"" + exe + "\" --uninstall --quiet", ctx.Platform.Settings.GetUninstall("QuietUninstallString"), "quiet uninstall string");
Check(File.Exists(Path.Combine(root, "Desktop", "Triforce.lnk")), "desktop shortcut in the test root");
Check(File.Exists(Path.Combine(root, "Start Menu", "Triforce", "Triforce.lnk")), "start menu shortcut in the test root");
Throws<InvalidOperationException>(() => inst.Run(Path.Combine(Path.GetTempPath(), "elsewhere-" + Guid.NewGuid().ToString("N")), false, false), "outside the test root refused");
Directory.CreateDirectory(Path.Combine(root, "build", "objcache"));
ctx.Settings.GameFolder = Path.Combine(root, "Games", "Triforce");
var plan = new Uninstaller(ctx).Describe();
Check(plan.Keeps.Any(k => k.Contains("saves")) && plan.Removes.Count >= 3, "the plan says what goes and stays");
new Uninstaller(ctx).Run();
Check(!File.Exists(Path.Combine(root, "Desktop", "Triforce.lnk")) && !Directory.Exists(Path.Combine(root, "Start Menu", "Triforce")), "shortcuts gone");
Check(!Directory.Exists(Path.Combine(root, "build")), "work folder gone");
Equal(null, Ctx(root, self).Platform.Settings.GetUninstall("InstallLocation"), "uninstall entry gone");
Equal(null, Ctx(root, self).Settings.GameFolder, "settings gone");
}
// ---- report, languages ----
static void ReportNames()
{
var text = @"C:\Users\Ann\AppData\x and c:/users/ann//Games and C:\Users\Anna\y and C:\Users\ANN~1\Temp";
var o = Report.NoName(text, @"C:\Users\Ann", @"C:\Users\ANN~1");
Equal(@"%USERPROFILE%\AppData\x and %USERPROFILE%//Games and C:\Users\Anna\y and %USERPROFILE%\Temp", o, "the account's folder read as %USERPROFILE%");
Equal("b\nc", Report.Tail("a\nb\nc\n\n", 2).Replace("\r", ""), "tail");
}
static void LanguagesTest()
{
Equal(16, Languages.All.Count, "16 codes");
Equal("zh-Hant", Languages.Default("zh-TW").Code, "zh-TW");
Equal("zh-Hans", Languages.Default("zh-CN").Code, "zh-CN");
Equal("es-419", Languages.Default("es-MX").Code, "es-MX");
Equal("es", Languages.Default("es-ES").Code, "es-ES");
Equal("pt-BR", Languages.Default("pt-PT").Code, "pt-PT");
Equal("de", Languages.Default("de-AT").Code, "de-AT");
Equal("en-US", Languages.Default("xx-YY").Code, "unknown");
Equal("fr-CA", Languages.Default("fr-CA").Code, "exact");
}
}

View File

@@ -0,0 +1,386 @@
using System.IO.Compression;
using System.Text;
using Triforce.Logic;
using static Triforce.LogicTests.T;
namespace Triforce.LogicTests;
static partial class Tests
{
const string LabGame = @"D:\src\lab-game-merge98";
// ---- saves ----
static void SavesListing()
{
// (READ ONLY: lab-game-merge98 holds real slots. Nothing here copies, locks or writes there)
var saves = new Saves(Ctx(NewRoot("saves-list")));
Equal(Path.Combine(LabGame, "user", "save", Saves.TriforceUid), saves.TriforceFolder(LabGame), "Triforce's save folder");
var slots = saves.Slots(LabGame);
Equal(6, slots.Count, "six files");
Check(slots.Count(s => s.Used) >= 1, "slots in use");
foreach (var s in slots.Where(s => s.Used))
{
Check(s.Caption != null && File.Exists(s.Caption), "File " + s.FileNumber + " has its caption.sav");
var bytes = File.ReadAllBytes(s.Caption!);
var jpeg = bytes.AsSpan().IndexOf(new byte[] { 0xFF, 0xD8, 0xFF });
Check(jpeg > 0, "File " + s.FileNumber + "'s caption holds a JPEG (at " + jpeg + ")");
Check(s.Written != null, "written time");
}
var newest = saves.Newest(LabGame)!;
Check(slots.Where(s => s.Used).All(s => File.GetLastWriteTime(s.Caption!) <= File.GetLastWriteTime(newest.Caption!)), "the newest is the caption written last");
var set = Saves.Describe("Triforce", saves.TriforceNewest(LabGame));
Check(!set.Empty && set.Slots == slots.Count(s => s.Used), "described: " + set.Slots + " slots");
}
static void MakeSave(string dir, string marker, int slots = 2)
{
Directory.CreateDirectory(dir);
File.WriteAllText(Path.Combine(dir, "option.sav"), marker);
File.WriteAllText(Path.Combine(dir, "account.sav"), marker);
for (var i = 0; i < slots; i++)
{
Directory.CreateDirectory(Path.Combine(dir, "slot_0" + i));
File.WriteAllText(Path.Combine(dir, "slot_0" + i, "progress.sav"), marker + i);
File.WriteAllText(Path.Combine(dir, "slot_0" + i, "caption.sav"), marker + i);
}
}
static async Task SavesCopy()
{
var root = NewRoot("saves-copy");
var ctx = Ctx(root);
var saves = new Saves(ctx);
var eden = Path.Combine(root, "Roaming", "eden", "nand", "user", "save", "0000000000000000", "ABCDEF0123456789ABCDEF0123456789", Saves.TitleId);
MakeSave(eden, "eden", 3);
var ryu = Path.Combine(root, "Roaming", "Ryujinx", "bis", "user", "save", "0000000000000001", "0");
MakeSave(ryu, "ryujinx", 1);
var navi = Path.Combine(root, "Local", "Programs", "NX2navi", "game", "profile", "save", "0123456789abcdef0123456789abcdef");
MakeSave(navi, "navi", 1);
var found = saves.FindEmulatorSaves();
Check(found.Any(f => f.Name == "Eden" && f.Slots == 3), "Eden found: " + string.Join(", ", found.Select(f => f.Name)));
Check(found.Any(f => f.Name == "Ryujinx") && found.Any(f => f.Name == "NX2navi"), "Ryujinx and NX2navi found");
Equal(null, saves.RunningGame(), "nothing runs inside the test root");
var game = Path.Combine(root, "Games", "Triforce");
MakeSave(saves.TriforceFolder(game), "triforce", 1);
Directory.CreateDirectory(Path.Combine(game, "user", "save-tx", Saves.TriforceUid, "work"));
var backup = await saves.ImportAsync(found.First(f => f.Name == "Eden"), game);
Check(backup != null && File.ReadAllText(Path.Combine(backup, "option.sav")) == "triforce", "Triforce's saves backed up first");
Check(backup!.StartsWith(ctx.SaveBackupsFolder) && backup.EndsWith("_Triforce-before-Eden"), "the backup's name: " + backup);
Equal("eden", File.ReadAllText(Path.Combine(saves.TriforceFolder(game), "option.sav")), "Eden's saves in Triforce");
Equal(3, saves.Slots(game).Count(s => s.Used), "three files now");
Check(!Directory.Exists(Path.Combine(game, "user", "save-tx", Saves.TriforceUid)), "the old save's transaction removed");
Check(File.Exists(Path.Combine(game, "user", "save.lock")), "the game's lock was taken across the copy");
Check(!Directory.Exists(saves.TriforceFolder(game) + ".partial") && !Directory.Exists(saves.TriforceFolder(game) + ".old"), "no partial left");
// (out: a waiting commit is the newest save)
var ready = Path.Combine(game, "user", "save-tx", Saves.TriforceUid, "ready-2");
MakeSave(ready, "ready", 2);
Equal(ready, saves.TriforceNewest(game), "the waiting commit");
var target = Saves.Describe("Ryujinx", ryu);
var b2 = await saves.ExportAsync(game, target);
Equal("ready", File.ReadAllText(Path.Combine(ryu, "option.sav")), "Triforce's newest out to Ryujinx");
Check(b2 != null && File.ReadAllText(Path.Combine(b2, "option.sav")) == "ryujinx", "Ryujinx's backed up");
Equal(Path.Combine(game, "user", "save.lock"), SaveLock.PathOf(ready), "a commit's lock is its user folder's");
Equal(Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(navi))!, "instance.lock"), SaveLock.PathOf(navi), "NX2navi's lock");
// (only inside the test root)
await ThrowsAsync<InvalidOperationException>(() => saves.ExportAsync(game, Saves.Describe("lab", Path.Combine(LabGame, "user", "save", Saves.TriforceUid))), "a test run writes no save outside its root");
Equal(navi, Saves.FindIn(Path.Combine(root, "Local", "Programs", "NX2navi", "game")), "a chosen NX2navi game folder");
Equal(eden, Saves.FindIn(Path.Combine(root, "Roaming", "eden")), "a chosen emulator folder, searched down");
}
// ---- mods ----
static string MakeMod(string mods, string folder, params (string Rel, string Text)[] files)
{
var dir = Path.Combine(mods, folder);
foreach (var (rel, text) in files)
{
var p = Path.Combine(dir, rel.Replace('/', Path.DirectorySeparatorChar));
Directory.CreateDirectory(Path.GetDirectoryName(p)!);
File.WriteAllText(p, text);
}
return dir;
}
static void ModsFolder()
{
var root = NewRoot("mods");
var ctx = Ctx(root);
var game = Path.Combine(root, "Games", "Triforce");
var mods = Mods.FolderOf(game);
var mm = new ModManager(ctx) { GameRuns = _ => false };
MakeMod(mods, "Tall grass", ("romfs/Model/Grass.bfres", "a"), ("romfs/UI/x.bntx", "b"));
MakeMod(mods, "Better HUD", ("romfs/UI/X.bntx", "c"));
MakeMod(mods, "-Off one", ("romfs/Sound/a.bwav", "d"));
MakeMod(mods, "_pack/Inner", ("romfs/Event/e.bin", "e"));
MakeMod(mods, "Code mod", ("exefs/main.ips", "PATCH"), ("cheats/c.txt", "cheat"));
MakeMod(mods, ".hidden", ("romfs/a", "x"));
var list = mm.List(mods);
Equal("Better HUD,Code mod,Off one,Inner,Tall grass", string.Join(",", list.Select(m => m.Name)), "the game's order, switches ignored, dot folders left out");
Check(!list.First(m => m.Name == "Off one").On && list.First(m => m.Name == "Inner").OffAbove == "_pack", "off, and off by its folder");
var conflicts = Mods.Conflicts(list);
Equal(1, conflicts.Count, "one shared file");
Equal("ui/x.bntx", conflicts[0].File, "keyed in lower case with /");
Equal("Tall grass", conflicts[0].Winner.Name, "the last one wins");
Equal("2 game files", Mods.Carries(list.First(m => m.Name == "Tall grass")), "carries");
Equal("1 code patch file, 1 cheat file", Mods.Carries(list.First(m => m.Name == "Code mod")), "code");
// (the build mark)
Check(mm.NeedsRebuild(game), "code patches never built: build again");
mm.MarkBuilt(game);
Check(!mm.NeedsRebuild(game), "marked");
var state = Mods.CodeState(list);
Equal(16, state.Length, "16 hex digits");
// (on/off, order, remove)
var hud = list.First(m => m.Name == "Better HUD");
var off = mm.SetOn(mods, hud, false);
Equal(Path.Combine(mods, "-Better HUD"), off, "off is a - in front");
Throws<ModsException>(() => mm.SetOn(mods, mm.List(mods).First(m => m.Name == "Inner"), true), "a folder above switches it off");
var code = mm.List(mods).First(m => m.Name == "Code mod");
mm.SetOn(mods, code, false);
Check(mm.NeedsRebuild(game), "a code mod switched off: build again");
Check(mm.Move(mods, mm.List(mods).First(m => m.Name == "Tall grass"), later: false), "moved earlier");
var tops = Mods.Tops(mm.List(mods));
Check(tops.All(t => Mods.Parse(t).Number != null), "every folder numbered: " + string.Join(",", tops));
Check(tops.Contains("-01-Better HUD") || tops.Any(t => t.StartsWith("-0") && t.EndsWith("Better HUD")), "the switch kept in front of the number: " + string.Join(",", tops));
var order = mm.List(mods).Select(m => m.Name).ToList();
Check(order.IndexOf("Tall grass") < order.IndexOf("Inner"), "Tall grass passed Inner: " + string.Join(",", order));
Check(!mm.Move(mods, mm.List(mods)[0], later: false), "the first cannot go earlier");
var removed = mm.Remove(mods, mm.List(mods).First(m => m.Name == "Tall grass"));
Check(removed.StartsWith(Path.Combine(mods, Mods.Removed)) && Directory.Exists(removed), "removed to .removed, nothing deleted");
Check(mm.List(mods).All(m => m.Name != "Tall grass"), "out of the list");
var busy = new ModManager(ctx) { GameRuns = _ => true };
Equal("Close the game first. Mods are added, switched, ordered and removed only while it is not running.",
Throws<ModsException>(() => busy.Remove(mods, busy.List(mods)[0]), "refused while the game runs").Message, "said so");
// (the romfs file the game reads)
MakeMod(mods, "99-Sound", ("romfs/Sound/Resource/Stream/SE_Sys_Do00.bwav", "mod's"));
Directory.CreateDirectory(Path.Combine(game, "romfs", "Sound", "Resource", "Stream"));
File.WriteAllText(Path.Combine(game, "romfs", "Sound", "Resource", "Stream", "SE_Sys_Cancel00.bwav"), "game's");
Equal("mod's", File.ReadAllText(mm.RomfsFile(game, "Sound/Resource/Stream/SE_Sys_Do00.bwav")!), "a mod's file wins");
Equal("game's", File.ReadAllText(mm.RomfsFile(game, "Sound/Resource/Stream/SE_Sys_Cancel00.bwav")!), "else the game's");
Equal(null, mm.RomfsFile(game, "../secret"), "no way out");
Equal<(bool, int?, string)>((true, 2, "Grass"), Mods.Parse("-02-Grass"), "parse");
Equal((false, (int?)null, "4K-grass"), Mods.Parse("4K-grass"), "4K- is a name");
Check(Mods.Compare("a", "B") < 0 && Mods.Compare("_", "a") < 0, "_stricmp order");
}
static byte[] ZipBytes(Action<ZipArchive> fill)
{
using var m = new MemoryStream();
using (var z = new ZipArchive(m, ZipArchiveMode.Create, true)) fill(z);
return m.ToArray();
}
static void Put(ZipArchive z, string name, string text)
{
using var w = new StreamWriter(z.CreateEntry(name).Open());
w.Write(text);
}
static void ModsArchives()
{
var root = NewRoot("modzip");
var ctx = Ctx(root);
var game = Path.Combine(root, "Games", "Triforce");
var mods = Mods.FolderOf(game);
var mm = new ModManager(ctx) { GameRuns = _ => false };
var good = Path.Combine(root, "Cool Link.zip");
File.WriteAllBytes(good, ZipBytes(z => { Put(z, "contents/0400486024DEC000/romfs/Model/Link.bfres", "link"); Put(z, "readme.txt", "hi"); }));
var m = mm.Add(mods, good);
Equal("Cool Link", m.Name, "named after the archive when its folder is generic");
Equal("model/link.bfres", m.Files.Single(), "its file");
Check(!Directory.EnumerateDirectories(mods, ".adding-*").Any(), "the temporary folder removed");
File.WriteAllBytes(good, ZipBytes(z => Put(z, "Hat/romfs/UI/hat.bntx", "hat")));
Equal("Hat", mm.Add(mods, good).Name, "named after its own folder");
void Refused(string name, Action<ZipArchive> fill, string words)
{
var f = Path.Combine(root, name);
File.WriteAllBytes(f, ZipBytes(fill));
var e = Throws<ModsException>(() => mm.Add(mods, f), name);
Check(e.Message.Contains(words), name + ": " + e.Message);
}
Refused("escape.zip", z => Put(z, "../../evil/romfs/x", "x"), "leaves its own folder");
Refused("device.zip", z => Put(z, "m/romfs/CON.txt", "x"), "device");
Refused("two.zip", z => { Put(z, "a/romfs/x", "x"); Put(z, "b/romfs/y", "y"); }, "versions to choose from");
Refused("none.zip", z => Put(z, "just/a/file.txt", "x"), "no romfs, exefs or cheats");
Refused("other.zip", z => Put(z, "contents/0100000000010000/romfs/x", "x"), "another game");
Refused("link.zip", z => { var e = z.CreateEntry("m/romfs/link"); e.ExternalAttributes = unchecked((int)(0xA1FFu << 16)); using var w = new StreamWriter(e.Open()); w.Write("/etc/passwd"); }, "link");
Refused("dup.zip", z => { Put(z, "m/romfs/a", "1"); Put(z, "m/romfs/a", "2"); }, "two files of one name");
var big = new ModManager(ctx) { GameRuns = _ => false, MaxBytes = 10 };
File.WriteAllBytes(good, ZipBytes(z => Put(z, "m/romfs/big", new string('x', 100))));
Check(Throws<ModsException>(() => big.Add(mods, good), "too big").Message.Contains("more than"), "the size bound");
Throws<ModsException>(() => mm.Add(mods, Path.Combine(root, "x.txt")), "not an archive");
Equal("Mod", Mods.Clean("..."), "clean: nothing left");
Equal("Mod", Mods.Clean("NUL"), "clean: a device");
Equal("Tall grass", Mods.Clean("-_Tall grass. "), "clean: switches and dots");
Equal(2, mm.List(mods).Count, "only the two good ones added");
}
// ---- GameBanana ----
const string PageJson = """
{"_aMetadata":{"_nRecordCount":3,"_bIsComplete":true},"_aRecords":[
{"_idRow":101,"_sModelName":"Mod","_sName":"Hat","_sProfileUrl":"https://gamebanana.com/mods/101","_nLikeCount":5,"_nViewCount":50,
"_tsDateModified":1700000000,"_aSubmitter":{"_sName":"ann"},"_aRootCategory":{"_sName":"Models"},"_aGame":{"_idRow":26242},
"_aPreviewMedia":{"_aImages":[{"_sBaseUrl":"https://images.gamebanana.com/img/ss/mods","_sFile":"a.jpg","_sFile530":"530-90_a.jpg"}]}},
{"_idRow":105323,"_sModelName":"Wip","_sName":"Squadala!","_bHasFiles":true,"_aSubmitter":{"_sName":"daurosk"},"_aRootCategory":{"_sName":"Other"}},
{"_idRow":7,"_sModelName":"Wip","_sName":"Showcase","_bHasFiles":false},
{"_idRow":8,"_sModelName":"Request","_sName":"Please"},
{"_idRow":9,"_sModelName":"Mod","_sName":"Other game","_aGame":{"_idRow":1}}
]}
""";
static void GameBananaParse()
{
var p = GameBanana.ParsePage(PageJson, null, 1, false);
Equal(2, p.Mods.Count, "a mod and a WiP with files; no showcase, request or other game");
Equal("https://images.gamebanana.com/img/ss/mods/530-90_a.jpg", p.Mods[0].ThumbUrl, "the 530 picture");
Check(p.Mods[1].IsKit && p.Mods[1].Wip, "Squadala is the kit");
Check(p.Complete && p.Total == 3, "metadata");
Equal("https://gamebanana.com/apiv11/Game/26242/Subfeed?_sSort=default&_csvModelInclusions=Mod,Wip&_nPage=2", GameBanana.ListUrl(2), "the section's URL");
Equal("https://gamebanana.com/apiv11/Util/Search/Results?_sModelName=Wip&_idGameRow=26242&_sOrder=best_match&_nPage=1&_sSearchString=link%20%26%20zelda%C3%A9",
GameBanana.SearchUrl(true, 1, "link & zeldaé"), "search URL, UTF-8 escaped");
// (as the game's own: </p> and <br> each a line, at most one blank line; <li> opens "- " where it stands)
Equal("Line one\n\nLine two- item\nA & B", GameBanana.Plain("<p>Line one</p><br>Line two<ul><li>item</li></ul>A &amp; B"), "plain text");
using var d = System.Text.Json.JsonDocument.Parse("""{"_sText":"<b>Hi</b>","_nDownloadCount":12,"_aFiles":[{"_idRow":1,"_sFile":"x-linux.zip","_sDownloadUrl":"https://gamebanana.com/dl/1","_nFilesize":10,"_tsDateAdded":5},{"_idRow":2,"_sFile":"x-windows.zip","_sDownloadUrl":"https://gamebanana.com/dl/2","_nFilesize":11,"_tsDateAdded":6},{"_idRow":3,"_sFile":"nolink"}]}""");
var det = GameBanana.ParseDetails(d.RootElement, 105323, true);
Equal(2, det.Files.Count, "files with a link");
Equal(1, det.DefaultFile(true), "a kit's Windows file first");
Equal("Hi", det.Text, "description");
}
static async Task GameBananaLive()
{
// (one read-only list call to the real API)
var gb = new GameBanana();
var page = await gb.ListAsync(1);
Check(page.Mods.Count > 0 && page.Total > 0, "the section lists mods: " + page.Mods.Count + " of " + page.Total);
Check(page.Mods.All(m => m.Id > 0 && m.Name.Length > 0), "cards have ids and names");
}
static async Task GameBananaInstall()
{
using var s = new FakeServer();
var root = NewRoot("gbinstall");
var ctx = Ctx(root);
var game = Path.Combine(root, "Games", "Triforce");
var mods = Mods.FolderOf(game);
MakeMod(mods, "01-Old one", ("romfs/a", "a"));
var mm = new ModManager(ctx) { GameRuns = _ => false };
var inst = new GameBananaInstaller(ctx, mm);
s.Add("/dl/1", ZipBytes(z => { Put(z, "Fancy Hat v2/romfs/UI/hat.bntx", "hat"); Put(z, "readme.txt", "r"); }));
var mod = new GbMod(101, false, "Fancy Hat", "ann", "Models", "https://gamebanana.com/mods/101", 1, 1, 1, null);
var file = new GbFile(1, "hat.zip", "", s.Url + "/dl/1", 0, 1700000000);
using var http = Downloader.CreateHttp();
var msg = await inst.InstallAsync(http, mod, file, game, null, CancellationToken.None);
Check(msg.Contains("02-Fancy Hat"), "installed after the highest number: " + msg);
var info = ModManager.ReadInfo(Path.Combine(mods, "02-Fancy Hat"))!;
Check(info.GameBananaId == 101 && info.Author == "ann" && info.FileDate == 1700000000, "triforce_mod.json");
Check(inst.Installed(game).Any(i => i.Id == 101), "listed as installed");
Check(!Directory.Exists(Path.Combine(mods, ".triforce-download")), "the download folder removed");
// (switched off, then updated: the new one takes its place and its switch)
mm.SetOn(mods, mm.List(mods).First(m => m.Name == "Fancy Hat"), false);
s.Add("/dl/2", ZipBytes(z => Put(z, "romfs/UI/hat2.bntx", "hat2")));
await inst.InstallAsync(http, mod, file with { Url = s.Url + "/dl/2", Added = 1800000000 }, game, null, CancellationToken.None);
var now = mm.List(mods).Where(m => m.Info?.GameBananaId == 101).ToList();
Equal(1, now.Count, "one folder for the mod after its update");
Check(now[0].Folder.StartsWith("_02-") && !now[0].On, "its place and its off kept: " + now[0].Folder);
Equal("ui/hat2.bntx", now[0].Files.Single(), "the new files");
s.Add("/dl/3", ZipBytes(z => Put(z, "docs/readme.txt", "x")));
await ThrowsAsync<ModsException>(() => inst.InstallAsync(http, mod with { Id = 5 }, file with { Url = s.Url + "/dl/3" }, game, null, CancellationToken.None), "no romfs: refused");
// (bare game folders, no romfs above them: wrapped)
s.Add("/dl/4", ZipBytes(z => Put(z, "MyPack/Model/x.bfres", "m")));
await inst.InstallAsync(http, mod with { Id = 6, Name = "Bare" }, file with { Url = s.Url + "/dl/4" }, game, null, CancellationToken.None);
Check(mm.List(mods).Any(m => m.Name == "Bare" && m.Files.Contains("model/x.bfres")), "wrapped in a romfs");
}
// ---- Linux update logic (tests/test_linux_update.py's cases) ----
static void LinuxLogic()
{
string M(string? g, string t, string? l, bool p, bool k) => LinuxUpdate.ChooseMode(g, t, l, p, k);
Equal("update-game", M("v1", "v2", "v2", false, true), "1");
Equal("up-to-date", M("v2", "v2", "v2", false, true), "2");
Equal("up-to-date", M("v1", "v1", null, false, true), "3");
Equal("update-game", M("v1", "v1", "v2", false, true), "4");
Equal("update-builder", M(null, "v1", "v2", false, false), "5");
Equal("build", M(null, "v2", "v2", false, false), "6");
Equal("build", M("v2", "v2", "v2", true, true), "7");
var ci = "v2.0.5-3-g1a2b3c4";
Equal("build", M(null, ci, "v2.0.5", false, false), "an Actions build is not taken back");
Equal("build", M(null, "1a2b3c4", "v2.0.5", false, false), "a bare commit");
Equal("build", M(null, "dev", "v2.0.5", false, false), "dev");
Equal("build", M(null, "v2.0.6", "v2.0.5", false, false), "newer");
Equal("build", M(null, "v2.1.0-rc.1", "v2.0.5", false, false), "an rc after");
Equal("up-to-date", M(ci, ci, "v2.0.5", false, true), "its own game");
Equal("update-game", M("v2.0.4", ci, "v2.0.5", false, true), "an older game");
Equal(ci, LinuxUpdate.UpdateTarget("v2.0.5", ci), "target stays");
Equal("update-game", M("v2.0.5", ci, "v2.0.5", false, true), "the release's game is older than this builder");
Equal("update-builder", M(null, "v2.0.4", "v2.0.5", false, false), "an older release");
Equal("update-builder", M(null, "v2.1.0-rc.1", "v2.1.0", false, false), "rc before its release");
Equal("build", M(null, "v2.0.10", "v2.0.9", false, false), "numbers, not text");
Equal("update-builder", M(null, "v2.0.4-3-g1a2b3c4", "v2.0.5", false, false), "after an older release");
Equal("build", M(null, "v2.0.5-3-g1a2b3c4-dirty", "v2.0.5", false, false), "dirty after");
Equal("update-builder", M(null, "v2.1.0-rc.1-2-gabc1234", "v2.1.0", false, false), "rc commits before the release");
var sha = new string('a', 64);
var list = LinuxUpdate.ParseList("# x\ntag v0.5.2\npart " + sha + " 10 usr/share/hookshot https://x/a.zip\ntree\npart " + sha + " 5 usr/lib/hookshot https://x/b.zip\nfile hookshot_vk.so\nfile libSDL2-2.0.so.0\n", local: false);
Equal("v0.5.2", list.Tag, "tag");
Check(list.Parts[0].Files == null && list.Parts[1].Files!.Count == 2, "tree and files");
Throws<FormatException>(() => LinuxUpdate.ParseList("tag v1\npart " + sha + " 1 a file:///x\ntree\n", local: false), "file:// only in a local list");
Throws<FormatException>(() => LinuxUpdate.ParseList("tag ../x\npart " + sha + " 1 a https://x\ntree\n"), "a tag that is a path");
Throws<FormatException>(() => LinuxUpdate.ParseList("tag v1\npart " + sha + " 1 ../a https://x\ntree\n"), "a part out of its folder");
Throws<FormatException>(() => LinuxUpdate.ParseList("tag v1\nwhat\n"), "unknown line");
Equal("\"/home/a/100%% Games/\\\\\\\\x\\\\$y\"", LinuxPlatform.DesktopExec("/home/a/100% Games/\\x$y"), "desktop Exec escaping");
}
// ---- Steam ----
static void SteamShortcut()
{
var root = NewRoot("steam");
var ctx = Ctx(root);
var steamRoot = Path.Combine(root, "Steam");
Directory.CreateDirectory(Path.Combine(steamRoot, "userdata", "1001", "config"));
Directory.CreateDirectory(Path.Combine(steamRoot, "userdata", "2002", "config"));
Directory.CreateDirectory(Path.Combine(steamRoot, "config"));
File.WriteAllText(Path.Combine(steamRoot, "config", "loginusers.vdf"),
"\"users\"\n{\n\t\"" + (76561197960265728L + 2002) + "\"\n\t{\n\t\t\"PersonaName\"\t\t\"Link\"\n\t\t\"MostRecent\"\t\t\"1\"\n\t}\n}\n");
var lib = new SteamLibrary(ctx) { Running = _ => false };
Equal(steamRoot, lib.Root(), "the test root's Steam only");
var user = lib.User()!;
Check(user.Id == "2002" && user.Name == "Link", "the most recent account");
// (another shortcut there first, kept byte for byte)
var other = SteamVdf.With(Array.Empty<byte>(), "\"C:\\Other\\other.exe\"", "\"C:\\Other\"", "", out _, out _);
var otherBytes = other.ToArray();
// (named Triforce but not ours: its program is no game exe, and its number is another)
File.WriteAllBytes(user.Shortcuts, otherBytes);
var before = File.ReadAllBytes(user.Shortcuts);
var game = Path.Combine(root, "Games", "Triforce");
Directory.CreateDirectory(game);
var exe = Path.Combine(game, "Triforce.exe");
File.WriteAllText(exe, "");
var pics = SteamVdf.Pictures.ToDictionary(p => p.Kind, p => new byte[] { 0x89, (byte)'P', (byte)'N', (byte)'G' });
Check(lib.Add(user, exe, pics), "added");
Check(lib.Added(user, exe), "there");
Equal(exe, lib.Where(user, exe), "it starts the game");
var id = SteamVdf.Id("\"" + exe + "\"", "Triforce");
Check(id >= 0x80000000u, "the top bit set");
Check(File.Exists(Path.Combine(user.Grid, id + "p.png")) && File.Exists(Path.Combine(user.Grid, id + "_icon.png")), "pictures under the id");
Check(File.ReadAllBytes(user.Shortcuts + SteamLibrary.First).SequenceEqual(before), "the file before the first change kept");
// (the game folder moved: the shortcut set to it, its pictures moved along)
var moved = Path.Combine(root, "Games", "Moved");
Directory.CreateDirectory(moved);
var exe2 = Path.Combine(moved, "Triforce.exe");
File.WriteAllText(exe2, "");
Equal(exe, lib.Where(user, exe2), "the old shortcut found by its name and program");
Check(!lib.Add(user, exe2, pics), "set, not added");
var id2 = SteamVdf.Id("\"" + exe2 + "\"", "Triforce");
Check(File.Exists(Path.Combine(user.Grid, id2 + "p.png")) && !File.Exists(Path.Combine(user.Grid, id + "p.png")), "pictures moved to the new id");
var busy = new SteamLibrary(ctx) { Running = _ => true };
Equal(SteamLibrary.CloseFirst, Throws<SteamException>(() => busy.Remove(user, exe2), "Steam running").Message, "close Steam first");
Check(lib.Remove(user, exe2), "removed");
Check(!lib.Added(user, exe2), "gone");
Check(File.ReadAllBytes(user.Shortcuts).SequenceEqual(before), "the file as it was before");
File.WriteAllBytes(user.Shortcuts, new byte[] { 0, 1, 2 });
Check(Throws<SteamException>(() => lib.Add(user, exe, pics), "a broken file").Message.Contains("left it alone"), "left alone");
}
}

View File

@@ -0,0 +1,515 @@
using System.Text;
using System.Text.RegularExpressions;
using Triforce.Logic;
using static Triforce.LogicTests.T;
namespace Triforce.LogicTests;
static partial class Tests
{
// (READ ONLY: the owner's own game folder. Nothing here writes there; the tests that write work on a copy in a test root)
const string RealGame = @"D:\src\triforce-game";
public static IEnumerable<(string Name, Func<Task> Run)> GameOptionsTests()
{
(string, Func<Task>) Sync(string n, Action a) => (n, () => { a(); return Task.CompletedTask; });
yield return Sync("game options: schema matches vk_menu.cpp's table", GameOptionsMatchMenu);
yield return Sync("game options: keys, labels, choices, no Hookshot", GameOptionsLabels);
yield return Sync("game options: the real triforce_options.ini (read only)", GameOptionsRealFile);
yield return Sync("game options: round trip, merge, atomic write (a copy)", GameOptionsWrite);
yield return Sync("game options: Set's rules, Quality preset, Apply", GameOptionsSetRules);
yield return Sync("game options: an older options_version, a new file", GameOptionsOldVersion);
}
// ---- the schema against the game's source ----
/// <summary>gpu/vk of this source tree (the launcher's own repository), found from this file's folder up, else from the test
/// program's.</summary>
static string? MenuSource([System.Runtime.CompilerServices.CallerFilePath] string here = "")
{
foreach (var start in new[] { Path.GetDirectoryName(here), AppContext.BaseDirectory })
for (var d = start is { Length: > 0 } ? new DirectoryInfo(start) : null; d != null; d = d.Parent)
if (File.Exists(Path.Combine(d.FullName, "gpu", "vk", "vk_menu.cpp"))) return Path.Combine(d.FullName, "gpu", "vk");
return null;
}
sealed record MenuRow(string Tab, string Name, string Value, string Lo, string Hi, string Step, string Text, string? Help, bool Restart, bool Exempt, bool Heading);
/// <summary>vk_menu.cpp's rows[] table, each entry's fields (comments out, adjacent string literals joined).</summary>
static List<MenuRow> ReadMenuTable(string cpp)
{
var body = cpp[cpp.IndexOf("Row rows[] = {", StringComparison.Ordinal)..cpp.IndexOf("constexpr int kRowsEnd", StringComparison.Ordinal)];
var sb = new StringBuilder();
for (int i = 0, inStr = 0; i < body.Length; i++)
{
var c = body[i];
if (inStr == 1)
{
sb.Append(c);
if (c == '\\') { sb.Append(body[++i]); continue; }
if (c == '"') inStr = 0;
continue;
}
if (c == '"') { inStr = 1; sb.Append(c); continue; }
if (c == '/' && i + 1 < body.Length && body[i + 1] == '/') { while (i < body.Length && body[i] != '\n') i++; sb.Append('\n'); continue; }
sb.Append(c);
}
body = sb.ToString();
var rows = new List<MenuRow>();
foreach (Match m in Regex.Matches(body, @"\{(TAB_[A-Z]+),"))
{
int k = m.Index + m.Length, depth = 1;
var inS = false;
var fields = new List<string>();
var cur = new StringBuilder();
for (; depth > 0; k++)
{
var c = body[k];
if (inS)
{
cur.Append(c);
if (c == '\\') { cur.Append(body[++k]); continue; }
if (c == '"') inS = false;
continue;
}
if (c == '"') { inS = true; cur.Append(c); }
else if (c == '{') { depth++; cur.Append(c); }
else if (c == '}') { if (--depth > 0) cur.Append(c); }
else if (c == ',') { fields.Add(cur.ToString().Trim()); cur.Clear(); }
else cur.Append(c);
}
if (cur.ToString().Trim().Length > 0) fields.Add(cur.ToString().Trim());
string? Lit(int i) => i < fields.Count && fields[i].StartsWith('"')
? string.Concat(Regex.Matches(fields[i], "\"((?:[^\"\\\\]|\\\\.)*)\"").Select(x => x.Groups[1].Value)).Replace("\\\"", "\"").Replace("\\\\", "\\")
: null;
string F(int i, string dflt) => i < fields.Count ? fields[i] : dflt;
rows.Add(new MenuRow(m.Groups[1].Value, Lit(0) ?? fields[0], fields[1], fields[2], fields[3], fields[4], fields[5], Lit(6),
F(8, "false") == "true", F(9, "false") == "true", F(11, "false") == "true"));
}
return rows;
}
/// <summary>vk_menu.h's Options defaults, by field.</summary>
static Dictionary<string, int> ReadOptionDefaults(string h)
{
var s = h[h.IndexOf("struct Options {", StringComparison.Ordinal)..h.IndexOf("extern Options opts;", StringComparison.Ordinal)];
var d = new Dictionary<string, int>();
foreach (var line in s.Split('\n'))
{
var code = line.Split("//")[0];
var m = Regex.Match(code, @"^\s*int\s+(.*);");
if (!m.Success) continue;
foreach (var part in m.Groups[1].Value.Split(','))
{
var kv = part.Split('=');
d[kv[0].Trim()] = int.Parse(kv[1].Trim());
}
}
return d;
}
static void GameOptionsMatchMenu()
{
var dir = MenuSource();
Check(dir != null, "gpu/vk/vk_menu.cpp is found above the test program");
var table = ReadMenuTable(File.ReadAllText(Path.Combine(dir!, "vk_menu.cpp")));
var defaults = ReadOptionDefaults(File.ReadAllText(Path.Combine(dir!, "vk_menu.h")));
Check(table.Count > 100, "the table read: " + table.Count + " entries");
var symbols = new Dictionary<string, int>
{
["kLastOutput"] = 6, ["ur::kValues - 1"] = 6, ["ur::kUpscalers - 1"] = 6, ["ur::kModels - 1"] = 3, ["aa_rows::kValues - 1"] = 3,
["2 + kMaxMics"] = 18, ["HOS_PROMPT_N"] = 6,
};
int Num(string s, string what) => int.TryParse(s, out var v) ? v : symbols.TryGetValue(s, out v) ? v : throw new TestFailed(what + ": a symbol the test does not know, " + s);
var tabs = new Dictionary<string, GameOptionTab>
{
["TAB_DISPLAY"] = GameOptionTab.Display, ["TAB_GRAPHICS"] = GameOptionTab.Graphics, ["TAB_AUDIO"] = GameOptionTab.Audio,
["TAB_CONTROLS"] = GameOptionTab.Controls, ["TAB_SYSTEM"] = GameOptionTab.System, ["TAB_MOTION"] = GameOptionTab.Controls,
["TAB_PAGE"] = GameOptionTab.Controls,
};
var left = new[] { "&opts.language", "&opts.pad_layout" }; // (Game language: language.txt's; Layout preset: KeptKeys)
var sections = new Dictionary<string, string>();
var names = new List<string>();
foreach (var r in table)
{
if (r.Heading) { sections[r.Tab] = r.Name; continue; }
if (r.Value == "nullptr" || r.Tab == "TAB_DEBUG" || left.Contains(r.Value)) continue;
var row = GameOptionsSchema.ByName(r.Name);
Check(row != null, "the menu's row \"" + r.Name + "\" is in the schema");
names.Add(r.Name);
Equal(tabs[r.Tab], row!.Tab, r.Name + ": tab");
var section = r.Tab == "TAB_MOTION" ? "Motion" : r.Tab == "TAB_PAGE" ? "Controls" : sections.GetValueOrDefault(r.Tab);
Equal(section, row.Section, r.Name + ": section");
Equal(Num(r.Lo, r.Name), row.Lo, r.Name + ": lo");
Equal(Num(r.Hi, r.Name), row.Hi, r.Name + ": hi");
Equal(Num(r.Step, r.Name), row.Step, r.Name + ": step");
Equal(r.Help, row.Help, r.Name + ": help");
Equal(r.Restart, row.Restart, r.Name + ": restart");
Equal(r.Exempt, row.PresetExempt, r.Name + ": preset exempt");
Equal(defaults[r.Value["&opts.".Length..]], row.Default, r.Name + ": default");
}
Equal(string.Join("|", names), string.Join("|", GameOptionsSchema.All.Select(r => r.Name)), "the rows, in the menu's order");
// (the Debug tab's keys, and the Layout preset's, are the KeptKeys: each with its reason)
foreach (var r in table.Where(r => r.Value != "nullptr" && !r.Heading && (r.Tab == "TAB_DEBUG" || r.Value == "&opts.pad_layout")))
Check(GameOptionsSchema.KeptKeys.ContainsKey(GameOptionsSchema.IniKey(r.Name)), r.Name + "'s key " + GameOptionsSchema.IniKey(r.Name) + " is a kept key");
}
// ---- keys and labels ----
static void GameOptionsLabels()
{
var all = GameOptionsSchema.All;
Equal(all.Count, all.Select(r => r.Key).Distinct().Count(), "keys are unique");
Check(all.All(r => r.Key.Length <= 31 && !r.Key.Contains(' ')), "keys as ini_key makes them");
Equal("frame_rate_cap", GameOptionsSchema.Get("frame_rate_cap").Key, "renamed row keeps its key");
Equal("Game frame rate cap", GameOptionsSchema.Get("frame_rate_cap").Name, "by key");
Equal("amd_anti-lag_2", GameOptionsSchema.ByName("AMD Anti-Lag 2")!.Key, "AMD Anti-Lag 2's key");
Equal("upscaling", GameOptionsSchema.ByName("Window scaling filter")!.Key, "Window scaling filter's key");
Equal("tail_early", GameOptionsSchema.IniKey("Start next frame early"), "Start next frame early's key");
Equal("export_save_for_a_bug_report", GameOptionsSchema.IniKey("Export save for a bug report"), "a long name: 28 letters");
Equal("abcdefghijklmnopqrstuvwxyzabcde", GameOptionsSchema.IniKey("ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGH"), "cut at 31");
Equal(null, GameOptionsSchema.ByKey("Fullscreen"), "keys are exact");
Throws<KeyNotFoundException>(() => GameOptionsSchema.Get("nope"), "an unknown key");
foreach (var r in all)
{
foreach (var text in new[] { r.Name, r.Help }.Concat(r.Choices.Select(c => c.Label)).Concat(new[] { r.Label(r.Lo), r.Label(r.Hi), r.Label(r.Default) }))
Check(!text.Contains("hookshot", StringComparison.OrdinalIgnoreCase), r.Name + ": no Hookshot in \"" + text + "\"");
Check(r.Help.Length > 10, r.Name + ": has its help");
Check(r.Default >= r.Lo && r.Default <= r.Hi, r.Name + ": default in range");
Equal(r.Default, r.Clamp(r.Default), r.Name + ": default on its steps");
if (r.Kind == GameOptionKind.Choice)
{
Check(r.Key == GameOptionsSchema.GpuKey || r.Choices.Count >= 2, r.Name + ": choices");
Check(r.Key == GameOptionsSchema.GpuKey || r.Choices.Any(c => c.Value == r.Default), r.Name + ": its default is a choice");
Equal(r.Choices.Count, r.Choices.Select(c => c.Label).Distinct().Count(), r.Name + ": labels differ");
}
else Equal(0, r.Choices.Count, r.Name + ": a slider has no choice list");
}
Equal(1, all.Count(r => r.Tab == GameOptionTab.Graphics && r.Key == GameOptionsSchema.PresetKey), "the preset row");
Equal("Screen,Widescreen,Frame rate,High dynamic range,RenoDX", string.Join(",", GameOptionsSchema.Sections(GameOptionTab.Display)), "Display's sections");
Equal("Quality,Upscaling and edges,Smoothness,Latency,Advanced", string.Join(",", GameOptionsSchema.Sections(GameOptionTab.Graphics)), "Graphics' sections");
Equal("Camera,Sticks,Movement,Vibration,Other,Motion,Controls", string.Join(",", GameOptionsSchema.Sections(GameOptionTab.Controls)), "Controls' sections");
Equal(0, GameOptionsSchema.Sections(GameOptionTab.Audio).Count, "Audio has none");
string L(string key, int v) => GameOptionsSchema.Get(key).Label(v);
string Cs(string key) => string.Join("|", GameOptionsSchema.Get(key).Choices.Select(c => c.Value + "=" + c.Label));
Equal("-3=30|-2=40|-1=45|0=60 (the console's)|1=90|2=120|3=144|4=165|5=240|6=Monitor's rate", Cs("frame_rate_cap"), "fps cap");
Equal("3=1920x1080|0=2048x1152|1=2560x1440|2=3840x2160|4=5120x1440|6=5120x2160|5=5120x2880", Cs("output_res"), "output sizes, smallest first");
Equal("0=Game|1=NVIDIA DLSS|2=NVIDIA DLAA|3=AMD FSR 3.1|6=AMD FSR 3.1 Native AA|4=AMD FSR 4|5=AMD FSR 4 Native AA", Cs("dlss"), "upscalers in the menu's order");
Equal("0=Auto (dynamic)|1=100% (2048x1152)|2=75% (1536x864)|3=67% (1366x768)|4=50% (1024x576)", Cs("resolution"), "render resolution, the game's own");
Equal("0=Custom|1=Minimum (6GB)|2=Low (8GB)|3=Balanced (12GB)|4=High (16GB)|5=Ultra (20GB+)", Cs("quality_preset"), "presets");
Equal("0=Off|1=Default", Cs("microphone"), "microphone without devices");
Equal("0=Game SMAA|1=Off|2=FXAA|3=SMAA Ultra", Cs("anti-aliasing"), "anti-aliasing");
Equal("0=Off|1=Auto|2=2x|3=3x|4=4x|5=5x|6=6x|7=7x|8=8x|9=AMD FSR 4", Cs("frame_generation"), "frame generation");
Equal("0=Auto|1=Switch|2=Xbox|3=PlayStation 4|4=PlayStation 5|5=Steam Deck|6=Keyboard & mouse", Cs("button_prompts"), "prompts");
Equal("0=Auto|1=Off|2=On", Cs("robust_buffers"), "robust");
Equal("0=Insert or F1|1=F1 only", Cs("menu_shortcut"), "menu shortcut");
Equal("1.25", L("mouse_sensitivity", 125), "sensitivity");
Equal("0.51", L("walk_scale", 51), "walk scale");
Equal("10000 nits", L("hdr_peak_brightness", 10000), "nits");
Equal("Muted", L("master_volume", 0), "volume 0");
Equal("85%", L("master_volume", 85), "volume");
Equal("Off", L("menu_sounds", 0), "menu sounds 0");
Equal("Off", L("rumble_strength", 0), "rumble 0");
Equal("As Stick dead zone", L("left_stick_dead_zone", -1), "own dead zone");
Equal("0%", L("right_stick_dead_zone", 0), "own dead zone 0");
Equal("50", L("renodx_bloom", 50), "grade");
Equal("Default (24%)", L("stick_dead_zone", 0), "stick dead zone");
Equal("Off", L("upscaling", 7), "past the row: its first");
Equal("16:9", L("ultrawide", 0), "ultrawide");
// (the GPU device row: the names the launcher gives it)
var before = GameOptionsSchema.GpuNames;
try
{
GameOptionsSchema.GpuNames = null;
Equal("Auto", L("gpu_device", 0), "gpu 0");
Equal("1: Device 1", L("gpu_device", 2), "gpu without names");
Equal("0=Auto", Cs("gpu_device"), "gpu choices without names");
GameOptionsSchema.GpuNames = () => new[] { "NVIDIA GeForce RTX 4070", "AMD Radeon(TM) Graphics" };
Equal("0=Auto|1=0: NVIDIA GeForce RTX 4070|2=1: AMD Radeon(TM) Graphics", Cs("gpu_device"), "gpu choices");
Equal("0: NVIDIA GeForce RTX 4070", L("gpu_device", 1), "gpu 1");
GameOptionsSchema.UseSystemGpus(); // (not asked here: the tests do not read this PC's registry)
Check(GameOptionsSchema.GpuNames != null, "the hook is set");
}
finally { GameOptionsSchema.GpuNames = before; }
Equal(6, GameOptionsSchema.PresetSummaries.Count, "a summary for each preset");
Equal(0, GameOptionsSchema.PresetValues(0).Count, "Custom sets nothing");
}
// ---- the real file ----
static void GameOptionsRealFile()
{
var path = Path.Combine(RealGame, GameOptionsSchema.FileName);
Check(File.Exists(path), "the real options file is there: " + path);
var info = new FileInfo(path);
var (len, time) = (info.Length, info.LastWriteTimeUtc);
var f = GameOptionsFile.Load(RealGame);
Check(f.Exists && f.Version == GameOptionsSchema.CurrentVersion, "read, version " + f.Version);
// (every key is a row or a kept one: these, knowingly. options_version: the format; menu_size: the old Menu size row;
// layout_preset: rebinds the pad_ lines in the game; the Debug tab's; pad_* and key_*: the Controls page's bindings)
Equal("", string.Join(",", f.UnknownKeys), "no key nobody knows");
var kept = f.OtherLines.Select(o => o.Key).Where(k => !k.StartsWith("pad_") && !k.StartsWith("key_")).ToList();
foreach (var k in kept) Check(GameOptionsSchema.KeptKeys.ContainsKey(k), k + " is a kept key");
Check(f.OtherLines.Any(o => o.Key.StartsWith("key_")), "the bindings are other lines");
foreach (var r in GameOptionsSchema.All)
{
var v = f.Get(r.Key);
var label = f.Label(r.Key);
Check(label.Length > 0 && !label.Contains("Device"), r.Name + ": label \"" + label + "\"");
if (r.Kind == GameOptionKind.Choice)
Check(f.ChoicesOf(r.Key).Any(c => c.Value == v && c.Label == label), r.Name + ": " + v + " = \"" + label + "\" is one of its choices");
else
Check(Regex.IsMatch(label, @"^(-?\d+( nits|%)?|\d\.\d\d|Off|Muted|As Stick dead zone)$"), r.Name + ": a slider's label \"" + label + "\"");
Check(f.Raw(r.Key) == null || v == r.AsRead(GameOptionsFile.Atoi(f.Raw(r.Key)!)), r.Name + ": the file's value as the game reads it");
}
info.Refresh();
Equal(len, info.Length, "the real file is not written");
Equal(time, info.LastWriteTimeUtc, "the real file's time is the same");
Check(!File.Exists(path + ".new"), "nothing beside it");
}
/// <summary>The real file's lines as of 11-19 (version 7, CRLF), for the exact checks: the real one changes as he plays.</summary>
const string OptionsFixture = "fullscreen=0\r\noutput_res=1\r\ngpu_device=0\r\nultrawide=0\r\nultrawide_hud=0\r\nultrawide_menus=1\r\nframe_rate_cap=0\r\n" +
"fps_counter=1\r\nhdr=0\r\nhdr_paper_white=400\r\nhdr_peak_brightness=4000\r\nrenodx_midgray=2\r\nrenodx_color_space=2\r\nquality_preset=0\r\n" +
"resolution=1\r\ntexture_detail=1\r\ndlss=0\r\ndlss_model=1\r\nanti-aliasing=1\r\nsharpness=50\r\nupscaling=2\r\nframe_pacing=1\r\nnvidia_reflex=0\r\n" +
"robust_buffers=1\r\nmicrophone=1\r\nmouse_sensitivity=125\r\ncontroller_in_background=1\r\nlayout_preset=1\r\nbutton_prompts=2\r\ndebug_tools=0\r\n" +
"replay_helper_threads=0\r\ntail_early=1\r\noptions_version=7\r\nmenu_size=1\r\npad_a=0\r\nkey_a=69,0\r\nkey_cam_right=39,76\r\n";
static string NewGameFolder(string name, string content)
{
var game = Path.Combine(NewRoot(name), "game");
Directory.CreateDirectory(game);
File.WriteAllText(Path.Combine(game, GameOptionsSchema.FileName), content, Encoding.Latin1);
return game;
}
static void GameOptionsWrite()
{
// (a copy of the real file, in a test root)
var root = NewRoot("game-options");
var game = Path.Combine(root, "game");
Directory.CreateDirectory(game);
var path = Path.Combine(game, GameOptionsSchema.FileName);
File.Copy(Path.Combine(RealGame, GameOptionsSchema.FileName), path);
var original = File.ReadAllBytes(path);
var f = GameOptionsFile.Load(game);
f.Save();
Check(File.ReadAllBytes(path).SequenceEqual(original), "nothing changed: nothing written");
f.Set("hdr", f.Get("hdr"));
Equal(0, f.Changes.Count, "set to what it is: no change");
f.Save();
Check(File.ReadAllBytes(path).SequenceEqual(original), "still the same bytes");
// (one row changed: that line alone)
var sens = f.Get("mouse_sensitivity") == 200 ? 300 : 200;
f.Set("mouse_sensitivity", sens);
f.Save();
var before = Encoding.Latin1.GetString(original).Split("\r\n");
var after = File.ReadAllText(path, Encoding.Latin1).Split("\r\n");
Equal(before.Length, after.Length, "as many lines, CRLF kept");
for (var i = 0; i < before.Length; i++)
Equal(before[i].StartsWith("mouse_sensitivity=") ? "mouse_sensitivity=" + sens : before[i], after[i], "line " + i);
Equal(sens, GameOptionsFile.Load(game).Get("mouse_sensitivity"), "read back");
Check(!File.Exists(path + ".new"), "no .new left");
// (exact labels on the fixture)
var fx = GameOptionsFile.Load(NewGameFolder("game-options-fixture", OptionsFixture));
string Lb(string k) => fx.Label(k);
Equal("2560x1440", Lb("output_res"), "output");
Equal("100% (2560x1440)", Lb("resolution"), "render resolution at 2560x1440");
Equal("1.25", Lb("mouse_sensitivity"), "mouse sensitivity 125");
Equal("4000 nits", Lb("hdr_peak_brightness"), "peak");
Equal("400 nits", Lb("hdr_paper_white"), "paper white");
Equal("Off", Lb("anti-aliasing"), "aa");
Equal("Xbox", Lb("button_prompts"), "prompts");
Equal("On", Lb("fps_counter"), "fps counter");
Equal("DCI-P3", Lb("renodx_color_space"), "colour space");
Equal("Eye adaptation", Lb("renodx_midgray"), "midgray");
Equal("Transformer 2 (M)", Lb("dlss_model"), "dlss model");
Equal("Lanczos", Lb("upscaling"), "filter");
Equal("50%", Lb("sharpness"), "sharpness");
Equal("Off", Lb("robust_buffers"), "robust 1");
Equal("Default", Lb("microphone"), "microphone");
Equal("Full", Lb("texture_detail"), "texture detail");
Equal("Off", Lb("nvidia_reflex"), "reflex 0");
Equal("Per frame", GameOptionsSchema.Get("game_speed").Label(0), "game speed 0");
Equal("Real time", Lb("game_speed"), "game speed: its default without a line");
Equal("80%", Lb("menu_sounds"), "menu sounds' default");
Equal("Middle", Lb("ultrawide_hud"), "wide HUD");
Equal("Centred, blurred sides", Lb("ultrawide_menus"), "wide menus");
Equal("layout_preset,debug_tools,replay_helper_threads,tail_early,options_version,menu_size,pad_a,key_a,key_cam_right",
string.Join(",", fx.OtherLines.Select(o => o.Key)), "other lines in the file's order");
Equal("69,0", fx.OtherLines.Single(o => o.Key == "key_a").Value, "a binding's value as it is");
fx.Set("dlss", 1);
Equal("Quality (67%)", fx.Label("resolution"), "with DLSS: its mode (100% moved to Quality)");
Equal("DLSS's own", fx.Label("anti-aliasing"), "aa with DLSS");
Equal("0,3,5,4,6", string.Join(",", fx.ChoicesOf("resolution").Select(c => c.Value)), "DLSS's steps");
fx.Set("dlss", 2);
Equal("Native (DLAA)", fx.Label("resolution"), "DLAA");
fx.Set("dlss", 3);
Equal("FSR's own", fx.Label("anti-aliasing"), "aa with FSR");
fx.Set("dlss", 0);
fx.Set("handheld_profile", 1);
Equal("67% (1024x576)", fx.Label("resolution"), "handheld profile's size (100% went to DLSS's Quality, which stays with the game's own)");
// (the merge: a line changed outside since Load stays; the launcher's own change goes in; an unknown line stays in place)
var m = NewGameFolder("game-options-merge", OptionsFixture);
var mp = Path.Combine(m, GameOptionsSchema.FileName);
var a = GameOptionsFile.Load(m);
a.Set("fullscreen", 1);
a.Set("sharpness", 70);
var outside = File.ReadAllText(mp, Encoding.Latin1).Replace("hdr=0\r\n", "hdr=2\r\nzz_tool_line=5\r\n").Replace("sharpness=50", "sharpness=20");
File.WriteAllText(mp, outside, Encoding.Latin1);
a.Save();
var merged = File.ReadAllText(mp, Encoding.Latin1);
Check(merged.Contains("\r\nhdr=2\r\nzz_tool_line=5\r\n"), "the outside change and its new line kept in place");
Check(merged.StartsWith("fullscreen=1\r\n"), "the launcher's change in its line");
Check(merged.Contains("\r\nsharpness=70\r\n"), "a row changed on both sides: the launcher's (the later writer)");
Equal(outside.Replace("fullscreen=0", "fullscreen=1").Replace("sharpness=20", "sharpness=70"), merged, "every other line as the file had it");
Equal("zz_tool_line", a.UnknownKeys.Single(), "an unknown key, kept");
Equal(2, a.Get("hdr"), "this object holds the file as written");
// (a row with no line goes in before options_version; duplicates all take the value)
var d = NewGameFolder("game-options-dup", "sharpness=10\nsharpness=20\n#note\noptions_version=7\nmenu_size=1\n");
var df = GameOptionsFile.Load(d);
Equal(20, df.Get("sharpness"), "the last line wins, as the game reads it");
df.Set("sharpness", 30);
df.Set("vsync", 0);
df.Save();
Equal("sharpness=30\nsharpness=30\n#note\nvsync=0\noptions_version=7\nmenu_size=1\n", File.ReadAllText(Path.Combine(d, GameOptionsSchema.FileName)), "LF kept, line added, comment kept");
// (a device's name in UTF-8: its bytes as they were, its label as text)
var mic = "microphone_device=Mikrofon (Ä USB)";
var micBytes = Encoding.UTF8.GetBytes("microphone=2\r\n" + mic + "\r\noptions_version=7\r\n");
var mg = Path.Combine(NewRoot("game-options-mic"), "game");
Directory.CreateDirectory(mg);
File.WriteAllBytes(Path.Combine(mg, GameOptionsSchema.FileName), micBytes);
var mf = GameOptionsFile.Load(mg);
Equal("Mikrofon (Ä USB)", mf.Label("microphone"), "the device's name");
Equal("0=Off|1=Default|2=Mikrofon (Ä USB)", string.Join("|", mf.ChoicesOf("microphone").Select(c => c.Value + "=" + c.Label)), "its choices");
mf.Set("fullscreen", 1);
mf.Save();
var micAfter = File.ReadAllBytes(Path.Combine(mg, GameOptionsSchema.FileName));
Check(micAfter.AsSpan().IndexOf(Encoding.UTF8.GetBytes(mic)) >= 0, "the name's UTF-8 bytes kept");
// (atomic: the .new cannot be made, the file is as it was and the error is the caller's)
var w = NewGameFolder("game-options-atomic", OptionsFixture);
var wp = Path.Combine(w, GameOptionsSchema.FileName);
Directory.CreateDirectory(wp + ".new");
var wf = GameOptionsFile.Load(w);
wf.Set("vsync", 0);
Throws<Exception>(() => wf.Save(), "a failed write throws");
Equal(OptionsFixture, File.ReadAllText(wp, Encoding.Latin1), "the old file whole");
Equal(1, wf.Changes.Count, "the change is still to be saved");
Directory.Delete(wp + ".new");
wf.Save();
Equal(0, GameOptionsFile.Load(w).Get("vsync"), "saved once it can be");
Check(!File.Exists(wp + ".new") && !Directory.Exists(wp + ".new"), "nothing left beside it");
}
static void GameOptionsSetRules()
{
var f = GameOptionsFile.Load(NewGameFolder("game-options-set", OptionsFixture));
Equal(10000, f.Set("hdr_peak_brightness", 12345), "past the end: the end");
Equal(130, f.Set("mouse_sensitivity", 125), "onto the steps: the nearest, the larger on a tie");
Equal(50, f.Set("rumble_strength", 60), "rumble on 25s");
Equal(0, f.Set("output_res", 9), "an output past the list: the first");
Equal(-1, f.Set("left_stick_dead_zone", -7), "a range below 0");
Equal(-3, f.Set("frame_rate_cap", -3), "the cap's 30");
// (the preset sets its rows; a row not exempt changed by hand makes it Custom, an exempt one does not)
f.Set("quality_preset", 4);
foreach (var (k, v) in new Dictionary<string, int> { ["resolution"] = 1, ["upscaling"] = 2, ["sharpness"] = 40, ["frame_pacing"] = 1, ["game_speed"] = 1, ["handheld_profile"] = 0, ["texture_detail"] = 1 })
Equal(v, f.Get(k), "High sets " + k);
Equal("High (16GB)", f.Label("quality_preset"), "the preset's label");
f.Set("fullscreen", 1);
Equal(4, f.Get("quality_preset"), "an exempt row leaves the preset");
f.Set("sharpness", 40);
Equal(4, f.Get("quality_preset"), "the same value is no change");
f.Set("sharpness", 60);
Equal(0, f.Get("quality_preset"), "a scaling row by hand: Custom");
// (with DLSS the preset's resolution is its nearest mode)
f.Set("dlss", 1);
f.Set("quality_preset", 2);
Equal(3, f.Get("resolution"), "Low's 75% with DLSS: Quality (67%)");
Equal(2, f.Get("texture_detail"), "Low: Reduced textures");
f.Set("quality_preset", 1);
Equal(4, f.Get("resolution"), "Minimum's 50% is DLSS's Performance");
Equal(3, f.Get("texture_detail"), "Minimum: Low textures");
Equal(1, f.Get("handheld_profile"), "Minimum: handheld profile");
// (another Upscaler moves the resolution onto its steps)
f.Set("dlss", 0);
f.Set("resolution", 2);
f.Set("dlss", 3);
Equal(3, f.Get("resolution"), "75% with FSR 3.1: 67%");
Equal(0, f.Get("quality_preset"), "the Upscaler is not exempt");
// (Apply: the preset first, then the rest by the same rules)
var b = GameOptionsFile.Load(NewGameFolder("game-options-apply", OptionsFixture));
var got = b.Apply(new Dictionary<string, int> { ["frame_generation"] = 2, ["quality_preset"] = 3, ["sharpness"] = 30 });
Equal(3, got["quality_preset"], "a preset row at the preset's own value keeps the preset");
Equal(2, got["frame_generation"], "frame generation set");
Equal(1, b.Get("upscaling"), "Balanced: Catmull-Rom");
var c = b.Apply(new Dictionary<string, int> { ["quality_preset"] = 5, ["sharpness"] = 80 });
Equal(0, c["quality_preset"], "a preset row changed after it: Custom, as in the game");
Equal(80, c["sharpness"], "and its value");
var changes = b.Changes.Count;
Throws<KeyNotFoundException>(() => b.Apply(new Dictionary<string, int> { ["vsync"] = 0, ["descriptor_reuse"] = 0 }), "a key that is no row");
Equal(changes, b.Changes.Count, "nothing set then");
Equal(1, b.Get("vsync"), "vsync untouched");
b.Save();
var back = GameOptionsFile.Load(Path.GetDirectoryName(b.Path)!);
Equal(80, back.Get("sharpness"), "saved");
Equal(2, back.Get("frame_generation"), "saved");
Equal(0, back.Changes.Count, "a fresh read has no changes");
}
static void GameOptionsOldVersion()
{
// (options_version 5: Frame pacing's and Start next frame early's old off defaults, Ultrawide's 1 the monitor's shape)
var g = NewGameFolder("game-options-v5", "frame_pacing=0\r\nultrawide=1\r\nnvidia_reflex=0\r\nsharpness=20\r\noptions_version=5\r\npad_a=0\r\n");
var f = GameOptionsFile.Load(g, (2560, 1080));
Equal(5, f.Version, "version");
Equal(1, f.Get("frame_pacing"), "pacing on, as the game reads a file before 7");
Equal(2, f.Get("ultrawide"), "the monitor's shape at 2560x1080: 21:9");
Equal(0, f.Get("nvidia_reflex"), "Reflex as saved from 5 on");
Equal(0, GameOptionsFile.Load(g).Get("ultrawide"), "without the screen: 16:9, as the game where it cannot ask");
f.Set("sharpness", 30);
f.Save();
Equal("frame_pacing=1\r\nultrawide=2\r\nnvidia_reflex=0\r\nsharpness=30\r\noptions_version=7\r\npad_a=0\r\n",
File.ReadAllText(Path.Combine(g, GameOptionsSchema.FileName)).Replace("tail_early=1\r\n", ""), "brought up to 7 as the game would read it");
Check(File.ReadAllText(Path.Combine(g, GameOptionsSchema.FileName)).Contains("tail_early=1\r\noptions_version=7"), "the Debug tab's tail_early too, before the version");
var again = GameOptionsFile.Load(g);
Equal(7, again.Version, "now 7");
again.Set("frame_pacing", 0);
again.Save();
Equal(0, GameOptionsFile.Load(g).Get("frame_pacing"), "and from 7 on the choice is read as it is");
// (no options_version line: Game speed real time; no resolution line but the old dynamic_resolution)
var o = NewGameFolder("game-options-v0", "game_speed=0\ndynamic_resolution=0\n");
var of = GameOptionsFile.Load(o);
Equal(1, of.Get("game_speed"), "the old default real time");
Equal(1, of.Get("resolution"), "dynamic_resolution 0: 100%");
Equal(2, of.Get("nvidia_reflex"), "Reflex On + Boost before 5");
// (no file: the defaults; a Save makes it with the changed rows and the version)
var n = Path.Combine(NewRoot("game-options-new"), "game");
Directory.CreateDirectory(n);
var nf = GameOptionsFile.Load(n);
Check(!nf.Exists, "no file");
Equal(1, nf.Get("vsync"), "default");
Equal("Off", nf.Label("fullscreen"), "default label");
nf.Save();
Check(!File.Exists(nf.Path), "nothing to write: no file made");
nf.Set("vsync", 0);
nf.Set("master_volume", 83);
nf.Save();
var nl = OperatingSystem.IsWindows() ? "\r\n" : "\n";
Equal("vsync=0" + nl + "master_volume=85" + nl + "options_version=7" + nl, File.ReadAllText(nf.Path), "a new file: the rows in the menu's order, then the version");
Check(nf.Exists, "now there");
}
}

View File

@@ -0,0 +1,303 @@
using System.IO.Compression;
using System.Security.Cryptography;
using System.Text;
using Triforce.Logic;
using static Triforce.LogicTests.T;
namespace Triforce.LogicTests;
static partial class Tests
{
const string Notes = "Triforce v0.5.2 brings these:\n\n**Faster updates.** The tools come in two parts now.\n* **Mods page.** GameBanana's mods in the launcher, with `kits`.\n" +
"**A new look.** The launcher is [rebuilt](https://example.invalid).\n**A fourth one.** Not shown.\n\n## Fixes\n* one\n";
/// <summary>A Forgejo answer: a list of one release whose assets each carry a nested uploader object.</summary>
static string ReleaseJson(string server, string tag, IEnumerable<(string Name, long Size)> assets, string body = Notes)
{
var list = string.Join(",", assets.Select((a, i) =>
"{\"id\":" + (100 + i) + ",\"name\":\"" + a.Name + "\",\"size\":" + a.Size + ",\"download_count\":3,\"uploader\":{\"id\":1,\"login\":\"triforce\",\"assets\":[]}," +
"\"browser_download_url\":\"" + server + "/assets/" + a.Name + "\"}"));
return "[{\"id\":17,\"tag_name\":\"" + tag + "\",\"name\":\"Triforce " + tag + "\",\"prerelease\":true,\"html_url\":\"" + server + "/release\",\"published_at\":\"2026-11-19T10:00:00Z\"," +
"\"body\":" + System.Text.Json.JsonSerializer.Serialize(body) + ",\"assets\":[" + list + "]}]";
}
static async Task ReleaseCheck()
{
using var s = new FakeServer();
var root = NewRoot("release");
var setup = Encoding.ASCII.GetBytes("new setup");
s.Add("/api/releases", ReleaseJson(s.Url, "v0.5.2", new[] { ("TriforceSetup.exe", (long)setup.Length), ("triforce-tools.ZIP", 1234L), ("Triforce-Tools-code.zip", 12L),
("Triforce-Tools-base.zip", 34L), ("Triforce-v0.5.2-linux-test-x86_64.AppImage", 99L), ("other.txt", 1L) }));
var ctx = Ctx(root, env: new() { ["TRIFORCE_RELEASE_API"] = s.Url + "/api/releases" });
using var http = Downloader.CreateHttp();
var r = await new Updater(ctx).CheckAsync(http, CancellationToken.None);
Equal("v0.5.2", r.Tag, "tag");
Equal(s.Url + "/assets/TriforceSetup.exe", r.SetupUrl, "setup url");
Equal((long)setup.Length, r.SetupSize, "setup size");
Equal(1234L, r.ToolsSize, "tools matched without case");
Check(r.ToolsCodeUrl != null && r.ToolsBaseSize == 34, "parts");
Check(r.LinuxAppImageUrl != null && r.LinuxListUrl == null, "the AppImage; no linux list (none published)");
Check(r.Prerelease && r.PageUrl == s.Url + "/release", "page and prerelease");
var newIn = r.NewIn;
Equal(3, newIn.Count, "three New in items");
Equal("Faster updates", newIn[0].Title, "title without its dot");
Equal("The tools come in two parts now.", newIn[0].Text, "its line");
Equal("GameBanana's mods in the launcher, with kits.", newIn[1].Text, "markdown out");
Equal("The launcher is rebuilt.", newIn[2].Text, "link text kept");
var bullets = ReleaseNotes.NewIn("Intro\n\n* First fix\n* **Second.** two\n- third\n- fourth");
Equal("First fix|Second|third", string.Join("|", bullets.Select(b => b.Title)), "fallback: the first bullets");
// (404: no release yet)
var none = Ctx(root, env: new() { ["TRIFORCE_RELEASE_API"] = s.Url + "/missing" });
await ThrowsAsync<NoReleaseException>(() => Release.LatestAsync(none, http, CancellationToken.None), "404");
s.Add("/empty", "[]");
var empty = Ctx(root, env: new() { ["TRIFORCE_RELEASE_API"] = s.Url + "/empty" });
await ThrowsAsync<NoReleaseException>(() => Release.LatestAsync(empty, http, CancellationToken.None), "an empty list");
var single = Release.Parse("{\"tag_name\":\"v1\",\"assets\":[]}");
Equal("v1", single.Tag, "a single release object");
}
static async Task DownloadResume()
{
using var s = new FakeServer();
var root = NewRoot("download");
var ctx = Ctx(root);
var data = RandomNumberGenerator.GetBytes(3_000_000);
s.Add("/assets/big.bin", data);
using var http = Downloader.CreateHttp();
var file = Path.Combine(root, "downloads", "big.bin");
var seen = new List<DownloadProgress>();
await new Downloader(ctx).ToFileAsync(http, s.Url + "/assets/big.bin", file, data.Length, p => seen.Add(p), CancellationToken.None);
Check(File.ReadAllBytes(file).SequenceEqual(data), "the file whole");
Check(seen.Count > 0 && seen[^1].Fraction == 1, "progress to 1");
Check(!File.Exists(file + ".part") && !File.Exists(file + ".part.of"), "no part left");
// (the size the release lists is not what the server sends: refused before a byte is kept)
var bad = Path.Combine(root, "downloads", "bad.bin");
await ThrowsAsync<IOException>(() => new Downloader(ctx).ToFileAsync(http, s.Url + "/assets/big.bin", bad, data.Length + 5, null, CancellationToken.None), "a size that contradicts the release");
Check(!File.Exists(bad), "nothing kept");
// (a part from a cut download goes on from where it stopped: Range + If-Range)
var resumed = Path.Combine(root, "downloads", "resumed.bin");
File.WriteAllBytes(resumed + ".part", data.AsSpan(0, 1_000_000).ToArray());
File.WriteAllLines(resumed + ".part.of", new[] { s.Url + "/assets/big.bin", data.Length.ToString(), "\"v" + data.Length + "\"" });
long first = -1;
await new Downloader(ctx).ToFileAsync(http, s.Url + "/assets/big.bin", resumed, data.Length, p => { if (first < 0) first = p.Bytes; }, CancellationToken.None);
Check(File.ReadAllBytes(resumed).SequenceEqual(data), "resumed file whole");
Equal(1_000_000L, first, "it went on from the part");
// (a part whose note names another address is fetched anew)
var other = Path.Combine(root, "downloads", "other.bin");
File.WriteAllBytes(other + ".part", new byte[] { 1, 2, 3 });
File.WriteAllLines(other + ".part.of", new[] { "https://elsewhere.invalid/x", data.Length.ToString(), "\"x\"" });
await new Downloader(ctx).ToFileAsync(http, s.Url + "/assets/big.bin", other, data.Length, null, CancellationToken.None);
Check(File.ReadAllBytes(other).SequenceEqual(data), "a foreign part was not joined on");
}
/// <summary>An installed launcher in a test root that can run: this program's files beside a TriforceSetup.exe that says "OLD".</summary>
static (TriforceContext Ctx, string Dir, string Root) InstalledRoot(string name)
{
var root = NewRoot(name);
var dir = Path.Combine(root, "Programs", "Triforce");
CopySelf(dir, "copy-of-tests.exe");
File.WriteAllText(Path.Combine(dir, BuildInfo.SetupAsset), "OLD");
var ctx = Ctx(root, Path.Combine(dir, BuildInfo.SetupAsset));
ctx.Platform.Settings.SetUninstall("InstallLocation", dir);
return (ctx, dir, root);
}
static async Task<Release> ServeNewSetup(FakeServer s, string tag)
{
var bytes = SelfBytes;
s.Add("/assets/TriforceSetup.exe", bytes);
s.Add("/api", ReleaseJson(s.Url, tag, new[] { ("TriforceSetup.exe", (long)bytes.Length) }));
await Task.CompletedTask;
return Release.Parse(ReleaseJson(s.Url, tag, new[] { ("TriforceSetup.exe", (long)bytes.Length) }));
}
static async Task SelfSwapUp()
{
using var s = new FakeServer();
var (ctx, dir, root) = InstalledRoot("selfswap-up");
var r = await ServeNewSetup(s, "v9.0.0");
var held = InstanceLock.TryTake(dir, root)!;
Environment.SetEnvironmentVariable("TRIFORCE_TEST_ROOT", root);
Environment.SetEnvironmentVariable("LOGICTESTS_CHILD", "up");
var hidden = false;
try
{
using var http = Downloader.CreateHttp();
var u = new Updater(ctx) { HandoverLimit = TimeSpan.FromSeconds(20) };
var result = await u.SelfUpdateAsync(http, r, new StartArgs(), held, null, () => hidden = true, CancellationToken.None);
Equal(SelfUpdateResult.CloseNow, result, "the old one closes");
Check(hidden, "the window was hidden while it waited");
Check(File.ReadAllBytes(Path.Combine(dir, BuildInfo.SetupAsset)).SequenceEqual(SelfBytes), "the new exe under the name");
Equal("OLD", File.ReadAllText(Path.Combine(dir, "TriforceSetup.old.exe")), "the running one stepped aside");
Check(!File.Exists(Path.Combine(dir, "TriforceSetup.new.exe")), "no .new left");
Equal("--relaunched|--merge", File.ReadAllText(Path.Combine(root, "child-args.txt")), "started as an old Setup starts it");
Check(ctx.Log.ReadAll().Contains("its window is up"), "it gave its sign: " + ctx.Log.ReadAll());
Equal(null, ctx.Settings.SetupSkip, "nothing skipped");
}
finally
{
Environment.SetEnvironmentVariable("LOGICTESTS_CHILD", null);
Environment.SetEnvironmentVariable("TRIFORCE_TEST_ROOT", null);
held.Dispose();
}
}
static async Task SelfSwapFails()
{
using var s = new FakeServer();
var (ctx, dir, root) = InstalledRoot("selfswap-fail");
var r = await ServeNewSetup(s, "v9.0.1");
var held = InstanceLock.TryTake(dir, root)!;
Environment.SetEnvironmentVariable("TRIFORCE_TEST_ROOT", root);
Environment.SetEnvironmentVariable("LOGICTESTS_CHILD", "fail");
try
{
using var http = Downloader.CreateHttp();
var u = new Updater(ctx) { HandoverLimit = TimeSpan.FromSeconds(20) };
var e = await ThrowsAsync<NotStartedException>(() => u.SelfUpdateAsync(http, r, new StartArgs { UpdateFolder = @"C:\G", Merge = true }, held, null, null, CancellationToken.None), "a new launcher that fails");
Check(e.Message.Contains("is back in its place"), e.Message);
Equal("OLD", File.ReadAllText(Path.Combine(dir, BuildInfo.SetupAsset)), "the old exe back under the name");
Equal("v9.0.1", ctx.Settings.SetupSkip, "that tag is skipped from now on");
Check(held.Held, "the lock taken again");
Equal("--update|C:\\G|--relaunched", File.ReadAllText(Path.Combine(root, "child-args.txt")), "the game's folder passed on");
Check(!new Updater(ctx).LauncherNewer(r), "a skipped (or dev) launcher is not newer");
}
finally
{
Environment.SetEnvironmentVariable("LOGICTESTS_CHILD", null);
Environment.SetEnvironmentVariable("TRIFORCE_TEST_ROOT", null);
held.Dispose();
}
}
static void Decide()
{
var root = NewRoot("decide");
var ctx = Ctx(root);
var u = new Updater(ctx);
var r = new Release { Tag = "v0.5.2", SetupUrl = "x", ToolsUrl = "y" };
Equal(CheckOutcome.Merge, u.Decide(new StartArgs(), r, null).Outcome, "first start, nothing here: the tools come at once");
Equal(CheckOutcome.Failed, u.Decide(new StartArgs(), null, new HttpRequestException("x")).Outcome, "offline with nothing");
Equal(FailureKind.Offline, u.Decide(new StartArgs(), null, new HttpRequestException("x")).Failure!.Kind, "said as offline");
Equal(FailureKind.Cancelled, u.Decide(new StartArgs(), null, new OperationCanceledException(), cancelled: true).Failure!.Kind, "cancelled");
// (tools here)
Directory.CreateDirectory(Path.Combine(ctx.ToolsFolder, "nx2"));
File.WriteAllText(Path.Combine(ctx.ToolsFolder, "nx2", "make_game.py"), "");
File.WriteAllText(Path.Combine(ctx.ToolsFolder, "version.txt"), "v0.5.1\n");
Equal(CheckOutcome.Home, u.Decide(new StartArgs(), r, null).Outcome, "with tools: Home");
Equal(CheckOutcome.Merge, u.Decide(new StartArgs { Merge = true }, r, null).Outcome, "--merge: carries on");
Equal(CheckOutcome.HomeOffline, u.Decide(new StartArgs(), null, new HttpRequestException("x")).Outcome, "offline with tools: Home");
Check(u.ToolsNewer(r), "tools v0.5.1 behind v0.5.2");
var game = Path.Combine(root, "Games", "Triforce");
Directory.CreateDirectory(game);
File.WriteAllText(Path.Combine(game, "Triforce.exe"), "");
File.WriteAllText(Path.Combine(game, "triforce_version.txt"), "version=v0.5.0\n");
ctx.Settings.GameFolder = game;
var st = u.State(r);
Check(st.ToolsNewer && st.GameBehind && !st.LauncherNewer && st.Any, "home's update state (a dev launcher never replaces itself)");
var plan = u.Plan(new StartArgs { Merge = true }, r);
Check(plan.Tools && plan.RebuildFolder == game && !plan.SelfUpdate, "merge plan: tools, then the game rebuilt");
}
// ---- tools ----
static byte[] Zip(params (string Name, string Text)[] files)
{
using var m = new MemoryStream();
using (var z = new ZipArchive(m, ZipArchiveMode.Create, true))
foreach (var (name, text) in files)
{
var e = z.CreateEntry(name);
if (!name.EndsWith('/')) using (var w = new StreamWriter(e.Open())) w.Write(text);
}
return m.ToArray();
}
static string Sha(string text) => Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(text)));
static string BaseList(params (string Path, string Text)[] files) =>
"triforce-tools-base\t1\nid\t" + Sha("base") + "\ndir\tpython\n" + string.Concat(files.Select(f => "file\t" + Encoding.UTF8.GetByteCount(f.Text) + "\t" + Sha(f.Text) + "\t" + f.Path + "\n"));
static void ToolsUnpack()
{
var root = NewRoot("tools");
var ctx = Ctx(root);
var tools = new Tools(ctx);
var zip = Path.Combine(root, "t.zip");
File.WriteAllBytes(zip, Zip(("tools/nx2/make_game.py", "print('x')"), ("tools/python/python.exe", "py"), ("tools/scripts/", ""),
("tools/base.list", BaseList(("python/python.exe", "py")))));
Directory.CreateDirectory(tools.Folder + ".part"); // (left by a cut-off unpacking)
tools.Sweep();
Check(!Directory.Exists(tools.Folder + ".part"), "sweep");
double last = -1;
tools.Unpack(zip, "v0.5.2", f => last = f);
Equal("v0.5.2", tools.InstalledVersion, "version.txt written");
Equal(1.0, last, "progress to 1");
Check(File.Exists(Path.Combine(tools.Folder, "nx2", "make_game.py")) && Directory.Exists(Path.Combine(tools.Folder, "scripts")), "the prefix tools/ stripped");
Equal(Sha("base"), File.ReadAllText(Path.Combine(tools.Folder, Tools.BaseHave)).Trim(), "base.have from the whole zip's list");
var found = tools.Find()!;
Equal(Path.Combine(tools.Folder, "python", "python.exe"), found.Python, "its own python");
// (unsafe names: the whole zip refused, the tools there kept)
foreach (var bad in new[] { "tools/../evil.txt", "tools/CON.txt", "tools/a:b", "tools/name. " })
{
File.WriteAllBytes(zip, Zip(("tools/nx2/make_game.py", "x"), (bad, "x")));
Throws<InvalidDataException>(() => tools.Unpack(zip, "v9", null), "refused: " + bad);
Equal("v0.5.2", tools.InstalledVersion, "the tools there kept after " + bad);
}
// (no tools in a test root without its own: never the development checkout above the test program)
Equal(null, new Tools(Ctx(NewRoot("notools"))).Find(), "no dev-checkout fallback in a test run");
}
static void ToolsParts()
{
Equal(null, Tools.ParseBaseList("triforce-tools-base\t1\nid\tabc\n"), "a short id is no list");
Equal(null, Tools.ParseBaseList("triforce-tools-base\t1\nid\t" + Sha("x") + "\ndir\tpython\nfile\t1\t" + Sha("a") + "\ta\nwhat\tnow\n"), "an unknown line");
var root = NewRoot("parts");
var ctx = Ctx(root);
var tools = new Tools(ctx);
var list = BaseList(("python/python.exe", "py"), ("python/lib.txt", "library"));
var b = Tools.ParseBaseList(list)!;
Equal(2, b.Files.Count, "two base files");
// (tools here with that base)
Directory.CreateDirectory(Path.Combine(tools.Folder, "python"));
Directory.CreateDirectory(Path.Combine(tools.Folder, "nx2"));
File.WriteAllText(Path.Combine(tools.Folder, "python", "python.exe"), "py");
File.WriteAllText(Path.Combine(tools.Folder, "python", "lib.txt"), "library");
File.WriteAllText(Path.Combine(tools.Folder, "nx2", "make_game.py"), "old");
File.WriteAllText(Path.Combine(tools.Folder, "version.txt"), "v0.5.1");
Check(Tools.HasBase(b, tools.Folder, null), "the base is here (sha read)");
Equal(b.Id, File.ReadAllText(Path.Combine(tools.Folder, Tools.BaseHave)).Trim(), "base.have remembered");
var code = Path.Combine(root, "code.zip");
File.WriteAllBytes(code, Zip(("tools/nx2/make_game.py", "new"), ("tools/base.list", list)));
Equal(b.Id, Tools.BaseListIn(code)!.Id, "the code zip's list");
tools.UnpackParts(code, null, b, "v0.5.2", null);
Equal("v0.5.2", tools.InstalledVersion, "new version");
Equal("new", File.ReadAllText(Path.Combine(tools.Folder, "nx2", "make_game.py")), "new code");
Equal("library", File.ReadAllText(Path.Combine(tools.Folder, "python", "lib.txt")), "the base moved over");
File.WriteAllText(Path.Combine(tools.Folder, "python", "lib.txt"), "changed!");
Check(!Tools.HasBase(b, tools.Folder, null), "a changed base file (other size) is not the base");
}
static async Task ToolsUpdate()
{
using var s = new FakeServer();
var root = NewRoot("toolsupdate");
var zip = Zip(("tools/nx2/make_game.py", "print('x')"), ("tools/python/python.exe", "py"));
s.Add("/assets/Triforce-Tools.zip", zip);
var r = Release.Parse(ReleaseJson(s.Url, "v0.5.2", new[] { ("Triforce-Tools.zip", (long)zip.Length) }));
var ctx = Ctx(root);
var inst = new ToolsInstaller(ctx);
var steps = new List<ToolsStep>();
inst.Progress += p => steps.Add(p.Step);
Check(inst.Needed(r), "no tools: needed");
using var http = Downloader.CreateHttp();
await inst.UpdateAsync(http, r, CancellationToken.None);
Equal("v0.5.2", new Tools(ctx).InstalledVersion, "tools installed");
Check(steps.Contains(ToolsStep.Download) && steps.Contains(ToolsStep.Unpack) && steps[^1] == ToolsStep.Done, "progress steps: " + string.Join(",", steps));
Check(Directory.GetFiles(ctx.DownloadsFolder).Length == 0, "the download cache emptied");
Check(!inst.Needed(r), "up to date now");
var n = s.Requests;
await inst.UpdateAsync(http, r, CancellationToken.None);
Equal(n, s.Requests, "nothing fetched when up to date");
}
}

View File

@@ -0,0 +1,22 @@
<Project Sdk="Microsoft.NET.Sdk">
<!-- Triforce.Logic's own tests: a console program (exit 0 = all passed). Everything runs inside TRIFORCE_TEST_ROOT temp folders and
a fake release server on 127.0.0.1; it never starts a real build or the real game, never touches the registry, the real
shortcuts or Steam, and only reads D:\src\lab-game-merge98, D:\src\triforce-test-game and the NX2navi .nup.
The exe doubles as the fakes it needs (Program.cs Fakes): a "python" that plays make_game.py's lines, and a new
"TriforceSetup.exe" for the self-update. -->
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<AssemblyName>Triforce.LogicTests</AssemblyName>
<RootNamespace>Triforce.LogicTests</RootNamespace>
<InvariantGlobalization>true</InvariantGlobalization>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Logic\Triforce.Logic.csproj" />
</ItemGroup>
</Project>