using System.Diagnostics; using System.IO.Compression; using System.Text; using System.Text.RegularExpressions; using Febe.Desktop.Core; using Febe.Installer; using Febe.Tests.Desktop.Support; using Febe.Tests.Support; namespace Febe.Tests.Desktop; /// /// The installer of Windows (spec §12, question 6 of §16), written in house in src/Febe.Installer since 18 November /// 2026 instead of NSIS: the package (Febe.exe compressed after the program, with its SHA-256), the command line, and /// the installation and uninstallation against a fake Windows (registry and shortcuts) and real files in a temporary /// folder, on any system. Per user without administrator rights; an installation over another replaces the program /// and keeps the data; the uninstaller never touches the Data folder or the library. The real Windows, with the /// published installer, is in tests/Febe.Tests.Windows (InstallerTests). /// [TestClass] public sealed partial class InstallerTests { public TestContext TestContext { get; set; } = null!; [TestMethod] public void ThePackageCarriesFebeAfterTheProgramAndGivesItBackIdentical() { using var temp = new TempFolder("pacchetto"); var stub = WriteBytes(temp.Combine("Febe.Installer.exe"), Bytes(200_000, seed: 1, compressible: false)); var program = WriteBytes(temp.Combine("Febe.exe"), Bytes(3_000_000, seed: 2, compressible: true)); var setup = temp.Combine("Febe-Setup-1.2.3-ci.4.exe"); var written = Package.Write(stub, program, "1.2.3-ci.4", setup); var info = Package.Read(setup); Assert.IsNotNull(info); Assert.AreEqual(PackageKind.Installer, info.Kind); Assert.AreEqual("1.2.3-ci.4", info.Version); Assert.AreEqual(200_000L, info.StubLength); Assert.AreEqual(3_000_000L, info.ProgramLength); Assert.AreEqual(written.DataLength, info.DataLength); Assert.IsLessThan(3_000_000L, info.DataLength, "compressed"); CollectionAssert.AreEqual(File.ReadAllBytes(stub), File.ReadAllBytes(setup)[..200_000], "the program comes first, untouched: its single-file bundle still works"); Assert.IsFalse(File.Exists(setup + ".part")); var shares = new List(); Package.ExtractProgram(setup, info, temp.Combine("estratto.exe"), shares.Add); CollectionAssert.AreEqual(File.ReadAllBytes(program), File.ReadAllBytes(temp.Combine("estratto.exe"))); Assert.AreEqual(1.0, shares[^1], 1e-9); // The uninstaller: the same program, no Febe.exe, a footer of its own. Package.WriteUninstaller(setup, info, temp.Combine("Disinstalla Febe.exe")); var uninstaller = Package.Read(temp.Combine("Disinstalla Febe.exe")); Assert.IsNotNull(uninstaller); Assert.AreEqual(PackageKind.Uninstaller, uninstaller.Kind); Assert.AreEqual("1.2.3-ci.4", uninstaller.Version); Assert.AreEqual(200_000L + "1.2.3-ci.4".Length + Package.FooterLength, new FileInfo(temp.Combine("Disinstalla Febe.exe")).Length); CollectionAssert.AreEqual(File.ReadAllBytes(stub), File.ReadAllBytes(temp.Combine("Disinstalla Febe.exe"))[..200_000]); } [TestMethod] public void ADamagedPackageIsRefusedAndNeverInstalled() { using var temp = new TempFolder("pacchetto"); var stub = WriteBytes(temp.Combine("Febe.Installer.exe"), Bytes(50_000, seed: 3, compressible: false)); var program = WriteBytes(temp.Combine("Febe.exe"), Bytes(500_000, seed: 4, compressible: true)); var setup = temp.Combine("Febe-Setup.exe"); var info = Package.Write(stub, program, "0.0.1", setup); // Not a package at all: the bare program, or anything with bytes after the footer. Assert.IsNull(Package.Read(stub)); var longer = WriteBytes(temp.Combine("piu-lungo.exe"), [.. File.ReadAllBytes(setup), 0]); Assert.IsNull(Package.Read(longer)); // A byte of Febe.exe changed: the SHA-256 (or Brotli itself) says no. var bytes = File.ReadAllBytes(setup); bytes[info.ProgramStart + (info.DataLength / 2)] ^= 0x5A; var damaged = WriteBytes(temp.Combine("rovinato.exe"), bytes); var damagedInfo = Package.Read(damaged)!; var error = Assert.ThrowsExactly(() => Package.ExtractProgram(damaged, damagedInfo, temp.Combine("x.exe"))); Assert.AreEqual(Texts.Damaged, error.Message); // A footer that does not describe the file: an error, not a guess. bytes = File.ReadAllBytes(setup); bytes[bytes.Length - Package.FooterLength + 16] ^= 1; Assert.ThrowsExactly(() => Package.Read(WriteBytes(temp.Combine("piede.exe"), bytes))); // The tool never packs a package again, nor without a version of the build. Assert.ThrowsExactly(() => Package.Write(setup, program, "0.0.1", temp.Combine("doppio.exe"))); Assert.ThrowsExactly(() => Package.Write(stub, program, "1.0", temp.Combine("v.exe"))); Assert.IsFalse(File.Exists(temp.Combine("doppio.exe")) || File.Exists(temp.Combine("doppio.exe.part"))); } [TestMethod] public void TheCommandLineHasTheOptionsOfNsis() { var root = Root("Prove"); Assert.AreEqual(new CommandLine(), CommandLine.Parse([])); Assert.IsTrue(CommandLine.Parse(["/S"]).Silent); Assert.IsTrue(CommandLine.Parse(["/s"]).Silent); // /D= is the last and takes the rest of the line, spaces included, as with NSIS. var folder = Path.Combine(root, "Programmi personali", "Febe"); var line = CommandLine.Parse(["/S", "/D=" + Path.Combine(root, "Programmi"), "personali" + Path.DirectorySeparatorChar + "Febe"]); Assert.IsTrue(line.Silent); Assert.AreEqual(folder, line.InstallFolder); line = CommandLine.Parse(["/PROVA=" + root, $"/_?={folder}", "/ATTENDI=4242"]); Assert.AreEqual(root, line.TestRoot); Assert.AreEqual(folder, line.UninstallFolder); Assert.AreEqual(4242, line.WaitFor); CollectionAssert.AreEqual(new[] { "/PROVA=" + root }, line.PassOn().ToArray(), "the internal options are not passed on"); CollectionAssert.AreEqual(new[] { "/S" }, CommandLine.Parse(["/S"]).PassOn().ToArray()); Assert.ThrowsExactly(() => CommandLine.Parse(["/X"])); Assert.ThrowsExactly(() => CommandLine.Parse(["/D=relativa"])); Assert.ThrowsExactly(() => CommandLine.Parse(["/D="])); // /PROVA= at the root of a drive: refused here, with its message, not later as an unhandled crash (the name of // the folder is the registry key of the test, and a root has none). var driveRoot = Path.GetPathRoot(Path.GetTempPath())!; var refused = Assert.ThrowsExactly(() => CommandLine.Parse(["/S", "/PROVA=" + driveRoot])); StringAssert.Contains(refused.Message, "/PROVA="); Assert.ThrowsExactly(() => Locations.ForTest(driveRoot), "what Parse refuses is what ForTest would refuse"); // The build tool. Assert.AreEqual(ToolCommand.Pack, CommandLine.Parse(["--impacchetta", "a", "b", "1.0.0", "c"]).Tool); Assert.AreEqual(ToolCommand.Verify, CommandLine.Parse(["--verifica", "a", "b"]).Tool); Assert.AreEqual(ToolCommand.Zip, CommandLine.Parse(["--zip", "a.zip", "b"]).Tool); Assert.ThrowsExactly(() => CommandLine.Parse(["--impacchetta", "a"])); Assert.ThrowsExactly(() => CommandLine.Parse(["--altro"])); } [TestMethod] public void AnInstallationIsPerUserWithTheShortcutsAndTheEntryInAppsInstalled() { using var bed = new SetupBed("installa"); var setup = bed.Package("0.1.2", seed: 5); var ui = new ScriptedInterface { DesktopShortcut = true, StartFebe = true }; Assert.AreEqual(ExitCodes.Done, bed.Flow(ui).Install(setup, Package.Read(setup)!, new CommandLine())); var folder = bed.Locations.DefaultInstallFolder; Assert.AreEqual(Path.Combine(bed.Root, "AppData", "Programs", "Febe"), folder, "%LOCALAPPDATA%\\Programs\\Febe"); CollectionAssert.AreEqual(bed.Program(5), File.ReadAllBytes(Path.Combine(folder, "Febe.exe"))); Assert.AreEqual(PackageKind.Uninstaller, Package.Read(Path.Combine(folder, "Disinstalla Febe.exe"))!.Kind); CollectionAssert.AreEquivalent(new[] { "Febe.exe", "Disinstalla Febe.exe" }, Directory.GetFiles(folder).Select(Path.GetFileName).ToArray(), "nothing else, no .nuovo left"); // The shortcuts: Start menu always, desktop as chosen; both to Febe.exe, from its folder, with its icon. Assert.HasCount(2, bed.System.Shortcuts); foreach (var (shortcut, path) in bed.System.Shortcuts.Zip([bed.Locations.StartMenuShortcut, bed.Locations.DesktopShortcut])) { Assert.AreEqual(path, shortcut.Path); Assert.AreEqual(Path.Combine(folder, "Febe.exe"), shortcut.Target); Assert.AreEqual(folder, shortcut.WorkingDirectory); Assert.AreEqual(Path.Combine(folder, "Febe.exe"), shortcut.IconPath); Assert.AreEqual(0, shortcut.IconIndex); Assert.AreEqual("Archivio personale di foto, video e storie da Instagram", shortcut.Description); } // Apps installed: under HKEY_CURRENT_USER only (the fake has nothing else to write to). var key = bed.Locations.UninstallKey; Assert.AreEqual(Locations.TestRegistryRoot(bed.Root) + @"Software\Microsoft\Windows\CurrentVersion\Uninstall\Febe", key); Assert.AreEqual("Febe", bed.System.String(key, "DisplayName")); Assert.AreEqual("0.1.2", bed.System.String(key, "DisplayVersion")); Assert.AreEqual("Alberto Balbo", bed.System.String(key, "Publisher")); Assert.AreEqual(Path.Combine(folder, "Febe.exe") + ",0", bed.System.String(key, "DisplayIcon")); Assert.AreEqual(folder, bed.System.String(key, "InstallLocation")); var uninstaller = $"\"{Path.Combine(folder, "Disinstalla Febe.exe")}\""; Assert.AreEqual($"{uninstaller} \"/PROVA={bed.Root}\"", bed.System.String(key, "UninstallString")); Assert.AreEqual($"{uninstaller} /S \"/PROVA={bed.Root}\"", bed.System.String(key, "QuietUninstallString")); Assert.AreEqual("https://gitea.encke-hake.ts.net/Alby96/Febe", bed.System.String(key, "URLInfoAbout")); Assert.AreEqual(1, bed.System.ReadUserDword(key, "NoModify")); Assert.AreEqual(1, bed.System.ReadUserDword(key, "NoRepair")); var size = new DirectoryInfo(folder).EnumerateFiles().Sum(f => f.Length) / 1024; Assert.AreEqual((int)size, bed.System.ReadUserDword(key, "EstimatedSize")); // WebView2 is there (in the fake): no question. Febe starts, from its folder. CollectionAssert.DoesNotContain(ui.Calls, "webview2"); Assert.HasCount(1, bed.System.Started); Assert.AreEqual(Path.Combine(folder, "Febe.exe"), bed.System.Started[0].Executable); Assert.AreEqual(folder, bed.System.Started[0].WorkingDirectory); CollectionAssert.AreEqual(new[] { "benvenuto", "avanzamento", "installato" }, ui.Calls); Assert.IsNull(ui.Version, "a fresh installation: nothing installed before"); } [TestMethod] public void WithoutTheDesktopShortcutAndInAnotherFolderOnlyTheStartMenuHasFebe() { using var bed = new SetupBed("cartella"); var setup = bed.Package("0.1.2", seed: 6); var folder = Path.Combine(bed.Root, "Altrove", "Febe"); var ui = new ScriptedInterface { DesktopShortcut = false }; Assert.AreEqual(ExitCodes.Done, bed.Flow(ui).Install(setup, Package.Read(setup)!, CommandLine.Parse(["/D=" + folder]))); Assert.IsTrue(File.Exists(Path.Combine(folder, "Febe.exe"))); Assert.IsFalse(Directory.Exists(bed.Locations.DefaultInstallFolder)); Assert.AreEqual(bed.Locations.StartMenuShortcut, bed.System.Shortcuts.Single().Path); Assert.AreEqual(folder, ui.Folder); Assert.IsEmpty(bed.System.Started, "«Apri Febe adesso» unchecked"); } [TestMethod] public void AnUpdateWithoutAFolderGoesWhereFebeIsAlreadyInstalled() { using var bed = new SetupBed("dove-era"); var folder = Path.Combine(bed.Root, "Altrove", "Febe"); var first = bed.Package("0.1.1", seed: 20); Assert.AreEqual(ExitCodes.Done, bed.Flow(new ScriptedInterface()).Install(first, Package.Read(first)!, CommandLine.Parse(["/D=" + folder]))); // With the dialogs: the first page names the folder where Febe is, and the update replaces that program. var second = bed.Package("0.2.0", seed: 21); var ui = new ScriptedInterface(); Assert.AreEqual(ExitCodes.Done, bed.Flow(ui).Install(second, Package.Read(second)!, new CommandLine())); Assert.AreEqual(folder, ui.Folder); Assert.AreEqual("0.1.1", ui.Version); CollectionAssert.AreEqual(bed.Program(21), File.ReadAllBytes(Path.Combine(folder, "Febe.exe"))); Assert.IsFalse(Directory.Exists(bed.Locations.DefaultInstallFolder), "no second Febe in the default folder"); Assert.AreEqual(folder, bed.System.String(bed.Locations.UninstallKey, "InstallLocation")); Assert.IsTrue(bed.System.Shortcuts.All(s => s.Target == Path.Combine(folder, "Febe.exe"))); // Silent too; and a Febe open there is seen there. var third = bed.Package("0.3.0", seed: 22); using (new FileStream(Path.Combine(folder, "Febe.exe"), FileMode.Open, FileAccess.Read, FileShare.None)) { var errors = new StringWriter(); Assert.AreEqual(ExitCodes.Failed, bed.Flow(new SilentInterface(errors)).Install(third, Package.Read(third)!, CommandLine.Parse(["/S"]))); StringAssert.Contains(errors.ToString(), "Febe è aperto"); } Assert.AreEqual(ExitCodes.Done, bed.Flow(new SilentInterface(TextWriter.Null)).Install(third, Package.Read(third)!, CommandLine.Parse(["/S"]))); CollectionAssert.AreEqual(bed.Program(22), File.ReadAllBytes(Path.Combine(folder, "Febe.exe"))); Assert.IsFalse(Directory.Exists(bed.Locations.DefaultInstallFolder)); // /D= still decides when given; an entry whose folder is not a full path counts as none. var actions = new SetupActions(bed.System, bed.Locations); Assert.AreEqual(folder, actions.InstalledFolder()); bed.System.WriteUserString(bed.Locations.UninstallKey, "InstallLocation", "Programs\\Febe"); Assert.IsNull(actions.InstalledFolder()); bed.System.WriteUserString(bed.Locations.UninstallKey, "InstallLocation", folder + Path.DirectorySeparatorChar); Assert.AreEqual(folder, actions.InstalledFolder()); } [TestMethod] public void TheSizeInAppsInstalledCountsOnlyTheFilesOfTheInstaller() { using var bed = new SetupBed("dimensione"); var folder = Path.Combine(bed.Root, "Disco", "Febe"); // A folder with something else in it, and below it: never walked (a drive root would have folders nobody may read). Directory.CreateDirectory(Path.Combine(folder, "altro", "dentro")); File.WriteAllBytes(Path.Combine(folder, "altro", "dentro", "grande.bin"), new byte[3 * 1024 * 1024]); File.WriteAllBytes(Path.Combine(folder, "accanto.bin"), new byte[1024 * 1024]); var setup = bed.Package("0.1.2", seed: 23); Assert.AreEqual(ExitCodes.Done, bed.Flow(new ScriptedInterface()).Install(setup, Package.Read(setup)!, CommandLine.Parse(["/D=" + folder]))); var ours = new FileInfo(Path.Combine(folder, "Febe.exe")).Length + new FileInfo(Path.Combine(folder, "Disinstalla Febe.exe")).Length; Assert.AreEqual((int)(ours / 1024), bed.System.ReadUserDword(bed.Locations.UninstallKey, "EstimatedSize")); } [TestMethod] public void AReadOnlyFebeIsNotAnOpenFebeAndIsReplacedAndRemoved() { using var bed = new SetupBed("sola-lettura"); var first = bed.Package("0.1.1", seed: 24); Assert.AreEqual(ExitCodes.Done, bed.Flow(new ScriptedInterface()).Install(first, Package.Read(first)!, new CommandLine())); var folder = bed.Locations.DefaultInstallFolder; var executable = Path.Combine(folder, "Febe.exe"); var uninstaller = Path.Combine(folder, "Disinstalla Febe.exe"); try { // Left read-only by a copy or a restore: Windows refuses to open it for writing, but nothing is running. File.SetAttributes(executable, File.GetAttributes(executable) | FileAttributes.ReadOnly); File.SetAttributes(uninstaller, File.GetAttributes(uninstaller) | FileAttributes.ReadOnly); Assert.IsFalse(SetupActions.IsFebeOpen(folder), "«Riprova» could never help: not «Febe è aperto»"); var second = bed.Package("0.2.0", seed: 25); var ui = new ScriptedInterface { Retries = new Queue([true, true, false]) }; Assert.AreEqual(ExitCodes.Done, bed.Flow(ui).Install(second, Package.Read(second)!, new CommandLine())); CollectionAssert.AreEqual(new[] { "benvenuto", "avanzamento", "installato" }, ui.Calls); CollectionAssert.AreEqual(bed.Program(25), File.ReadAllBytes(executable)); File.SetAttributes(executable, File.GetAttributes(executable) | FileAttributes.ReadOnly); File.SetAttributes(uninstaller, File.GetAttributes(uninstaller) | FileAttributes.ReadOnly); Assert.AreEqual(ExitCodes.Done, bed.Flow(new ScriptedInterface()).Uninstall(Path.Combine(bed.Locations.Temp, "copia.exe"), CommandLine.Parse(["/_?=" + folder]))); Assert.IsFalse(File.Exists(executable)); Assert.IsFalse(File.Exists(uninstaller)); } finally { foreach (var file in new[] { executable, uninstaller }) { if (File.Exists(file)) { File.SetAttributes(file, FileAttributes.Normal); } } } } [TestMethod] public void AnInstallationOverAnotherReplacesTheProgramAndKeepsTheData() { using var bed = new SetupBed("aggiorna"); var first = bed.Package("0.1.1", seed: 7); Assert.AreEqual(ExitCodes.Done, bed.Flow(new ScriptedInterface()).Install(first, Package.Read(first)!, new CommandLine())); // Febe has been used: data, a library, a Data folder moved elsewhere, start with the computer. var data = bed.FillData(); var folder = bed.Locations.DefaultInstallFolder; var second = bed.Package("0.2.0", seed: 8); var ui = new ScriptedInterface(); Assert.AreEqual(ExitCodes.Done, bed.Flow(ui).Install(second, Package.Read(second)!, new CommandLine())); Assert.AreEqual("0.1.1", ui.Version, "the first page says it is an update"); CollectionAssert.AreEqual(bed.Program(8), File.ReadAllBytes(Path.Combine(folder, "Febe.exe"))); Assert.AreEqual("0.2.0", Package.Read(Path.Combine(folder, "Disinstalla Febe.exe"))!.Version); Assert.AreEqual("0.2.0", bed.System.String(bed.Locations.UninstallKey, "DisplayVersion")); CollectionAssert.AreEquivalent(new[] { "Febe.exe", "Disinstalla Febe.exe" }, Directory.GetFiles(folder).Select(Path.GetFileName).ToArray()); data.AssertUntouched(); } [TestMethod] public void AnOpenFebeStopsTheInstallationUntilItIsClosed() { using var bed = new SetupBed("aperto"); var first = bed.Package("0.1.1", seed: 9); Assert.AreEqual(ExitCodes.Done, bed.Flow(new ScriptedInterface()).Install(first, Package.Read(first)!, new CommandLine())); var executable = Path.Combine(bed.Locations.DefaultInstallFolder, "Febe.exe"); var second = bed.Package("0.2.0", seed: 10); using (new FileStream(executable, FileMode.Open, FileAccess.Read, FileShare.None)) { Assert.IsTrue(SetupActions.IsFebeOpen(bed.Locations.DefaultInstallFolder)); // Silent: an error on the standard error, nothing replaced. var errors = new StringWriter(); Assert.AreEqual(ExitCodes.Failed, bed.Flow(new SilentInterface(errors)).Install(second, Package.Read(second)!, CommandLine.Parse(["/S"]))); StringAssert.Contains(errors.ToString(), "Febe è aperto"); // With dialogs: «Annulla» gives up. var ui = new ScriptedInterface { Retries = new Queue([false]) }; Assert.AreEqual(ExitCodes.Cancelled, bed.Flow(ui).Install(second, Package.Read(second)!, new CommandLine())); CollectionAssert.AreEqual(new[] { "benvenuto", "aperto" }, ui.Calls); } CollectionAssert.AreEqual(bed.Program(9), File.ReadAllBytes(executable)); Assert.AreEqual("0.1.1", bed.System.String(bed.Locations.UninstallKey, "DisplayVersion")); // Closed now: «Riprova» goes on. Assert.IsFalse(SetupActions.IsFebeOpen(bed.Locations.DefaultInstallFolder)); var retry = new ScriptedInterface(); Assert.AreEqual(ExitCodes.Done, bed.Flow(retry).Install(second, Package.Read(second)!, new CommandLine())); CollectionAssert.AreEqual(bed.Program(10), File.ReadAllBytes(executable)); } [TestMethod] public void TheUninstallerRemovesOnlyTheProgramItsShortcutsAndItsEntriesAndSaysWhereTheDataAre() { using var bed = new SetupBed("disinstalla"); var setup = bed.Package("0.1.2", seed: 11); Assert.AreEqual(ExitCodes.Done, bed.Flow(new ScriptedInterface()).Install(setup, Package.Read(setup)!, new CommandLine())); var folder = bed.Locations.DefaultInstallFolder; var data = bed.FillData(); // Something of Alberto's in the program folder, and the libraries Febe.exe extracted by itself. File.WriteAllText(Path.Combine(folder, "appunti.txt"), "miei"); Directory.CreateDirectory(Path.Combine(bed.Locations.ExtractionFolder, "abc")); File.WriteAllText(Path.Combine(bed.Locations.ExtractionFolder, "abc", "e_sqlite3.dll"), "x"); // Start with the computer: this Febe, this Febe with --dati, a portable Febe with --dati, something else. var run = bed.Locations.RunKey; var executable = Path.Combine(folder, "Febe.exe"); bed.System.WriteUserString(run, "Febe", Autostart.Command(executable)); bed.System.WriteUserString(run, "Febe-AbC", Autostart.Command(executable.ToUpperInvariant(), Path.Combine(bed.Root, "Secondo"))); bed.System.WriteUserString(run, "Febe-Portabile", Autostart.Command(Path.Combine(bed.Root, "Portabile", "Febe.exe"), Path.Combine(bed.Root, "Terzo"))); bed.System.WriteUserString(run, "Altro", Autostart.Command(executable)); var ui = new ScriptedInterface(); Assert.AreEqual(ExitCodes.Done, bed.Flow(ui).Uninstall(Path.Combine(bed.Locations.Temp, "copia.exe"), CommandLine.Parse(["/_?=" + folder]))); Assert.IsFalse(File.Exists(executable)); Assert.IsFalse(File.Exists(Path.Combine(folder, "Disinstalla Febe.exe"))); Assert.IsTrue(File.Exists(Path.Combine(folder, "appunti.txt")), "not ours: it stays, and so does the folder"); Assert.IsFalse(File.Exists(bed.Locations.StartMenuShortcut)); Assert.IsFalse(File.Exists(bed.Locations.DesktopShortcut)); Assert.IsFalse(Directory.Exists(bed.Locations.ExtractionFolder)); Assert.IsFalse(bed.System.HasKey(bed.Locations.UninstallKey)); CollectionAssert.AreEquivalent(new[] { "Febe-Portabile", "Altro" }, bed.System.UserValueNames(run).ToArray()); data.AssertUntouched(); // It asked nothing about the data and said where they are: the folder chosen in Impostazioni. CollectionAssert.AreEqual(new[] { "conferma", "disinstallato" }, ui.Calls); Assert.AreEqual((data.MovedDataFolder, bed.Locations.Library), ui.UninstalledWith); // A second time, with the program folder now empty: the folder goes too. Meanwhile a portable Febe with the // default Data folder took «Febe» for itself: it starts another Febe.exe, so it stays. File.Delete(Path.Combine(folder, "appunti.txt")); var portable = Autostart.Command(Path.Combine(bed.Root, "Portabile", "Febe.exe")); bed.System.WriteUserString(run, "Febe", portable); Assert.AreEqual(ExitCodes.Done, bed.Flow(new ScriptedInterface()).Uninstall(Path.Combine(bed.Locations.Temp, "copia.exe"), CommandLine.Parse(["/_?=" + folder]))); Assert.IsFalse(Directory.Exists(folder)); Assert.AreEqual(portable, bed.System.String(run, "Febe"), "«Febe» of another Febe.exe is not ours to remove"); } [TestMethod] public void TheUninstallerAsksAndAnOpenFebeOrANoStopsItBeforeAnything() { using var bed = new SetupBed("rifiuto"); var setup = bed.Package("0.1.2", seed: 12); Assert.AreEqual(ExitCodes.Done, bed.Flow(new ScriptedInterface()).Install(setup, Package.Read(setup)!, new CommandLine())); var folder = bed.Locations.DefaultInstallFolder; var line = CommandLine.Parse(["/_?=" + folder]); var no = new ScriptedInterface { Confirm = false }; Assert.AreEqual(ExitCodes.Cancelled, bed.Flow(no).Uninstall("copia.exe", line)); using (new FileStream(Path.Combine(folder, "Febe.exe"), FileMode.Open, FileAccess.Read, FileShare.None)) { Assert.AreEqual(ExitCodes.Cancelled, bed.Flow(new ScriptedInterface { Retries = new Queue([false]) }).Uninstall("copia.exe", line)); var errors = new StringWriter(); Assert.AreEqual(ExitCodes.Failed, bed.Flow(new SilentInterface(errors)).Uninstall("copia.exe", CommandLine.Parse(["/S", "/_?=" + folder]))); StringAssert.Contains(errors.ToString(), "La disinstallazione non è riuscita: Febe è aperto"); } Assert.IsTrue(File.Exists(Path.Combine(folder, "Febe.exe"))); Assert.IsTrue(File.Exists(bed.Locations.StartMenuShortcut)); Assert.IsTrue(bed.System.HasKey(bed.Locations.UninstallKey)); } [TestMethod] public void StartedFromTheProgramFolderTheUninstallerRunsACopyOfItselfFromTemp() { using var bed = new SetupBed("copia"); var setup = bed.Package("0.1.2", seed: 13); Assert.AreEqual(ExitCodes.Done, bed.Flow(new ScriptedInterface()).Install(setup, Package.Read(setup)!, new CommandLine())); var folder = bed.Locations.DefaultInstallFolder; var uninstaller = Path.Combine(folder, "Disinstalla Febe.exe"); // An old copy left by an earlier uninstallation goes; nothing else in %TEMP% does. Directory.CreateDirectory(bed.Locations.Temp); File.WriteAllText(Path.Combine(bed.Locations.Temp, "Febe-disinstalla-1.exe"), "vecchia"); File.WriteAllText(Path.Combine(bed.Locations.Temp, "altro.exe"), "non nostro"); SetupFlow.RemoveOldUninstallerCopies(bed.Locations, selfPath: uninstaller); Assert.IsFalse(File.Exists(Path.Combine(bed.Locations.Temp, "Febe-disinstalla-1.exe"))); Assert.IsTrue(File.Exists(Path.Combine(bed.Locations.Temp, "altro.exe"))); var ui = new ScriptedInterface(); Assert.AreEqual(ExitCodes.Done, bed.Flow(ui).Uninstall(uninstaller, CommandLine.Parse(["/S", "/PROVA=" + bed.Root]))); Assert.IsEmpty(ui.Calls, "the copy asks, not this one"); Assert.IsTrue(File.Exists(uninstaller), "nothing removed yet"); var (copy, arguments, workingDirectory) = bed.System.Started.Single(); Assert.AreEqual(Path.Combine(bed.Locations.Temp, $"Febe-disinstalla-{Environment.ProcessId}.exe"), copy); CollectionAssert.AreEqual(File.ReadAllBytes(uninstaller), File.ReadAllBytes(copy)); CollectionAssert.AreEqual(new[] { "/S", "/PROVA=" + bed.Root, "/_?=" + folder, $"/ATTENDI={Environment.ProcessId}" }, arguments.ToArray()); Assert.AreEqual(bed.Locations.Temp, workingDirectory); // The copy waits for the first one to end, then does the work. var copyLine = CommandLine.Parse(arguments.ToArray()); Assert.AreEqual(ExitCodes.Done, bed.Flow(new SilentInterface(TextWriter.Null)).Uninstall(copy, copyLine)); Assert.AreEqual(Environment.ProcessId, bed.System.WaitedFor.Single()); Assert.IsFalse(Directory.Exists(folder)); } [TestMethod] public void WebView2IsLookedForWhereMicrosoftPutsItAndItsPageOfferedWhenMissing() { using var bed = new SetupBed("webview2"); var actions = new SetupActions(bed.System, bed.Locations); const string Client = @"Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}"; bed.System.Machine.Clear(); Assert.IsNull(actions.WebView2Version()); bed.System.Machine[(@"SOFTWARE\WOW6432Node\" + Client, "pv")] = "0.0.0.0"; Assert.IsNull(actions.WebView2Version(), "0.0.0.0: removed"); bed.System.Machine[(@"SOFTWARE\" + Client, "pv")] = "131.0.2903.70"; Assert.AreEqual("131.0.2903.70", actions.WebView2Version()); bed.System.Machine.Clear(); bed.System.WriteUserString(@"Software\" + Client, "pv", "130.0.1.2"); Assert.AreEqual("130.0.1.2", actions.WebView2Version(), "installed for the user only; never under the test key"); bed.System.DeleteUserKeyTree(@"Software\" + Client); // Missing: the question, and the page of Microsoft only on «Apri la pagina»; never in silent mode. var setup = bed.Package("0.1.2", seed: 14); var yes = new ScriptedInterface { OpenWebView2Page = true }; Assert.AreEqual(ExitCodes.Done, bed.Flow(yes).Install(setup, Package.Read(setup)!, new CommandLine())); CollectionAssert.AreEqual(new[] { "benvenuto", "avanzamento", "webview2", "installato" }, yes.Calls); CollectionAssert.AreEqual(new[] { "https://developer.microsoft.com/microsoft-edge/webview2/" }, bed.System.Opened); Assert.AreEqual(ExitCodes.Done, bed.Flow(new SilentInterface(TextWriter.Null)).Install(setup, Package.Read(setup)!, CommandLine.Parse(["/S"]))); Assert.HasCount(1, bed.System.Opened); Assert.IsEmpty(bed.System.Started, "silent: Febe is not started"); Assert.IsTrue(File.Exists(bed.Locations.DesktopShortcut), "silent: the desktop shortcut, as the NSIS sections chosen by default"); } [TestMethod] public void TheKeysAreThoseFebeForWindowsWritesItself() { string[] desktop = [Autostart.RunKey, Autostart.ValueName]; string[] installer = [Product.RunKey, Product.AutostartValue]; CollectionAssert.AreEqual(desktop, installer); StringAssert.StartsWith(Autostart.ValueNameFor(Path.Combine(Root("x"), "Secondo")), Product.AutostartPrefix); StringAssert.StartsWith(Autostart.Command(@"C:\Febe\Febe.exe", @"D:\Dati"), "\"C:\\Febe\\Febe.exe\"", "the uninstaller recognizes the values by the quoted program"); var shell = File.ReadAllText(Repository.PathOf("src", "Febe.Desktop", "WindowsShell.cs")); StringAssert.Contains(shell, $"public const string Key = @\"{Product.FebeKey}\";"); StringAssert.Contains(shell, $"Read(\"{Product.DataFolderValue}\")"); } [TestMethod] public void TheToolWritesThePortableZipWithEachFileAtTheTop() { using var temp = new TempFolder("zip"); var program = WriteBytes(temp.Combine("Febe.exe"), Bytes(300_000, seed: 15, compressible: true)); File.WriteAllText(temp.Combine("LEGGIMI.txt"), "Febe portabile\r\n"); var zip = temp.Combine("Febe-0.1.2-portabile.zip"); Febe.Installer.Program.Zip(zip, [program, temp.Combine("LEGGIMI.txt")]); using var archive = ZipFile.OpenRead(zip); CollectionAssert.AreEqual(new[] { "Febe.exe", "LEGGIMI.txt" }, archive.Entries.Select(e => e.FullName).ToArray()); using var entry = archive.GetEntry("Febe.exe")!.Open(); using var copy = new MemoryStream(); entry.CopyTo(copy); CollectionAssert.AreEqual(File.ReadAllBytes(program), copy.ToArray()); Assert.IsFalse(File.Exists(zip + ".part")); } [TestMethod] public void TheBuildScriptIsValidBashUsesOnlyDotnetAndProducesTheTwoFilesUnder100Mb() { var script = Repository.PathOf("installer", "costruisci.sh"); var text = File.ReadAllText(script); StringAssert.Contains(text, "set -euo pipefail"); StringAssert.Contains(text, "-p:PublishSingleFile=true -p:IncludeNativeLibrariesForSelfExtract=true -p:EnableCompressionInSingleFile=true"); StringAssert.Contains(text, "dotnet publish src/Febe.Installer/Febe.Installer.csproj -c Release -r win-x64"); StringAssert.Contains(text, "pacchetto --impacchetta \"$installatore/Febe.Installer.exe\" \"$pubblicazione/Febe.exe\" \"$versione\" \"$setup\""); StringAssert.Contains(text, "pacchetto --verifica \"$setup\" \"$pubblicazione/Febe.exe\""); StringAssert.Contains(text, "pacchetto --zip \"$zip_portabile\""); StringAssert.Contains(text, "Febe-Setup-$versione.exe"); StringAssert.Contains(text, "Febe-$versione-portabile.zip"); StringAssert.Contains(text, "100 * 1024 * 1024"); Assert.DoesNotContain("\r\n", text, "Unix line ends: bash would choke on CR"); foreach (var program in new[] { "makensis", "python3", "command -v zip", "zip -q" }) { Assert.DoesNotContain(program, text, "only the .NET SDK"); } // The publication of the installer: self-contained, single file, trimmed, compressed; no package of others. var project = File.ReadAllText(Repository.PathOf("src", "Febe.Installer", "Febe.Installer.csproj")); foreach (var property in new[] { "true", "true", "true", "true", "app.manifest" }) { StringAssert.Contains(project, property); } Assert.DoesNotContain("PackageReference", project); var manifest = File.ReadAllText(Repository.PathOf("src", "Febe.Installer", "app.manifest")); StringAssert.Contains(manifest, "", "never administrator rights, even with «Setup» in the name"); StringAssert.Contains(manifest, "name=\"Microsoft.Windows.Common-Controls\" version=\"6.0.0.0\"", "the dialogs of Windows need the common controls 6"); var bash = FindBash(); if (bash is null) { Assert.Inconclusive("Manca bash (su Windows: Git Bash): la prova della sintassi di costruisci.sh si salta."); } using var process = Process.Start(new ProcessStartInfo(bash, ["-n", script]) { RedirectStandardError = true })!; var errors = process.StandardError.ReadToEnd(); process.WaitForExit(); Assert.AreEqual(0, process.ExitCode, errors); } [TestMethod] public void NsisIsGoneFromTheProgramTheBuildAndTheGuide() { var root = Repository.Root(); if (root is null) { Assert.Inconclusive("Il repository non è accanto alle prove."); } Assert.IsFalse(File.Exists(Path.Combine(root, "installer", "febe.nsi"))); var offending = new List(); var files = new[] { "src", "tools", "installer", "docker", ".gitea", Path.Combine("docs", "guida") } .Select(folder => Path.Combine(root, folder)) .Where(Directory.Exists) .SelectMany(folder => Directory.EnumerateFiles(folder, "*", SearchOption.AllDirectories)) .Concat(new[] { "CLAUDE.md", ".gitattributes", Path.Combine("docs", "windows.md"), Path.Combine("docs", "processo.md") }.Select(file => Path.Combine(root, file))) .Where(file => File.Exists(file) && !IsBuildOutput(root, file) && IsText(file)); foreach (var file in files) { var text = File.ReadAllText(file); if (string.Equals(Path.GetFileName(file), "CLAUDE.md", StringComparison.Ordinal)) { // Rule 12 is the copy of spec appendix A, which says with which stage NSIS left // (SpecificationConsistencyTests wants it there): only that line may name it, and only to say it is gone. text = string.Join('\n', text.Split('\n').Where(line => !(line.StartsWith("12. Niente componenti esterni", StringComparison.Ordinal) && line.Contains("Sono già usciti", StringComparison.Ordinal)))); } if (NsisWord().IsMatch(text)) { offending.Add(Path.GetRelativePath(root, file)); } } Assert.IsEmpty(offending, "NSIS is still named in: " + string.Join(", ", offending)); } private static bool IsBuildOutput(string root, string file) { var relative = Path.GetRelativePath(root, file).Replace('\\', '/'); return relative.Contains("/bin/", StringComparison.Ordinal) || relative.Contains("/obj/", StringComparison.Ordinal) || relative.Contains("/node_modules/", StringComparison.Ordinal); } private static bool IsText(string file) => Path.GetExtension(file).ToLowerInvariant() is ".cs" or ".csproj" or ".md" or ".sh" or ".yml" or ".yaml" or ".json" or ".xml" or ".js" or ".css" or ".html" or ".txt" or ".props" or ".manifest" or "" or ".gitattributes" or ".nsi"; private static string Root(string name) => Path.Combine(Path.GetTempPath(), name); private static byte[] Bytes(int length, int seed, bool compressible) { var random = new Random(seed); var bytes = new byte[length]; random.NextBytes(bytes); if (compressible) { // Long runs, as in an executable: Brotli has something to do. for (var i = 0; i < length; i += 4096) { bytes.AsSpan(i, Math.Min(2048, length - i)).Fill((byte)(i / 4096)); } } return bytes; } private static string WriteBytes(string path, byte[] bytes) { File.WriteAllBytes(path, bytes); return path; } /// /// A bash that checks the script on this system. Elsewhere than Windows, the first on PATH. On Windows Git Bash /// first (next to git on PATH, then where its installer puts it), else any bash on PATH except the WSL launcher: /// System32\bash.exe and the WindowsApps alias start a Linux distribution, which may be missing /// («execvpe(/bin/bash) failed») and does not see the script by its Windows path. /// private static string? FindBash() { if (!OperatingSystem.IsWindows()) { return OnPath("bash").FirstOrDefault(); } var roots = new List(); if (OnPath("git").FirstOrDefault() is { } git) { // git.exe sits in \cmd, \bin or \mingw64\bin. for (var folder = Path.GetDirectoryName(git); folder is not null && roots.Count < 3; folder = Path.GetDirectoryName(folder)) { roots.Add(folder); } } foreach (var variable in new[] { "ProgramW6432", "ProgramFiles", "ProgramFiles(x86)" }) { if (Environment.GetEnvironmentVariable(variable) is { Length: > 0 } programs) { roots.Add(Path.Combine(programs, "Git")); } } roots.Add(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Programs", "Git")); var gitBash = roots .SelectMany(root => new[] { Path.Combine(root, "bin", "bash.exe"), Path.Combine(root, "usr", "bin", "bash.exe") }) .FirstOrDefault(path => File.Exists(path) && !IsWslLauncher(path)); return gitBash ?? OnPath("bash").FirstOrDefault(path => !IsWslLauncher(path)); } private static bool IsWslLauncher(string path) { var full = Path.GetFullPath(path); var windows = Environment.GetFolderPath(Environment.SpecialFolder.Windows); return (windows.Length > 0 && full.StartsWith(Path.TrimEndingDirectorySeparator(windows) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)) || full.Contains(@"\Microsoft\WindowsApps\", StringComparison.OrdinalIgnoreCase); } /// Every file called on PATH, in order (on Windows only .exe: the others do not start). private static IEnumerable OnPath(string name) { var candidates = OperatingSystem.IsWindows() ? new[] { name + ".exe" } : new[] { name, name + ".exe" }; foreach (var folder in (Environment.GetEnvironmentVariable("PATH") ?? string.Empty).Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries)) { foreach (var candidate in candidates) { var path = Path.Combine(folder, candidate); if (File.Exists(path)) { yield return path; } } } } [GeneratedRegex(@"\b(?:nsis|makensis)\b|\.nsi\b", RegexOptions.IgnoreCase)] private static partial Regex NsisWord(); /// A test installation: a folder of its own (Locations.ForTest), a fake Windows, packages made on the spot. private sealed class SetupBed : IDisposable { private readonly TempFolder _temp; private readonly Dictionary _programs = []; public SetupBed(string name) { _temp = new TempFolder("installatore-" + name); Root = _temp.Path; Locations = Locations.ForTest(Root); System.Machine[(@"SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}", "pv")] = "131.0.2903.70"; } public string Root { get; } public Locations Locations { get; } public FakeSystem System { get; } = new(); public SetupFlow Flow(ISetupInterface ui) => new(System, Locations, ui); public byte[] Program(int seed) => _programs[seed]; /// A package of version with a Febe.exe of its own (by ). public string Package(string version, int seed) { var folder = Directory.CreateDirectory(Path.Combine(Root, "pacchetti", seed.ToString(global::System.Globalization.CultureInfo.InvariantCulture))).FullName; var stub = WriteBytes(Path.Combine(folder, "Febe.Installer.exe"), Bytes(20_000, seed: 1000 + seed, compressible: false)); _programs[seed] = Bytes(400_000 + seed, seed, compressible: true); var program = WriteBytes(Path.Combine(folder, "Febe.exe"), _programs[seed]); var setup = Path.Combine(folder, $"Febe-Setup-{version}.exe"); Febe.Installer.Package.Write(stub, program, version, setup); return setup; } /// Febe used for a while: a Data folder (moved by Impostazioni), the default one, a library. public UsedData FillData() { var moved = Path.Combine(Root, "DatiSpostati"); System.WriteUserString(Locations.FebeKey, "CartellaDati", moved); var files = new[] { Path.Combine(moved, "febe.sqlite"), Path.Combine(moved, "sessione", "sessione.json"), Path.Combine(Locations.DefaultDataFolder, "febe.sqlite"), Path.Combine(Locations.DefaultDataFolder, "browser", "Default", "Cookies"), Path.Combine(Locations.Library, "alberto", "2026-11-18_post.jpg"), }; foreach (var file in files) { Directory.CreateDirectory(Path.GetDirectoryName(file)!); File.WriteAllText(file, file); } return new UsedData(this, moved, files); } public void Dispose() => _temp.Dispose(); } private sealed record UsedData(SetupBed Bed, string MovedDataFolder, string[] Files) { public void AssertUntouched() { foreach (var file in Files) { Assert.IsTrue(File.Exists(file), file); Assert.AreEqual(file, File.ReadAllText(file)); } Assert.AreEqual(MovedDataFolder, Bed.System.String(Bed.Locations.FebeKey, "CartellaDati"), "Febe's key is not the installer's"); } } /// Windows for the tests: a registry of HKEY_CURRENT_USER in memory, HKLM read from a table, shortcuts as small files. private sealed class FakeSystem : ISystemAccess { private readonly Dictionary> _user = new(StringComparer.OrdinalIgnoreCase); public Dictionary<(string Key, string Name), string> Machine { get; } = []; public List Shortcuts { get; } = []; public List Opened { get; } = []; public List<(string Executable, IReadOnlyList Arguments, string WorkingDirectory)> Started { get; } = []; public List WaitedFor { get; } = []; public string? String(string key, string name) => ReadUserString(key, name); public bool HasKey(string key) => _user.Keys.Any(k => k.Equals(key, StringComparison.OrdinalIgnoreCase) || k.StartsWith(key + "\\", StringComparison.OrdinalIgnoreCase)); public string? ReadUserString(string key, string name) => _user.TryGetValue(key, out var values) && values.TryGetValue(name, out var value) ? value as string : null; public int? ReadUserDword(string key, string name) => _user.TryGetValue(key, out var values) && values.TryGetValue(name, out var value) && value is int number ? number : null; public void WriteUserString(string key, string name, string value) => Values(key)[name] = value; public void WriteUserDword(string key, string name, int value) => Values(key)[name] = value; public IReadOnlyList UserValueNames(string key) => _user.TryGetValue(key, out var values) ? [.. values.Keys] : []; public void DeleteUserValue(string key, string name) { if (_user.TryGetValue(key, out var values)) { values.Remove(name); } } public void DeleteUserKeyTree(string key) { foreach (var existing in _user.Keys.Where(k => k.Equals(key, StringComparison.OrdinalIgnoreCase) || k.StartsWith(key + "\\", StringComparison.OrdinalIgnoreCase)).ToList()) { _user.Remove(existing); } } public string? ReadMachineString(string key, string name) => Machine.GetValueOrDefault((key, name)); public void CreateShortcut(Shortcut shortcut) { Shortcuts.Add(shortcut); Directory.CreateDirectory(Path.GetDirectoryName(shortcut.Path)!); File.WriteAllText(shortcut.Path, shortcut.Target, Encoding.UTF8); } public void OpenAddress(string address) => Opened.Add(address); public void Start(string executable, IReadOnlyList arguments, string workingDirectory) => Started.Add((executable, arguments, workingDirectory)); public void WaitForExit(int processId, TimeSpan timeout) => WaitedFor.Add(processId); public void Pause(TimeSpan delay) { } private Dictionary Values(string key) { if (!_user.TryGetValue(key, out var values)) { values = new Dictionary(StringComparer.OrdinalIgnoreCase); _user[key] = values; } return values; } } /// The pages, answered as told; each records its name in . private sealed class ScriptedInterface : ISetupInterface { public bool DesktopShortcut { get; init; } = true; public bool StartFebe { get; init; } public bool OpenWebView2Page { get; init; } public bool Confirm { get; init; } = true; public Queue Retries { get; init; } = new([true]); public List Calls { get; } = []; public string? Version { get; private set; } public string? Folder { get; private set; } public (string DataFolder, string Library)? UninstalledWith { get; private set; } public bool? Welcome(string version, string? installedVersion, string installFolder) { Calls.Add("benvenuto"); Version = installedVersion; Folder = installFolder; return DesktopShortcut; } public bool RetryWhenFebeIsOpen(bool uninstalling) { Calls.Add("aperto"); return Retries.Count > 0 && Retries.Dequeue(); } public void RunWithProgress(string version, string installFolder, Action> work) { Calls.Add("avanzamento"); work(_ => { }); } public bool OfferWebView2Page() { Calls.Add("webview2"); return OpenWebView2Page; } public bool Installed() { Calls.Add("installato"); return StartFebe; } public bool ConfirmUninstall() { Calls.Add("conferma"); return Confirm; } public void Uninstalled(string dataFolder, string library) { Calls.Add("disinstallato"); UninstalledWith = (dataFolder, library); } public void Failed(bool uninstalling, string message) => Calls.Add("errore: " + message); } }