Files
Febe/tests/Febe.Tests/Collection/TestSiteSessionTests.cs
Alby96andClaude Opus 5.5 883ea4683c Sessione salvata: copia alla chiusura della finestra e alla fine della guida, «Serve «Ho finito»», scelta per la copia incompleta e stato in Collegamento (#36, S4b)
Risposte 1, 5, 6, 9 e 10 di Alberto a S4. I valori __spin_r, __spin_b e __spin_t si copiano dalla pagina come gli altri (su Instagram da SiteData, ipotesi H23, operazioni ancora non configurate; nel sito di prova dal modulo GiroProva). La sessione si copia anche quando si chiude la finestra del browser su Windows e quando il permesso di guida finisce, sempre prima che la pagina torni al motore e con le garanzie di «Ho finito». Con «richieste» «Collegato» vuole una sessione salvata leggibile, altrimenti lo stato è «Serve «Ho finito»» e il motore aspetta. Nuova impostazione sessione.copia-incompleta (sostituisci, predefinita, o tieni-completa) e riquadro della sessione salvata nella pagina Collegamento, con soli conteggi e nomi.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 11:41:35 +01:00

122 lines
6.0 KiB
C#

using Febe.Core.Abstractions;
using Febe.Core.Collection;
using Febe.Core.Collection.Requests;
using Febe.SitoDiProva;
using Febe.Tests.Support;
using VirtualClock = Febe.Tests.Browser.TestSupport.VirtualClock;
namespace Febe.Tests.Collection;
/// <summary>
/// What the test site gives its pages for the copy at «Ho finito» (issue #36, S4, spec §14.2): the cookies a real site
/// sets (the session, <c>csrftoken</c>, one limited to <c>/api/</c>), a module registry of its own whose names are the
/// <c>page</c> section of <c>richieste.prova.json</c> (never Instagram's), and a <c>/api/graphql</c> that refuses a
/// wrong or missing value of the page as it refuses a wrong token. No browser.
/// </summary>
[TestClass]
[TestCategory(SyntheticSite.Category)]
public sealed class TestSiteSessionTests
{
public TestContext TestContext { get; set; } = null!;
[TestMethod]
public async Task AVisitSetsTheSessionCsrftokenAndTheApiPathCookie()
{
await using var site = await SyntheticSite.StartAsync();
using var client = new HttpClient(new SocketsHttpHandler { UseProxy = false, UseCookies = false, AllowAutoRedirect = false });
using var response = await client.GetAsync(new Uri(site.Url("/")), TestContext.CancellationToken);
var lines = response.Headers.GetValues("Set-Cookie").ToList();
string Line(string name) => lines.Single(l => l.StartsWith(name + "=", StringComparison.Ordinal));
StringAssert.Contains(Line(TestSite.SessionCookie), "path=/;");
StringAssert.Contains(Line(TestSite.SessionCookie).ToLowerInvariant(), "httponly");
var csrf = Line(TestSite.CsrfCookie);
StringAssert.Contains(csrf, "path=/;");
Assert.DoesNotContain("httponly", csrf.ToLowerInvariant(), "the page reads it to send it back in x-csrftoken");
StringAssert.Contains(Line(TestSite.ApiPathCookie), "path=/api/");
// A second visit with the session and the token keeps them: no new cookie.
var session = Line(TestSite.SessionCookie).Split(';')[0];
var token = csrf.Split(';')[0];
using var again = new HttpRequestMessage(HttpMethod.Get, new Uri(site.Url("/")));
again.Headers.TryAddWithoutValidation("Cookie", $"{session}; {token}");
using var second = await client.SendAsync(again, TestContext.CancellationToken);
Assert.IsFalse(second.Headers.Contains("Set-Cookie"));
}
[TestMethod]
public async Task ThePageModulesAreThoseOfTheCatalogsPageSectionWithTheValuesTheSiteChecks()
{
var catalog = RequestCatalog.LoadTestSite();
var page = catalog.Page!;
var modules = TestSite.PageModules("1234");
var expected = HttpSiteRequesterTests.PageValues();
foreach (var field in page.Order)
{
var source = page.Values[field];
Assert.IsTrue(modules.TryGetValue(source.Module, out var module), $"{field}: module {source.Module}");
Assert.IsTrue(module.TryGetValue(source.Property, out var value), $"{field}: {source}");
Assert.AreEqual(field == "account_id" ? "1234" : expected[field], value, field);
}
foreach (var operation in catalog.Operations.Where(o => o.Kind == OperationKind.GraphQl))
{
var module = page.DocIdModuleFor(operation.Name)!;
Assert.AreEqual(operation.Name + TestSite.DocIdModuleSuffix, module);
Assert.AreEqual(TestSite.DocIds[operation.Name], modules[module][string.Empty]);
}
// Never Instagram's names in the test site.
foreach (var name in modules.Keys)
{
Assert.DoesNotContain("instagram", name.ToLowerInvariant());
Assert.IsFalse(RequestCatalog.LoadInstagram().Page!.Values.Values.Any(s => s.Module == name), name);
}
// Every page of the site carries the registry first in its head.
await using var site = await SyntheticSite.StartAsync();
using var client = new HttpClient(new SocketsHttpHandler { UseProxy = false, UseCookies = false, AllowAutoRedirect = false });
foreach (var path in new[] { "/", "/benvenuto", "/profilo/marta.prova/" })
{
var html = await client.GetStringAsync(new Uri(site.Url(path)), TestContext.CancellationToken);
StringAssert.Contains(html, "<head><script>(function () {", path);
StringAssert.Contains(html, "__d(\"GettoniProva\"", path);
StringAssert.Contains(html, "__d(\"ProvaProfiloQuery_operazioneProva\"", path);
}
}
[TestMethod]
public async Task TheGraphQlQueryRefusesAWrongOrMissingValueOfThePage()
{
await using var site = await SyntheticSite.StartAsync();
var catalog = RequestCatalog.LoadTestSite();
var values = HttpSiteRequesterTests.Values();
async Task<int> StatusWith(string field, string? value, bool header = false)
{
var fields = values.Fields.ToDictionary(StringComparer.Ordinal);
if (value is null)
{
// A value the page did not give: the client cannot send the request at all.
fields.Remove(field);
}
else
{
fields[field] = value;
}
using var requester = new HttpSiteRequester(catalog, new InMemorySiteSession(new SiteSessionValues(values.Cookies, values.UserAgent, fields, values.DocIds)), HttpSiteRequesterOptions.TestSite(new Uri(site.SiteUrl + "/")), new VirtualClock());
var answer = await requester.SendAsync(HttpSiteRequesterTests.Graph(), Permit.Grant(ActionKind.ProfileOpen, null), CancellationToken.None);
return answer.Status;
}
Assert.AreEqual(200, await StatusWith("rev", TestSite.Revision), "the right values pass");
foreach (var field in new[] { "rev", "hs", "hsi", "ccg", "dpr", "comet_req", "entry_nonce", "spin_r", "spin_b", "spin_t" })
{
Assert.AreEqual(400, await StatusWith(field, "altro-valore"), field);
}
await Assert.ThrowsExactlyAsync<SiteSessionMissingException>(() => StatusWith("hsi", null));
}
}