Files
Chronos/tests/Chronos.App.Tests/Setup/SetupEngineTests.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

357 lines
21 KiB
C#

using System.Globalization;
using System.IO;
using Microsoft.Win32;
using Chronos.Core.Packaging;
using Chronos.Setup.Cli;
using Chronos.Setup.Engine;
using Chronos.Setup.Interop;
using Chronos.Testing;
namespace Chronos.App.Tests.Setup;
/// <summary>
/// What setup leaves behind and what it registers: services and startup entries of the programs it installed, never
/// of other programs in the same folder (SETUP-1, SETUP-2), shortcuts another product owns or takes over (SRS-09), the
/// Server's all-users scope inside Program Files (SRS-06) and the file type name in setup's language (SRS-04).
/// </summary>
public sealed class SetupEngineTests(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];
[Theory]
[Case(@"""C:\Program Files\Chronos\Chronos.Server.exe"" --service", @"C:\Program Files\Chronos\Chronos.Server.exe")]
[Case(@"C:\Program Files\Chronos\Chronos.Server.exe --service", @"C:\Program Files\Chronos\Chronos.Server.exe")]
[Case(@"""C:\Program Files\dotnet\dotnet.exe"" ""C:\Apps\Chronos\Chronos.Server.dll"" --service", @"C:\Apps\Chronos\Chronos.Server.dll")]
[Case(@"C:\Windows\system32\svchost.exe -k netsvcs", @"C:\Windows\system32\svchost.exe")]
[Case(@"Chronos.Uploader.exe --tray", null)]
[Case("", null)]
public void TheProgramOfACommandLineIsItsFirstFullPath(string commandLine, string? program) =>
Assert.Equal(program, CommandProgram.Of(commandLine));
[Test]
public void ServiceStepsTravelToTheElevatedCopyWithTheirServices()
{
var arguments = new SetupArguments
{
Services = ServiceActions.Prune | ServiceActions.Start,
ServiceNames = ["ChronosServer"],
Directory = @"C:\Program Files\Chronos",
Elevated = true,
};
var switches = arguments.ToSwitches().ToList();
Assert.Contains("/SERVICES=prune,start", switches);
Assert.Contains("/NAMES=ChronosServer", switches);
var parsed = SetupArguments.Parse(switches);
Assert.Equal(arguments.Services, parsed.Services);
Assert.Equal(arguments.Directory, parsed.Directory);
Assert.SequenceEqual(["ChronosServer"], parsed.ServiceNames!);
Assert.True(parsed.Elevated);
Assert.Equal(ServiceActions.Remove, SetupArguments.Parse(["/SERVICES=Remove", "/NAMES=ChronosServer", "/DIR=C:\\Apps\\Chronos"]).Services);
// The step acts only on services the unelevated setup named.
Assert.Throws<ArgumentException>(() => SetupArguments.Parse(["/SERVICES=stop", "/NAMES=ChronosServer"]));
Assert.Throws<ArgumentException>(() => SetupArguments.Parse(["/SERVICES=stop", "/DIR=C:\\Apps\\Chronos"]));
Assert.Throws<ArgumentException>(() => SetupArguments.Parse(["/SERVICES=kill", "/NAMES=ChronosServer", "/DIR=C:\\Apps\\Chronos"]));
Assert.Throws<ArgumentException>(() => SetupArguments.Parse(["/SERVICES=none", "/NAMES=ChronosServer", "/DIR=C:\\Apps\\Chronos"]));
}
[Test]
[WindowsOnly]
public void OnlyTheServicesOfProgramsSetupInstalledAreFound()
{
var folder = Path.Combine(context.CreateTempDirectory("services"), "Apps");
var owned = CommandProgram.FullPaths(folder, ["Chronos.Server.exe", "Chronos.exe", "lib/Chronos.Core.dll"]);
var keyPath = ScratchRegistry.Create();
try
{
using var services = Registry.CurrentUser.CreateSubKey(keyPath, writable: true);
Service(services, "ChronosServer", 0x10, $"\"{Path.Combine(folder, "Chronos.Server.exe")}\" --service");
Service(services, "ChronosServerUnquoted", 0x10, Path.Combine(folder, "CHRONOS.SERVER.EXE") + " --service");
// Another vendor's service, and a driver, that live in the same folder (a shared D:\Apps): never Chronos's.
Service(services, "OtherVendor", 0x10, $"\"{Path.Combine(folder, "Other", "Other.exe")}\"");
Service(services, "OtherBeside", 0x10, $"\"{Path.Combine(folder, "Helper.exe")}\" /run");
Service(services, "Driver", 0x1, Path.Combine(folder, "Chronos.Server.exe"));
using (var deleting = services.CreateSubKey("Deleting", writable: true))
{
deleting.SetValue("Type", 0x10, RegistryValueKind.DWord);
deleting.SetValue("DeleteFlag", 1, RegistryValueKind.DWord);
deleting.SetValue("ImagePath", Path.Combine(folder, "Chronos.Server.exe"), RegistryValueKind.ExpandString);
}
var found = InstalledServices.Find(services, owned);
Assert.SequenceEqual(["ChronosServer", "ChronosServerUnquoted"], found.Select(s => s.Name).Order(StringComparer.Ordinal));
Assert.True(found.All(s => s.Program.Equals(Path.Combine(folder, "Chronos.Server.exe"), StringComparison.OrdinalIgnoreCase)));
Assert.Empty(InstalledServices.Find(services, CommandProgram.FullPaths(folder, ["Chronos.exe"])));
}
finally
{
ScratchRegistry.Delete(keyPath);
}
static void Service(RegistryKey services, string name, int type, string imagePath)
{
using var key = services.CreateSubKey(name, writable: true);
key.SetValue("Type", type, RegistryValueKind.DWord);
key.SetValue("ImagePath", imagePath, RegistryValueKind.ExpandString);
}
}
[Test]
[WindowsOnly]
public void AServiceThatIsNotRegisteredNeedsNothing()
{
var folder = context.CreateTempDirectory("services");
// No service starts a program of a fresh folder, and nothing is asked of the Service Control Manager.
Assert.Empty(InstalledServices.Find(CommandProgram.FullPaths(folder, ["Chronos.Server.exe"])));
Assert.Equal(SetupExitCode.Success, InstalledServices.Apply([], ServiceActions.Remove));
var gone = new InstalledService("ChronosTest" + Guid.NewGuid().ToString("N"), "Chronos Server", Path.Combine(folder, "Chronos.Server.exe"));
Assert.False(InstalledServices.IsRunning(gone));
foreach (var action in (ServiceActions[])[ServiceActions.Stop, ServiceActions.Prune, ServiceActions.Start, ServiceActions.Remove])
Assert.False(InstalledServices.NeedsWork([gone], action), $"{action} of a service that does not exist");
// Applying to it skips it: a service deleted meanwhile is not a failure.
Assert.Equal(SetupExitCode.Success, InstalledServices.Apply([gone], ServiceActions.Remove | ServiceActions.Start));
}
[Test]
[WindowsOnly]
public void AServiceWhoseProgramIsGoneIsDeletedAndAnotherFoldersServiceStays()
{
// The Service Control Manager registers services for administrators only; CI runners have the rights.
if (!Elevation.IsElevated) TestContext.Skip("needs administrator rights");
var root = context.CreateTempDirectory("services");
var folder = Path.Combine(root, "Apps");
Directory.CreateDirectory(folder);
var ours = "ChronosTest" + Guid.NewGuid().ToString("N");
var other = "ChronosTest" + Guid.NewGuid().ToString("N");
try
{
// Two stopped services whose programs are gone: one in the install folder, one in a folder setup did not install.
ScratchServices.Create(ours, $"\"{Path.Combine(folder, "Chronos.Server.exe")}\" --service");
ScratchServices.Create(other, $"\"{Path.Combine(root, "Elsewhere", "Chronos.Server.exe")}\" --service");
var found = InstalledServices.Find(CommandProgram.FullPaths(folder, ["Chronos.Server.exe"]));
var service = Assert.Contains(found, s => s.Name == ours);
Assert.False(found.Any(s => s.Name == other), "a service of another folder is not this installation's");
Assert.False(InstalledServices.IsRunning(service));
Assert.True(InstalledServices.NeedsWork([service], ServiceActions.Prune), "a service whose program is gone is pruned");
Assert.False(InstalledServices.NeedsWork([service], ServiceActions.Start), "nothing to start: its program is gone");
Assert.Equal(SetupExitCode.Success, InstalledServices.Apply(found, ServiceActions.Prune));
Assert.False(ScratchServices.Exists(ours), "the pruned service is deleted");
Assert.True(ScratchServices.Exists(other), "the other folder's service stays");
Assert.Empty(InstalledServices.Find(CommandProgram.FullPaths(folder, ["Chronos.Server.exe"])));
}
finally
{
ScratchServices.DeleteQuietly(ours);
ScratchServices.DeleteQuietly(other);
}
}
[Test]
[WindowsOnly]
public void UninstallRemovesOnlyTheSignInEntriesOfTheProgramsItRemoves()
{
var folder = Path.Combine(context.CreateTempDirectory("startup"), "Apps");
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(folder, "Uploader", "Chronos.Uploader.exe")}\" --tray");
// A portable Chronos unpacked in a subfolder of the same folder: not a program this installation lists.
run.SetValue("Chronos", $"\"{Path.Combine(folder, "Portable", "Chronos.exe")}\" --minimized");
// Another program in the same folder, and a copy in a sibling folder.
run.SetValue("Other", $"\"{Path.Combine(folder, "Other.exe")}\" --background");
run.SetValue("Sibling", $"\"{folder} 2\\Chronos.Uploader.exe\"");
// Both Chronos entries were turned off in Task Manager.
approval.SetValue("Chronos Uploader", TurnedOff, RegistryValueKind.Binary);
approval.SetValue("Chronos", TurnedOff, RegistryValueKind.Binary);
var programs = CommandProgram.FullPaths(folder, ["Chronos.exe", "Uploader/Chronos.Uploader.exe", "Other.exe"]);
Assert.SequenceEqual(["Chronos Uploader"], SetupRegistry.DeleteStartupEntries(run, approval, programs));
Assert.SequenceEqual(["Chronos", "Other", "Sibling"], run.GetValueNames().Order(StringComparer.Ordinal));
Assert.SequenceEqual(["Chronos"], approval.GetValueNames());
}
}
finally
{
ScratchRegistry.Delete(keyPath);
}
}
[Test]
[WindowsOnly]
public void AnUpgradeMovesTheSignInEntryOfARenamedProgramAndRemovesThatOfADroppedOne()
{
var folder = Path.Combine(context.CreateTempDirectory("upgrade"), "Apps");
// This version ships the client as Chronos.exe (the previous one as Chronos.old.exe), and the user left out the Uploader.
var manifest = Manifest();
manifest.Components.Add(new PayloadComponent { Id = "Uploader", DisplayName = "Chronos Uploader", DefaultSelected = true });
manifest.Shortcuts.Add(new PayloadShortcut { Component = "Chronos", Name = "Chronos", Target = "Chronos.exe", StartMenu = true });
manifest.Shortcuts.Add(new PayloadShortcut { Component = "Uploader", Name = "Chronos Uploader", Target = "Chronos.Uploader.exe", StartMenu = true });
var programs = InstallEngine.StartupPrograms(manifest, folder, ["Chronos", "Server"]);
Assert.SequenceEqual(["Chronos"], programs.Keys);
Assert.Equal(Path.Combine(folder, "Chronos.exe"), programs["Chronos"]);
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", $"\"{Path.Combine(folder, "Chronos.old.exe")}\" --minimized");
run.SetValue("Chronos Uploader", $"\"{Path.Combine(folder, "Chronos.Uploader.exe")}\" --tray");
run.SetValue("Other", $"\"{Path.Combine(folder, "Other.exe")}\" --background");
approval.SetValue("Chronos", TurnedOff, RegistryValueKind.Binary);
approval.SetValue("Chronos Uploader", TurnedOff, RegistryValueKind.Binary);
var dropped = CommandProgram.FullPaths(folder, ["Chronos.old.exe", "Chronos.Uploader.exe", "Other.exe"]);
Assert.SequenceEqual(["Chronos", "Chronos Uploader"], SetupRegistry.MoveStartupEntries(run, approval, dropped, programs));
// The new client finds its entry with its option, still turned off; the Uploader no longer starts; other values stay.
Assert.Equal($"\"{Path.Combine(folder, "Chronos.exe")}\" --minimized", run.GetValue("Chronos"));
Assert.SequenceEqual(["Chronos", "Other"], run.GetValueNames().Order(StringComparer.Ordinal));
Assert.SequenceEqual(["Chronos"], approval.GetValueNames());
// An entry that starts another copy is not this upgrade's to move.
var other = $"\"{Path.Combine(folder + " 2", "Chronos.old.exe")}\" --minimized";
run.SetValue("Chronos", other);
Assert.Empty(SetupRegistry.MoveStartupEntries(run, approval, dropped, programs));
Assert.Equal(other, run.GetValue("Chronos"));
}
}
finally
{
ScratchRegistry.Delete(keyPath);
}
}
[Test]
[WindowsOnly]
public void AShortcutTellsWhichProgramItStarts()
{
var folder = context.CreateTempDirectory("links");
var target = Path.Combine(folder, "Product A", "Chronos.Uploader.exe");
Directory.CreateDirectory(Path.GetDirectoryName(target)!);
File.WriteAllBytes(target, [0x4D, 0x5A]);
var link = Path.Combine(folder, "Chronos Uploader.lnk");
ShellLink.Create(link, target, "Chronos Uploader");
// The shell may store the long form of a short (8.3) temporary path: the same file either way.
var stored = Assert.NotNull(ShellLink.TargetOf(link));
Assert.Equal(Path.GetFileName(target), Path.GetFileName(stored));
Assert.FileExists(stored);
var productA = Path.GetDirectoryName(stored)!;
Assert.True(CommandProgram.IsPathInside(stored, productA));
Assert.False(CommandProgram.IsPathInside(stored, Path.Combine(Path.GetDirectoryName(productA)!, "Product B")));
Assert.False(CommandProgram.IsPathInside(stored, productA + " 2"));
Assert.Null(ShellLink.TargetOf(Path.Combine(folder, "missing.lnk")));
var notALink = Path.Combine(folder, "not a link.lnk");
File.WriteAllText(notALink, "plain text");
Assert.Null(ShellLink.TargetOf(notALink));
}
[Test]
[WindowsOnly]
public void AnUninstalledProductHandsItsShortcutToTheProductThatKeepsTheProgram()
{
var root = context.CreateTempDirectory("handover");
foreach (var product in (string[])["Product A", "Product B"])
{
Directory.CreateDirectory(Path.Combine(root, product));
File.WriteAllBytes(Path.Combine(root, product, "Chronos.Uploader.exe"), [0x4D, 0x5A]);
}
// A uniquely named shortcut in the user's own Start menu, the only folder setup deletes shortcuts from.
var link = Path.Combine(SetupPaths.StartMenu(InstallScope.CurrentUser), "Chronos Test " + Guid.NewGuid().ToString("N") + ".lnk");
try
{
ShellLink.Create(link, Path.Combine(root, "Product A", "Chronos.Uploader.exe"), "Chronos Test");
// The folders as the shell stores them (the long form of a short temporary path).
var productA = Path.GetDirectoryName(Assert.NotNull(ShellLink.TargetOf(link)))!;
var productB = Path.Combine(Path.GetDirectoryName(productA)!, "Product B");
var logB = new InstallLog { Product = "Chronos Uploader", Version = "1.0.0", Scope = InstallScope.CurrentUser, Files = ["Chronos.Uploader.exe"], Shortcuts = [link] };
// Product B also has the program and lists the shortcut: uninstalling A points it at B's copy.
UninstallEngine.DeleteShortcut(link, InstallScope.CurrentUser, productA, [new OtherInstall(productB, logB)]);
var handed = Assert.NotNull(ShellLink.TargetOf(link));
Assert.Equal("Product B", Path.GetFileName(Path.GetDirectoryName(handed)));
// Uninstalling A again leaves B's shortcut alone; uninstalling B with nobody left deletes it.
UninstallEngine.DeleteShortcut(link, InstallScope.CurrentUser, productA, []);
Assert.FileExists(link);
UninstallEngine.DeleteShortcut(link, InstallScope.CurrentUser, productB, [new OtherInstall(productA, null)]);
Assert.FileMissing(link);
// A product that does not list the shortcut, or whose folder cannot be read now, takes nothing over.
ShellLink.Create(link, Path.Combine(productA, "Chronos.Uploader.exe"), "Chronos Test");
UninstallEngine.DeleteShortcut(link, InstallScope.CurrentUser, productA, [new OtherInstall(productB, new InstallLog { Product = "Chronos", Version = "1.0.0", Files = ["Chronos.Uploader.exe"] })]);
Assert.FileMissing(link);
}
finally
{
if (File.Exists(link)) File.Delete(link);
}
}
[Test]
[WindowsOnly]
public void TheServerMakesANewInstallationAnAllUsersOneInsideProgramFiles()
{
var manifest = Manifest();
var plan = InstallPlan.Resolve(manifest, new SetupArguments { Components = ["Chronos", "Server"] });
Assert.Equal(InstallScope.AllUsers, plan.Scope);
Assert.Equal(SetupPaths.DefaultDirectory(InstallScope.AllUsers, manifest.Product), plan.Directory);
Assert.True(InstallPlan.IsValidDirectory(manifest, plan.Scope, plan.Directory, plan.Components));
// A folder standard users can change (C:\Chronos, D:\Apps\Chronos) would let them replace what the service starts.
var programFiles = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
var custom = Path.Combine(Path.GetPathRoot(programFiles)!, "Chronos");
Assert.False(InstallPlan.IsValidDirectory(manifest, InstallScope.AllUsers, custom, ["Chronos", "Server"]));
Assert.True(InstallPlan.IsValidDirectory(manifest, InstallScope.AllUsers, custom, ["Chronos"]));
Assert.True(InstallPlan.IsValidDirectory(manifest, InstallScope.CurrentUser, custom, ["Chronos"]));
Assert.False(InstallPlan.IsValidDirectory(manifest, InstallScope.CurrentUser, Path.Combine(programFiles, "Chronos"), ["Server"]));
Assert.True(InstallPlan.IsValidDirectory(manifest, InstallScope.AllUsers, Path.Combine(programFiles, "Vendor", "Chronos"), ["Server"]));
Assert.False(SetupPaths.IsInsideProgramFiles(programFiles), "Program Files itself is shared by every program");
Assert.False(SetupPaths.IsInsideProgramFiles(programFiles + " Extra" + Path.DirectorySeparatorChar + "Chronos"));
var desktop = InstallPlan.Resolve(manifest, new SetupArguments { Components = ["Chronos"] });
Assert.Equal(InstallScope.CurrentUser, desktop.Scope);
Assert.True(desktop.CanInstall(manifest.FindComponent("Server")!));
// A per-user installation upgraded in place keeps its scope, so it cannot take the Server; nor can an
// all-users one in a folder outside Program Files.
var perUser = desktop with { Existing = new ExistingInstall(InstallScope.CurrentUser, desktop.Directory, "0.9.0") };
Assert.False(perUser.CanInstall(manifest.FindComponent("Server")!));
Assert.True(perUser.CanInstall(manifest.FindComponent("Chronos")!));
var elsewhere = desktop with { Existing = new ExistingInstall(InstallScope.AllUsers, custom, "0.9.0") };
Assert.False(elsewhere.CanInstall(manifest.FindComponent("Server")!));
var protectedFolder = desktop with { Existing = new ExistingInstall(InstallScope.AllUsers, Path.Combine(programFiles, "Chronos"), "0.9.0") };
Assert.True(protectedFolder.CanInstall(manifest.FindComponent("Server")!));
}
[Test]
public void TheProjectFileTypeIsNamedInSetupsLanguage()
{
var association = new PayloadAssociation { Component = "Chronos", Extension = ".chronos", ProgId = "Chronos.Project", Description = "Chronos project", Target = "Chronos.exe" };
Assert.Equal("Chronos project", InstallEngine.FileTypeName(association, CultureInfo.GetCultureInfo("en")));
Assert.Equal("Progetto Chronos", InstallEngine.FileTypeName(association, CultureInfo.GetCultureInfo("it")));
var unknown = new PayloadAssociation { Component = "Chronos", Extension = ".tlx", ProgId = "Chronos.Unknown", Description = "Something else", Target = "Chronos.exe" };
Assert.Equal("Something else", InstallEngine.FileTypeName(unknown, CultureInfo.GetCultureInfo("it")));
}
/// <summary>A manifest under a product name no machine has installed, so the registry holds no installation of it.</summary>
private static PayloadManifest Manifest() => new()
{
Product = "ChronosTest" + Guid.NewGuid().ToString("N")[..12],
Version = "1.0.0",
Components =
[
new PayloadComponent { Id = "Chronos", DisplayName = "Chronos", DefaultSelected = true },
new PayloadComponent { Id = "Server", DisplayName = "Chronos Server", AllUsersOnly = true },
],
};
}