using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Text.Json;
using Febe.Core.Abstractions;
using Febe.Core.Collection.Search;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Tests.Support;
using Febe.Tests.Web.Support;
using Febe.Web.Engine;
using Microsoft.Extensions.DependencyInjection;
namespace Febe.Tests.Web;
///
/// The «Aggiungi account» dialog with its one search box (issue #37), in a real headless Chromium against a test server
/// with a scripted search: the profiles Alberto follows show at once, Instagram's results come after and merge without
/// doubles, photos swap in when Febe has them, the keyboard adds a row, Esc closes only the list, pasting several names
/// fills «Da aggiungere», and while Alberto drives the browser the dialog says so. The page only ever asks Febe.
///
[TestClass]
[DoNotParallelize]
public sealed class ProfileSearchInterfaceTests
{
private const string Box = "document.querySelector('.aggiungi input[role=combobox]')";
[TestMethod]
public async Task FollowedProfilesShowAtOnceThenInstagramsResultsWithTheirPhotos()
{
var search = new ScriptedSearch();
await using var server = await WebTestServer.StartAsync(services: s => s.AddSingleton(search));
await SeedAsync(server);
await using var ui = await UiBrowser.StartAsync();
await ui.AddInitScriptAsync(UiBrowser.Requests);
await OpenDialogAsync(ui, server);
// Instagram's answer waits: the followed profiles and the accounts in Febe are there before it.
await ui.EvalAsync("window.__hold('/api/ricerca')");
await TypeAsync(ui, "mar");
await ui.WaitAsync("window.__started['/api/ricerca'] >= 1", "testo mandato a Febe");
await ui.WaitAsync(Rows("@marta.rossi") + " === 1 && " + Rows("@mario.bianchi") + " === 1 && " + Rows("@marco.archivio") + " === 1", "suggerimenti locali subito");
Assert.AreEqual(0, (await ui.EvalAsync("window.__done['/api/ricerca'] || 0")).GetInt32(), "the local rows came before the answer");
StringAssert.Contains(await TextAsync(ui, ".suggerimenti"), "Cerco su Instagram");
StringAssert.Contains(await TextAsync(ui, ".suggerimenti"), "Già in Febe");
await ui.EvalAsync("window.__release('/api/ricerca')");
await ui.WaitForAsync(() => search.Texts.Contains("mar"), "testo arrivato al server");
search.Answer(
new SearchHit(0, "11", "marta.rossi", "Marta Rossi", false, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", false),
new SearchHit(1, "99", "mara.nuova", "Mara Nuova", true, "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", false));
await ui.WaitAsync(Rows("@mara.nuova") + " === 1", "risultato di Instagram");
Assert.AreEqual(1, (await ui.EvalAsync(Rows("@marta.rossi"))).GetInt32(), "a followed profile found on Instagram is shown once");
StringAssert.Contains(await TextAsync(ui, ".suggerimenti"), "Da Instagram");
// The photo replaces the initials once Febe has it.
search.PhotosReady();
await ui.WaitAsync(
"[...document.querySelectorAll('.suggerimenti [role=option]')].some((r) => r.textContent.includes('@mara.nuova') && [...r.querySelectorAll('.av img')].some((i) => i.complete && i.naturalWidth > 0))",
"foto del risultato");
// Keyboard: down to the Instagram result, Enter adds it; Esc closes the list and not the dialog.
for (var i = 0; i < 8; i++)
{
var current = await ui.EvalAsync($"(() => {{ const id = {Box}.getAttribute('aria-activedescendant'); return id ? document.getElementById(id).textContent : ''; }})()");
if (current.GetString()!.Contains("@mara.nuova", StringComparison.Ordinal))
{
break;
}
await KeyAsync(ui, "ArrowDown");
}
await KeyAsync(ui, "Enter");
await ui.WaitAsync("document.querySelector('.aggiungi .scelti').textContent.includes('@mara.nuova')", "aggiunto a «Da aggiungere»");
await KeyAsync(ui, "Escape");
await ui.WaitAsync("document.querySelector('.suggerimenti').hidden && document.querySelector('.aggiungi') !== null", "solo l'elenco chiuso");
// The page asked only Febe: every resource (fetches and photos) on its own address, the search by POST and polls.
Assert.IsTrue((await ui.EvalAsync("performance.getEntriesByType('resource').every((e) => new URL(e.name).origin === location.origin)")).GetBoolean());
var asked = await ui.AskedAsync("/api/ricerca");
Assert.IsTrue(asked.All(r => r == "POST /api/ricerca" || r.StartsWith("GET /api/ricerca?client=", StringComparison.Ordinal)), string.Join(", ", asked));
// Added with the identifier of the result the server holds.
await ui.EvalAsync("document.querySelector('.aggiungi footer .btn.primo').click()");
await ui.WaitAsync("document.querySelector('.aggiungi') === null", "dialogo chiuso dopo l'aggiunta");
var added = await server.Db.Accounts.FindByUsernameAsync("mara.nuova");
Assert.AreEqual("99", added?.InstagramId);
await ui.WaitForAsync(() => search.Ended > 0, "ricerca chiusa con il dialogo");
}
[TestMethod]
public async Task PastedNamesGoToTheListWhileATypedNameIsSearched()
{
var search = new ScriptedSearch();
await using var server = await WebTestServer.StartAsync(services: s => s.AddSingleton(search));
await SeedAsync(server);
await using var ui = await UiBrowser.StartAsync();
await ui.AddInitScriptAsync(UiBrowser.Requests);
await OpenDialogAsync(ui, server);
await ui.EvalAsync($$"""
(() => {
const data = new DataTransfer();
data.setData('text/plain', 'uno.nome\n@due.nome, instagram.com/tre.nome/\nmarta.rossi');
{{Box}}.focus();
{{Box}}.dispatchEvent(new ClipboardEvent('paste', { clipboardData: data, bubbles: true, cancelable: true }));
return true;
})()
""");
await ui.WaitAsync("['@uno.nome', '@due.nome', '@tre.nome', '@marta.rossi'].every((n) => document.querySelector('.aggiungi .scelti').textContent.includes(n))", "nomi incollati da aggiungere");
Assert.AreEqual("Aggiungi 4 account", (await TextAsync(ui, ".aggiungi footer .btn.primo")).Trim());
Assert.HasCount(1, await ui.AskedAsync("POST /api/accounts/parse"));
Assert.IsEmpty(await ui.AskedAsync("POST /api/ricerca"), "several names are never searched on Instagram");
// A name with a space is a search, not two names.
await TypeAsync(ui, "mario rossi");
await ui.WaitForAsync(() => search.Texts.Contains("mario rossi"), "ricerca di «mario rossi»");
Assert.IsFalse(search.Texts.Any(t => t.Contains('\n', StringComparison.Ordinal) || t.Contains(',', StringComparison.Ordinal)));
// The × takes a name away.
await ui.EvalAsync("document.querySelector('.aggiungi .scelti .voce.scelto button').click()");
await ui.WaitAsync("document.querySelector('.aggiungi footer .btn.primo').textContent.trim() === 'Aggiungi 3 account'", "un nome tolto");
}
[TestMethod]
public async Task WhileAlbertoUsesTheBrowserTheDialogSaysSoAndLocalSuggestionsWork()
{
var search = new ScriptedSearch { State = SearchState.NotPossible, Message = "Stai usando il browser di Febe: la ricerca su Instagram riprende quando hai finito." };
await using var server = await WebTestServer.StartAsync(services: s =>
{
s.AddSingleton(search);
s.AddSingleton(new DrivingMonitor());
});
await SeedAsync(server);
await using var ui = await UiBrowser.StartAsync();
await ui.AddInitScriptAsync(UiBrowser.Requests);
await OpenDialogAsync(ui, server);
await ui.WaitAsync("document.querySelector('.stato') !== null && document.querySelector('.stato').textContent.includes('Stai usando il browser')", "motore al volante");
await ui.EvalAsync("window.__hold('/api/ricerca')");
await TypeAsync(ui, "mar");
await ui.WaitAsync(Rows("@marta.rossi") + " === 1", "suggerimenti locali");
await ui.WaitAsync("document.querySelector('.suggerimenti').textContent.includes('Stai usando il browser di Febe')", "avviso subito, prima della risposta");
// The page sends the text after its debounce: release only once that request is held, or it would pass uncounted.
await ui.WaitAsync("window.__asked.includes('POST /api/ricerca') && window.__started['/api/ricerca'] >= 1", "testo mandato a Febe");
await ui.EvalAsync("window.__release('/api/ricerca')");
await ui.WaitAsync("window.__done['/api/ricerca'] >= 1", "risposta arrivata");
await ui.WaitAsync($"document.querySelector('.suggerimenti .stato-remoto').textContent === {JsonSerializer.Serialize(search.Message)}", "messaggio del server");
Assert.AreEqual(1, (await ui.EvalAsync(Rows("@marta.rossi"))).GetInt32());
}
// ------------------------------------------------------------------------------------------ helpers
private static async Task SeedAsync(WebTestServer server)
{
await server.Db.Following.UpsertAsync(
[
new FollowingRecord { InstagramId = "11", Username = "marta.rossi", DisplayName = "Marta Rossi", IsPrivate = true, Position = 0, ReadAt = server.Clock.Now },
new FollowingRecord { InstagramId = "12", Username = "mario.bianchi", DisplayName = "Mario Bianchi", Position = 1, ReadAt = server.Clock.Now },
new FollowingRecord { InstagramId = "13", Username = "luca.verdi", DisplayName = "Luca Verdi", Position = 2, ReadAt = server.Clock.Now },
]);
await server.Db.Accounts.AddAsync(Make.Account("marco.archivio") with { InstagramId = "14", DisplayName = "Marco" });
}
private static async Task OpenDialogAsync(UiBrowser ui, WebTestServer server)
{
await ui.OpenAsync(new Uri(server.Address, "/account?dialogo=aggiungi"));
await ui.WaitAsync($"{Box} !== null && document.querySelector('.aggiungi .scelti-testa .btn.collegamento').textContent.includes('(3)')", "dialogo con l'elenco dei seguiti");
}
private static Task TypeAsync(UiBrowser ui, string text) =>
ui.EvalAsync($"(() => {{ const b = {Box}; b.focus(); b.value = {JsonSerializer.Serialize(text)}; b.dispatchEvent(new Event('input', {{ bubbles: true }})); return true; }})()");
private static Task KeyAsync(UiBrowser ui, string key) =>
ui.EvalAsync($"{Box}.dispatchEvent(new KeyboardEvent('keydown', {{ key: {JsonSerializer.Serialize(key)}, bubbles: true, cancelable: true }}))");
private static string Rows(string text) =>
$"[...document.querySelectorAll('.suggerimenti [role=option]')].filter((r) => r.querySelector('b') && r.querySelector('b').textContent === {JsonSerializer.Serialize(text)}).length";
private static async Task TextAsync(UiBrowser ui, string selector) =>
(await ui.EvalAsync($"document.querySelector({JsonSerializer.Serialize(selector)}).textContent")).GetString() ?? string.Empty;
/// A search the test drives: the state of the next texts, then the answer and the photos when it says.
private sealed class ScriptedSearch : IProfileSearch
{
private readonly Lock _gate = new();
private SearchView _view = SearchView.Initial;
public SearchState State { get; init; } = SearchState.Searching;
public string? Message { get; init; }
public List Texts { get; } = [];
public int Ended { get; private set; }
public SearchView Current
{
get
{
lock (_gate)
{
return _view;
}
}
}
public SearchView Update(string client, string text)
{
lock (_gate)
{
Texts.Add(text);
var query = SearchText.Normalize(text);
_view = new SearchView(_view.Version + 1, client, query.Typed, query.Kind == SearchQueryKind.Typable ? State : SearchState.LocalOnly, Message, [], null);
return _view;
}
}
public void Answer(params SearchHit[] hits)
{
lock (_gate)
{
_view = _view with { Version = _view.Version + 1, State = SearchState.Ready, Hits = hits };
}
}
public void PhotosReady()
{
lock (_gate)
{
_view = _view with { Version = _view.Version + 1, Hits = [.. _view.Hits.Select(h => h with { PhotoReady = true })] };
}
}
public void End(string client)
{
lock (_gate)
{
Ended++;
}
}
public SearchHit? Known(string username)
{
lock (_gate)
{
return _view.Hits.FirstOrDefault(h => h.Username == username);
}
}
public bool TryOpenPhoto(string key, [NotNullWhen(true)] out Stream? stream)
{
lock (_gate)
{
stream = _view.Hits.Any(h => h.PhotoReady && h.PhotoKey == key)
? new MemoryStream(Febe.Web.Demo.DemoImages.Render(Febe.Web.Demo.DemoSubject.Portrait, 7, 32, 32))
: null;
return stream is not null;
}
}
}
/// An engine while Alberto uses the browser.
private sealed class DrivingMonitor : IEngineMonitor
{
public Task GetSnapshotAsync(CancellationToken ct = default) =>
Task.FromResult(SnapshotParts.Build(new ManualClock(Make.T0), EngineMode.UserDriving, "Stai usando il browser", ["Il motore resta fermo finché non hai finito."], "Stai usando il browser", CautionProfile.Prudent));
public async IAsyncEnumerable SubscribeAsync([EnumeratorCancellation] CancellationToken ct = default)
{
await Task.Delay(Timeout.Infinite, ct);
yield break;
}
}
}