Files
Febe/tests/Febe.Tests/Web/InterfaceTests.cs
T
Alby96andClaude Opus 5.5 7513f41d4d Prove dell'interfaccia: ridisegni rimandati e trascinamento senza pause
AfterInEvidenzaTheOtherTabsStayTheirs aspettava 500 e 600 ms perché un
ridisegno rimasto di «In evidenza» (150 ms dopo un cambio di dimensione)
avesse il tempo di coprire i post. Ora aspetta i timer della pagina che
erano in sospeso al cambio di filtro (PageTimers) e, dopo il cambio di
dimensione, un ResizeObserver della prova, chiamato dopo quelli della
pagina, e i timer che quelli hanno lasciato.

TheWindowBarHandleFollowsTheWholeDrag lasciava 60 ms fra un passo e
l'altro del trascinamento: su una macchina lenta più passi possono
arrivare come un solo movimento, e la prova non provava più che la
maniglia segua tutto il trascinamento. Ora ogni passo aspetta il suo
orario nel campo prima del successivo.

TheAccountHeaderFollowsEveryMenuAction aveva 200 ms fra un'azione e
l'altra che non proteggevano nulla: ogni giro aspetta già l'intestazione
ridisegnata.

Con copie dell'interfaccia rotte apposta (ridisegno non annullato,
osservatore non staccato, tessere tardive disegnate, trascinamento che
finisce al primo passo) le prove falliscono in ogni giro provato, anche
con Chrome rallentato 20 volte.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 10:45:17 +02:00

692 lines
41 KiB
C#

