Files
Febe/tests/Febe.Tests/Collection/SyntheticSiteSeedTests.cs
T
Alby96andClaude Opus 5.5 9941a2fa1f
verifica / controlli (push) Successful in 20s
verifica / prove (push) Failing after 19m40s
verifica / installatore (push) Skipped
verifica / immagine (push) Skipped
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>
2026-11-15 16:30:03 +01:00

285 lines
15 KiB
C#

using System.Globalization;
using System.Text.RegularExpressions;
using Febe.Core.Collection.Readers;
using Febe.Core.Domain;
using Febe.SitoDiProva;
using Febe.Tests.Desktop.Support;
using Febe.Tests.Support;
namespace Febe.Tests.Collection;
/// <summary>
/// The synthetic world of the test site and its seed (<see cref="SyntheticSite"/>), without a browser, so they run
/// everywhere: what the integration tests take for granted holds for every seed, and the readers of
/// <c>lettori.prova.json</c> read what the site serves with the seed of this run, page after page. Never Instagram:
/// the site is on 127.0.0.1.
/// </summary>
[TestClass]
[TestCategory(SyntheticSite.Category)]
public sealed partial class SyntheticSiteSeedTests
{
private static readonly ShapeReader Reader = new(ReaderVocabulary.LoadTestSite());
private static readonly string[] StoryBarOrder = ["marta.prova", "nadia.prova", "luca.prova", "giulia.prova"];
public TestContext TestContext { get; set; } = null!;
[TestMethod]
public void TheSeedComesFromTheVariableAndIsThirteenWithoutIt()
{
Assert.AreEqual(13, SyntheticSite.ParseSeed(null));
Assert.AreEqual(13, SyntheticSite.ParseSeed(" "));
Assert.AreEqual(4242, SyntheticSite.ParseSeed("4242"));
Assert.AreEqual(-7, SyntheticSite.ParseSeed(" -7 "));
Assert.ThrowsExactly<InvalidOperationException>(() => SyntheticSite.ParseSeed("tredici"));
Assert.ThrowsExactly<InvalidOperationException>(() => SyntheticSite.ParseSeed("99999999999"));
}
[TestMethod]
public void EveryTestThatStartsTheSiteTakesTheSeedOfTheRunAndIsInItsCategory()
{
var tests = Repository.PathOf("tests", "Febe.Tests");
var direct = new List<string>();
var outside = new List<string>();
foreach (var file in Directory.EnumerateFiles(tests, "*.cs", SearchOption.AllDirectories))
{
var name = Path.GetRelativePath(tests, file).Replace('\\', '/');
if (name.StartsWith("bin/", StringComparison.Ordinal) || name.StartsWith("obj/", StringComparison.Ordinal))
{
continue;
}
var text = File.ReadAllText(file);
if (name != "Support/SyntheticSite.cs" && DirectStart().IsMatch(text))
{
direct.Add(name);
}
if (SiteStart().IsMatch(text) && text.Contains("[TestClass]", StringComparison.Ordinal)
&& !text.Contains("[TestCategory(SyntheticSite.Category)]", StringComparison.Ordinal))
{
outside.Add(name);
}
}
Assert.IsEmpty(direct, "The site starts through SyntheticSite.StartAsync, which reads FEBE_SEME_PROVA: " + string.Join(", ", direct));
Assert.IsEmpty(outside, "The CI runs these tests again with the seed of the run only through their category: " + string.Join(", ", outside));
}
[TestMethod]
public void EverySeedGivesTheWorldTheIntegrationTestsRelyOn()
{
var now = new DateTimeOffset(2026, 10, 20, 9, 30, 0, TimeSpan.Zero);
int[] extremes = [SyntheticSite.Seed, int.MinValue, -1, 0, int.MaxValue];
foreach (var seed in extremes.Concat(Enumerable.Range(1, 300)).Distinct())
{
var world = World.Generate(seed, now);
var context = "seme " + seed.ToString(CultureInfo.InvariantCulture);
Assert.AreEqual(seed, world.Seed, context);
Assert.AreEqual("alberto.prova", world.Viewer.Username, context);
Assert.HasCount(31, world.Accounts, context);
Assert.HasCount(28, world.Following, context);
var counts = new Dictionary<string, int>
{
["alberto.prova"] = 4,
["marta.prova"] = 18,
["luca.prova"] = 40,
["giulia.prova"] = 6,
["nadia.prova"] = 3,
["paolo.prova"] = 8,
["riservato.prova"] = 5,
};
foreach (var (username, count) in counts)
{
Assert.HasCount(count, world.FindByUsername(username)!.Posts, $"{context}: {username}");
}
foreach (var account in world.Accounts)
{
if (account.Username.StartsWith("amico", StringComparison.Ordinal))
{
Assert.IsTrue(account.Posts.Count is 1 or 2, $"{context}: {account.Username}");
}
// Newest first, strictly: «known content at the top» and the cursors rely on it.
for (var i = 1; i < account.Posts.Count; i++)
{
Assert.IsTrue(account.Posts[i - 1].PublishedAt > account.Posts[i].PublishedAt, $"{context}: {account.Username} #{i}");
}
}
var posts = world.Accounts.SelectMany(a => a.Posts).ToList();
Assert.HasCount(posts.Count, posts.Select(p => p.Code).Distinct(StringComparer.Ordinal), $"{context}: codes are unique");
Assert.HasCount(posts.Count, posts.Select(p => p.Id).Distinct(StringComparer.Ordinal), $"{context}: identifiers are unique");
Assert.IsTrue(posts.All(p => p.Code.Length == 7 && p.PublishedAt <= now), context);
var feed = world.Feed();
for (var i = 1; i < feed.Count; i++)
{
Assert.IsTrue(feed[i - 1].PublishedAt >= feed[i].PublishedAt, $"{context}: feed #{i}");
}
CollectionAssert.AreEqual(StoryBarOrder, world.StoryBar(now).Select(a => a.Username).ToArray(), context);
var marta = world.FindByUsername("marta.prova")!;
var active = marta.Stories.Where(s => s.ExpiresAt > now).ToList();
Assert.HasCount(4, active, context);
Assert.AreEqual(1, active.Count(s => s.File.IsVideo), context);
Assert.HasCount(3, world.FindByUsername("nadia.prova")!.Stories.Where(s => s.ExpiresAt > now), context);
Assert.HasCount(2, world.FindByUsername("luca.prova")!.Stories.Where(s => s.ExpiresAt > now), context);
Assert.HasCount(5, world.FindByUsername("giulia.prova")!.Stories.Where(s => s.ExpiresAt > now), context);
var grid = world.Grid(marta, ProfileTab.Posts);
Assert.IsTrue(grid.Take(2).All(p => p.Pinned) && grid.Count(p => p.Pinned) == 2, $"{context}: two pinned posts on top");
Assert.IsTrue(grid.Take(DataApi.GridPageSize).Any(p => p.Files.Count == 3), $"{context}: a series on the first page");
Assert.HasCount(3, world.Grid(marta, ProfileTab.Tagged), context);
CollectionAssert.AreEqual(new[] { "Estate", "Viaggi" }, marta.Highlights.Select(h => h.Title).ToArray(), context);
Assert.IsTrue(marta.Highlights[0].Items.Any(i => i.Id == marta.Stories[1].Id), $"{context}: a story also in «Estate» (H9)");
}
}
[TestMethod]
[Timeout(30_000, CooperativeCancellation = true)]
public async Task TheLoginAddressOfTheTestSiteIsAWelcomePageThatOpensTheSession()
{
// Febe opens /benvenuto as the «pagina di accesso» of the test site (LoginUrl of DesktopOptions and ServerOptions).
await using var site = await SyntheticSite.StartAsync();
using var client = new HttpClient(new SocketsHttpHandler { UseProxy = false, UseCookies = false });
using var response = await client.GetAsync(new Uri(site.Url("/benvenuto")), TestContext.CancellationToken);
Assert.AreEqual(System.Net.HttpStatusCode.OK, response.StatusCode);
var html = await response.Content.ReadAsStringAsync(TestContext.CancellationToken);
StringAssert.Contains(html, "Ho finito");
Assert.DoesNotContain("<form", html, "No login form: the test site never asks for a password.");
Assert.IsTrue(
response.Headers.TryGetValues("Set-Cookie", out var cookies) && cookies.Any(c => c.StartsWith(TestSite.SessionCookie + "=", StringComparison.Ordinal)),
"The visit opens the session of the site.");
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task TheReadersReadWhatTheSiteServesWithTheSeedOfThisRun()
{
await using var site = await SyntheticSite.StartAsync();
TestContext.WriteLine($"Seme del mondo sintetico: {site.World.Seed.ToString(CultureInfo.InvariantCulture)}");
Assert.AreEqual(SyntheticSite.Seed, site.World.Seed);
string[] feed, firstFeedPageSeries, martaFirstPage, lucaGrid, martaStories, following;
string seriesCode, sharedStory, summerId;
lock (site.World.Gate)
{
var world = site.World;
var marta = world.FindByUsername("marta.prova")!;
feed = [.. world.Feed().Select(p => p.Id)];
firstFeedPageSeries = [.. world.Feed().Take(DataApi.FeedPageSize).Where(p => p.Files.Count > 1).Select(p => p.Id)];
martaFirstPage = [.. world.Grid(marta, ProfileTab.Posts).Take(DataApi.GridPageSize).Select(p => p.Id)];
seriesCode = world.Grid(marta, ProfileTab.Posts).First(p => p.Files.Count == 3).Code;
lucaGrid = [.. world.Grid(world.FindByUsername("luca.prova")!, ProfileTab.Posts).Select(p => p.Id)];
martaStories = [.. marta.Stories.Select(s => s.Id)];
sharedStory = marta.Stories[1].Id;
summerId = marta.Highlights[0].Id;
following = [.. world.Following.Select(a => a.Username)];
}
// The home: the connected account, the stories bar, then the whole feed page by page, as the recipe scrolls it.
var home = await ReadAsync(site, "/dati/inizio");
Assert.AreEqual(ReadShape.Recognized, home.Shape);
Assert.AreEqual("alberto.prova", home.Viewer?.Username);
CollectionAssert.AreEqual(StoryBarOrder, home.Profiles.Where(p => p.LatestStoryAt is not null).Select(p => p.Username).ToArray());
CollectionAssert.AreEqual(firstFeedPageSeries, home.Contents.Where(c => !c.IsComplete).Select(c => c.Id).ToArray(), "A series arrives incomplete in the feed.");
Assert.IsTrue(home.Contents.Where(c => !c.IsComplete).All(c => c.Files.Count == 1));
CollectionAssert.AreEqual(feed, await AllPagesAsync(site, home, "/dati/inizio/altri?dopo="));
// Marta's grid: two pinned posts on top, her highlights, her post count.
var profile = await ReadAsync(site, "/dati/profilo/marta.prova?scheda=post");
CollectionAssert.AreEqual(martaFirstPage, profile.Contents.Select(c => c.Id).ToArray());
Assert.IsTrue(profile.Contents.Take(2).All(c => c.Pinned) && profile.Contents.Count(c => c.Pinned) == 2);
CollectionAssert.AreEqual(new[] { "Estate", "Viaggi" }, profile.Highlights.Select(h => h.Title).ToArray());
Assert.AreEqual(18, profile.Profiles.Single(p => p.PostCount is not null).PostCount);
// Luca's history, page after page (the backfill): every post once, in order.
var luca = await ReadAsync(site, "/dati/profilo/luca.prova?scheda=post");
CollectionAssert.AreEqual(lucaGrid, await AllPagesAsync(site, luca, "/dati/profilo/luca.prova/altri?scheda=post&dopo="));
// A series on its own page: complete, in order, a video in the middle.
var series = (await ReadAsync(site, "/dati/post/" + seriesCode)).Contents.Single();
Assert.AreEqual(seriesCode, series.Code);
Assert.IsTrue(series.IsComplete);
CollectionAssert.AreEqual(new[] { MediaKind.Photo, MediaKind.Video, MediaKind.Photo }, series.Files.Select(f => f.Kind).ToArray());
// Stories and a highlight that shares one of them (H9).
var stories = await ReadAsync(site, "/dati/storie/marta.prova");
CollectionAssert.AreEqual(martaStories, stories.Contents.Select(c => c.Id).ToArray());
Assert.AreEqual(1, stories.Contents.Count(c => c.Files[0].Kind == MediaKind.Video));
var summer = (await ReadAsync(site, "/dati/evidenza/" + summerId)).Highlights.Single();
Assert.HasCount(3, summer.Items);
Assert.IsTrue(summer.Items.Any(i => i.Id == sharedStory));
// The following list, page after page, and a private profile Alberto does not follow.
var first = await ReadAsync(site, "/dati/seguiti");
var names = first.Profiles.Select(p => p.Username).ToList();
var page = first.Page;
while (page?.HasMore == true)
{
var next = await ReadAsync(site, "/dati/seguiti?dopo=" + Uri.EscapeDataString(page.Cursor!));
names.AddRange(next.Profiles.Select(p => p.Username));
page = next.Page;
}
CollectionAssert.AreEqual(following, names);
var hidden = await ReadAsync(site, "/dati/profilo/riservato.prova?scheda=post");
Assert.AreEqual(true, hidden.Profiles.Single().IsPrivate);
Assert.AreEqual(false, hidden.Profiles.Single().IsFollowed);
Assert.IsEmpty(hidden.Contents);
}
[TestMethod]
[Timeout(30_000, CooperativeCancellation = true)]
public async Task TheSearchOfTheSiteAnswersInTheShapeOfTheCleanedSample()
{
// Issue #37: the same keys as 000002-ricerca-profili, read by the same search vocabulary as Instagram's.
await using var site = await SyntheticSite.StartAsync();
var answer = await ReadAsync(site, "/dati/cerca?testo=" + Uri.EscapeDataString("Marta"));
Assert.IsNotNull(answer.Search);
Assert.AreEqual("marta.prova", answer.Search.Hits[0].Profile.Username);
Assert.AreEqual("1001", answer.Search.Hits[0].Profile.Id);
Assert.IsNotNull(answer.Search.Hits[0].Profile.Picture, "a photo on the CDN of the site");
Assert.IsEmpty(answer.Profiles, "search results are not followed profiles");
var all = await ReadAsync(site, "/dati/cerca?testo=prova");
Assert.IsTrue(all.Search!.Hits.Count is > 1 and <= DataApi.SearchSize);
Assert.IsFalse(all.Search.Hits.Any(h => h.Profile.Username == "alberto.prova"), "the connected account is not a result");
CollectionAssert.AreEqual(Enumerable.Range(0, all.Search.Hits.Count).ToArray(), all.Search.Hits.Select(h => h.Position).ToArray());
var none = await ReadAsync(site, "/dati/cerca?testo=qqqzzz");
Assert.HasCount(0, none.Search!.Hits);
}
private async Task<ReadResult> ReadAsync(TestSite site, string pathAndQuery)
{
var result = Reader.Read(await site.GetDataAsync(pathAndQuery, TestContext.CancellationToken));
Assert.AreEqual(ReadShape.Recognized, result.Shape, pathAndQuery);
return result;
}
/// <summary>The identifiers of a first page and of every page after it, following the cursors.</summary>
private async Task<string[]> AllPagesAsync(TestSite site, ReadResult first, string nextPath)
{
var ids = first.Contents.Select(c => c.Id).ToList();
var page = first.Page;
while (page?.HasMore == true)
{
var next = await ReadAsync(site, nextPath + Uri.EscapeDataString(page.Cursor!));
ids.AddRange(next.Contents.Select(c => c.Id));
page = next.Page;
}
return [.. ids];
}
[GeneratedRegex(@"\bTestSite\.StartAsync\(")]
private static partial Regex DirectStart();
[GeneratedRegex(@"\b(?:SyntheticSite\.StartAsync|CollectionHarness\.CreateAsync|ServerTestBed\.StartAsync)\(")]
private static partial Regex SiteStart();
}