Files
Febe/tests/Febe.Tests.Windows/InstallerTests.cs
Alby96andClaude Opus 5.5 be662f2d28 Correzioni della revisione di C6: installatore, CI senza jq, caratteri e schermate senza Node
Le 14 osservazioni della revisione di funzione/senza-terzi, ciascuna con la prova che l'avrebbe trovata.

Installatore: un aggiornamento senza /D= va nella cartella già installata (InstallLocation)
invece che in quella predefinita, che lasciava la vecchia copia. Una cartella senza permessi
non sembra più «Febe aperto». La dimensione in «App installate» conta solo i due file
dell'installatore. I file in sola lettura si sostituiscono e si tolgono. «Febe» in Esegui
all'avvio si toglie solo se avvia quella copia, non un Febe portatile. Febe parte alla fine
solo con «Fine» e la casella spuntata. /PROVA= rifiuta la radice di un disco.

CI: jq non c'era ed era un componente esterno. JSON letto e scritto con .gitea/scripts/json.sh
(json-campi.awk e json-stringa.awk sul lettore json.awk) per gitleaks, Trivy e la release.
Le credenziali del registro stanno solo in un DOCKER_CONFIG temporaneo della pubblicazione,
con plugin, contesti e contesto corrente del runner, tolto alla fine. Le prove del rilascio
girano in debian:trixie con Chromium, come la verifica, senza prove saltate. Ogni flusso usa
shell: bash.

Caratteri: tolti fonts-liberation e fonts-noto-color-emoji dall'immagine e dalle prove della
CI, perché Chromium non li chiede. Resta fonts-dejavu-core.

Icone: la prova della griglia legge davvero i percorsi SVG (tutti i comandi, archi e curve) e
i punti. La lettura dei nomi delle icone vede ogni forma con cui l'interfaccia li chiede.

Schermate: tools/schermate (Node) diventa tools/Febe.Schermate, in C# con ClientWebSocket e
System.Text.Json, nessun pacchetto, solo verso indirizzi di questo computer. Provato contro
una dimostrazione con Edge su Windows.

Documenti: CLAUDE.md, processo, guida, LEGGIMI e docker.md aggiornati. Righe nuove in
decisioni.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 16:04:39 +01:00

349 lines
16 KiB
C#

