Files
Chronos/tests/Chronos.App.Tests/Setup/SingleSetupTests.cs
T
Alby96andClaude Opus 5.5 c3273b7da5 test: serialise setup registry scratch keys and refresh the copy plan baselines
The setup tests running in parallel shared HKCU\Software\Chronos.Tests and each
removed it once it looked empty; one test's cleanup could race another's key
creation and fail ReplacingTheLegacyUploaderMovesItsSignInEntryAndKeepsItTurnedOff
in a whole-suite run. ScratchRegistry now creates each scratch key and removes
the parent under one lock.

The Plan and Blocked compare captures now count both server projects coming
to this PC (Vertical and Slow pan, as the Projects part lists them); the old
baselines still showed one.

Refs #73

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 22:48:17 +01:00

437 lines
23 KiB
C#

using System.Globalization;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using Microsoft.Win32;
using Chronos.Core.Localization;
using Chronos.Core.Packaging;
using Chronos.Setup.Cli;
using Chronos.Setup.Engine;
using Chronos.Setup.Views;
using Chronos.Testing;
namespace Chronos.App.Tests.Setup;
/// <summary>
/// One setup for Chronos Desktop and Chronos Uploader: what a run installs, keeps and removes. A 1.0 Server for Windows
/// is retained until the user unticks it or the switches leave it out, the separate 1.0 Uploader is replaced, a file
/// changed since setup installed it is never deleted, and the Changes line is the dry-run plan of all of it.
/// </summary>
public sealed class SingleSetupTests(TestContext context)
{
/// <summary>The StartupApproved state Task Manager writes for an entry it turned off.</summary>
private static readonly byte[] TurnedOff = [0x03, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
static SingleSetupTests() => Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
[Test]
public void ANewInstallationTakesTheDesktopAppAndDesktopNamesIt()
{
var manifest = Manifest();
var plan = InstallPlan.Resolve(manifest, new SetupArguments(), null, null, null);
Assert.SequenceEqual(["Chronos"], plan.Components);
Assert.Empty(plan.Retained);
Assert.True(plan.CanChangeLocation);
Assert.Equal(InstallScope.CurrentUser, plan.Scope);
var both = InstallPlan.Resolve(manifest, new SetupArguments { Components = ["Desktop", "Uploader"] }, null, null, null);
Assert.SequenceEqual(["Chronos", "Uploader"], both.Components);
Assert.SequenceEqual(["Uploader"], InstallPlan.Resolve(manifest, new SetupArguments { Components = ["uploader"] }, null, null, null).Components);
// The Server is no longer offered: asking for it without a 1.0 Server installed is a wrong switch.
var refused = Assert.Throws<SetupException>(() => InstallPlan.Resolve(manifest, new SetupArguments { Components = ["Server"] }, null, null, null));
Assert.Equal(SetupExitCode.InvalidArguments, refused.Code);
}
[Test]
public void A10ServerIsRetainedUntilTheSwitchesLeaveItOut()
{
var manifest = Manifest();
var directory = context.CreateTempDirectory("retained");
var previous = ServerLog(directory);
var existing = new ExistingInstall(InstallScope.AllUsers, directory, "1.0.0");
// Nothing said: the desktop app and the Uploader are updated, the Server is kept with every file this payload
// does not know (a format 1 log does not say which component installed what), and its own shortcut.
var plan = InstallPlan.Resolve(manifest, new SetupArguments(), existing, previous, null);
Assert.SequenceEqual(["Chronos", "Uploader"], plan.Components);
var server = Assert.Contains(plan.Retained, r => r.Id == "Server");
Assert.Count(1, plan.Retained);
Assert.Equal("1.0.0", server.Version);
Assert.SequenceEqual(["Chronos.Server.exe", "legacy.txt"], server.Files);
Assert.SequenceEqual([Path.Combine(directory, "Chronos Server.lnk")], server.Shortcuts);
Assert.SequenceEqual(["Server"], plan.Kept.Select(k => k.Id));
Assert.Empty(plan.Removed(plan.Kept));
Assert.False(plan.CanChangeLocation);
// Its program keeps running: it is not among those setup closes or whose service it stops.
previous.Save(directory);
var programs = InstallPlan.Programs(manifest, directory, plan.Kept).ToList();
Assert.Contains("Chronos.Uploader.exe", programs);
Assert.DoesNotContain("Chronos.Server.exe", programs);
Assert.DoesNotContain("legacy.txt", programs);
Assert.Contains("Chronos.Server.exe", InstallPlan.Programs(manifest, directory, []));
// Switches are exact: leaving the Server out removes it; naming it keeps it.
var desktop = InstallPlan.Resolve(manifest, new SetupArguments { Components = ["Desktop"] }, existing, previous, null);
Assert.SequenceEqual(["Chronos"], desktop.Components);
Assert.Empty(desktop.Kept);
Assert.SequenceEqual(["Server"], desktop.Removed(desktop.Kept).Select(r => r.Id));
var kept = InstallPlan.Resolve(manifest, new SetupArguments { Components = ["Desktop", "Server"] }, existing, previous, null);
Assert.SequenceEqual(["Chronos"], kept.Components);
Assert.SequenceEqual(["Server"], kept.Kept.Select(k => k.Id));
}
[Test]
public void AFormat2LogKeepsOnlyTheFilesOfTheRetainedComponent()
{
var manifest = Manifest();
var log = new InstallLog
{
FormatVersion = InstallLog.CurrentFormat,
Product = "Chronos",
Version = "1.1.0",
Scope = InstallScope.AllUsers,
Components = ["Chronos", "Server"],
Files = ["Chronos.exe", "old.dll", "Chronos.Server.exe"],
ComponentFiles = { ["Chronos"] = ["Chronos.exe", "old.dll"], ["Server"] = ["Chronos.Server.exe"] },
ComponentVersions = { ["Chronos"] = "1.1.0", ["Server"] = "1.0.0" },
Hashes = { ["Chronos.Server.exe"] = new string('a', 64) },
};
var server = Assert.Contains(LegacyProducts.Retained(manifest, log), r => r.Id == "Server");
Assert.Equal("1.0.0", server.Version);
Assert.SequenceEqual(["Chronos.Server.exe"], server.Files);
Assert.Equal(new string('a', 64), server.Hashes["chronos.server.exe"]);
Assert.Empty(LegacyProducts.Retained(manifest, null));
// Without an installation of its own (only a log), nothing is retained.
Assert.Empty(InstallPlan.Resolve(manifest, new SetupArguments(), null, log, null).Retained);
}
[Test]
public void TheInstallLogRecordsEachComponentAndStillReadsA10Log()
{
var log = new InstallLog
{
FormatVersion = InstallLog.CurrentFormat,
Product = "Chronos",
Version = "1.1.0",
Components = ["Chronos", "Server"],
Files = ["Chronos.exe", "Chronos.Server.exe"],
ComponentFiles = { ["Chronos"] = ["Chronos.exe"], ["Server"] = ["Chronos.Server.exe"] },
ComponentShortcuts = { ["Chronos"] = [@"C:\Links\Chronos.lnk"], ["Server"] = [] },
ComponentVersions = { ["Chronos"] = "1.1.0", ["Server"] = "1.0.0" },
Hashes = { ["Chronos.exe"] = new string('b', 64) },
};
var read = Assert.NotNull(InstallLog.FromJson(log.ToJson()));
Assert.Equal(2, read.FormatVersion);
Assert.True(read.HasComponentFiles);
Assert.SequenceEqual(["Chronos.Server.exe"], read.FilesOf("server")!);
Assert.SequenceEqual([@"C:\Links\Chronos.lnk"], read.ShortcutsOf("Chronos")!);
Assert.Equal("1.0.0", read.VersionOf("Server"));
Assert.Equal(new string('b', 64), read.HashOf("CHRONOS.EXE"));
Assert.Empty(read.FilesOf("Uploader")!);
// As Chronos 1.0 wrote it: no format, no record of which component installed what.
var old = Assert.NotNull(InstallLog.FromJson("""
{"product":"Chronos","version":"1.0.0","scope":"CurrentUser","components":["Chronos","Server"],
"files":["Chronos.exe","Chronos.Server.exe"],"shortcuts":[],"associations":[]}
"""u8));
Assert.Equal(1, old.FormatVersion);
Assert.False(old.HasComponentFiles);
Assert.Null(old.FilesOf("Server"));
Assert.Equal("1.0.0", old.VersionOf("Server"));
Assert.Null(old.HashOf("Chronos.exe"));
}
[Test]
public void AFileChangedSinceSetupInstalledItIsNeverDeleted()
{
var directory = context.CreateTempDirectory("changed");
var same = Encoding.UTF8.GetBytes("as installed");
File.WriteAllBytes(Path.Combine(directory, "same.exe"), same);
File.WriteAllText(Path.Combine(directory, "edited.exe"), "changed since");
File.WriteAllText(Path.Combine(directory, "unknown.exe"), "a 1.0 log has no hash");
var hash = Convert.ToHexStringLower(SHA256.HashData(same));
var log = new InstallLog
{
FormatVersion = InstallLog.CurrentFormat,
Product = "Chronos",
Version = "1.1.0",
Hashes = { ["same.exe"] = hash, ["edited.exe"] = hash, ["gone.exe"] = hash },
};
// Only the edited file is kept; a missing file or one without a recorded hash is removed as before.
Assert.SequenceEqual(["edited.exe"], InstallEngine.Changed(directory, log, ["same.exe", "edited.exe", "unknown.exe", "gone.exe"]));
}
[Test]
public void ALegacyUploaderPreselectsTheUploaderAndFixesTheScope()
{
var manifest = Manifest();
var root = context.CreateTempDirectory("legacy");
var legacy = Legacy(Path.Combine(root, "Chronos Uploader"), InstallScope.CurrentUser);
// Its removal needs the same account, so the scope is the legacy copy's whatever the switches say.
var plan = InstallPlan.Resolve(manifest, new SetupArguments { AllUsers = true, Directory = Path.Combine(root, "Elsewhere") }, null, null, legacy);
Assert.Equal(InstallScope.CurrentUser, plan.Scope);
Assert.Equal(SetupPaths.DefaultDirectory(InstallScope.CurrentUser, manifest.Product), plan.Directory);
Assert.SequenceEqual(["Uploader"], plan.Components);
Assert.False(plan.CanChangeLocation);
Assert.Same(legacy, plan.LegacyToReplace(plan.Components, plan.Scope, plan.Directory));
Assert.Null(plan.LegacyToReplace(["Chronos"], plan.Scope, plan.Directory));
// An all-users copy stays under a per-user installation (its removal needs administrator approval), and a
// copy is never replaced by an installation in its own folder.
var allUsers = Legacy(Path.Combine(root, "Program Files", "Chronos Uploader"), InstallScope.AllUsers);
Assert.False(LegacyProducts.CanMerge(allUsers, InstallScope.CurrentUser, Path.Combine(root, "Chronos")));
Assert.True(LegacyProducts.CanMerge(allUsers, InstallScope.AllUsers, Path.Combine(root, "Program Files", "Chronos")));
Assert.False(LegacyProducts.CanMerge(legacy, InstallScope.CurrentUser, legacy.Directory));
Assert.False(LegacyProducts.CanMerge(legacy, InstallScope.CurrentUser, Path.Combine(legacy.Directory, "Chronos")));
// Another product's setup leaves the 1.0 Uploader alone.
Assert.Null(LegacyProducts.FindUploader(Manifest("ChronosTest" + Guid.NewGuid().ToString("N")[..12])));
}
[Test]
public void ALegacyUploaderLeftInPlaceFixesNeitherTheScopeNorTheFolder()
{
var manifest = Manifest();
var root = context.CreateTempDirectory("legacy-kept");
var legacy = Legacy(Path.Combine(root, "Chronos Uploader"), InstallScope.CurrentUser);
var elsewhere = Path.Combine(root, "Apps", "Chronos");
// The Uploader is not installed, so nothing is merged: the switches decide where Chronos goes.
var plan = InstallPlan.Resolve(manifest, new SetupArguments { AllUsers = true, Directory = elsewhere, Components = ["Desktop"] }, null, null, legacy);
Assert.Equal(InstallScope.AllUsers, plan.Scope);
Assert.Equal(elsewhere, plan.Directory);
Assert.SequenceEqual(["Chronos"], plan.Components);
Assert.True(plan.CanChangeLocation);
Assert.Null(plan.LegacyToReplace(plan.Components, plan.Scope, plan.Directory));
Assert.True(plan.LocksLocation(["Chronos", "Uploader"]), "ticking the Uploader would replace the legacy one");
}
[Test]
[WindowsOnly]
public void ReplacingTheLegacyUploaderMovesItsSignInEntryAndKeepsItTurnedOff()
{
var root = context.CreateTempDirectory("merge");
var legacyDir = Path.Combine(root, "Chronos Uploader");
var directory = Path.Combine(root, "Chronos");
Directory.CreateDirectory(directory);
File.WriteAllBytes(Path.Combine(directory, "Chronos.Uploader.exe"), [0x4D, 0x5A]);
var programs = LegacyProducts.StartupPrograms(Manifest(), directory);
Assert.SequenceEqual(["Chronos Uploader"], programs.Keys);
var keyPath = ScratchRegistry.Create();
try
{
using var run = Registry.CurrentUser.CreateSubKey(keyPath + @"\Run", writable: true);
using var approval = Registry.CurrentUser.CreateSubKey(keyPath + @"\Approved", writable: true);
run.SetValue("Chronos Uploader", $"\"{Path.Combine(legacyDir, "Chronos.Uploader.exe")}\" --tray");
approval.SetValue("Chronos Uploader", TurnedOff, RegistryValueKind.Binary);
var dropped = CommandProgram.FullPaths(legacyDir, ["Chronos.Uploader.exe", "Uninstall Chronos Uploader.exe"]);
Assert.SequenceEqual(["Chronos Uploader"], SetupRegistry.MoveStartupEntries(run, approval, dropped, programs));
Assert.Equal($"\"{Path.Combine(directory, "Chronos.Uploader.exe")}\" --tray", run.GetValue("Chronos Uploader"));
Assert.SequenceEqual(["Chronos Uploader"], approval.GetValueNames());
}
finally
{
ScratchRegistry.Delete(keyPath);
}
}
[Test]
[WindowsOnly]
public void ReplacingTheLegacyUploaderRemovesItsEntryAndFolder()
{
var root = context.CreateTempDirectory("merge");
// A product name no machine has, so the entry written and removed is the test's own.
var product = "ChronosTest" + Guid.NewGuid().ToString("N")[..12];
var legacyDir = Path.Combine(root, product);
Directory.CreateDirectory(legacyDir);
File.WriteAllBytes(Path.Combine(legacyDir, "Chronos.Uploader.exe"), [0x4D, 0x5A]);
var log = new InstallLog { Product = product, Version = "1.0.0", Scope = InstallScope.CurrentUser, Components = ["Uploader"], Files = ["Chronos.Uploader.exe"] };
log.Save(legacyDir);
File.WriteAllBytes(Path.Combine(legacyDir, log.UninstallerName), [0x4D, 0x5A]);
var key = SetupPaths.ProductKey(product);
try
{
SetupRegistry.WriteUninstallEntry(InstallScope.CurrentUser, key, new UninstallEntry(product, "1.0.0", "Chronos", legacyDir,
Path.Combine(legacyDir, log.UninstallerName), Path.Combine(legacyDir, "Chronos.Uploader.exe"), 2, null));
Assert.NotNull(SetupRegistry.FindInstall(key));
var directory = Path.Combine(root, "Chronos");
Directory.CreateDirectory(directory);
LegacyProducts.Merge(new LegacyInstall(new InstalledProduct(legacyDir, log), InstallScope.CurrentUser), Manifest(), directory);
Assert.Null(SetupRegistry.FindInstall(key));
Assert.False(Directory.Exists(legacyDir), "the legacy folder is removed");
Assert.True(Directory.Exists(directory));
}
finally
{
SetupRegistry.DeleteUninstallEntry(InstallScope.CurrentUser, key);
}
}
[Test]
[WindowsOnly]
public void TheChangesLineIsTheDryRunPlanAndNothingTickedUninstalls()
{
var root = context.CreateTempDirectory("changes");
using var payload = PayloadReader.Open(WritePayload(root));
var manifest = payload.Manifest;
var directory = Path.Combine(root, "Installed");
var existing = new ExistingInstall(InstallScope.AllUsers, directory, "1.0.0");
var previous = ServerLog(directory);
previous.Components = ["Chronos", "Server"];
// Updating keeps the Server and adds nothing: nothing to say.
using (var update = SetupViewModel.ForInstall(new SetupArguments(), payload, InstallPlan.Resolve(manifest, new SetupArguments(), existing, previous, null)))
{
Assert.Equal("Update", update.InstallText);
Assert.False(update.HasChanges);
var server = Assert.Contains(update.Components, c => c.IsRetained);
Assert.Equal("Chronos Server 1.0.0", server.Name);
Assert.Equal("No longer offered", server.StateText);
Assert.Contains(update.Components, c => c.Id == "Uploader").IsSelected = true;
Assert.Equal("Adds Chronos Uploader", update.ChangesText);
server.IsSelected = false;
Assert.Equal("Adds Chronos Uploader · Removes Chronos Server 1.0.0", update.ChangesText);
Assert.True(update.Changes[1].IsRemoval);
Assert.Contains("Chronos.Server.exe", update.Changes[1].ToolTip);
// Every program unticked: the primary action removes the installation, and Cancel is the default.
foreach (var c in update.Components) c.IsSelected = false;
Assert.True(update.IsUninstallAll);
Assert.True(update.IsUninstallAllPrimary);
Assert.False(update.IsInstallPrimary);
Assert.True(update.IsCancelDefault);
Assert.False(update.HasChanges);
}
// A new installation beside the separate 1.0 Uploader replaces it, and says so.
var legacy = Legacy(Path.Combine(root, "Chronos Uploader"), InstallScope.CurrentUser);
using (var replace = SetupViewModel.ForInstall(new SetupArguments(), payload, InstallPlan.Resolve(manifest, new SetupArguments(), null, null, legacy)))
{
Assert.Equal("Install", replace.InstallText);
Assert.False(replace.CanChangeLocation);
Assert.Equal("Replaces Chronos Uploader 1.0.0", replace.ChangesText);
Assert.False(replace.IsUninstallAll);
// Unticked, the Uploader replaces nothing: the folder and the scope can change; ticked again, they are the legacy copy's.
var uploader = Assert.Contains(replace.Components, c => c.Id == "Uploader");
uploader.IsSelected = false;
Assert.True(replace.CanChangeLocation);
replace.IsAllUsers = true;
replace.Directory = Path.Combine(root, "Apps", "Chronos");
uploader.IsSelected = true;
Assert.False(replace.CanChangeLocation);
Assert.False(replace.IsAllUsers);
Assert.Equal(SetupPaths.DefaultDirectory(InstallScope.CurrentUser, manifest.Product), replace.Directory);
}
// Removing a program of a 1.0 installation (its log has no SHA-256) never promises to keep a changed file.
var hashed = ServerLog(directory);
hashed.FormatVersion = 2;
hashed.Components = ["Chronos", "Uploader"];
hashed.Hashes["Chronos.Uploader.exe"] = new string('2', 64);
foreach (var (log, key) in new[] { (hashed, "Tooltips.Setup.Changes.Remove"), (ServerLog(directory), "Tooltips.Setup.Changes.RemoveUnchecked") })
{
log.Components = ["Chronos", "Uploader"];
using var removal = SetupViewModel.ForInstall(new SetupArguments(), payload, InstallPlan.Resolve(manifest, new SetupArguments(), existing, log, null));
Assert.Contains(removal.Components, c => c.Id == "Uploader").IsSelected = false;
Assert.Count(1, removal.Changes);
Assert.Equal(Loc.L(key), removal.Changes[0].ToolTip);
}
// A new installation with nothing ticked cannot start, and is no uninstall.
using var fresh = SetupViewModel.ForInstall(new SetupArguments(), payload, InstallPlan.Resolve(manifest, new SetupArguments(), null, null, null));
Assert.Equal("Install", fresh.InstallText);
foreach (var c in fresh.Components) c.IsSelected = false;
Assert.False(fresh.IsUninstallAll);
Assert.False(fresh.PrimaryCommand.CanExecute(null));
}
/// <summary>The single setup's payload as pack-installer writes it, its programs one byte each.</summary>
private static PayloadManifest Manifest(string product = "Chronos") => new()
{
Product = product,
Version = "1.1.0",
Components =
[
new PayloadComponent { Id = "Chronos", DisplayName = "Chronos Desktop", DefaultSelected = true },
new PayloadComponent { Id = "Uploader", DisplayName = "Chronos Uploader" },
],
Files =
[
new PayloadFile { Path = "Chronos.exe", Component = "Chronos", Sha256 = new string('1', 64) },
new PayloadFile { Path = "Chronos.Uploader.exe", Component = "Uploader", Sha256 = new string('2', 64) },
],
Shortcuts =
[
new PayloadShortcut { Component = "Chronos", Name = "Chronos", Target = "Chronos.exe", StartMenu = true, Desktop = true },
new PayloadShortcut { Component = "Uploader", Name = "Chronos Uploader", Target = "Chronos.Uploader.exe", StartMenu = true, Desktop = true },
],
};
/// <summary>The log Chronos 1.0 wrote for the desktop app, the Uploader and the Server for Windows (format 1).</summary>
private static InstallLog ServerLog(string directory) => new()
{
Product = "Chronos",
Version = "1.0.0",
Scope = InstallScope.AllUsers,
Components = ["Chronos", "Uploader", "Server"],
Files = ["Chronos.exe", "Chronos.Uploader.exe", "Chronos.Server.exe", "legacy.txt"],
Shortcuts =
[
Path.Combine(directory, "Chronos.lnk"),
Path.Combine(directory, "Chronos Uploader.lnk"),
Path.Combine(directory, "Chronos Server.lnk"),
],
};
private static LegacyInstall Legacy(string directory, InstallScope scope) =>
new(new InstalledProduct(directory, new InstallLog
{
Product = LegacyProducts.UploaderProduct,
Version = "1.0.0",
Scope = scope,
Components = ["Uploader"],
Files = ["Chronos.Uploader.exe"],
}), scope);
/// <summary>Writes the single setup's payload (the two programs, the desktop app preselected) to a scratch installer.</summary>
private static string WritePayload(string root)
{
var stub = Path.Combine(root, "stub.exe");
var bytes = new byte[4096];
new Random(7).NextBytes(bytes);
"MZ"u8.CopyTo(bytes);
File.WriteAllBytes(stub, bytes);
foreach (var (id, program) in (ReadOnlySpan<(string, string)>)[("Chronos", "Chronos.exe"), ("Uploader", "Chronos.Uploader.exe")])
{
var folder = Directory.CreateDirectory(Path.Combine(root, "payload", id)).FullName;
File.WriteAllText(Path.Combine(folder, program), "MZ " + program);
}
var installer = Path.Combine(root, "setup.exe");
PayloadWriter.Write(stub, new PayloadSource
{
Product = "Chronos",
Version = "1.1.0",
Components =
[
new PayloadComponentSource("Chronos", "Chronos Desktop", true, Path.Combine(root, "payload", "Chronos")),
new PayloadComponentSource("Uploader", "Chronos Uploader", false, Path.Combine(root, "payload", "Uploader")),
],
Shortcuts =
[
new PayloadShortcut { Component = "Chronos", Name = "Chronos", Target = "Chronos.exe", StartMenu = true, Desktop = true },
new PayloadShortcut { Component = "Uploader", Name = "Chronos Uploader", Target = "Chronos.Uploader.exe", StartMenu = true, Desktop = true },
],
}, installer);
return installer;
}
}