Files
Febe/tests/Febe.Tests/Desktop/DesktopLogicTests.cs
T

303 lines
16 KiB
C#

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;
/// <summary>
/// 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.
/// </summary>
[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<BrowserHosting>())
{
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<ArgumentException>(() => 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<string>([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<DataFolderMoveProgress>();
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<BadRequestException>(() => fixedByCommandLine.RequestChangeAsync(temp.Combine("altrove"), TestContext.CancellationToken).GetAwaiter().GetResult());
var store = new MemoryLocationStore();
Assert.ThrowsExactly<BadRequestException>(() => new DesktopDataFolderChange(store, current, false).RequestChangeAsync(Path.Combine(current, "x"), TestContext.CancellationToken).GetAwaiter().GetResult());
Assert.IsNull(store.Pending);
}
private sealed class SyncProgress(Action<DataFolderMoveProgress> report) : IProgress<DataFolderMoveProgress>
{
public void Report(DataFolderMoveProgress value) => report(value);
}
}