using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
using Febe.Installer;
using Febe.Installer.Windows;
using Febe.Tests.Windows.Support;
using Microsoft.Win32;
namespace Febe.Tests.Windows;
/// <summary>
/// The installer on a real Windows: published for win-x64 as installer/costruisci.sh does it (self-contained, single
/// file, trimmed), packed with a stand-in Febe.exe, then installed in silent mode into a folder of the test
/// (<c>/PROVA=</c>: Start menu, desktop, %TEMP% and registry keys of the test, never those of an installed Febe),
/// installed again over itself, refused while Febe is open, and uninstalled with the command recorded in Apps
/// installed. The first page of the dialogs opens and «Annulla» closes it. Nothing here starts Febe.
/// </summary>
[TestClass]
public sealed class InstallerTests
{
private static string? s_publishedInstaller;
private static TestFolder? s_build;
public TestContext TestContext { get; set; } = null!;
[ClassInitialize]
public static void PublishTheInstaller(TestContext context)
{
var project = Path.Combine(RepositoryRoot(), "src", "Febe.Installer", "Febe.Installer.csproj");
s_build = new TestFolder("installatore-pubblicato");
var output = s_build.Combine("uscita");
var start = new ProcessStartInfo("dotnet")
{
RedirectStandardOutput = true,
RedirectStandardError = true,
};
foreach (var argument in new[] { "publish", project, "-c", "Release", "-r", "win-x64", "-p:Version=0.0.1", "-nologo", "-o", output, "--artifacts-path", s_build.Combine("artefatti") })
{
start.ArgumentList.Add(argument);
}
using var process = Process.Start(start)!;
var stdout = process.StandardOutput.ReadToEndAsync(context.CancellationToken);
var stderr = process.StandardError.ReadToEndAsync(context.CancellationToken);
process.WaitForExit();
Assert.AreEqual(0, process.ExitCode, $"dotnet publish:\n{stdout.Result}\n{stderr.Result}");
CollectionAssert.AreEqual(new[] { "Febe.Installer.exe" }, Directory.GetFiles(output).Select(Path.GetFileName).ToArray(), "a single file");
s_publishedInstaller = Path.Combine(output, "Febe.Installer.exe");
}
[ClassCleanup]
public static void RemoveTheBuild() => s_build?.Dispose();
[TestMethod]
[Timeout(300_000, CooperativeCancellation = true)]
public async Task InstalledSilentlyIntoATestFolderUpdatedRefusedWhileOpenAndUninstalled()
{
using var folder = new TestFolder("installazione");
var root = folder.Combine("utente");
Directory.CreateDirectory(root);
var locations = Locations.ForTest(root);
var registryRoot = Locations.TestRegistryRoot(root).TrimEnd('\\');
try
{
// The program and its version resource: not elevated (it would not even start here), version and names.
var first = Pack(folder, "0.0.1", seed: 1);
Assert.IsGreaterThan(1_000_000L, new FileInfo(s_publishedInstaller!).Length);
Assert.IsLessThan(20_000_000L, new FileInfo(s_publishedInstaller!).Length, "trimmed: a few MB beside Febe.exe");
var version = FileVersionInfo.GetVersionInfo(first.Setup);
Assert.AreEqual("Febe", version.ProductName);
Assert.AreEqual("Installazione di Febe", version.FileDescription);
Assert.AreEqual("Alberto Balbo", version.CompanyName);
StringAssert.StartsWith(version.ProductVersion, "0.0.1");
var bytes = await File.ReadAllBytesAsync(s_publishedInstaller!, TestContext.CancellationToken);
Assert.IsTrue(Contains(bytes, "asInvoker"u8), "the manifest is inside: no administrator rights");
Assert.IsTrue(Contains(bytes, "Microsoft.Windows.Common-Controls"u8), "the manifest asks for the common controls 6");
// Installation, silent, default folder of the test user.
Assert.AreEqual(0, await Run(first.Setup, ["/S", "/PROVA=" + root]));
var program = locations.DefaultInstallFolder;
CollectionAssert.AreEqual(first.Program, await File.ReadAllBytesAsync(Path.Combine(program, "Febe.exe"), TestContext.CancellationToken));
Assert.AreEqual(PackageKind.Uninstaller, Package.Read(Path.Combine(program, "Disinstalla Febe.exe"))!.Kind);
foreach (var shortcut in new[] { locations.StartMenuShortcut, locations.DesktopShortcut })
{
var (target, workingDirectory, description) = ShellLinks.Read(shortcut);
Assert.AreEqual(Path.Combine(program, "Febe.exe"), target, shortcut);
Assert.AreEqual(program, workingDirectory);
Assert.AreEqual("Archivio personale di foto, video e storie da Instagram", description);
}
using (var key = Registry.CurrentUser.OpenSubKey(locations.UninstallKey)!)
{
Assert.AreEqual("Febe", key.GetValue("DisplayName"));
Assert.AreEqual("0.0.1", key.GetValue("DisplayVersion"));
Assert.AreEqual("Alberto Balbo", key.GetValue("Publisher"));
Assert.AreEqual(program, key.GetValue("InstallLocation"));
Assert.AreEqual(1, key.GetValue("NoModify"));
Assert.AreEqual(RegistryValueKind.DWord, key.GetValueKind("EstimatedSize"));
}
// The data of Febe and «Start with the computer».
var data = Path.Combine(locations.DefaultDataFolder, "febe.sqlite");
Directory.CreateDirectory(locations.DefaultDataFolder);
await File.WriteAllTextAsync(data, "dati", TestContext.CancellationToken);
using (var run = Registry.CurrentUser.CreateSubKey(locations.RunKey))
{
run.SetValue("Febe", $"\"{Path.Combine(program, "Febe.exe")}\" --nascosto");
run.SetValue("Febe-Altro", "\"C:\\Altrove\\Febe.exe\" --nascosto --dati \"D:\\Altro\"");
}
// Again, a newer version over it: the program changes, the data stay.
var second = Pack(folder, "0.0.2", seed: 2);
Assert.AreEqual(0, await Run(second.Setup, ["/S", "/PROVA=" + root]));
CollectionAssert.AreEqual(second.Program, await File.ReadAllBytesAsync(Path.Combine(program, "Febe.exe"), TestContext.CancellationToken));
Assert.AreEqual("0.0.2", Registry.GetValue(@"HKEY_CURRENT_USER\" + locations.UninstallKey, "DisplayVersion", null));
Assert.AreEqual("dati", await File.ReadAllTextAsync(data, TestContext.CancellationToken));
// Febe open: the installer stops (exit 2), says why on the standard error, changes nothing.
using (new FileStream(Path.Combine(program, "Febe.exe"), FileMode.Open, FileAccess.Read, FileShare.Read))
{
var errors = new StringBuilder();
Assert.AreEqual(2, await Run(first.Setup, ["/S", "/PROVA=" + root], errors));
StringAssert.Contains(errors.ToString(), "Febe è aperto");
}
CollectionAssert.AreEqual(second.Program, await File.ReadAllBytesAsync(Path.Combine(program, "Febe.exe"), TestContext.CancellationToken));
// Uninstallation with the command Apps installed would use in silent mode: it hands over to a copy of
// itself in %TEMP% and ends; the copy does the work.
var quiet = (string)Registry.GetValue(@"HKEY_CURRENT_USER\" + locations.UninstallKey, "QuietUninstallString", null)!;
var (uninstaller, arguments) = Split(quiet);
Assert.AreEqual(Path.Combine(program, "Disinstalla Febe.exe"), uninstaller);
Assert.AreEqual(0, await Run(uninstaller, arguments));
await WaitUntil(() => !Directory.Exists(program) && Registry.CurrentUser.OpenSubKey(locations.UninstallKey) is null, TimeSpan.FromSeconds(60));
Assert.IsFalse(File.Exists(locations.StartMenuShortcut));
Assert.IsFalse(File.Exists(locations.DesktopShortcut));
Assert.AreEqual("dati", await File.ReadAllTextAsync(data, TestContext.CancellationToken), "never the Data folder");
using (var run = Registry.CurrentUser.OpenSubKey(locations.RunKey)!)
{
CollectionAssert.AreEqual(new[] { "Febe-Altro" }, run.GetValueNames(), "only the value of another Febe stays");
}
// The copy that did the work ends by itself; the next run of the installer removes it.
await WaitUntil(() => !Process.GetProcesses().Any(p => p.ProcessName.StartsWith("Febe-disinstalla-", StringComparison.Ordinal) && SafePath(p)?.StartsWith(root, StringComparison.OrdinalIgnoreCase) == true), TimeSpan.FromSeconds(30));
}
finally
{
Registry.CurrentUser.DeleteSubKeyTree(registryRoot, throwOnMissingSubKey: false);
DeleteEmptyTestKey();
}
}
[TestMethod]
[Timeout(120_000, CooperativeCancellation = true)]
public async Task TheFirstPageOpensAsADialogOfWindowsAndAnnullaInstallsNothing()
{
using var folder = new TestFolder("dialogo");
var root = folder.Combine("utente");
Directory.CreateDirectory(root);
var locations = Locations.ForTest(root);
try
{
var package = Pack(folder, "0.0.1", seed: 3);
using var process = Process.Start(new ProcessStartInfo(package.Setup, ["/PROVA=" + root]))!;
var window = IntPtr.Zero;
await WaitUntil(() => (window = VisibleWindowOf(process.Id)) != IntPtr.Zero, TimeSpan.FromSeconds(30));
Assert.AreEqual("Installazione di Febe", WindowTitle(window));
// Close: with «Annulla» allowed, it answers as «Annulla».
PostMessage(window, 0x0010, IntPtr.Zero, IntPtr.Zero);
Assert.IsTrue(process.WaitForExit(30_000));
Assert.AreEqual(1, process.ExitCode, "cancelled");
Assert.IsFalse(Directory.Exists(locations.DefaultInstallFolder));
Assert.IsNull(Registry.CurrentUser.OpenSubKey(locations.UninstallKey));
}
finally
{
Registry.CurrentUser.DeleteSubKeyTree(Locations.TestRegistryRoot(root).TrimEnd('\\'), throwOnMissingSubKey: false);
DeleteEmptyTestKey();
}
}
[TestMethod]
public void TheLastPageStartsFebeOnlyWithFine()
{
// Windows gives back the state of the box on a cancel too: Esc or the close button must not start Febe.
Assert.IsTrue(DialogInterface.StartsFebe(DialogInterface.Yes, runChecked: true));
Assert.IsFalse(DialogInterface.StartsFebe(DialogInterface.Yes, runChecked: false));
Assert.IsFalse(DialogInterface.StartsFebe(TaskDialog.CancelId, runChecked: true), "Esc or ✕ with «Apri Febe adesso» ticked");
Assert.IsFalse(DialogInterface.StartsFebe(TaskDialog.CancelId, runChecked: false));
}
private static (string Setup, byte[] Program) Pack(TestFolder folder, string version, int seed)
{
// Not an executable: if anything tried to start it, Windows would refuse it at once.
var program = new byte[300_000 + seed];
new Random(seed).NextBytes(program);
program[0] = (byte)'F';
program[1] = (byte)'B';
var source = folder.Combine($"Febe-{seed}.exe");
File.WriteAllBytes(source, program);
var setup = folder.Combine($"Febe-Setup-{version}-{seed}.exe");
Package.Write(s_publishedInstaller!, source, version, setup);
return (setup, program);
}
private async Task<int> Run(string executable, IReadOnlyList<string> arguments, StringBuilder? errors = null)
{
var start = new ProcessStartInfo(executable) { UseShellExecute = false, RedirectStandardError = true, StandardErrorEncoding = Encoding.UTF8 };
foreach (var argument in arguments)
{
start.ArgumentList.Add(argument);
}
using var process = Process.Start(start)!;
var text = await process.StandardError.ReadToEndAsync(TestContext.CancellationToken);
await process.WaitForExitAsync(TestContext.CancellationToken);
errors?.Append(text);
return process.ExitCode;
}
private async Task WaitUntil(Func<bool> condition, TimeSpan timeout)
{
var deadline = Stopwatch.StartNew();
while (!condition())
{
Assert.IsLessThan(timeout, deadline.Elapsed, "timed out");
await Task.Delay(200, TestContext.CancellationToken);
}
}
/// <summary>The program and the arguments of a command line as Windows reads it (quotes group).</summary>
private static (string Program, string[] Arguments) Split(string commandLine)
{
var words = new List<string>();
var word = new StringBuilder();
var quoted = false;
foreach (var c in commandLine)
{
if (c == '"')
{
quoted = !quoted;
}
else if (c == ' ' && !quoted)
{
if (word.Length > 0)
{
words.Add(word.ToString());
word.Clear();
}
}
else
{
word.Append(c);
}
}
if (word.Length > 0)
{
words.Add(word.ToString());
}
return (words[0], words.Skip(1).ToArray());
}
private static string? SafePath(Process process)
{
try
{
return process.MainModule?.FileName;
}
catch (Exception ex) when (ex is System.ComponentModel.Win32Exception or InvalidOperationException)
{
return null;
}
}
private static bool Contains(byte[] haystack, ReadOnlySpan<byte> needle) => haystack.AsSpan().IndexOf(needle) >= 0;
private static void DeleteEmptyTestKey()
{
using var tests = Registry.CurrentUser.OpenSubKey(@"Software\FebeProve");
if (tests is not null && tests.SubKeyCount == 0 && tests.ValueCount == 0)
{
Registry.CurrentUser.DeleteSubKey(@"Software\FebeProve", throwOnMissingSubKey: false);
}
}
private static string RepositoryRoot()
{
for (var folder = new DirectoryInfo(AppContext.BaseDirectory); folder is not null; folder = folder.Parent)
{
if (File.Exists(Path.Combine(folder.FullName, "Febe.slnx")))
{
return folder.FullName;
}
}
Assert.Inconclusive("Il repository non è accanto alle prove.");
return string.Empty;
}
/// <summary>The first visible top-level window of the process, zero for none.</summary>
private static IntPtr VisibleWindowOf(int processId)
{
var found = IntPtr.Zero;
EnumWindows((window, data) =>
{
GetWindowThreadProcessId(window, out var owner);
if (owner == (uint)processId && IsWindowVisible(window))
{
found = window;
return false;
}
return true;
}, IntPtr.Zero);
return found;
}
private static string WindowTitle(IntPtr window)
{
var buffer = new char[256];
var length = GetWindowText(window, buffer, buffer.Length);
return new string(buffer, 0, Math.Max(length, 0));
}
private delegate bool WindowVisitor(IntPtr window, IntPtr data);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool EnumWindows(WindowVisitor visitor, IntPtr data);
[DllImport("user32.dll")]
private static extern uint GetWindowThreadProcessId(IntPtr window, out uint processId);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool IsWindowVisible(IntPtr window);
[DllImport("user32.dll", EntryPoint = "GetWindowTextW", CharSet = CharSet.Unicode)]
private static extern int GetWindowText(IntPtr window, [Out] char[] text, int maxCount);
[DllImport("user32.dll", EntryPoint = "PostMessageW")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool PostMessage(IntPtr window, uint message, IntPtr wParam, IntPtr lParam);
}