using Febe.Browser.Hosting; using Febe.Core.Library; using Febe.Desktop.Core; using Febe.Tests.Desktop.Support; using Febe.Tests.Support; using Febe.Web.Api; namespace Febe.Tests.Desktop; /// /// The parts of the Windows application that do not need Windows (spec §12): command line, single instance, start-up /// checks, start with the computer, Edge for S2, the switches of S2, the move of the Data folder. /// [TestClass] public sealed class DesktopLogicTests { public TestContext TestContext { get; set; } = null!; [TestMethod] public void TheCommandLineIsReadAndWrongValuesAreRefusedInItalian() { Assert.IsTrue(DesktopCommandLine.TryParse([], out var plain, out _)); Assert.IsFalse(plain.StartHidden); Assert.IsNull(plain.Hosting); Assert.IsNull(plain.DataFolder); Assert.AreEqual("https://www.instagram.com/accounts/login/", plain.LoginUrl); Assert.AreEqual("instagram", plain.Site.Name); var data = Path.Combine(Path.GetTempPath(), "febe-dati"); var library = Path.Combine(Path.GetTempPath(), "febe-libreria"); Assert.IsTrue(DesktopCommandLine.TryParse(["--nascosto", "--browser", "composizione", "--dati", data, "--sviluppo", "--libreria", library], out var options, out _)); Assert.AreEqual(Path.GetFullPath(library), options.AppOptions(data, new DesktopFolders("a", "b")).LibraryFolder); Assert.IsTrue(options.StartHidden); Assert.AreEqual(BrowserHosting.Composition, options.Hosting); Assert.AreEqual(Path.GetFullPath(data), options.DataFolder); Assert.IsTrue(options.DeveloperTools); Assert.IsTrue(DesktopCommandLine.TryParse(["--sito-di-prova", "http://127.0.0.1:8481", "--accesso-di-prova", "--prima-sessione", "5", "--browser", "EDGE"], out var test, out _)); Assert.AreEqual("http://127.0.0.1:8481/benvenuto", test.LoginUrl); Assert.AreNotEqual("instagram", test.Site.Name); Assert.AreEqual(TimeSpan.FromSeconds(5), test.FirstSessionDelay); Assert.AreEqual(BrowserHosting.Edge, test.Hosting); foreach (var (args, fragment) in new (string[], string)[] { (["--browser", "nascosto"], "--browser"), (["--dati", "relativo"], "--dati"), (["--libreria"], "--libreria"), (["--sito-di-prova", "https://www.instagram.com/"], "questo computer"), (["--accesso-di-prova"], "--sito-di-prova"), (["--prima-sessione", "0"], "--prima-sessione"), (["--password", "x"], "Opzione sconosciuta"), }) { Assert.IsFalse(DesktopCommandLine.TryParse(args, out _, out var problem), string.Join(' ', args)); StringAssert.Contains(problem, fragment); } } [TestMethod] public void TheHostingNamesAreItalianAndRoundTrip() { foreach (var hosting in Enum.GetValues()) { Assert.IsTrue(BrowserHostingNames.TryParse(BrowserHostingNames.Name(hosting), out var back)); Assert.AreEqual(hosting, back); } Assert.IsFalse(BrowserHostingNames.TryParse(null, out var fallback)); Assert.AreEqual(BrowserHosting.Window, fallback, "the default of S2 is the first attempt"); } [TestMethod] public void TheDefaultFoldersAreLocalAppDataAndPictures() { var folders = new DesktopFolders(Path.Combine("C", "Users", "alberto", "AppData", "Local"), Path.Combine("C", "Users", "alberto", "Pictures")); Assert.AreEqual(Path.Combine(folders.LocalAppData, "Febe"), folders.DefaultDataFolder); Assert.AreEqual(Path.Combine(folders.Pictures, "Febe"), folders.DefaultLibraryFolder); Assert.IsTrue(DesktopCommandLine.TryParse([], out var options, out _)); var app = options.AppOptions(folders.DefaultDataFolder, folders); Assert.IsTrue(app.LibraryFolderFromSettings, "the library chosen in Impostazioni wins over the default"); Assert.IsNull(app.ImportFolder, "any folder can be imported on Windows"); Assert.AreEqual(folders.DefaultLibraryFolder, app.LibraryFolder); } [TestMethod] public void OneInstancePerDataFolderAndTheMessagesBetweenLaunches() { var a = Path.Combine(Path.GetTempPath(), "febe", "dati"); Assert.AreEqual(InstanceIdentity.For(a), InstanceIdentity.For(a + Path.DirectorySeparatorChar), "the same folder"); Assert.AreEqual(InstanceIdentity.For(a), InstanceIdentity.For(a.ToUpperInvariant()), "whatever the case of the letters"); Assert.AreNotEqual(InstanceIdentity.For(a), InstanceIdentity.For(a + "2"), "another account, another instance"); StringAssert.StartsWith(InstanceIdentity.MutexName(a), @"Local\Febe-"); Assert.AreEqual(21, InstanceIdentity.PipeName(a).Length); Assert.IsTrue(DesktopCommandLine.TryParse([], out var normal, out _)); Assert.IsTrue(DesktopCommandLine.TryParse(["--nascosto"], out var hidden, out _)); Assert.AreEqual(InstanceRequest.Show, InstanceMessages.Parse(InstanceMessages.For(normal))); Assert.AreEqual(InstanceRequest.StayHidden, InstanceMessages.Parse(InstanceMessages.For(hidden))); Assert.AreEqual(InstanceRequest.Show, InstanceMessages.Parse("FEBE1 mostra\n")); foreach (var junk in new[] { null, string.Empty, "mostra", "FEBE2 mostra", "FEBE1 apri C:\\", new string('x', 500) }) { Assert.IsNull(InstanceMessages.Parse(junk), junk); } } [TestMethod] public void WithoutWebView2TheProblemNamesTheOfficialPage() { using var temp = new TempFolder("desktop-controlli"); var data = temp.Combine("dati"); Assert.IsEmpty(DesktopStartupChecks.Run(data, () => "141.0.3537.71")); var problems = DesktopStartupChecks.Run(data, () => null); var missing = problems.Single(); Assert.AreEqual("webview2-assente", missing.Code); StringAssert.Contains(missing.Remedy, "https://developer.microsoft.com/microsoft-edge/webview2/"); StringAssert.Contains(missing.Message, "WebView2"); // The probe throws when the runtime is missing (WebView2RuntimeNotFoundException): same problem. Assert.AreEqual("webview2-assente", DesktopStartupChecks.Run(data, () => throw new InvalidOperationException("nessun runtime")).Single().Code); } [TestMethod] public void ADataFolderOnANetworkShareOrNotWritableStopsTheEngine() { using var temp = new TempFolder("desktop-controlli"); var file = temp.Combine("un-file"); File.WriteAllText(file, "x"); Assert.AreEqual("dati-non-scrivibili", DesktopStartupChecks.Run(file, () => "1.0").Single().Code); if (OperatingSystem.IsLinux()) { var share = temp.Combine("rete"); var mounts = $"//nas/condivisa {share} cifs rw 0 0\n"; var problems = DesktopStartupChecks.Run(share, () => null, new DataFolderCheck(() => mounts)); CollectionAssert.AreEqual(new[] { "dati-in-rete", "webview2-assente" }, problems.Select(p => p.Code).ToArray()); } } [TestMethod] public void StartWithTheComputerWritesTheQuotedExecutableAndRecognisesItsOwnValue() { var exe = Path.Combine(Path.GetTempPath(), "Programmi", "Febe", "Febe.exe"); var command = Autostart.Command(exe); Assert.AreEqual($"\"{exe}\" --nascosto", command); Assert.IsTrue(Autostart.PointsTo(command, exe)); Assert.IsTrue(Autostart.PointsTo(exe, exe), "a value without quotes"); Assert.IsFalse(Autostart.PointsTo(Autostart.Command(exe + ".vecchio"), exe), "another copy of Febe"); Assert.IsFalse(Autostart.PointsTo(null, exe)); Assert.IsFalse(Autostart.PointsTo("\"senza fine", exe)); Assert.ThrowsExactly(() => Autostart.Command("C:\\a\"b.exe")); } [TestMethod] public void EdgeIsFoundThroughAppPathsThenTheUsualFolders() { var candidates = EdgeLocator.Candidates("\"D:\\Edge\\msedge.exe\"", "C:\\Program Files (x86)", "C:\\Program Files", "C:\\Users\\a\\AppData\\Local"); Assert.AreEqual("D:\\Edge\\msedge.exe", candidates[0]); Assert.HasCount(4, candidates); Assert.AreEqual(Path.Combine("C:\\Program Files (x86)", "Microsoft", "Edge", "Application", "msedge.exe"), candidates[1]); var exists = new HashSet([candidates[2]]); Assert.AreEqual(candidates[2], EdgeLocator.Find(candidates, exists.Contains)); Assert.IsNull(EdgeLocator.Find(candidates, _ => false)); Assert.IsNull(EdgeLocator.Find(["C:\\Windows\\notepad.exe"], _ => true), "only msedge.exe"); } [TestMethod] public void TheSwitchesOfS2PassTheChecksOfRule2AndChangeNothingTheBrowserDeclares() { foreach (var argument in BrowserArguments.KeepPaintingOutOfView) { ChromiumCommandLine.EnsureAllowed(argument); foreach (var declared in new[] { "user-agent", "lang", "headless", "automation", "proxy", "blink-features", "timezone", "fingerprint", "webdriver" }) { Assert.DoesNotContain(declared, argument, StringComparison.OrdinalIgnoreCase); } } Assert.AreEqual("--disable-features=CalculateNativeWinOcclusion --disable-backgrounding-occluded-windows", BrowserArguments.ForWebView2()); // Edge started as a process gets the same switches, after Febe's own (fixed port on 127.0.0.1, profile, size). var line = ChromiumCommandLine.Build(new Febe.Core.Abstractions.BrowserOptions("profilo", 1280, 900, 9222), new ChromiumLaunchOptions { ExtraArguments = BrowserArguments.ForEdge() }); CollectionAssert.IsSubsetOf(BrowserArguments.KeepPaintingOutOfView.ToList(), line.ToList()); Assert.IsFalse(line.Any(a => a.StartsWith("--headless", StringComparison.Ordinal) || a.StartsWith("--enable-automation", StringComparison.Ordinal))); } [TestMethod] public void TheDataFolderMovesOnlyAfterEveryFileIsCopiedAndVerified() { using var temp = new TempFolder("desktop-sposta"); var from = temp.Combine("vecchia"); var to = temp.Combine("nuova", "Febe"); Directory.CreateDirectory(Path.Combine(from, "browser", "Default")); Directory.CreateDirectory(Path.Combine(from, "miniature", "ab")); Directory.CreateDirectory(Path.Combine(from, "vuota")); File.WriteAllText(Path.Combine(from, "febe.sqlite"), "database"); File.WriteAllText(Path.Combine(from, "browser", "Default", "Cookies"), "sessione"); var big = new byte[3 * 1024 * 1024 + 17]; new Random(4).NextBytes(big); File.WriteAllBytes(Path.Combine(from, "miniature", "ab", "x.jpg"), big); var store = new MemoryLocationStore(); Assert.AreEqual(DataFolderMoveOutcome.NotRequested, DataFolderMove.ApplyPending(store, from).Outcome); var change = new DesktopDataFolderChange(store, from, fixedByCommandLine: false); Assert.IsTrue(change.CanChange); var message = change.RequestChangeAsync(to, TestContext.CancellationToken).Result; StringAssert.Contains(message, "prossimo avvio"); Assert.AreEqual(Path.GetFullPath(to), store.Pending); Assert.IsFalse(Directory.Exists(to), "nothing moves while Febe runs"); var reports = new List(); var result = DataFolderMove.ApplyPending(store, from, new SyncProgress(reports.Add)); Assert.AreEqual(DataFolderMoveOutcome.Moved, result.Outcome, result.Message); Assert.AreEqual(Path.GetFullPath(to), result.DataFolder); Assert.AreEqual(Path.GetFullPath(to), store.Current); Assert.IsNull(store.Pending); Assert.IsFalse(Directory.Exists(from), "the old folder, with a copy of the session, is gone"); Assert.AreEqual("sessione", File.ReadAllText(Path.Combine(to, "browser", "Default", "Cookies"))); CollectionAssert.AreEqual(big, File.ReadAllBytes(Path.Combine(to, "miniature", "ab", "x.jpg"))); Assert.IsTrue(Directory.Exists(Path.Combine(to, "vuota")), "empty folders too"); Assert.AreEqual(3, reports[^1].FilesTotal); Assert.AreEqual(3, reports[^1].FilesDone); } [TestMethod] public void AFailedCopyLeavesTheOldFolderInUseAndRemovesThePartialCopy() { using var temp = new TempFolder("desktop-sposta"); var from = temp.Combine("vecchia"); Directory.CreateDirectory(from); File.WriteAllText(Path.Combine(from, "febe.sqlite"), "database"); var to = temp.Combine("nuova"); var store = new MemoryLocationStore { Pending = to }; // The target appears with a file before the start (someone used it): refused, nothing touched. Directory.CreateDirectory(to); File.WriteAllText(Path.Combine(to, "altro.txt"), "non di Febe"); var refused = DataFolderMove.ApplyPending(store, from); Assert.AreEqual(DataFolderMoveOutcome.Failed, refused.Outcome); Assert.AreEqual(from, refused.DataFolder); StringAssert.Contains(refused.Message, "vuota"); Assert.IsNull(store.Pending); Assert.IsNull(store.Current); Assert.IsTrue(File.Exists(Path.Combine(from, "febe.sqlite"))); Assert.IsTrue(File.Exists(Path.Combine(to, "altro.txt")), "a folder that is not Febe's is never emptied"); // A copy interrupted half way (the disk fills up after the first file): the old folder stays, the copy goes. File.WriteAllText(Path.Combine(from, "secondo"), "y"); var halfway = temp.Combine("quarta"); store.Pending = halfway; var interrupted = DataFolderMove.ApplyPending(store, from, new SyncProgress(_ => throw new IOException("disco pieno"))); Assert.AreEqual(DataFolderMoveOutcome.Failed, interrupted.Outcome); StringAssert.Contains(interrupted.Message, "disco pieno"); Assert.IsFalse(Directory.Exists(halfway), "the partial copy is removed"); Assert.IsNull(store.Current); Assert.IsTrue(File.Exists(Path.Combine(from, "febe.sqlite"))); // A file the copy cannot read: the same. if (OperatingSystem.IsLinux() && Environment.UserName != "root") { var locked = Path.Combine(from, "bloccato"); File.WriteAllText(locked, "x"); File.SetUnixFileMode(locked, UnixFileMode.None); var target = temp.Combine("terza"); store.Pending = target; var failed = DataFolderMove.ApplyPending(store, from); Assert.AreEqual(DataFolderMoveOutcome.Failed, failed.Outcome); Assert.IsFalse(Directory.Exists(target), "the partial copy is removed"); Assert.IsTrue(File.Exists(Path.Combine(from, "febe.sqlite"))); File.SetUnixFileMode(locked, UnixFileMode.UserRead | UnixFileMode.UserWrite); } } [TestMethod] public void TheNewDataFolderMustBeEmptyLocalAndOutsideTheCurrentOne() { using var temp = new TempFolder("desktop-sposta"); var current = temp.Combine("dati"); Directory.CreateDirectory(current); Assert.IsNotNull(DataFolderMove.Validate(current, "relativa")); Assert.IsNotNull(DataFolderMove.Validate(current, current)); Assert.IsNotNull(DataFolderMove.Validate(current, Path.Combine(current, "dentro"))); Assert.IsNotNull(DataFolderMove.Validate(Path.Combine(current, "sotto"), current)); Assert.IsNull(DataFolderMove.Validate(current, temp.Combine("altrove"))); Assert.IsFalse(Directory.Exists(temp.Combine("altrove")), "checking a choice does not leave a folder behind"); var fixedByCommandLine = new DesktopDataFolderChange(new MemoryLocationStore(), current, fixedByCommandLine: true); Assert.IsFalse(fixedByCommandLine.CanChange); Assert.ThrowsExactly(() => fixedByCommandLine.RequestChangeAsync(temp.Combine("altrove"), TestContext.CancellationToken).GetAwaiter().GetResult()); var store = new MemoryLocationStore(); Assert.ThrowsExactly(() => new DesktopDataFolderChange(store, current, false).RequestChangeAsync(Path.Combine(current, "x"), TestContext.CancellationToken).GetAwaiter().GetResult()); Assert.IsNull(store.Pending); } [TestMethod] public void AfterAMoveThisFebeHoldsTheNewFolderSoASecondLaunchDoesNotStartASecondFebe() { // pkg-1: the guard is named after the Data folder. After a move every launch reads the new folder: this Febe // must hold its guard, or the next launch would start a second interface, browser and engine on it. using var temp = new TempFolder("desktop-sposta"); var from = temp.Combine("vecchia"); var to = temp.Combine("nuova"); Directory.CreateDirectory(from); File.WriteAllText(Path.Combine(from, "febe.sqlite"), "database"); var guards = new FakeInstanceGuards(); var store = new MemoryLocationStore { Pending = to }; using var started = guards.TryAcquire(from); Assert.IsNotNull(started, "Program: the guard of the folder this Febe started on"); (string? Recorded, bool Written)? atClaim = null; var result = DataFolderMove.ApplyPending(store, from, claimTarget: folder => { atClaim = (store.Current, Directory.Exists(folder)); return guards.TryAcquire(folder); }); Assert.AreEqual(DataFolderMoveOutcome.Moved, result.Outcome, result.Message); Assert.AreEqual((null, false), atClaim, "the guard comes before the folder is recorded and before anything is written in it"); Assert.IsNotNull(result.TargetGuard); Assert.AreEqual(Path.GetFullPath(to), store.Current); // The next launch (Start menu, a start with the computer) reads the recorded folder and finds this Febe. Assert.IsNull(guards.TryAcquire(store.Current!), "a second launch signals this Febe instead of starting another"); result.TargetGuard!.Dispose(); using var afterExit = guards.TryAcquire(store.Current!); Assert.IsNotNull(afterExit, "after Esci the folder is free again"); } [TestMethod] public void AMoveIntoAFolderAnotherFebeHoldsDoesNotHappenAndAFailedMoveGivesTheGuardBack() { using var temp = new TempFolder("desktop-sposta"); var from = temp.Combine("vecchia"); Directory.CreateDirectory(from); File.WriteAllText(Path.Combine(from, "febe.sqlite"), "database"); var guards = new FakeInstanceGuards(); // Another Febe (started with --dati) already holds the new folder: nothing is copied, the old folder stays. var taken = temp.Combine("presa"); using (guards.TryAcquire(taken)) { var store = new MemoryLocationStore { Pending = taken }; var refused = DataFolderMove.ApplyPending(store, from, claimTarget: guards.TryAcquire); Assert.AreEqual(DataFolderMoveOutcome.Failed, refused.Outcome); StringAssert.Contains(refused.Message, "un altro Febe la sta già usando"); Assert.IsNull(refused.TargetGuard); Assert.IsNull(store.Pending); Assert.IsNull(store.Current); Assert.IsFalse(Directory.Exists(taken), "nothing written there"); Assert.IsTrue(File.Exists(Path.Combine(from, "febe.sqlite"))); } // A copy that fails: Febe stays on the old folder and does not keep the guard of the new one. var halfway = temp.Combine("a-meta"); var failing = new MemoryLocationStore { Pending = halfway }; var failed = DataFolderMove.ApplyPending(failing, from, new SyncProgress(_ => throw new IOException("disco pieno")), claimTarget: guards.TryAcquire); Assert.AreEqual(DataFolderMoveOutcome.Failed, failed.Outcome); Assert.IsNull(failed.TargetGuard); using var free = guards.TryAcquire(halfway); Assert.IsNotNull(free, "the guard of a move that did not happen is given back"); } [TestMethod] public void TheDataFolderLockLetsOneFebeOpenTheFolderWhateverItsSpelling() { using var temp = new TempFolder("desktop-blocco"); var data = temp.Combine("dati"); Assert.AreEqual(DataFolderLockOutcome.Acquired, DataFolderLock.TryAcquire(data, out var first, TimeSpan.Zero)); Assert.IsNotNull(first); Assert.AreEqual(Path.Combine(data, DataFolderLock.FileName), first.Path); Assert.IsTrue(File.Exists(first.Path)); // The same folder under another name (on Windows: a short 8.3 name, subst, a junction; here a symbolic link): // the guards are named after the path and differ, the lock is the same file. var alias = temp.Combine("alias"); Directory.CreateSymbolicLink(alias, data); Assert.AreNotEqual(InstanceIdentity.For(data), InstanceIdentity.For(alias)); Assert.AreEqual(DataFolderLockOutcome.HeldByAnother, DataFolderLock.TryAcquire(alias, out var second, TimeSpan.Zero)); Assert.IsNull(second); // Held for a moment only (an antivirus looking at the file): the start waits instead of giving up. var release = Task.Run(async () => { await Task.Delay(300, TestContext.CancellationToken); first.Dispose(); }, TestContext.CancellationToken); Assert.AreEqual(DataFolderLockOutcome.Acquired, DataFolderLock.TryAcquire(alias, out var later, TimeSpan.FromSeconds(10))); release.Wait(TestContext.CancellationToken); later!.Dispose(); // A Data folder where nothing can be written: the start-up checks explain it, the lock does not decide. var file = temp.Combine("un-file"); File.WriteAllText(file, "x"); Assert.AreEqual(DataFolderLockOutcome.Unavailable, DataFolderLock.TryAcquire(file, out var none, TimeSpan.Zero)); Assert.IsNull(none); } [TestMethod] public void AFebeStartedWithItsOwnDataFolderHasItsOwnStartWithTheComputer() { // pkg-5: «Febe.exe --dati D:\FebeSecondo» (a second account) must start that folder at the next login, and its // switch must neither show nor remove the start of the usual Febe. var exe = Path.Combine(Path.GetTempPath(), "Programmi", "Febe", "Febe.exe"); var second = Path.Combine(Path.GetTempPath(), "Febe Secondo"); Assert.AreEqual("Febe", Autostart.ValueNameFor(null)); Assert.AreEqual(InstanceIdentity.For(second), Autostart.ValueNameFor(second)); StringAssert.StartsWith(Autostart.ValueNameFor(second), "Febe-"); Assert.AreNotEqual(Autostart.ValueNameFor(second), Autostart.ValueNameFor(second + "2")); var command = Autostart.Command(exe, second); Assert.AreEqual($"\"{exe}\" --nascosto --dati \"{second}\"", command); Assert.IsTrue(Autostart.PointsTo(command, exe, second)); Assert.IsTrue(Autostart.PointsTo(command, exe, second + Path.DirectorySeparatorChar), "the same folder"); Assert.IsFalse(Autostart.PointsTo(command, exe), "the usual Febe does not take it for its own"); Assert.IsFalse(Autostart.PointsTo(Autostart.Command(exe), exe, second), "nor the reverse: that command starts the usual folder"); Assert.IsFalse(Autostart.PointsTo(Autostart.Command(exe, second + "2"), exe, second), "another account"); Assert.IsFalse(Autostart.PointsTo($"\"{exe}\" --nascosto --dati", exe, second)); // Febe.exe reads the command back as written: hidden, on that Data folder. var words = Autostart.Split(command)!; Assert.AreEqual(exe, words[0]); Assert.IsTrue(DesktopCommandLine.TryParse([.. words.Skip(1)], out var options, out var problem), problem); Assert.IsTrue(options.StartHidden); Assert.AreEqual(Path.GetFullPath(second), options.DataFolder); // A folder at the root of a drive: the backslash before the closing quote is doubled, so it reads back whole. CollectionAssert.AreEqual(new[] { exe, "--nascosto", "--dati", @"D:\" }, Autostart.Split(Autostart.Command(exe, @"D:\"))); CollectionAssert.AreEqual(new[] { "a", "b\"c", @"d\e" }, Autostart.Split("a \"b\\\"c\" d\\e")); Assert.ThrowsExactly(() => Autostart.Command(exe, "C:\\a\"b")); } /// The single-instance guards of Windows (named mutexes), by Data folder, in memory. private sealed class FakeInstanceGuards { private readonly HashSet _held = []; public IDisposable? TryAcquire(string dataFolder) { var name = InstanceIdentity.MutexName(dataFolder); lock (_held) { return _held.Add(name) ? new Guard(this, name) : null; } } private void Release(string name) { lock (_held) { _held.Remove(name); } } private sealed class Guard(FakeInstanceGuards owner, string name) : IDisposable { public void Dispose() => owner.Release(name); } } private sealed class SyncProgress(Action report) : IProgress { public void Report(DataFolderMoveProgress value) => report(value); } }