Files
Chronos/tests/Titano.App.Tests/Setup/SetupEngineTests.cs
T
Claude 180bfc623a test(setup): prune a real stopped service whose program is gone, and leave another folder's
The service steps were only checked against in-memory records and registry copies. On an elevated runner the test
registers two throwaway demand-start services through the Service Control Manager, one starting a program of the
install folder and one of another folder, and checks that setup finds only the first, prunes it, and leaves the
second registered.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
2026-10-12 11:50:29 +00:00

316 lines
18 KiB
C#

using System.Globalization;
using System.IO;
using Microsoft.Win32;
using Titano.Core.Packaging;
using Titano.Setup.Cli;
using Titano.Setup.Engine;
using Titano.Setup.Interop;
using Titano.Testing;
namespace Titano.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)
{
private const string TestsKey = @"Software\Titano.Tests";
[Theory]
[Case(@"""C:\Program Files\Titano\Titano.Server.exe"" --service", @"C:\Program Files\Titano\Titano.Server.exe")]
[Case(@"C:\Program Files\Titano\Titano.Server.exe --service", @"C:\Program Files\Titano\Titano.Server.exe")]
[Case(@"""C:\Program Files\dotnet\dotnet.exe"" ""C:\Apps\Titano\Titano.Server.dll"" --service", @"C:\Apps\Titano\Titano.Server.dll")]
[Case(@"C:\Windows\system32\svchost.exe -k netsvcs", @"C:\Windows\system32\svchost.exe")]
[Case(@"Titano.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 = ["TitanoServer"],
Directory = @"C:\Program Files\Titano",
Elevated = true,
};
var switches = arguments.ToSwitches().ToList();
Assert.Contains("/SERVICES=prune,start", switches);
Assert.Contains("/NAMES=TitanoServer", switches);
var parsed = SetupArguments.Parse(switches);
Assert.Equal(arguments.Services, parsed.Services);
Assert.Equal(arguments.Directory, parsed.Directory);
Assert.SequenceEqual(["TitanoServer"], parsed.ServiceNames!);
Assert.True(parsed.Elevated);
Assert.Equal(ServiceActions.Remove, SetupArguments.Parse(["/SERVICES=Remove", "/NAMES=TitanoServer", "/DIR=C:\\Apps\\Titano"]).Services);
// The step acts only on services the unelevated setup named.
Assert.Throws<ArgumentException>(() => SetupArguments.Parse(["/SERVICES=stop", "/NAMES=TitanoServer"]));
Assert.Throws<ArgumentException>(() => SetupArguments.Parse(["/SERVICES=stop", "/DIR=C:\\Apps\\Titano"]));
Assert.Throws<ArgumentException>(() => SetupArguments.Parse(["/SERVICES=kill", "/NAMES=TitanoServer", "/DIR=C:\\Apps\\Titano"]));
Assert.Throws<ArgumentException>(() => SetupArguments.Parse(["/SERVICES=none", "/NAMES=TitanoServer", "/DIR=C:\\Apps\\Titano"]));
}
[Test]
[WindowsOnly]
public void OnlyTheServicesOfProgramsSetupInstalledAreFound()
{
var folder = Path.Combine(context.CreateTempDirectory("services"), "Apps");
var owned = CommandProgram.FullPaths(folder, ["Titano.Server.exe", "Titano.exe", "lib/Titano.Core.dll"]);
var keyPath = TestsKey + @"\" + Guid.NewGuid().ToString("N");
try
{
using var services = Registry.CurrentUser.CreateSubKey(keyPath, writable: true);
Service(services, "TitanoServer", 0x10, $"\"{Path.Combine(folder, "Titano.Server.exe")}\" --service");
Service(services, "TitanoServerUnquoted", 0x10, Path.Combine(folder, "TITANO.SERVER.EXE") + " --service");
// Another vendor's service, and a driver, that live in the same folder (a shared D:\Apps): never Titano'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, "Titano.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, "Titano.Server.exe"), RegistryValueKind.ExpandString);
}
var found = InstalledServices.Find(services, owned);
Assert.SequenceEqual(["TitanoServer", "TitanoServerUnquoted"], found.Select(s => s.Name).Order(StringComparer.Ordinal));
Assert.True(found.All(s => s.Program.Equals(Path.Combine(folder, "Titano.Server.exe"), StringComparison.OrdinalIgnoreCase)));
Assert.Empty(InstalledServices.Find(services, CommandProgram.FullPaths(folder, ["Titano.exe"])));
}
finally
{
DeleteTestKey(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, ["Titano.Server.exe"])));
Assert.Equal(SetupExitCode.Success, InstalledServices.Apply([], ServiceActions.Remove));
var gone = new InstalledService("TitanoTest" + Guid.NewGuid().ToString("N"), "Titano Server", Path.Combine(folder, "Titano.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 = "TitanoTest" + Guid.NewGuid().ToString("N");
var other = "TitanoTest" + 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, "Titano.Server.exe")}\" --service");
ScratchServices.Create(other, $"\"{Path.Combine(root, "Elsewhere", "Titano.Server.exe")}\" --service");
var found = InstalledServices.Find(CommandProgram.FullPaths(folder, ["Titano.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, ["Titano.Server.exe"])));
}
finally
{
ScratchServices.DeleteQuietly(ours);
ScratchServices.DeleteQuietly(other);
}
}
[Test]
[WindowsOnly]
public void UninstallRemovesOnlyTheSignInEntriesOfTheProgramsItRemoves()
{
var folder = Path.Combine(context.CreateTempDirectory("startup"), "Apps");
var keyPath = TestsKey + @"\" + Guid.NewGuid().ToString("N");
try
{
using (var run = Registry.CurrentUser.CreateSubKey(keyPath, writable: true))
{
run.SetValue("Titano Uploader", $"\"{Path.Combine(folder, "Uploader", "Titano.Uploader.exe")}\" --tray");
// A portable Titano unpacked in a subfolder of the same folder: not a program this installation lists.
run.SetValue("Titano", $"\"{Path.Combine(folder, "Portable", "Titano.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\\Titano.Uploader.exe\"");
var programs = CommandProgram.FullPaths(folder, ["Titano.exe", "Uploader/Titano.Uploader.exe", "Other.exe"]);
Assert.SequenceEqual(["Titano Uploader"], SetupRegistry.DeleteStartupEntries(run, programs));
Assert.SequenceEqual(["Other", "Sibling", "Titano"], run.GetValueNames().Order(StringComparer.Ordinal));
}
}
finally
{
DeleteTestKey(keyPath);
}
}
[Test]
[WindowsOnly]
public void AShortcutTellsWhichProgramItStarts()
{
var folder = context.CreateTempDirectory("links");
var target = Path.Combine(folder, "Product A", "Titano.Uploader.exe");
Directory.CreateDirectory(Path.GetDirectoryName(target)!);
File.WriteAllBytes(target, [0x4D, 0x5A]);
var link = Path.Combine(folder, "Titano Uploader.lnk");
ShellLink.Create(link, target, "Titano 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, "Titano.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), "Titano Test " + Guid.NewGuid().ToString("N") + ".lnk");
try
{
ShellLink.Create(link, Path.Combine(root, "Product A", "Titano.Uploader.exe"), "Titano 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 = "Titano Uploader", Version = "1.0.0", Scope = InstallScope.CurrentUser, Files = ["Titano.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, "Titano.Uploader.exe"), "Titano Test");
UninstallEngine.DeleteShortcut(link, InstallScope.CurrentUser, productA, [new OtherInstall(productB, new InstallLog { Product = "Titano", Version = "1.0.0", Files = ["Titano.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 = ["Titano", "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:\Titano, D:\Apps\Titano) would let them replace what the service starts.
var programFiles = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
var custom = Path.Combine(Path.GetPathRoot(programFiles)!, "Titano");
Assert.False(InstallPlan.IsValidDirectory(manifest, InstallScope.AllUsers, custom, ["Titano", "Server"]));
Assert.True(InstallPlan.IsValidDirectory(manifest, InstallScope.AllUsers, custom, ["Titano"]));
Assert.True(InstallPlan.IsValidDirectory(manifest, InstallScope.CurrentUser, custom, ["Titano"]));
Assert.False(InstallPlan.IsValidDirectory(manifest, InstallScope.CurrentUser, Path.Combine(programFiles, "Titano"), ["Server"]));
Assert.True(InstallPlan.IsValidDirectory(manifest, InstallScope.AllUsers, Path.Combine(programFiles, "Vendor", "Titano"), ["Server"]));
Assert.False(SetupPaths.IsInsideProgramFiles(programFiles), "Program Files itself is shared by every program");
Assert.False(SetupPaths.IsInsideProgramFiles(programFiles + " Extra" + Path.DirectorySeparatorChar + "Titano"));
var desktop = InstallPlan.Resolve(manifest, new SetupArguments { Components = ["Titano"] });
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("Titano")!));
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, "Titano"), "0.9.0") };
Assert.True(protectedFolder.CanInstall(manifest.FindComponent("Server")!));
}
[Test]
public void TheProjectFileTypeIsNamedInSetupsLanguage()
{
var association = new PayloadAssociation { Component = "Titano", Extension = ".titano", ProgId = "Titano.Project", Description = "Titano project", Target = "Titano.exe" };
Assert.Equal("Titano project", InstallEngine.FileTypeName(association, CultureInfo.GetCultureInfo("en")));
Assert.Equal("Progetto Titano", InstallEngine.FileTypeName(association, CultureInfo.GetCultureInfo("it")));
var unknown = new PayloadAssociation { Component = "Titano", Extension = ".tlx", ProgId = "Titano.Unknown", Description = "Something else", Target = "Titano.exe" };
Assert.Equal("Something else", InstallEngine.FileTypeName(unknown, CultureInfo.GetCultureInfo("it")));
}
/// <summary>Deletes a scratch key under <see cref="TestsKey"/>, and that key too once it is empty.</summary>
private static void DeleteTestKey(string keyPath)
{
Registry.CurrentUser.DeleteSubKeyTree(keyPath, throwOnMissingSubKey: false);
bool empty;
using (var tests = Registry.CurrentUser.OpenSubKey(TestsKey)) empty = tests is { SubKeyCount: 0, ValueCount: 0 };
if (empty) Registry.CurrentUser.DeleteSubKey(TestsKey, throwOnMissingSubKey: false);
}
/// <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 = "TitanoTest" + Guid.NewGuid().ToString("N")[..12],
Version = "1.0.0",
Components =
[
new PayloadComponent { Id = "Titano", DisplayName = "Titano", DefaultSelected = true },
new PayloadComponent { Id = "Server", DisplayName = "Titano Server", AllUsersOnly = true },
],
};
}