using System.Runtime.CompilerServices;
using System.Text.Json.Nodes;
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Core.Storage;
using Febe.Tests.Server.Support;
using Febe.Tests.Support;
using Febe.Tests.Web.Part2Support;
using Febe.Tests.Web.Support;
using Febe.Web;
using Febe.Web.Connection;
using Febe.Web.Engine;
using Febe.Web.Library;
using Microsoft.Extensions.DependencyInjection;
namespace Febe.Tests.Web;
/// <summary>
/// The interface itself in a real (headless) Chromium against a test server: what only shows when the scripts run.
/// The «driving» lease of the Browser and Collegamento pages (spec §4.1, §10.3: the engine is still only while Alberto
/// uses the browser), the remote view's keyboard and mouse, the mosaic and the account card when filters change,
/// the empty library that follows the connection, the unsaved-changes guard on the browser's Back button, the window
/// bar of Limiti, the sidebar status box.
/// </summary>
[TestClass]
[DoNotParallelize]
public sealed class InterfaceTests
{
private static readonly ConnectionStatus Connected = new(ConnectionState.Connected, "tuo.profilo", "Il tuo profilo", false, null);
private static readonly ConnectionStatus Verification = new(ConnectionState.VerificationRequired, "tuo.profilo", "Il tuo profilo", false, "https://www.instagram.com/challenge/");
/// <summary>
/// Installed before the page scripts: the answer of <c>/api/engine</c> waits until <c>window.__releaseEngine()</c>,
/// and without the event stream (the interface then asks <c>/api/engine</c>) nothing brings the engine sooner.
/// </summary>
private const string HoldEngine = """
(() => {
const original = window.fetch.bind(window);
let release;
const gate = new Promise((resolve) => { release = resolve; });
window.__releaseEngine = () => { release(); return true; };
window.fetch = async (input, init) => {
const url = typeof input === 'string' ? input : input.url;
if (url.includes('/api/engine')) await gate;
return original(input, init);
};
delete window.EventSource;
})();
""";
/// <summary>
/// Installed before the page scripts: <c>window.__timers()</c> lists the timeouts of the page still pending and
/// <c>window.__timersOver(ids)</c> says whether those have all run or been cleared. A test waits for the timers that
/// were pending at a given moment (a debounced redraw, say) to be over, instead of a pause that may be too short.
/// </summary>
private const string PageTimers = """
(() => {
const set = window.setTimeout.bind(window);
const clear = window.clearTimeout.bind(window);
const pending = new Set();
window.setTimeout = (fn, ms, ...rest) => {
const id = set((...args) => {
pending.delete(id);
fn(...args);
}, ms, ...rest);
pending.add(id);
return id;
};
window.clearTimeout = (id) => {
pending.delete(id);
clear(id);
};
window.__timers = () => [...pending];
window.__timersOver = (ids) => ids.every((id) => !pending.has(id));
})();
""";
// ------------------------------------------------------------------------------------------ the driving lease
[TestMethod]
public async Task LeavingTheBrowserPageWithoutHoFinitoGivesTheBrowserBack()
{
var connection = new RecordingConnection { Status = Connected };
var view = new FakeRemoteViewHost();
await using var server = await DockerAsync(connection, view);
await using var ui = await UiBrowser.StartAsync();
await ui.OpenAsync(new Uri(server.Address, "/browser"));
await ui.WaitForAsync(() => connection.Snapshot().Contains("begin:False") && view.Opened.Count == 1, "il browser in uso con la vista aperta");
// Another page from the sidebar: the view closes and the lease of «begin» goes too (like «Annulla»).
await ui.EvalAsync("document.querySelector('a[data-nav=libreria]').click()");
await ui.WaitAsync("location.pathname === '/libreria'", "Libreria");
await ui.WaitForAsync(() => connection.Snapshot().Contains("cancel"), "il browser restituito lasciando la pagina");
await ui.WaitForAsync(() => view.Opened.All(v => v.Disposed), "vista remota chiusa");
CollectionAssert.AreEqual(new[] { "begin:False", "cancel" }, connection.Snapshot());
}
[TestMethod]
public async Task ClosingOrReloadingTheTabGivesTheBrowserBack()
{
var connection = new RecordingConnection { Status = Connected };
var view = new FakeRemoteViewHost();
await using var server = await DockerAsync(connection, view);
await using var ui = await UiBrowser.StartAsync();
await ui.OpenAsync(new Uri(server.Address, "/browser"));
await ui.WaitForAsync(() => connection.Snapshot().Contains("begin:False"), "il browser in uso");
// The document goes away (tab closed, reload, another site): only the page-hide event is left to say so.
await ui.SendAsync("Page.navigate", new JsonObject { ["url"] = "about:blank" });
await ui.WaitForAsync(() => connection.Snapshot().Contains("cancel"), "il browser restituito chiudendo la scheda");
}
[TestMethod]
public async Task ABrowserPageLeftWhileLoadingNeverTakesTheBrowser()
{
var connection = new RecordingConnection { Status = Connected };
var view = new FakeRemoteViewHost();
await using var server = await DockerAsync(connection, view);
await using var ui = await UiBrowser.StartAsync();
await ui.AddInitScriptAsync(UiBrowser.Requests);
await ui.OpenAsync(new Uri(server.Address, "/libreria"));
// The status of the connection answers late: the Browser page asks for it, Alberto goes elsewhere, then it
// comes. In this order on any machine (issue #8: a page left after a fixed delay may not have asked yet).
await ui.EvalAsync("window.__hold('/api/connection')");
await ui.NavigateAsync("/browser");
await ui.WaitAsync("window.__started['/api/connection'] >= 1", "pagina Browser in attesa dello stato del collegamento");
await ui.NavigateAsync("/libreria");
await ui.WaitAsync("location.pathname === '/libreria'", "Libreria");
await ui.EvalAsync("window.__release('/api/connection')");
await ui.WaitAsync("window.__done['/api/connection'] >= 1", "risposta in ritardo arrivata");
// What the page did with the late answer is done: whatever it asked then is in the list.
CollectionAssert.AreEqual(new[] { "GET /api/connection" }, await ui.AskedAsync("/api/connection"), "nothing taken by a page that is gone");
Assert.IsEmpty(await ui.AskedAsync("/api/vista"), "no remote view for a page that is gone");
Assert.IsEmpty(connection.Snapshot());
Assert.IsEmpty(view.Opened);
}
[TestMethod]
public async Task AfterHoFinitoLeavingTheBrowserPageChangesNothingMore()
{
var connection = new RecordingConnection { Status = Connected };
var view = new FakeRemoteViewHost();
await using var server = await DockerAsync(connection, view);
await using var ui = await UiBrowser.StartAsync();
await ui.AddInitScriptAsync(UiBrowser.Requests);
await ui.OpenAsync(new Uri(server.Address, "/browser"));
await ui.WaitForAsync(() => connection.Snapshot().Contains("begin:False"), "il browser in uso");
await ui.EvalAsync("document.querySelector('.salva .btn.primo').click()");
await ui.WaitAsync("location.pathname === '/attivita'", "Attività dopo «Ho finito»");
await ui.WaitForAsync(() => view.Opened.All(v => v.Disposed), "vista remota chiusa");
await ui.NavigateAsync("/libreria");
await ui.WaitAsync("location.pathname === '/libreria'", "Libreria");
// A page gives the browser back as it is left (PageFrame.onLeave): a «cancel» would be asked by now, and once
// the page is quiet every command it asked has reached the server.
await ui.WaitForQuietAsync("richieste della pagina finite");
CollectionAssert.AreEqual(new[] { "POST /api/connection/begin", "POST /api/connection/finish" }, await ui.AskedAsync("POST /api/connection/"), "«Ho finito» already gave the browser back");
CollectionAssert.AreEqual(new[] { "begin:False", "finish" }, connection.Snapshot());
}
[TestMethod]
public async Task ConnectedBeforeTheFirstRoundSaysTheNameIsNotKnownYet()
{
// Right after «Ho finito» the session exists but no round has read the name of the account yet.
var connection = new RecordingConnection { Status = new ConnectionStatus(ConnectionState.Connected, null, null, false, null) };
await using var server = await DockerAsync(connection, new FakeRemoteViewHost());
await using var ui = await UiBrowser.StartAsync();
await ui.OpenAsync(new Uri(server.Address, "/impostazioni/collegamento"));
await ui.WaitAsync("document.querySelector('.pannello.collegato') !== null", "collegato");
Assert.AreEqual("Collegato", (await ui.EvalAsync("document.querySelector('.chi-collegato h2').textContent")).GetString());
Assert.AreEqual("Nome non ancora noto", (await ui.EvalAsync("document.querySelector('.chi-collegato .muto').textContent")).GetString());
Assert.IsFalse((await ui.EvalAsync("document.querySelector('.chi-collegato').textContent.includes('@')")).GetBoolean(), "no «@» without a name");
}
[TestMethod]
public async Task HoFinitoOnCollegamentoClosesTheRemoteView()
{
var connection = new RecordingConnection();
var view = new FakeRemoteViewHost();
await using var server = await DockerAsync(connection, view);
await using var ui = await UiBrowser.StartAsync();
await ui.AddInitScriptAsync(UiBrowser.Requests);
await ui.OpenAsync(new Uri(server.Address, "/impostazioni/collegamento"));
await ui.WaitForAsync(() => connection.Snapshot().Contains("begin:True") && view.Opened.Count == 1, "pagina di accesso nella vista remota");
await ui.EvalAsync("document.querySelector('.bottoni-collegamento .btn.primo').click()");
await ui.WaitAsync("document.querySelector('.pannello.collegato') !== null", "collegato");
// The view held the engine still for as long as the page stayed open (PROTOCOLLO.md: closing it frees it).
await ui.WaitForAsync(() => view.Opened.All(v => v.Disposed), "vista remota chiusa dopo «Ho finito»");
await ui.NavigateAsync("/libreria");
await ui.WaitAsync("location.pathname === '/libreria'", "Libreria");
await ui.WaitForQuietAsync("richieste della pagina finite");
CollectionAssert.AreEqual(new[] { "POST /api/connection/begin", "POST /api/connection/finish" }, await ui.AskedAsync("POST /api/connection/"), "«Ho finito» already gave the browser back");
CollectionAssert.AreEqual(new[] { "WS /api/vista" }, await ui.AskedAsync("WS "), "no view opened again");
CollectionAssert.AreEqual(new[] { "begin:True", "finish" }, connection.Snapshot());
Assert.HasCount(1, view.Opened);
}
[TestMethod]
public async Task HoFinitoDuringAVerificationDoesNotTakeTheBrowserAgain()
{
var connection = new RecordingConnection { Status = Verification, StatusAfterFinish = Verification };
var view = new FakeRemoteViewHost();
await using var server = await DockerAsync(connection, view, new FixedMonitor(EngineMode.StoppedForVerification));
await using var ui = await UiBrowser.StartAsync();
await ui.AddInitScriptAsync(UiBrowser.Requests);
await ui.OpenAsync(new Uri(server.Address, "/impostazioni/collegamento"));
await ui.WaitForAsync(() => connection.Snapshot().Contains("begin:False") && view.Opened.Count == 1, "verifica nella vista remota");
await ui.EvalAsync("document.querySelector('.bottoni-collegamento .btn.primo').click()");
await ui.WaitAsync("document.querySelector('.riapri-browser') !== null", "«Ho finito» fatto, in attesa di «Riprendi»");
await ui.WaitForAsync(() => view.Opened.All(v => v.Disposed), "vista remota chiusa dopo «Ho finito»");
// «Ho finito» also asks for the engine: what its answer brings has been drawn once the page is quiet.
await ui.WaitForQuietAsync("richieste di «Ho finito» finite");
CollectionAssert.AreEqual(new[] { "POST /api/connection/begin", "POST /api/connection/finish" }, await ui.AskedAsync("POST /api/connection/"), "no new lease after «Ho finito»");
CollectionAssert.AreEqual(new[] { "WS /api/vista" }, await ui.AskedAsync("WS "), "no new view after «Ho finito»");
CollectionAssert.AreEqual(new[] { "begin:False", "finish" }, connection.Snapshot());
Assert.HasCount(1, view.Opened);
// «Riapri il browser» takes it again; leaving the page then gives it back.
await ui.EvalAsync("document.querySelector('.riapri-browser').click()");
await ui.WaitForAsync(() => connection.Snapshot().Length == 3 && view.Opened.Count == 2, "browser riaperto");
await ui.NavigateAsync("/libreria");
await ui.WaitAsync("location.pathname === '/libreria'", "Libreria");
await ui.WaitForQuietAsync("richieste della pagina finite");
CollectionAssert.AreEqual(new[] { "begin:False", "finish", "begin:False", "cancel" }, connection.Snapshot(), "leaving the page gives the browser back");
await ui.WaitForAsync(() => view.Opened.All(v => v.Disposed), "vista remota chiusa");
}
[TestMethod]
public async Task AfterRiprendiCollegamentoShowsTheConnectionWithoutTakingTheBrowser()
{
var connection = new RecordingConnection { Status = Verification, StatusAfterFinish = Verification };
var view = new FakeRemoteViewHost();
var engine = new FixedMonitor(EngineMode.StoppedForVerification);
await using var server = await DockerAsync(connection, view, engine);
await using var ui = await UiBrowser.StartAsync();
await ui.AddInitScriptAsync(UiBrowser.Requests);
await ui.OpenAsync(new Uri(server.Address, "/impostazioni/collegamento"));
await ui.WaitAsync("document.querySelector('.arresto') !== null", "striscia rossa della verifica");
await ui.WaitForAsync(() => connection.Snapshot().Contains("begin:False"), "verifica nella vista remota");
await ui.EvalAsync("document.querySelector('.bottoni-collegamento .btn.primo').click()");
await ui.WaitAsync("document.querySelector('.riapri-browser') !== null", "in attesa di «Riprendi»");
// «Riprendi»: the engine works again and the session is there.
engine.Mode = EngineMode.Resting;
connection.Status = Connected;
await ui.EvalAsync("import('/js/core/engine.js').then((m) => m.refreshEngine()).then(() => true)");
await ui.WaitAsync("document.querySelector('.pannello.collegato') !== null", "collegato dopo «Riprendi»");
await ui.WaitForQuietAsync("richieste dopo «Riprendi» finite");
CollectionAssert.AreEqual(new[] { "POST /api/connection/begin", "POST /api/connection/finish" }, await ui.AskedAsync("POST /api/connection/"), "the browser is not taken again");
CollectionAssert.AreEqual(new[] { "begin:False", "finish" }, connection.Snapshot());
await ui.WaitForAsync(() => view.Opened.All(v => v.Disposed), "vista remota chiusa");
Assert.HasCount(1, view.Opened);
}
// ------------------------------------------------------------------------------------------ remote view input
[TestMethod]
public async Task AltGrCharactersReachTheRemotePageAsText()
{
var connection = new RecordingConnection { Status = Connected };
var view = new FakeRemoteViewHost();
await using var server = await DockerAsync(connection, view);
await using var ui = await UiBrowser.StartAsync();
await ui.AddInitScriptAsync(UiBrowser.Requests);
await ui.OpenAsync(new Uri(server.Address, "/browser"));
await ui.WaitForAsync(() => view.Opened.Count == 1, "vista aperta");
await ui.WaitAsync("document.querySelector('canvas.vista-schermo') !== null", "schermo della vista");
// The view sends keys only once its socket is open (the server opens the view before it answers the socket).
await ui.WaitAsync("window.__sockets.some((s) => s.url.endsWith('/api/vista') && s.readyState === WebSocket.OPEN)", "vista collegata");
// Italian layout on Windows: AltGr+ò is «@», reported as Ctrl+Alt with the AltGraph modifier.
Assert.IsTrue((await ui.EvalAsync("new KeyboardEvent('keydown', { key: '@', modifierAltGraph: true }).getModifierState('AltGraph')")).GetBoolean());
await ui.EvalAsync("""
(() => {
const c = document.querySelector('canvas.vista-schermo');
const key = (type, init) => c.dispatchEvent(new KeyboardEvent(type, { bubbles: true, cancelable: true, ...init }));
const altGr = { ctrlKey: true, altKey: true, modifierAltGraph: true };
key('keydown', { key: '@', code: 'Semicolon', ...altGr });
key('keyup', { key: '@', code: 'Semicolon', ...altGr });
key('keydown', { key: 'a', code: 'KeyA' });
key('keyup', { key: 'a', code: 'KeyA' });
key('keydown', { key: 'f', code: 'KeyF', altKey: true });
key('keyup', { key: 'f', code: 'KeyF', altKey: true });
return true;
})()
""");
var connectionView = view.Opened.Single();
await ui.WaitForAsync(() => Keys(connectionView).Any(k => k.Action == RemoteViewKeyAction.Up && k.Key == "f"), "tasti arrivati");
var keys = Keys(connectionView);
Assert.IsTrue(keys.Any(k => k is { Action: RemoteViewKeyAction.Char, Text: "@", Modifiers: 0 }), "AltGr+ò types «@»: " + Describe(keys));
Assert.IsFalse(keys.Any(k => k.Key == "@" && k.Action != RemoteViewKeyAction.Char), "no Ctrl+Alt shortcut for «@»: " + Describe(keys));
Assert.IsTrue(keys.Any(k => k is { Action: RemoteViewKeyAction.Down, Key: "a", Text: "a", Modifiers: 0 }), "a plain key keeps its text");
Assert.IsTrue(keys.Any(k => k is { Action: RemoteViewKeyAction.Down, Key: "f", Text: null, Modifiers: 1 }), "Alt+F on Windows stays a shortcut: " + Describe(keys));
}
[TestMethod]
public async Task ReleasingTheMouseOutsideTheViewReleasesTheRemoteButton()
{
var connection = new RecordingConnection { Status = Connected };
var view = new FakeRemoteViewHost();
await using var server = await DockerAsync(connection, view);
await using var ui = await UiBrowser.StartAsync();
await ui.OpenAsync(new Uri(server.Address, "/browser"));
await ui.WaitForAsync(() => view.Opened.Count == 1, "vista aperta");
var remote = view.Opened.Single();
// What the view writes waits in it until the socket is open, and the page listens from the start; the first
// frame on the screen says that the socket is open, so the buttons can go.
remote.Write(new RemoteViewMeta(320, 225, "https://www.instagram.com/"));
remote.Write(new RemoteViewFrame(TestFile.PhotoBytes(3, 320, 225)));
await ui.WaitAsync("!document.querySelector('canvas.vista-schermo').hidden", "primo fotogramma");
var (x, y, _, _) = await ui.BoxAsync("canvas.vista-schermo");
await ui.MouseAsync("mouseMoved", x, y);
await ui.MouseAsync("mousePressed", x, y, buttons: 1);
await ui.MouseAsync("mouseMoved", x + 20, y + 10, buttons: 1);
await ui.MouseAsync("mouseMoved", 60, 60, buttons: 1);
await ui.MouseAsync("mouseReleased", 60, 60);
await ui.WaitForAsync(() => Mice(remote).Any(m => m.Action == RemoteViewMouseAction.Up), "pulsante rilasciato anche fuori dalla vista");
Assert.AreEqual(RemoteViewButton.Left, Mice(remote).Single(m => m.Action == RemoteViewMouseAction.Up).Button);
}
// ------------------------------------------------------------------------------------------ mosaic and account card
[TestMethod]
public async Task AfterInEvidenzaTheOtherTabsStayTheirs()
{
await using var server = await WebTestServer.StartAsync();
var account = await server.AddAccountWithEntriesAsync("marta.prova", 6, Make.T0, TimeSpan.FromHours(20));
var stories = await server.Db.Entries.AddManyAsync([.. Enumerable.Range(0, 3).Select(i => new NewEntry(
Make.Entry(account.Id, $"storia-{i}", Make.T0 - TimeSpan.FromDays(3 + i), EntryKind.Story) with { State = EntryState.Downloaded },
[Make.Stored(Make.Photo(), Make.Sha(9000 + i), $"storie/storia-{i}.jpg")]))]);
var summer = await server.Db.Highlights.UpsertAsync(new Highlight { AccountId = account.Id, InstagramId = "h1", Title = "Estate", Position = 0, DiscoveredAt = Make.T0 });
foreach (var story in stories)
{
await server.Db.Highlights.AddItemAsync(summer.Id, story.Stored.Entry.Id);
}
await using var ui = await UiBrowser.StartAsync();
await ui.AddInitScriptAsync(UiBrowser.Requests);
await ui.AddInitScriptAsync(PageTimers);
await ui.OpenAsync(new Uri(server.Address, $"/account/{account.Id}?tipo=evidenza"));
await ui.WaitAsync("document.querySelector('main .raccolta-titolo') !== null", "raccolte in evidenza");
// «Post» after «In evidenza»: the posts stay, also once what «In evidenza» left pending has run (it redraws
// itself 150 ms after a change of size, and it has just been drawn).
await ui.EvalAsync("""
(() => {
window.__pendingAtSwitch = window.__timers();
document.querySelectorAll('.strumenti .filtri button')[0].click();
return true;
})()
""");
await ui.WaitAsync("document.querySelector('main .mosaico .gruppo-giorno') !== null", "mosaico dei post");
await ui.WaitAsync("window.__timersOver(window.__pendingAtSwitch)", "attese di «In evidenza» finite");
await AssertPostsShownAsync(ui);
// The area changes size. The page's own observers see it before this one, which came last: what they left
// pending then (a redraw, a frame) runs, and the posts are still there.
await ui.EvalAsync("""
(() => {
let before = null;
window.__afterResize = null;
new ResizeObserver((entries, observer) => {
const width = entries[0].contentRect.width;
if (before === null) {
before = width;
return;
}
if (Math.abs(width - before) < 1) return;
observer.disconnect();
const pending = window.__timers();
requestAnimationFrame(() => { window.__afterResize = pending; });
}).observe(document.querySelector('main .corpo > div'));
window.__resizeWatched = () => before !== null;
return true;
})()
""");
await ui.WaitAsync("window.__resizeWatched()", "dimensione dei contenuti osservata");
await ui.SendAsync("Emulation.setDeviceMetricsOverride", new JsonObject { ["width"] = 1100, ["height"] = 900, ["deviceScaleFactor"] = 1, ["mobile"] = false });
await ui.WaitAsync("window.__afterResize !== null && window.__timersOver(window.__afterResize)", "contenuti ridisegnati alla nuova larghezza");
await AssertPostsShownAsync(ui);
// «In evidenza» and at once «Post», while the tiles of the collections are still loading: they come after the
// posts are drawn.
await ui.EvalAsync("""
(() => {
window.__hold('/api/library/tiles');
const chips = document.querySelectorAll('.strumenti .filtri button');
chips[2].click();
chips[0].click();
return true;
})()
""");
await ui.WaitAsync("window.__started['/api/library/tiles'] >= 1 && document.querySelector('main .mosaico .gruppo-giorno') !== null", "mosaico dei post");
await ui.EvalAsync("window.__release('/api/library/tiles')");
await ui.WaitAsync("window.__done['/api/library/tiles'] >= 1", "tessere delle raccolte arrivate in ritardo");
await AssertPostsShownAsync(ui);
}
[TestMethod]
public async Task AStaleAnswerOfTheLibraryDoesNotHideTheNewFilter()
{
await using var server = await WebTestServer.StartAsync();
await server.AddAccountWithEntriesAsync("anna.prova", 5, Make.T0, TimeSpan.FromHours(30));
await using var ui = await UiBrowser.StartAsync();
await ui.AddInitScriptAsync(UiBrowser.Requests);
await ui.OpenAsync(new Uri(server.Address, "/libreria"));
await ui.WaitAsync("document.querySelector('main .mosaico .gruppo-giorno .tess') !== null", "mosaico");
// «Storie» (nothing: an empty answer, late) and at once «Foto»: the stories answer after the photos are drawn.
await ui.EvalAsync("""
(() => {
window.__hold('kind=stories');
const chips = document.querySelectorAll('.strumenti .filtri button');
chips[3].click();
chips[1].click();
return true;
})()
""");
await ui.WaitAsync("window.__started['kind=stories'] >= 1 && document.querySelector('main .mosaico .gruppo-giorno .tess') !== null", "foto");
await ui.EvalAsync("window.__release('kind=stories')");
await ui.WaitAsync("window.__done['kind=stories'] >= 1", "risposta delle storie arrivata in ritardo");
Assert.IsTrue((await ui.EvalAsync("location.search.includes('tipo=foto')")).GetBoolean());
Assert.IsTrue((await ui.EvalAsync("document.querySelector('main .mosaico .gruppo-giorno .tess') !== null")).GetBoolean(), "the photos are shown " + ui.Report());
Assert.IsTrue((await ui.EvalAsync("document.querySelector('main .vuoto-pagina') === null")).GetBoolean(), "no empty state over the results");
StringAssert.StartsWith((await ui.EvalAsync("document.querySelector('.testa .quanti').textContent")).GetString(), "5 ");
}
[TestMethod]
public async Task NewEntriesAppearAfterTheEmptyLibrary()
{
await using var server = await WebTestServer.StartAsync();
await using var ui = await UiBrowser.StartAsync();
await ui.OpenAsync(new Uri(server.Address, "/libreria"));
await ui.WaitAsync("document.querySelector('main .vuoto-pagina, main .benvenuto') !== null", "libreria vuota (primo avvio)");
var account = await server.AddAccountWithEntriesAsync("primo.prova", 4, Make.T0, TimeSpan.FromHours(10));
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(30);
var shown = false;
while (!shown && DateTime.UtcNow < deadline)
{
server.Changes.Publish(new LibraryChange(server.Clock.Now, account.Id, "stored"));
await Task.Delay(700);
shown = (await ui.EvalAsync("document.querySelector('main .mosaico .gruppo-giorno') !== null")).GetBoolean();
}
Assert.IsTrue(shown, "the new entries appear at the top (spec §10.3) " + ui.Report());
Assert.IsTrue((await ui.EvalAsync("document.querySelector('main .vuoto-pagina, main .benvenuto') === null")).GetBoolean(), "the empty state goes away");
await ui.WaitAsync("document.querySelector('main .mosaico .tess') !== null", "tessere disegnate");
}
[TestMethod]
public async Task TheEmptyLibraryFollowsTheConnectionAlsoWhenTheEngineAnswersLate()
{
await using var server = await WebTestServer.StartAsync();
await using var ui = await UiBrowser.StartAsync();
await ui.AddInitScriptAsync(HoldEngine);
await ui.OpenAsync(new Uri(server.Address, "/libreria"));
// The library answered first (empty: its count and its empty state come together) and nothing says yet whether
// Febe is connected: the page waits blank, neither the empty library nor the welcome, and not the mosaic.
await ui.WaitAsync("document.querySelector('main [aria-busy=true]') !== null", "libreria vuota in attesa del motore");
Assert.IsTrue((await ui.EvalAsync("import('/js/core/engine.js').then((m) => m.engineState() === null)")).GetBoolean(), "the engine has not answered yet");
Assert.IsTrue((await ui.EvalAsync("document.querySelector('main .vuoto-pagina, main .benvenuto, main .mosaico') === null")).GetBoolean(), "no empty state is guessed " + ui.Report());
StringAssert.StartsWith((await ui.EvalAsync("document.querySelector('.testa .quanti').textContent")).GetString(), "0 ");
// Not connected (no own account): the first start with its two ways to begin (spec §10.3).
await ui.EvalAsync("window.__releaseEngine()");
await ui.WaitAsync("document.querySelector('main .benvenuto') !== null && document.querySelector('main [aria-busy=true]') === null", "primo avvio dopo la risposta del motore");
// Connected now (the own account is known): the welcome gives way to the empty library.
await server.Db.Accounts.AddAsync(Make.Account("tuo.profilo", mine: true));
await ui.EvalAsync("import('/js/core/engine.js').then((m) => m.refreshEngine()).then(() => true)");
await ui.WaitAsync("document.querySelector('main .benvenuto') === null && document.querySelector('main .vuoto-pagina h2') !== null", "libreria vuota da collegato");
Assert.AreEqual("La libreria è ancora vuota", (await ui.EvalAsync("document.querySelector('main .vuoto-pagina h2').textContent")).GetString());
}
[TestMethod]
public async Task TheAccountHeaderFollowsEveryMenuAction()
{
await using var server = await WebTestServer.StartAsync();
var account = await server.AddAccountWithEntriesAsync("luca.prova", 2, Make.T0, TimeSpan.FromHours(10));
await using var ui = await UiBrowser.StartAsync();
await ui.OpenAsync(new Uri(server.Address, $"/account/{account.Id}"));
await ui.WaitAsync("document.querySelector('.scheda-testa h1') !== null", "scheda");
foreach (var (choice, next) in new[] { ("Metti in pausa", "Riattiva"), ("Riattiva", "Metti in pausa"), ("Metti in pausa", "Riattiva") })
{
await ui.EvalAsync("document.querySelector('.scheda-testa .azioni button[aria-haspopup]').click()");
await ui.WaitAsync("document.querySelector('.menu') !== null", "menu");
await ui.EvalAsync($$"""
(() => {
const item = [...document.querySelectorAll('.menu button')].find((b) => b.textContent.trim() === '{{choice}}');
if (!item) throw new Error('voce mancante: {{choice}} in ' + document.querySelector('.menu').textContent);
item.click();
return true;
})()
""");
// The header (and its menu) is drawn again with the new state of the account.
await ui.WaitAsync(
$$"""
(async () => {
document.querySelector('.scheda-testa .azioni button[aria-haspopup]').click();
const menu = document.querySelector('.menu');
const ok = Boolean(menu) && [...menu.querySelectorAll('button')].some((b) => b.textContent.trim() === '{{next}}');
(await import('/js/core/ui.js')).closeMenu();
return ok;
})()
""",
$"intestazione aggiornata dopo «{choice}»");
}
}
// ------------------------------------------------------------------------------------------ shell
[TestMethod]
public async Task TheBackButtonAsksBeforeLosingUnsavedChanges()
{
await using var server = await WebTestServer.StartAsync();
await using var ui = await UiBrowser.StartAsync();
await ui.OpenAsync(new Uri(server.Address, "/libreria"));
await ui.NavigateAsync("/impostazioni/limiti");
await ui.WaitAsync("document.querySelector('.cerchio-giorno') !== null", "Limiti");
await ui.EvalAsync("document.querySelector('.cerchio-giorno').click()");
await ui.WaitAsync("!document.querySelector('.salva').hidden", "modifiche da salvare");
await ui.EvalAsync("history.back()");
await ui.WaitAsync("document.querySelector('.dialogo') !== null", "«Modifiche non salvate» con il pulsante Indietro");
await ui.EvalAsync("[...document.querySelectorAll('.dialogo footer button')].find((b) => b.textContent === 'Annulla').click()");
await ui.WaitAsync("document.querySelector('.dialogo') === null", "dialogo chiuso");
Assert.AreEqual("/impostazioni/limiti", (await ui.EvalAsync("location.pathname")).GetString());
Assert.IsTrue((await ui.EvalAsync("!document.querySelector('.salva').hidden && document.querySelector('.cerchio-giorno') !== null")).GetBoolean(), "the edits are still there");
await ui.EvalAsync("history.back()");
await ui.WaitAsync("document.querySelector('.dialogo') !== null", "di nuovo il dialogo");
await ui.EvalAsync("[...document.querySelectorAll('.dialogo footer button')].find((b) => b.textContent === 'Lascia le modifiche').click()");
// The Libreria drawn to its end, not its empty mosaic of the first milliseconds: this library is empty and Febe
// is not connected, so it ends on the welcome of the first start (spec §10.3).
await ui.WaitAsync("location.pathname === '/libreria' && document.querySelector('main .benvenuto') !== null", "Libreria (primo avvio)");
Assert.IsTrue((await ui.EvalAsync("document.querySelector('.dialogo') === null && document.querySelector('.cerchio-giorno') === null && document.querySelector('.salva').hidden")).GetBoolean(), "Limiti and its edits are gone");
}
[TestMethod]
public async Task APageLeftWhileLoadingLeavesNothingBehind()
{
await using var server = await WebTestServer.StartAsync();
await using var ui = await UiBrowser.StartAsync();
await ui.AddInitScriptAsync(UiBrowser.Requests);
await ui.AddInitScriptAsync("""
(() => {
const live = new Map();
const set = window.setInterval.bind(window);
const clear = window.clearInterval.bind(window);
window.setInterval = (fn, ms, ...rest) => { const id = set(fn, ms, ...rest); live.set(id, ms); return id; };
window.clearInterval = (id) => { live.delete(id); clear(id); };
window.__intervals = (ms) => [...live.values()].filter((v) => v === ms).length;
})();
""");
await ui.OpenAsync(new Uri(server.Address, "/libreria"));
// Attività waits for its alerts and Alberto goes back to the Libreria before they come. Issue #8: going back
// after a fixed 200 ms, a slow machine had not even loaded the page yet, and the alerts were never asked.
await ui.EvalAsync("window.__hold('/api/alerts')");
await ui.NavigateAsync("/attivita");
await ui.WaitAsync("window.__started['/api/alerts'] >= 1", "Attività in attesa dei suoi avvisi");
await ui.NavigateAsync("/libreria");
await ui.WaitAsync("location.pathname === '/libreria' && document.querySelector('main .benvenuto') !== null", "Libreria (primo avvio)");
await ui.EvalAsync("window.__release('/api/alerts')");
await ui.WaitAsync("window.__done['/api/alerts'] >= 1", "risposta in ritardo arrivata");
Assert.AreEqual(0, (await ui.EvalAsync("window.__intervals(60000)")).GetInt32(), "the minute timer of Attività is gone with its page");
Assert.IsTrue((await ui.EvalAsync("document.querySelector('main .attivita') === null && document.querySelector('main .benvenuto') !== null")).GetBoolean(), "nothing of Attività drawn over the Libreria " + ui.Report());
// The page that stays open still works as usual.
await ui.NavigateAsync("/attivita");
await ui.WaitAsync("window.__intervals(60000) === 1", "Attività aperta");
await ui.NavigateAsync("/libreria");
await ui.WaitAsync("window.__intervals(60000) === 0", "Attività lasciata");
}
[TestMethod]
public async Task TheWindowBarHandleFollowsTheWholeDrag()
{
await using var server = await WebTestServer.StartAsync();
await using var ui = await UiBrowser.StartAsync();
await ui.OpenAsync(new Uri(server.Address, "/impostazioni/limiti"));
await ui.WaitAsync("document.querySelector('.fascia-barra .maniglia') !== null", "barra della fascia");
var (barX, barY, barWidth, _) = await ui.BoxAsync(".fascia-barra");
var handle = await ui.EvalAsync("(() => { const r = document.querySelector('.fascia-barra .maniglia').getBoundingClientRect(); return [r.left + r.width / 2, r.top + r.height / 2]; })()");
var (handleX, handleY) = (handle[0].GetDouble(), handle[1].GetDouble());
var left = barX - (barWidth / 2);
string TimeAt(double at)
{
var minutes = (int)(Math.Round((at - left) / barWidth * 1440 / 15) * 15);
return $"{minutes / 60:00}:{minutes % 60:00}";
}
await ui.MouseAsync("mouseMoved", handleX, handleY);
await ui.MouseAsync("mousePressed", handleX, handleY, buttons: 1);
var x = handleX;
foreach (var ratio in new[] { 0.30, 0.34, 0.38, 0.42, 0.46 })
{
// Each step is followed before the next one moves: a handle drawn again would lose the drag after the
// first step, and steps sent together may reach the page as one move.
x = left + (barWidth * ratio);
await ui.MouseAsync("mouseMoved", x, barY, buttons: 1);
var step = TimeAt(x);
await ui.WaitAsync($"document.querySelector('#fascia-inizio').value === '{step}'", $"inizio della fascia a {step} durante il trascinamento");
}
await ui.MouseAsync("mouseReleased", x, barY);
var expected = TimeAt(x);
await ui.WaitAsync($"document.querySelector('#fascia-inizio').value === '{expected}'", $"inizio della fascia a {expected}");
}
[TestMethod]
public async Task TheStatusBoxDoesNotShowANameItDoesNotKnow()
{
var monitor = new FixedMonitor(EngineMode.StoppedForVerification);
await using var server = await WebTestServer.StartAsync(services: s => s.AddSingleton<IEngineMonitor>(monitor));
await using var ui = await UiBrowser.StartAsync();
await ui.OpenAsync(new Uri(server.Address, "/libreria"));
await ui.WaitAsync("document.querySelector('.stato .chi') !== null", "riquadro di stato");
var text = (await ui.EvalAsync("document.querySelector('.stato .chi').textContent")).GetString()!;
Assert.DoesNotContain("@", text, "no handle before the first sweep learns it: " + text);
StringAssert.Contains(text, "Verifica richiesta");
}
// ------------------------------------------------------------------------------------------ helpers
private static Task<WebTestServer> DockerAsync(RecordingConnection connection, FakeRemoteViewHost view, IEngineMonitor? engine = null) =>
Part2.StartAsync(FebeEdition.Docker, s =>
{
s.AddSingleton<IConnectionService>(connection);
s.AddSingleton<IRemoteViewHost>(view);
if (engine is not null)
{
s.AddSingleton(engine);
}
});
private static List<RemoteViewKey> Keys(FakeRemoteViewConnection view) => [.. view.Inputs.OfType<RemoteViewKey>()];
private static List<RemoteViewMouse> Mice(FakeRemoteViewConnection view) => [.. view.Inputs.OfType<RemoteViewMouse>()];
private static string Describe(IEnumerable<RemoteViewKey> keys) =>
string.Join(", ", keys.Select(k => $"{k.Action}:{k.Key}:{k.Text ?? "∅"}:{k.Modifiers}"));
private static async Task AssertPostsShownAsync(UiBrowser ui)
{
Assert.IsTrue((await ui.EvalAsync("document.querySelector('main .raccolta-titolo') === null")).GetBoolean(), "the collections are gone " + ui.Report());
Assert.IsTrue((await ui.EvalAsync("document.querySelector('main .mosaico .gruppo-giorno') !== null")).GetBoolean(), "the posts are shown " + ui.Report());
Assert.IsTrue((await ui.EvalAsync("document.querySelector('.strumenti .filtri button[aria-pressed=true]').textContent.startsWith('Post')")).GetBoolean());
}
/// <summary>An engine in the mode the test sets; stopped for a verification it shows the red strip.</summary>
private sealed class FixedMonitor(EngineMode mode) : IEngineMonitor
{
public EngineMode Mode { get; set; } = mode;
public Task<EngineSnapshot> GetSnapshotAsync(CancellationToken ct = default)
{
var snapshot = SnapshotParts.Build(new ManualClock(Make.T0), Mode, "Fermo", ["In attesa che tu completi la verifica"], "Serve il tuo intervento", CautionProfile.Prudent);
return Task.FromResult(Mode == EngineMode.StoppedForVerification
? snapshot with { Banner = new StopBanner(BannerLevel.Error, "Instagram chiede una verifica", "Ho fermato tutto e non riparto da solo.", true) }
: snapshot);
}
public async IAsyncEnumerable<EngineNotification> SubscribeAsync([EnumeratorCancellation] CancellationToken ct = default)
{
await Task.Delay(Timeout.Infinite, ct);
yield break;
}
}
}