using System.Text.Json.Nodes; using Febe.Core.Abstractions; using Febe.Core.Collection; using Febe.Core.Collection.Readers; using Febe.Core.Collection.Recipes; using Febe.Core.Collection.Requests; using Febe.Core.Engine; using Febe.Tests.Collection.Support; namespace Febe.Tests.Collection; /// /// Which recipe goes by requests (issue #36, S3): the roles of the catalog, checked when it loads; on Instagram none, /// so nothing changes there; the configuration tells which recipes go by requests and a new role changes its fingerprint. /// [TestClass] public sealed class RequestRoutingTests { [TestMethod] public void OnInstagramNoRecipeGoesByRequests() { var instagram = RequestCatalog.LoadInstagram(); foreach (var kind in Enum.GetValues()) { Assert.IsNull(RecipeRunner.RequestOperations(instagram, kind), $"{kind}: every operation of Instagram is still not configured."); } // The roles are written all the same, waiting for S4. Assert.AreEqual("PolarisProfilePageContentQuery", instagram.HolderOf(RequestRole.Profile)?.Name); Assert.AreEqual("PolarisProfilePostsQuery", instagram.HolderOf(RequestRole.Posts)?.Name); Assert.IsNull(instagram.HolderOf(RequestRole.PostsNext), "The posts query of the HAR has no cursor."); Assert.AreEqual(ActionKind.ProfileOpen, instagram.HolderOf(RequestRole.Posts)!.FirstPageCategory); Assert.IsNull(instagram.HolderOf(RequestRole.Following), "No shapes of the following list yet."); } [TestMethod] public async Task OnInstagramTheRunnerRefusesAsBefore() { var instagram = RequestCatalog.LoadInstagram(); var map = InstagramMap(); await using var withClient = await RequestBed.CreateAsync(map, instagram); await using var without = await RequestBed.CreateAsync(map, instagram, requests: false); foreach (var kind in Enum.GetValues()) { Assert.IsFalse(withClient.Runner.HasRequestRoute(kind), kind.ToString()); Assert.AreEqual(without.Runner.NotConfiguredReason(kind), withClient.Runner.NotConfiguredReason(kind), kind.ToString()); } } [TestMethod] public async Task TheEngineChecksTheBudgetOfTheFirstRequestOfTheRoute() { await using var byRequests = await RequestBed.CreateAsync(); await using var byPages = await RequestBed.CreateAsync(requests: false); await using var instagram = await RequestBed.CreateAsync(InstagramMap(), RequestCatalog.LoadInstagram()); // Taggati and Reel by requests start with a page of the tab, not with the profile. Assert.AreEqual(ActionKind.BackfillPage, byRequests.Runner.FirstCategory(RecipeKind.Tagged)); Assert.AreEqual(ActionKind.BackfillPage, byRequests.Runner.FirstCategory(RecipeKind.Reels)); foreach (var kind in Enum.GetValues()) { Assert.AreEqual(CheckPolicy.CategoryOf(kind), byPages.Runner.FirstCategory(kind), kind.ToString()); Assert.AreEqual(CheckPolicy.CategoryOf(kind), instagram.Runner.FirstCategory(kind), $"{kind}: Instagram as before."); if (kind is not (RecipeKind.Tagged or RecipeKind.Reels)) { Assert.AreEqual(CheckPolicy.CategoryOf(kind), byRequests.Runner.FirstCategory(kind), kind.ToString()); } } } [TestMethod] public async Task ARecipeByRequestsNeedsNoPageOfTheMap() { var empty = new SiteMap("prova", new Dictionary(), [], SiteTargets.All); await using var bed = await RequestBed.CreateAsync(empty); Assert.IsNull(bed.Runner.NotConfiguredReason(RecipeKind.ProfileCheck)); Assert.IsNull(bed.Runner.NotConfiguredReason(RecipeKind.AccountStories)); Assert.IsNotNull(bed.Runner.NotConfiguredReason(RecipeKind.FollowingSweep), "The sweep needs the home page."); } [TestMethod] public void OnTheTestSiteEveryRecipeButTheSweepGoesByRequests() { var prova = RequestCatalog.LoadTestSite(); string[]? Names(RecipeKind kind) => RecipeRunner.RequestOperations(prova, kind)?.Select(o => o.Name).ToArray(); CollectionAssert.AreEqual(new[] { "ProvaProfiloQuery", "profilo-altri" }, Names(RecipeKind.ProfileCheck)); CollectionAssert.AreEqual(new[] { "ProvaProfiloQuery", "profilo-altri" }, Names(RecipeKind.Backfill)); CollectionAssert.AreEqual(new[] { "taggati" }, Names(RecipeKind.Tagged), "No next pages of the tagged posts: their answer has them all."); CollectionAssert.AreEqual(new[] { "reel" }, Names(RecipeKind.Reels)); CollectionAssert.AreEqual(new[] { "storie" }, Names(RecipeKind.AccountStories)); CollectionAssert.AreEqual(new[] { "evidenza" }, Names(RecipeKind.Highlight)); CollectionAssert.AreEqual(new[] { "post" }, Names(RecipeKind.SinglePost)); CollectionAssert.AreEqual(new[] { "seguiti" }, Names(RecipeKind.FollowingList), "One operation, the first page and the next."); Assert.IsNull(Names(RecipeKind.FollowingSweep)); } [TestMethod] public void TheFirstPageOfTheGridCountsAsTheProfile() { var instagram = RequestCatalog.LoadInstagram(); var posts = instagram.HolderOf(RequestRole.Posts)!; Assert.AreEqual(ActionKind.BackfillPage, posts.Category); Assert.AreEqual(ActionKind.ProfileOpen, posts.CategoryFor(new SiteRequest(posts.Name, new Dictionary { [CaseValues.AccountId] = "5555" }))); } [TestMethod] public void TheGuardWantsThePermitOfTheCategoryOfTheRequest() { // ProvaProfiloQuery counts as a profile; profilo-altri, with its cursor, as a page of history. var prova = RequestCatalog.LoadTestSite(); var spent = new SpentPermits(); var next = new SiteRequest("profilo-altri", new Dictionary { [CaseValues.Username] = "marta.prova", [CaseValues.Cursor] = "c12" }); var refusal = Assert.ThrowsExactly(() => SiteRequestGuard.Check(prova, next, Permit.Grant(ActionKind.ProfileOpen, null), spent)); StringAssert.Contains(refusal.Message, "conta come"); Assert.AreEqual("profilo-altri", SiteRequestGuard.Check(prova, next, Permit.Grant(ActionKind.BackfillPage, null), spent).Name); } [TestMethod] [DataRow("[\"seguiti-di-qualcuno\"]", "sconosciuto")] [DataRow("[\"posts-next\"]", "va da una pagina alla successiva")] [DataRow("[null]", "sconosciuto")] public void ARoleThatCannotBeIsRefusedWhenTheCatalogLoads(string roles, string said) { var operation = Rest("post-in-piu", "/api/dati/post-in-piu/{code}"); operation["roles"] = JsonNode.Parse(roles); StringAssert.Contains(Refuse(Alone(operation)), said); } [TestMethod] public void AFirstPageRoleOnAnOperationThatAlwaysWantsACursorIsRefused() { var operation = Rest("altri-in-piu", "/api/dati/altri-in-piu"); operation["parameters"] = new JsonObject { ["dopo"] = "{cursor}" }; operation["roles"] = new JsonArray("posts"); StringAssert.Contains(Refuse(Alone(operation)), "prima pagina"); } [TestMethod] public void ARoleOfTwoOperationsIsRefused() { var file = JsonNode.Parse(SiteMap.ReadEmbeddedText("richieste.prova.json"))!.AsObject(); var second = Rest("post-due", "/api/dati/post-due/{code}"); second["roles"] = new JsonArray("post"); file["operations"]!.AsArray().Add(second); StringAssert.Contains(Refuse(file.ToJsonString()), "un ruolo appartiene a una sola operazione"); } [TestMethod] public void ASearchHasNoRoleAndTheFirstPageCategoryIsOnlyForTheHistory() { var search = Rest("cerca-in-piu", "/api/dati/cerca-in-piu"); search["category"] = "ricerca"; search["parameters"] = new JsonObject { ["testo"] = "{search_text}" }; search["roles"] = new JsonArray("profile"); StringAssert.Contains(Refuse(Alone(search)), "una ricerca non ha ruoli"); var post = Rest("post-in-piu", "/api/dati/post-in-piu/{code}"); post["firstPageCategory"] = "profilo"; StringAssert.Contains(Refuse(Alone(post)), "solo per un'operazione della categoria «storico»"); var history = Rest("storico-in-piu", "/api/dati/storico-in-piu/{username}"); history["category"] = "storico"; history["firstPageCategory"] = "post"; StringAssert.Contains(Refuse(Alone(history)), "ammette solo «profilo»"); } [TestMethod] public void ARoleOfAnOperationNotConfiguredGivesNoRoute() { var file = JsonNode.Parse(SiteMap.ReadEmbeddedText("richieste.prova.json"))!.AsObject(); var stories = file["operations"]!.AsArray().Single(o => o!["name"]!.GetValue() == "storie")!.AsObject(); stories["configured"] = false; stories["reason"] = "prova"; var catalog = RequestCatalog.Parse(file.ToJsonString(), "richieste.prova.json"); Assert.IsNull(catalog.ForRole(RequestRole.Stories)); Assert.AreEqual("storie", catalog.HolderOf(RequestRole.Stories)?.Name); Assert.IsNull(RecipeRunner.RequestOperations(catalog, RecipeKind.AccountStories)); } [TestMethod] public void TheConfigurationSaysWhichRecipesGoByRequests() { var vocabulary = ReaderVocabulary.LoadTestSite(); var empty = new SiteMap("prova", new Dictionary(), [], SiteTargets.All); var without = CollectionConfiguration.Describe("prova", vocabulary, empty); var with = CollectionConfiguration.Describe("prova", vocabulary, empty, RequestCatalog.LoadTestSite()); Assert.AreEqual(Enum.GetValues().Length, without.Blocked.Count, "Without pages nothing runs by the browser."); CollectionAssert.AreEqual(new[] { RecipeKind.FollowingSweep }, with.Blocked.ToArray(), "Only the sweep needs the pages."); CollectionAssert.Contains(with.Lines.ToList(), "Controllo del profilo: per richieste (ProvaProfiloQuery, profilo-altri)."); Assert.IsFalse(without.Lines.Any(l => l.Contains("per richieste", StringComparison.Ordinal))); Assert.AreNotEqual(without.Fingerprint, with.Fingerprint, "A new route clears the suspensions too."); Assert.AreEqual(without.Fingerprint, CollectionConfiguration.Describe("prova", vocabulary, empty, RequestCatalog.LoadInstagram()).Fingerprint, "No route: the fingerprint of before."); Assert.AreEqual(0, CollectionConfiguration.Describe("prova", vocabulary, empty, RequestCatalog.LoadInstagram()).ByRequests.Count); } private static SiteMap InstagramMap() => SiteMap.LoadEmbedded("bersagli.instagram.json"); private static string Refuse(string json) => Assert.ThrowsExactly(() => RequestCatalog.Parse(json, "richieste.prova.json")).Message; private static string Alone(JsonObject operation) => new JsonObject { ["site"] = "prova", ["operations"] = new JsonArray(operation) }.ToJsonString(); private static JsonObject Rest(string name, string path) => new() { ["name"] = name, ["kind"] = "rest", ["method"] = "GET", ["path"] = path, ["category"] = "post", ["configured"] = true, ["headers"] = new JsonObject { ["user-agent"] = "session:user_agent" }, ["rootFields"] = new JsonArray("contenuto"), ["sample"] = "000005-post-serie", }; }