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; /// /// The synthetic world of the test site and its seed (), without a browser, so they run /// everywhere: what the integration tests take for granted holds for every seed, and the readers of /// lettori.prova.json read what the site serves with the seed of this run, page after page. Never Instagram: /// the site is on 127.0.0.1. /// [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(() => SyntheticSite.ParseSeed("tredici")); Assert.ThrowsExactly(() => SyntheticSite.ParseSeed("99999999999")); } [TestMethod] public void EveryTestThatStartsTheSiteTakesTheSeedOfTheRunAndIsInItsCategory() { var tests = Repository.PathOf("tests", "Febe.Tests"); var direct = new List(); var outside = new List(); 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 { ["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(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); } private async Task ReadAsync(TestSite site, string pathAndQuery) { var result = Reader.Read(await site.GetDataAsync(pathAndQuery, TestContext.CancellationToken)); Assert.AreEqual(ReadShape.Recognized, result.Shape, pathAndQuery); return result; } /// The identifiers of a first page and of every page after it, following the cursors. private async Task 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(); }