refactor!: rename Titano to Chronos and move CI and releases to Gitea (#6)
CI / Build and test (push) Successful in 8m14s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 7s
Release / Build, test and publish (push) Successful in 13m19s
CI / PostgreSQL 16 integration (push) Successful in 4m49s
CI / PostgreSQL 17 integration (push) Successful in 5m28s
CI / Docker image (push) Successful in 53s
Release / Server image (push) Failing after 10s
CI / Build and test (push) Successful in 8m14s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 7s
Release / Build, test and publish (push) Successful in 13m19s
CI / PostgreSQL 16 integration (push) Successful in 4m49s
CI / PostgreSQL 17 integration (push) Successful in 5m28s
CI / Docker image (push) Successful in 53s
Release / Server image (push) Failing after 10s
The owner renamed the product and moved the repository to the self-hosted Gitea (https://gitea.encke-hake.ts.net/BalboSoft/Chronos) for more control, and asked for Actions and a first automatic release with the server package and the Windows exe (docs/requests/2026-10-23-chronos-gitea.md). - Chronos everywhere: a byte-exact rename of contents and paths, then a per-language review of the forms the old name's ending had dictated. - Gitea instead of GitHub: the update check, licence, issue and support links read ChronosReleasesUrl; the update check takes the highest stable version, offers a pre-release build its final release and reports a repository it cannot see as a failed check. EULA, security policy and Gitea issue forms live at the repository root. - Gitea Actions for the Linux act_runner (.gitea/workflows): CI, release, nightly image and performance gates in the .NET SDK container with git checkout and the system SQLite. The release cross-compiles the Windows programs, checks their icon, version and DPI manifest, packs installers and zips, publishes the Gitea release and pushes the server image (REGISTRY_TOKEN). Windows-only tests run in an opt-in job on a Windows runner (WINDOWS_RUNNER). - New Chronos.Tools commands: zip, gitea-release, postgres-ci (replaces the docker-exec script, which Gitea's service containers do not allow; the throw-away server runs without durability) and pe-check. - Timed tests take their budget from TestTiming (CHRONOS_TEST_TIME_FACTOR, 3 on the shared runner; the weekly performance gates keep theirs). BREAKING CHANGE: programs, settings, data folders, file types, environment variables and the Docker image use the new name; nothing is migrated from Titano, which never had a release. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #6.
This commit is contained in:
1 parent
c99842cc86
commit
f2b58522b9
1801 files changed
+11804
-10676
No files matched your search
@@ -0,0 +1,90 @@
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Chronos.App.Tests.Setup;
|
||||
|
||||
/// <summary>
|
||||
/// Throwaway Windows services for the tests of setup's service steps: stopped, started on demand only, never running.
|
||||
/// Creating and deleting them needs administrator rights.
|
||||
/// </summary>
|
||||
internal static partial class ScratchServices
|
||||
{
|
||||
private const uint ScManagerConnect = 0x1;
|
||||
private const uint ScManagerCreateService = 0x2;
|
||||
private const uint ServiceAllAccess = 0xF01FF;
|
||||
private const uint Delete = 0x10000;
|
||||
private const uint ServiceWin32OwnProcess = 0x10;
|
||||
private const uint ServiceDemandStart = 0x3;
|
||||
private const uint ServiceErrorNormal = 0x1;
|
||||
|
||||
/// <summary>Registers <paramref name="name"/> to start <paramref name="commandLine"/>; throws when Windows refuses.</summary>
|
||||
public static void Create(string name, string commandLine)
|
||||
{
|
||||
var manager = OpenSCManagerW(null, null, ScManagerConnect | ScManagerCreateService);
|
||||
if (manager == 0) throw new InvalidOperationException($"Service Control Manager not opened (error {Marshal.GetLastPInvokeError()})");
|
||||
try
|
||||
{
|
||||
var service = CreateServiceW(manager, name, name, ServiceAllAccess, ServiceWin32OwnProcess, ServiceDemandStart, ServiceErrorNormal,
|
||||
commandLine, null, 0, null, null, null);
|
||||
if (service == 0) throw new InvalidOperationException($"Service {name} not created (error {Marshal.GetLastPInvokeError()})");
|
||||
CloseServiceHandle(service);
|
||||
}
|
||||
finally
|
||||
{
|
||||
CloseServiceHandle(manager);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>True while <paramref name="name"/> is registered (marked for deletion or not).</summary>
|
||||
public static bool Exists(string name)
|
||||
{
|
||||
var manager = OpenSCManagerW(null, null, ScManagerConnect);
|
||||
if (manager == 0) return false;
|
||||
try
|
||||
{
|
||||
var service = OpenServiceW(manager, name, Delete);
|
||||
if (service == 0) return false;
|
||||
CloseServiceHandle(service);
|
||||
return true;
|
||||
}
|
||||
finally
|
||||
{
|
||||
CloseServiceHandle(manager);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Deletes <paramref name="name"/> when it is still registered; never throws (test clean-up).</summary>
|
||||
public static void DeleteQuietly(string name)
|
||||
{
|
||||
var manager = OpenSCManagerW(null, null, ScManagerConnect);
|
||||
if (manager == 0) return;
|
||||
try
|
||||
{
|
||||
var service = OpenServiceW(manager, name, Delete);
|
||||
if (service == 0) return;
|
||||
DeleteService(service);
|
||||
CloseServiceHandle(service);
|
||||
}
|
||||
finally
|
||||
{
|
||||
CloseServiceHandle(manager);
|
||||
}
|
||||
}
|
||||
|
||||
[LibraryImport("advapi32.dll", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)]
|
||||
private static partial nint OpenSCManagerW(string? machineName, string? databaseName, uint desiredAccess);
|
||||
|
||||
[LibraryImport("advapi32.dll", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)]
|
||||
private static partial nint CreateServiceW(nint manager, string serviceName, string displayName, uint desiredAccess, uint serviceType, uint startType,
|
||||
uint errorControl, string binaryPathName, string? loadOrderGroup, nint tagId, string? dependencies, string? serviceStartName, string? password);
|
||||
|
||||
[LibraryImport("advapi32.dll", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)]
|
||||
private static partial nint OpenServiceW(nint manager, string serviceName, uint desiredAccess);
|
||||
|
||||
[LibraryImport("advapi32.dll", SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static partial bool DeleteService(nint service);
|
||||
|
||||
[LibraryImport("advapi32.dll", SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static partial bool CloseServiceHandle(nint handle);
|
||||
}
|
||||
@@ -0,0 +1,367 @@
|
||||
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)
|
||||
{
|
||||
private const string TestsKey = @"Software\Chronos.Tests";
|
||||
|
||||
/// <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 = TestsKey + @"\" + Guid.NewGuid().ToString("N");
|
||||
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
|
||||
{
|
||||
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, ["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 = TestsKey + @"\" + Guid.NewGuid().ToString("N");
|
||||
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
|
||||
{
|
||||
DeleteTestKey(keyPath);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void AnUpgradeMovesTheSignInEntryOfARenamedProgramAndRemovesThatOfADroppedOne()
|
||||
{
|
||||
var folder = Path.Combine(context.CreateTempDirectory("upgrade"), "Apps");
|
||||
var keyPath = TestsKey + @"\" + Guid.NewGuid().ToString("N");
|
||||
// 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"]);
|
||||
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
|
||||
{
|
||||
DeleteTestKey(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>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 = "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 },
|
||||
],
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
using System.IO;
|
||||
using Chronos.Setup.Engine;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.App.Tests.Setup;
|
||||
|
||||
/// <summary>
|
||||
/// "Remove my data" covers only the programs being removed (SRS-05): the desktop app and the Uploader share
|
||||
/// %LOCALAPPDATA%\Chronos and its logs folder, and uninstalling one product never deletes what another still uses.
|
||||
/// </summary>
|
||||
public sealed class UserDataPlanTests(TestContext context)
|
||||
{
|
||||
[Test]
|
||||
public void TheDesktopAppsPlanLeavesTheUploadersFiles()
|
||||
{
|
||||
var folder = SampleFolder();
|
||||
var plan = UserDataPlan.Measure(folder, Owners(UserDataOwners.Chronos));
|
||||
|
||||
Assert.SequenceEqual(
|
||||
["backups", "cache", "chronos.db", "logs" + Path.DirectorySeparatorChar + "chronos-20261012.log", "settings.json"],
|
||||
plan.Entries.Select(e => e.Name).Order(StringComparer.Ordinal));
|
||||
Assert.Equal(4000L + 3000 + 300 + 20 + 100, plan.TotalBytes);
|
||||
|
||||
plan.Remove();
|
||||
Assert.SequenceEqual(
|
||||
["logs" + Path.DirectorySeparatorChar + "uploader-20261012.log", "uploader-queue.json", "uploader.json"],
|
||||
Directory.EnumerateFiles(folder, "*", SearchOption.AllDirectories).Select(f => Path.GetRelativePath(folder, f)).Order(StringComparer.Ordinal));
|
||||
Assert.False(Directory.Exists(Path.Combine(folder, "cache")));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TheUploadersPlanLeavesTheDesktopAppsFilesAndEmptiedFoldersGo()
|
||||
{
|
||||
var folder = SampleFolder();
|
||||
var plan = UserDataPlan.Measure(folder, Owners(UserDataOwners.Uploader));
|
||||
|
||||
Assert.SequenceEqual(
|
||||
["logs" + Path.DirectorySeparatorChar + "uploader-20261012.log", "uploader-queue.json", "uploader.json"],
|
||||
plan.Entries.Select(e => e.Name).Order(StringComparer.Ordinal));
|
||||
|
||||
plan.Remove();
|
||||
Assert.True(File.Exists(Path.Combine(folder, "chronos.db")));
|
||||
Assert.True(File.Exists(Path.Combine(folder, "logs", "chronos-20261012.log")));
|
||||
Assert.FileMissing(Path.Combine(folder, "uploader.json"));
|
||||
Assert.FileMissing(Path.Combine(folder, "logs", "uploader-20261012.log"));
|
||||
|
||||
// Once the desktop app's data goes too, nothing is left of the folder.
|
||||
UserDataPlan.Measure(folder, Owners(UserDataOwners.Chronos)).Remove();
|
||||
Assert.False(Directory.Exists(folder));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void BothProgramsDataIsTheWholeFolderAndNoOwnerIsAnEmptyPlan()
|
||||
{
|
||||
var folder = SampleFolder();
|
||||
var whole = UserDataPlan.Measure(folder, UserDataOwners.All);
|
||||
Assert.SequenceEqual(
|
||||
["backups", "cache", "chronos.db", "logs", "settings.json", "uploader-queue.json", "uploader.json"],
|
||||
whole.Entries.Select(e => e.Name).Order(StringComparer.Ordinal));
|
||||
Assert.Empty(UserDataPlan.Measure(folder, Owners()).Entries);
|
||||
|
||||
whole.Remove();
|
||||
Assert.False(Directory.Exists(folder));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AProductRemovesTheDataOfItsProgramsThatNoOtherInstalledProductHas()
|
||||
{
|
||||
string[] chronos = ["Chronos", "Uploader", "Server"];
|
||||
string[] uploader = ["Uploader"];
|
||||
|
||||
Assert.SequenceEqual(["Chronos", "Uploader"], UserDataOwners.Removable(chronos, []).Order(StringComparer.Ordinal));
|
||||
Assert.SequenceEqual(["Chronos"], UserDataOwners.Removable(chronos, [uploader]).Order(StringComparer.Ordinal));
|
||||
Assert.Empty(UserDataOwners.Removable(uploader, [chronos]));
|
||||
Assert.SequenceEqual(["Uploader"], UserDataOwners.Removable(uploader, [["chronos"]]));
|
||||
// Chronos Server keeps its data elsewhere: a Server-only product removes nothing here.
|
||||
Assert.Empty(UserDataOwners.Removable(["Server"], []));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AnInstallationThatCannotBeReadNowKeepsEveryProgramsData()
|
||||
{
|
||||
string[] chronos = ["Chronos", "Uploader", "Server"];
|
||||
var uploader = new InstallLog { Product = "Chronos Uploader", Version = "1.0.0", Components = ["Uploader"] };
|
||||
|
||||
Assert.SequenceEqual(["Chronos"], UserDataOwners.RemovableBeside(chronos, [new OtherInstall(@"D:\Chronos Uploader", uploader)]).Order(StringComparer.Ordinal));
|
||||
// Its drive is offline, its folder is gone or its log is damaged: it may still use the desktop app's index.
|
||||
Assert.Empty(UserDataOwners.RemovableBeside(chronos, [new OtherInstall(@"E:\Chronos Uploader", null)]));
|
||||
Assert.Empty(UserDataOwners.RemovableBeside(chronos, [new OtherInstall(null, null)]));
|
||||
}
|
||||
|
||||
private static HashSet<string> Owners(params string[] owners) => new(owners, StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
private string SampleFolder()
|
||||
{
|
||||
var folder = Path.Combine(context.CreateTempDirectory("userdata"), "Chronos");
|
||||
Write(folder, "chronos.db", 4000);
|
||||
Write(folder, "settings.json", 20);
|
||||
Write(folder, Path.Combine("cache", "proxies", "a.jpg"), 3000);
|
||||
Write(folder, Path.Combine("backups", "chronos-1.db"), 100);
|
||||
Write(folder, Path.Combine("logs", "chronos-20261012.log"), 300);
|
||||
Write(folder, Path.Combine("logs", "uploader-20261012.log"), 200);
|
||||
Write(folder, "uploader.json", 10);
|
||||
Write(folder, "uploader-queue.json", 50);
|
||||
return folder;
|
||||
}
|
||||
|
||||
private static void Write(string folder, string relative, int bytes)
|
||||
{
|
||||
var path = Path.Combine(folder, relative);
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||||
File.WriteAllBytes(path, new byte[bytes]);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user