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(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("