Files
Febe/tests/Febe.Tests/Web/InterfaceTests.cs
T
Alby96andClaude Opus 5.5 fbb9e602b9 Prove dell'interfaccia: il pulsante Indietro aspetta la Libreria finita, non il suo mosaico vuoto (issue #5)
TheBackButtonAsksBeforeLosingUnsavedChanges, dopo «Lascia le modifiche», aspettava
«main .vuoto-pagina, main .mosaico». Una libreria vuota con Febe non collegato (il server
di prova: motore spento, nessun account proprio) finisce però sul benvenuto del primo
avvio (.benvenuto, §10.3); .mosaico c'è solo nei millisecondi fra la costruzione del
mosaico e la risposta di /api/library/days. La prova passava quando il primo controllo
cadeva in quella finestra (circa 10 ms, misurati con Chrome) e falliva per 30 secondi
quando arrivava un poco dopo, come nella esecuzione 19 della CI. Con il primo controllo
ritardato di 5 ms o più falliva sempre; con la nuova condizione 16 su 16.

Ora aspetta il benvenuto e controlla che il dialogo e la pagina Limiti non ci siano più.
Il prodotto non c'entra: «Lascia le modifiche» torna alla Libreria anche con la pagina lenta.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 20:32:37 +02:00

557 lines
32 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 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/");
// ------------------------------------------------------------------------------------------ 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.FetchDelays);
await ui.OpenAsync(new Uri(server.Address, "/libreria"));
// The status of the connection answers late; Alberto is already elsewhere.
await ui.EvalAsync("""
import('/js/core/shell.js').then((m) => {
window.__delays.push({ match: '/api/connection', ms: 600 });
m.navigate('/browser');
setTimeout(() => m.navigate('/libreria'), 150);
return true;
})
""");
await ui.WaitAsync("location.pathname === '/libreria'", "Libreria");
await ui.WaitAsync("window.__done['/api/connection'] >= 1", "risposta in ritardo arrivata");
await Task.Delay(300);
Assert.IsEmpty(connection.Snapshot(), "nothing taken by a page that is gone");
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.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");
await Task.Delay(500);
CollectionAssert.AreEqual(new[] { "begin:False", "finish" }, connection.Snapshot(), "«Ho finito» already gave the browser back");
}
[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.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 Task.Delay(500);
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.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»");
await Task.Delay(500);
CollectionAssert.AreEqual(new[] { "begin:False", "finish" }, connection.Snapshot(), "no new lease after «Ho finito»");
Assert.HasCount(1, view.Opened, "no new view after «Ho finito»");
// «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.WaitForAsync(() => connection.Snapshot().Length == 4, "il browser restituito lasciando la pagina");
CollectionAssert.AreEqual(new[] { "begin:False", "finish", "begin:False", "cancel" }, connection.Snapshot());
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.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 Task.Delay(300);
CollectionAssert.AreEqual(new[] { "begin:False", "finish" }, connection.Snapshot());
Assert.IsTrue(view.Opened.All(v => v.Disposed));
}
// ------------------------------------------------------------------------------------------ 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.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");
await Task.Delay(300);
// 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();
await Task.Delay(300);
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.FetchDelays);
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 when the area changes size.
await ui.EvalAsync("document.querySelectorAll('.strumenti .filtri button')[0].click()");
await ui.WaitAsync("document.querySelector('main .mosaico .gruppo-giorno') !== null", "mosaico dei post");
await Task.Delay(500);
await ui.SendAsync("Emulation.setDeviceMetricsOverride", new JsonObject { ["width"] = 1100, ["height"] = 900, ["deviceScaleFactor"] = 1, ["mobile"] = false });
await Task.Delay(600);
await AssertPostsShownAsync(ui);
// «In evidenza» and at once «Post», while the tiles of the collections are still loading.
await ui.EvalAsync("""
(() => {
window.__delays.push({ match: '/api/library/tiles', ms: 600 });
const chips = document.querySelectorAll('.strumenti .filtri button');
chips[2].click();
chips[0].click();
return true;
})()
""");
await ui.WaitAsync("window.__done['/api/library/tiles'] >= 1", "tessere delle raccolte arrivate in ritardo");
await ui.WaitAsync("document.querySelector('main .mosaico .gruppo-giorno') !== null", "mosaico dei post");
await Task.Delay(400);
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.FetchDelays);
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».
await ui.EvalAsync("""
(() => {
window.__delays.push({ match: 'kind=stories', ms: 700 });
const chips = document.querySelectorAll('.strumenti .filtri button');
chips[3].click();
chips[1].click();
return true;
})()
""");
await ui.WaitAsync("document.querySelector('main .mosaico .gruppo-giorno .tess') !== null", "foto");
await ui.WaitAsync("window.__done['kind=stories'] >= 1", "risposta delle storie arrivata in ritardo");
await Task.Delay(300);
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 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}»");
await Task.Delay(200);
}
}
// ------------------------------------------------------------------------------------------ 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.FetchDelays);
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"));
await ui.EvalAsync("""
import('/js/core/shell.js').then((m) => {
window.__delays.push({ match: '/api/alerts', ms: 600 });
m.navigate('/attivita');
setTimeout(() => m.navigate('/libreria'), 200);
return true;
})
""");
await ui.WaitAsync("location.pathname === '/libreria'", "Libreria");
await ui.WaitAsync("window.__done['/api/alerts'] >= 1", "risposta in ritardo arrivata");
await Task.Delay(300);
Assert.AreEqual(0, (await ui.EvalAsync("window.__intervals(60000)")).GetInt32(), "the minute timer of Attività is gone with its page");
// 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);
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 })
{
x = left + (barWidth * ratio);
await ui.MouseAsync("mouseMoved", x, barY, buttons: 1);
await Task.Delay(60);
}
await ui.MouseAsync("mouseReleased", x, barY);
var minutes = (int)(Math.Round((x - left) / barWidth * 1440 / 15) * 15);
var expected = $"{minutes / 60:00}:{minutes % 60:00}";
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;
}
}
}