Ricerca dei profili con suggerimenti e foto (#37)
«Aggiungi account» ha una sola casella: mentre Alberto scrive compaiono subito i suggerimenti locali, poi i profili di Instagram con la foto, come chiesto in #37. Il browser di Febe scrive nella casella «Cerca» di Instagram con tasti veri da una mappa chiusa (mai Invio, Tab o Esc), controlla prima il fuoco, legge la risposta della pagina e non clicca mai un risultato. La ricerca ha una categoria propria nel Governatore, con tetti larghi che non consumano quelli della raccolta, e si dà il turno con il motore sull'unica pagina; a fine sessione la pagina torna comunque al riposo. Le foto passano dal CDN con un permesso ciascuna e restano solo in memoria. Le risposte di Alberto del 15 novembre (controllo del fuoco, turni, evento requestWillBeSent, niente foto dei seguiti per ora) sono in §6.1 e in docs/decisioni.md. Su Instagram vero la ricerca parte quando i bersagli search-open e search-box saranno raccolti dal vivo. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
5e417c666d
commit
9941a2fa1f
98 files changed
+8021
-229
No files matched your search
@@ -260,6 +260,51 @@ public sealed class DemoTests
|
||||
Assert.IsFalse(string.IsNullOrWhiteSpace(body.RootElement.Str("message")));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheSearchOfTheDemoFindsProfilesWithDrawnPhotos()
|
||||
{
|
||||
var origin = $"{Demo.Address.Scheme}://{Demo.Address.Authority}";
|
||||
async Task<JsonElement> PostAsync(string text, string scene = "normale")
|
||||
{
|
||||
using var request = new HttpRequestMessage(HttpMethod.Post, $"/api/ricerca?scena={scene}")
|
||||
{
|
||||
Content = new StringContent(JsonSerializer.Serialize(new { client = "0123456789abcdef", text }), System.Text.Encoding.UTF8, "application/json"),
|
||||
};
|
||||
request.Headers.Add("Origin", origin);
|
||||
using var response = await Client.SendAsync(request);
|
||||
var body = await response.Content.ReadAsStringAsync();
|
||||
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, body);
|
||||
return JsonDocument.Parse(body).RootElement.Clone();
|
||||
}
|
||||
|
||||
Assert.AreEqual("solo-locale", (await PostAsync("m")).Str("state"));
|
||||
Assert.AreEqual("cerca", (await PostAsync("marta")).Str("state"));
|
||||
JsonElement view = default;
|
||||
await TestWait.UntilAsync(
|
||||
async () =>
|
||||
{
|
||||
view = await GetAsync("/api/ricerca?client=0123456789abcdef");
|
||||
return view.Str("state") == "pronta" && view.Items("hits").All(h => h.Bool("photoReady"));
|
||||
},
|
||||
"the demo answer with its photos");
|
||||
var hits = view.Items("hits").ToList();
|
||||
Assert.IsTrue(hits.Count is > 0 and <= 6);
|
||||
Assert.IsTrue(hits.Any(h => h.Str("username") == "marta.demo"), "a demo account whose name holds the text");
|
||||
Assert.IsTrue(hits.Any(h => h.GetProperty("accountId").ValueKind == JsonValueKind.Number), "already in Febe");
|
||||
using var photo = await Client.GetAsync($"/api/ricerca/foto/{hits[0].Str("photo")}");
|
||||
Assert.AreEqual(HttpStatusCode.OK, photo.StatusCode);
|
||||
Assert.AreEqual("image/jpeg", photo.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
Assert.AreEqual("ferma", (await PostAsync("luca", "fermo")).Str("state"));
|
||||
Assert.AreEqual("non-pronto", (await PostAsync("luca", "scollegato")).Str("state"));
|
||||
|
||||
// «alvolante»: Alberto uses the browser; the engine says so and the search on Instagram is not possible.
|
||||
var driving = await PostAsync("luca", "alvolante");
|
||||
Assert.AreEqual("non-possibile", driving.Str("state"));
|
||||
StringAssert.Contains(driving.Str("message"), "Stai usando il browser");
|
||||
Assert.AreEqual("UserDriving", (await GetAsync("/api/engine?scena=alvolante")).GetProperty("snapshot").Str("mode"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheEditionCanBeChosenByAddress()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,273 @@
|
||||
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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
[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<IProfileSearch>(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<IProfileSearch>(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<IProfileSearch>(search);
|
||||
s.AddSingleton<IEngineMonitor>(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");
|
||||
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<string> TextAsync(UiBrowser ui, string selector) =>
|
||||
(await ui.EvalAsync($"document.querySelector({JsonSerializer.Serialize(selector)}).textContent")).GetString() ?? string.Empty;
|
||||
|
||||
/// <summary>A search the test drives: the state of the next texts, then the answer and the photos when it says.</summary>
|
||||
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<string> 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>An engine while Alberto uses the browser.</summary>
|
||||
private sealed class DrivingMonitor : IEngineMonitor
|
||||
{
|
||||
public Task<EngineSnapshot> 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<EngineNotification> SubscribeAsync([EnumeratorCancellation] CancellationToken ct = default)
|
||||
{
|
||||
await Task.Delay(Timeout.Infinite, ct);
|
||||
yield break;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using Febe.Core.Collection.Search;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Tests.Support;
|
||||
using Febe.Tests.Web.Support;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Febe.Tests.Web;
|
||||
|
||||
/// <summary>
|
||||
/// The API of the profile search (issue #37): what the window sends, what it reads, the photos from Febe's memory,
|
||||
/// the local suggestions with the accounts not followed, and adding a found profile with its identifier.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class SearchApiTests
|
||||
{
|
||||
private const string Client = "0123456789abcdef";
|
||||
|
||||
[TestMethod]
|
||||
public async Task WithoutTheEngineTheSearchSaysOnlyLocalSuggestionsWork()
|
||||
{
|
||||
await using var server = await WebTestServer.StartAsync();
|
||||
|
||||
var (status, view) = await server.SendJsonAsync(HttpMethod.Post, "/api/ricerca", new { client = Client, text = "mario" });
|
||||
|
||||
Assert.AreEqual(HttpStatusCode.OK, status);
|
||||
Assert.AreEqual("non-pronto", view.Str("state"));
|
||||
Assert.IsTrue(view.Bool("mine"));
|
||||
StringAssert.Contains(view.Str("message"), "profili che segui");
|
||||
Assert.AreEqual("non-pronto", (await server.GetJsonAsync($"/api/ricerca?client={Client}")).Str("state"));
|
||||
Assert.IsFalse((await server.GetJsonAsync("/api/ricerca?client=fedcba9876543210")).Bool("mine"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task BadRequestsAreRefused()
|
||||
{
|
||||
await using var server = await WebTestServer.StartAsync();
|
||||
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/ricerca", new { client = "x", text = "mario" })).Status);
|
||||
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/ricerca", new { client = Client, text = new string('a', 61) })).Status);
|
||||
Assert.AreEqual(HttpStatusCode.NotFound, (await server.SendJsonAsync(HttpMethod.Get, "/api/ricerca/foto/nonunachiave")).Status);
|
||||
Assert.AreEqual(HttpStatusCode.NotFound, (await server.SendJsonAsync(HttpMethod.Get, "/api/ricerca/foto/0123456789abcdef0123456789abcdef")).Status);
|
||||
|
||||
using var end = server.Request(HttpMethod.Post, "/api/ricerca/fine", new { client = Client });
|
||||
using var ended = await server.Client.SendAsync(end);
|
||||
Assert.AreEqual(HttpStatusCode.NoContent, ended.StatusCode);
|
||||
|
||||
// Without the Origin of the interface a page of another site cannot make Febe type.
|
||||
using var foreign = server.Request(HttpMethod.Post, "/api/ricerca", new { client = Client, text = "mario" }, origin: "http://altro.esempio");
|
||||
using var refused = await server.Client.SendAsync(foreign);
|
||||
Assert.AreNotEqual(HttpStatusCode.OK, refused.StatusCode);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task HitsAreEnrichedWithWhatFebeKnowsAndPhotosComeFromMemory()
|
||||
{
|
||||
var fake = new FixedSearch();
|
||||
await using var server = await WebTestServer.StartAsync(services: s => s.AddSingleton<IProfileSearch>(fake));
|
||||
var renamed = await server.Db.Accounts.AddAsync(Make.Account("vecchio.nome") with { InstagramId = "100" });
|
||||
await server.Db.Following.UpsertAsync([new FollowingRecord { InstagramId = "200", Username = "seguito.uno", ReadAt = server.Clock.Now }]);
|
||||
|
||||
var (_, view) = await server.SendJsonAsync(HttpMethod.Post, "/api/ricerca", new { client = Client, text = "nome" });
|
||||
|
||||
Assert.AreEqual("pronta", view.Str("state"));
|
||||
var hits = view.Items("hits").ToList();
|
||||
Assert.HasCount(3, hits);
|
||||
Assert.AreEqual(renamed.Id, hits[0].Long("accountId"), "found by identifier under its new name");
|
||||
Assert.IsTrue(hits[1].Bool("followed"));
|
||||
Assert.AreEqual(System.Text.Json.JsonValueKind.Null, hits[2].GetProperty("accountId").ValueKind);
|
||||
Assert.IsTrue(hits[2].Bool("photoReady"));
|
||||
|
||||
using var photo = await server.Client.GetAsync($"/api/ricerca/foto/{hits[2].Str("photo")}");
|
||||
Assert.AreEqual(HttpStatusCode.OK, photo.StatusCode);
|
||||
Assert.AreEqual("image/jpeg", photo.Content.Headers.ContentType?.MediaType);
|
||||
Assert.IsTrue(photo.Headers.CacheControl?.NoStore == true, "the photos stay in Febe's memory, never on the disk of the viewer's browser");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheLocalSuggestionsAlsoHoldTheAccountsNotFollowed()
|
||||
{
|
||||
await using var server = await WebTestServer.StartAsync();
|
||||
var added = await server.Db.Accounts.AddAsync(Make.Account("aggiunto.per.nome"));
|
||||
await server.Db.Following.UpsertAsync([new FollowingRecord { InstagramId = "200", Username = "seguito.uno", ReadAt = server.Clock.Now }]);
|
||||
|
||||
var following = await server.GetJsonAsync("/api/following");
|
||||
|
||||
Assert.AreEqual(1, following.Int("total"), "the count is of the followed profiles");
|
||||
var profiles = following.Items("profiles").ToList();
|
||||
Assert.HasCount(2, profiles);
|
||||
Assert.IsTrue(profiles[0].Bool("followed"));
|
||||
Assert.AreEqual("200", profiles[0].Str("instagramId"));
|
||||
Assert.AreEqual("aggiunto.per.nome", profiles[1].Str("username"));
|
||||
Assert.IsFalse(profiles[1].Bool("followed"));
|
||||
Assert.AreEqual(added.Id, profiles[1].Long("accountId"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AFoundProfileIsAddedWithItsIdentifierAndARenamedOneIsReported()
|
||||
{
|
||||
var fake = new FixedSearch();
|
||||
await using var server = await WebTestServer.StartAsync(services: s => s.AddSingleton<IProfileSearch>(fake));
|
||||
await server.Db.Accounts.AddAsync(Make.Account("vecchio.nome") with { InstagramId = "100" });
|
||||
|
||||
var (status, result) = await server.SendJsonAsync(HttpMethod.Post, "/api/accounts", new { usernames = new[] { "nuovo.nome", "senza.nome" }, start = "newOnly" });
|
||||
|
||||
Assert.AreEqual(HttpStatusCode.OK, status);
|
||||
Assert.AreEqual(1, result.Int("added"));
|
||||
StringAssert.Contains(result.Str("message"), "con un altro nome");
|
||||
var account = await server.Db.Accounts.FindByUsernameAsync("senza.nome");
|
||||
Assert.AreEqual("300", account!.InstagramId);
|
||||
Assert.AreEqual("Senza Nome", account.DisplayName);
|
||||
Assert.IsNull(await server.Db.Accounts.FindByUsernameAsync("nuovo.nome"), "the same profile is not added twice");
|
||||
}
|
||||
|
||||
/// <summary>A search that always shows the same three results.</summary>
|
||||
private sealed class FixedSearch : IProfileSearch
|
||||
{
|
||||
private const string PhotoKey = "abcdefabcdefabcdefabcdefabcdef12";
|
||||
|
||||
private static readonly SearchHit[] Hits =
|
||||
[
|
||||
new(0, "100", "nuovo.nome", "Nuovo Nome", false, null, false),
|
||||
new(1, "200", "seguito.uno", null, false, null, false),
|
||||
new(2, "300", "senza.nome", "Senza Nome", true, PhotoKey, true),
|
||||
];
|
||||
|
||||
public SearchView Current { get; private set; } = SearchView.Initial;
|
||||
|
||||
public SearchView Update(string client, string text) =>
|
||||
Current = new SearchView(Current.Version + 1, client, text, SearchState.Ready, null, Hits, null);
|
||||
|
||||
public void End(string client)
|
||||
{
|
||||
}
|
||||
|
||||
public SearchHit? Known(string username) => Hits.FirstOrDefault(h => h.Username == username);
|
||||
|
||||
public bool TryOpenPhoto(string key, [NotNullWhen(true)] out Stream? stream)
|
||||
{
|
||||
stream = key == PhotoKey ? new MemoryStream(Febe.Web.Demo.DemoImages.Render(Febe.Web.Demo.DemoSubject.Portrait, 1, 32, 32)) : null;
|
||||
return stream is not null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -139,7 +139,7 @@ public sealed class SettingsApiTests
|
||||
Assert.AreEqual(20, rules.Int("maxWindowHours"));
|
||||
var current = limits.GetProperty("current");
|
||||
var kinds = current.Items("budgets").Select(b => b.Str("kind")).ToList();
|
||||
CollectionAssert.AreEqual(new[] { "Home", "ProfileOpen", "StoryView", "BackfillPage", "SinglePost", "FollowingListPage" }, kinds, "every row of the table of §7.5");
|
||||
CollectionAssert.AreEqual(new[] { "Home", "ProfileOpen", "StoryView", "BackfillPage", "SinglePost", "FollowingListPage", "ProfileSearch" }, kinds, "every row of the table of §7.5");
|
||||
CollectionAssert.AreEqual(new[] { "1 ora", "6 ore", "24 ore" }, limits.Items("stops").Select(s => s.GetString()).ToArray());
|
||||
|
||||
object Body(Func<Dictionary<string, object?>, Dictionary<string, object?>> edit, string profile = "custom")
|
||||
|
||||
Reference in new issue
Block a user