using System.Text;
using Febe.Core.Abstractions;
using Febe.Core.Collection;
using Febe.Core.Collection.Requests;
using Febe.Tests.Collection.Support;
namespace Febe.Tests.Collection;
///
/// The stop signals of §7.6 read from the answers of the site client (issue #36, S2), whatever brought them: 429 as for
/// the browser, and until the true shapes are known (H16) a redirect, a 401 or 403, an HTML or a JSON without the
/// expected fields, a deleted session cookie are a Verifica; a JSON with its fields is no signal.
///
[TestClass]
public sealed class SiteAnswerSignalsTests
{
private static readonly DateTimeOffset At = new(2026, 11, 16, 10, 0, 0, TimeSpan.Zero);
private static readonly SiteOperation Tray = SettledCatalog.Instagram().Operations.Single(o => o.Name == "PolarisProfileStoryHighlightsTrayContentQuery");
private static readonly SiteOperation Profile = RequestCatalog.LoadTestSite().Operations.Single(o => o.Name == "profilo");
private static readonly SiteAnswerSignals Instagram = new(SignalRules.LoadDefault(), "sessionid");
private static readonly SiteAnswerSignals Prova = new(SignalRules.LoadTestSite(), "sessione_prova");
[TestMethod]
public void AJsonWithItsFieldsIsNoSignal()
{
Assert.IsNull(Prova.Classify(Profile, Json(Profile, 200, """{"profilo":{"nome":"marta"}}"""), At));
Assert.IsNull(Prova.Classify(Profile, Json(Profile, 200, """{"profilo":{}}""", rootFieldsPresent: true), At));
// A cookie renewed or another cookie deleted is not a stop.
Assert.IsNull(Prova.Classify(Profile, new SiteAnswer(Profile, 200, "application/json", Bytes("""{"profilo":{}}"""), cookiesSet: ["sessione_prova"], cookiesDeleted: ["altro"], setsClaim: true), At));
}
[TestMethod]
public void A429IsARallentamentoAsForTheBrowser()
{
var signal = Instagram.Classify(Tray, new SiteAnswer(Tray, 429, "text/html", ReadOnlyMemory.Empty, retryAfter: TimeSpan.FromMinutes(2)), At)!;
Assert.AreEqual(SignalLevel.Throttle, signal.Signal.Level);
Assert.AreEqual("http-429", signal.Signal.Code);
Assert.AreEqual(At, signal.Signal.At);
StringAssert.Contains(signal.Message, "429");
StringAssert.Contains(signal.Message, "120 s");
Assert.AreEqual(SignalLevel.Throttle, Prova.Classify(Profile, Json(Profile, 429, """{"errore":"troppe-richieste"}"""), At)!.Signal.Level);
}
[TestMethod]
[DataRow(301)]
[DataRow(302)]
[DataRow(303)]
[DataRow(307)]
public void ARedirectIsAVerificaAndShowsOnlyTheShapeOfWhereItPointed(int status)
{
var answer = new SiteAnswer(Tray, status, "text/html", ReadOnlyMemory.Empty, redirectTo: "https://www.instagram.com/accounts/login/?next=%2Fmarta.prova%2F");
var signal = Instagram.Classify(Tray, answer, At)!;
Assert.AreEqual(SignalLevel.Challenge, signal.Signal.Level);
Assert.AreEqual(SiteAnswerSignals.RedirectCode, signal.Signal.Code);
Assert.AreEqual(SiteAnswerSignals.H16, signal.Hypothesis);
StringAssert.Contains(signal.Message, "/accounts/login/");
StringAssert.Contains(signal.Message, "non seguito");
Assert.IsFalse(signal.Message.Contains("marta", StringComparison.Ordinal));
Assert.IsFalse(signal.Message.Contains("instagram.com", StringComparison.Ordinal));
Assert.AreEqual(Tray.PathShape, signal.Signal.Url, "The address of the signal is the path shape, never a value.");
}
[TestMethod]
public void A401OrA403IsAVerifica()
{
Assert.AreEqual(SiteAnswerSignals.UnauthorizedCode, Instagram.Classify(Tray, Json(Tray, 401, """{"message":"login_required"}"""), At)!.Signal.Code);
var forbidden = Instagram.Classify(Tray, new SiteAnswer(Tray, 403, "text/html", Bytes("CSRF")), At)!;
Assert.AreEqual(SiteAnswerSignals.ForbiddenCode, forbidden.Signal.Code);
Assert.AreEqual(SignalLevel.Challenge, forbidden.Signal.Level);
}
[TestMethod]
public void AnHtmlANonJsonOrAJsonWithoutTheExpectedFieldsIsAVerifica()
{
Assert.AreEqual(SiteAnswerSignals.HtmlCode, Classify(new SiteAnswer(Profile, 200, "text/html; charset=utf-8", Bytes(""))));
Assert.AreEqual(SiteAnswerSignals.HtmlCode, Classify(new SiteAnswer(Profile, 200, "application/json", Bytes("\n "))), "Declared JSON, but an HTML document.");
Assert.AreEqual(SiteAnswerSignals.NotJsonCode, Classify(new SiteAnswer(Profile, 200, "text/javascript", Bytes("for (;;);{\"a\":1}"))));
Assert.AreEqual(SiteAnswerSignals.NotJsonCode, Classify(new SiteAnswer(Profile, 200, "application/json", ReadOnlyMemory.Empty)));
var missing = Prova.Classify(Profile, Json(Profile, 200, """{"risposta":{"voci":[]}}"""), At)!;
Assert.AreEqual(SiteAnswerSignals.MissingFieldsCode, missing.Signal.Code);
Assert.AreEqual(SignalLevel.Challenge, missing.Signal.Level);
StringAssert.Contains(missing.Message, "profilo", "Names the expected fields.");
Assert.IsFalse(missing.Message.Contains("voci", StringComparison.Ordinal), "Never the body.");
Assert.AreEqual(SiteAnswerSignals.MissingFieldsCode, Classify(Json(Profile, 200, """{"profilo":null}""")), "A null field is missing.");
Assert.AreEqual(SiteAnswerSignals.MissingFieldsCode, Classify(Json(Profile, 200, """{"profilo":{}}""", rootFieldsPresent: false)), "What the site client saw wins.");
Assert.AreEqual(SiteAnswerSignals.MissingFieldsCode, Classify(Json(Profile, 400, """{"errore":"richiesta-non-valida"}""")));
}
[TestMethod]
public void TheSessionCookieDeletedIsAVerificaEvenWithGoodData()
{
var answer = new SiteAnswer(Tray, 200, "text/javascript", Bytes("""{"data":{}}"""), cookiesDeleted: ["sessionid"]);
var signal = Instagram.Classify(Tray, answer, At)!;
Assert.AreEqual(SiteAnswerSignals.SessionCookieDeletedCode, signal.Signal.Code);
Assert.AreEqual(SignalLevel.Challenge, signal.Signal.Level);
StringAssert.Contains(signal.Message, "cookie di sessione");
Assert.AreEqual(SiteAnswerSignals.SessionCookieDeletedCode, Instagram.Classify(Tray, new SiteAnswer(Tray, 302, null, ReadOnlyMemory.Empty, redirectTo: "/accounts/login/", cookiesDeleted: ["sessionid"]), At)!.Signal.Code);
}
[TestMethod]
public void TheTextRulesOfTheSiteApplyToShortJsonAnswers()
{
var wait = Instagram.Classify(Tray, Json(Tray, 400, """{"message":"Please wait a few minutes before you try again.","status":"fail"}"""), At)!;
Assert.AreEqual(SignalLevel.Throttle, wait.Signal.Level);
Assert.AreEqual("wait-text", wait.Signal.Code);
}
[TestMethod]
public void AJsonNotFoundOrServerErrorIsLeftToTheCallerButAnHtmlOneStops()
{
Assert.IsNull(Classify(Json(Profile, 404, """{"errore":"non-trovato"}""")));
Assert.IsNull(Classify(Json(Profile, 500, """{"status":"fail"}""")));
// §6.0: not JSON where JSON is expected stops the session, whatever the status (an HTML login or error page).
Assert.AreEqual(SiteAnswerSignals.HtmlCode, Classify(new SiteAnswer(Profile, 404, "text/html", Bytes(""))));
Assert.AreEqual(SiteAnswerSignals.HtmlCode, Classify(new SiteAnswer(Profile, 500, "text/html", Bytes(""))));
Assert.AreEqual(SiteAnswerSignals.NotJsonCode, Classify(new SiteAnswer(Profile, 503, null, ReadOnlyMemory.Empty)));
// The text rules apply to a short JSON of any status.
Assert.AreEqual("wait-text", Instagram.Classify(Tray, Json(Tray, 500, """{"message":"Please wait a few minutes before you try again."}"""), At)!.Signal.Code);
}
[TestMethod]
public void AMissingSessionIsADisconnessioneAndAnAnswerOfAnotherOperationIsRefused()
{
var none = SiteAnswerSignals.ForMissingSession(new SiteSessionMissingException("…", missing: null), At);
Assert.AreEqual(SignalLevel.Disconnect, none.Signal.Level);
Assert.AreEqual(SiteAnswerSignals.SessionMissingCode, none.Signal.Code);
StringAssert.Contains(SiteAnswerSignals.ForMissingSession(new SiteSessionMissingException("…", "x-csrftoken"), At).Message, "x-csrftoken");
Assert.ThrowsExactly(() => Prova.Classify(Profile, Json(Tray, 200, "{}"), At));
}
private static string? Classify(SiteAnswer answer) => Prova.Classify(Profile, answer, At)?.Signal.Code;
private static SiteAnswer Json(SiteOperation operation, int status, string body, bool? rootFieldsPresent = null) =>
new(operation, status, "application/json; charset=utf-8", Bytes(body), rootFieldsPresent: rootFieldsPresent);
private static byte[] Bytes(string text) => Encoding.UTF8.GetBytes(text);
}
///
/// The saved session of the site client (issue #36, S2 and S4): cookies read and sent as a browser reads and sends
/// them, with their domain and path (RFC 6265), updates in one write, no value in any text.
///
[TestClass]
public sealed class SiteSessionTests
{
private static readonly DateTimeOffset Now = new(2026, 11, 16, 10, 0, 0, TimeSpan.Zero);
private static readonly Uri Graph = new("https://www.instagram.com/api/graphql");
[TestMethod]
[DataRow("sessionid=abc; Path=/; HttpOnly", "abc", false)]
[DataRow("sessionid=\"abc\"; Path=/", "\"abc\"", false)]
[DataRow("sessionid=\"\"; Path=/", "\"\"", true)]
[DataRow("sessionid=; Path=/", "", true)]
[DataRow("sessionid=abc; Max-Age=0; Path=/", "abc", true)]
[DataRow("sessionid=abc; Max-Age=-1", "abc", true)]
[DataRow("sessionid=abc; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/", "abc", true)]
[DataRow("sessionid=abc; expires=Wed, 16 Nov 2027 10:00:00 GMT; path=/", "abc", false)]
[DataRow("sessionid=abc; expires=Thu, 01 Jan 1970 00:00:00 GMT; Max-Age=3600", "abc", false)]
[DataRow("sessionid=abc; Domain=.instagram.com; Path=/", "abc", false)]
[DataRow("sessionid=abc; Domain=instagram.com", "abc", false)]
public void ACookieLineIsReadAsABrowserReadsIt(string line, string value, bool deletes)
{
var cookie = SiteCookies.Parse(line, Graph, Now);
Assert.IsNotNull(cookie);
Assert.AreEqual("sessionid", cookie.Cookie.Name);
Assert.AreEqual(value, cookie.Cookie.Value);
Assert.AreEqual(deletes, cookie.Deletes);
}
[TestMethod]
[DataRow("a=b", "www.instagram.com", true, "/api", false)]
[DataRow("a=b; Path=/api/", "www.instagram.com", true, "/api/", false)]
[DataRow("a=b; Path=relativo", "www.instagram.com", true, "/api", false)]
[DataRow("a=b; Path=/; Domain=.instagram.com", "instagram.com", false, "/", false)]
[DataRow("a=b; Domain=WWW.Instagram.com; Path=/", "www.instagram.com", false, "/", false)]
[DataRow("a=b; Path=/; Secure; HttpOnly", "www.instagram.com", true, "/", true)]
public void ACookieLineKeepsItsDomainAndPathAsABrowserReadsThem(string line, string domain, bool hostOnly, string path, bool secure)
{
// No Domain: host-only on the request host; no Path (or one not starting with «/»): the default path of the
// request, «/api» for «/api/graphql» (RFC 6265 §5.1.4).
var cookie = SiteCookies.Parse(line, Graph, Now)!.Cookie;
Assert.AreEqual(domain, cookie.Domain);
Assert.AreEqual(hostOnly, cookie.HostOnly);
Assert.AreEqual(path, cookie.Path);
Assert.AreEqual(secure, cookie.Secure);
}
[TestMethod]
public void TheDefaultPathIsTheRequestPathUpToItsLastSlash()
{
Assert.AreEqual("/", SiteCookies.DefaultPath(new Uri("https://www.instagram.com/")));
Assert.AreEqual("/", SiteCookies.DefaultPath(new Uri("https://www.instagram.com/marta")));
Assert.AreEqual("/api", SiteCookies.DefaultPath(new Uri("https://www.instagram.com/api/graphql")));
Assert.AreEqual("/api/v1/media/1/info", SiteCookies.DefaultPath(new Uri("https://www.instagram.com/api/v1/media/1/info/")));
}
[TestMethod]
public void ACookieGoesOnlyWhereItsDomainPathAndSchemeMatch()
{
var host = SiteCookie.ForHost("a", "1", "www.instagram.com");
var wide = new SiteCookie("b", "2", ".instagram.com", hostOnly: false);
var api = SiteCookie.ForHost("c", "3", "www.instagram.com", "/api");
var secure = SiteCookie.ForHost("d", "4", "127.0.0.1", secure: true);
Assert.IsTrue(host.Matches(Graph, Now));
Assert.IsFalse(host.Matches(new Uri("https://help.instagram.com/"), Now), "Host-only: not a subdomain.");
Assert.IsTrue(wide.Matches(new Uri("https://help.instagram.com/"), Now));
Assert.IsTrue(wide.Matches(new Uri("https://instagram.com/"), Now));
Assert.IsFalse(wide.Matches(new Uri("https://evilinstagram.com/"), Now), "A suffix only at a dot.");
Assert.IsTrue(api.Matches(Graph, Now));
Assert.IsTrue(api.Matches(new Uri("https://www.instagram.com/api"), Now));
Assert.IsFalse(api.Matches(new Uri("https://www.instagram.com/apix/graphql"), Now), "A path prefix only at a «/».");
Assert.IsFalse(api.Matches(new Uri("https://www.instagram.com/"), Now));
Assert.IsFalse(secure.Matches(new Uri("http://127.0.0.1:8481/api/dati"), Now), "Secure: only over https.");
Assert.IsTrue(secure.Matches(new Uri("https://127.0.0.1:8481/api/dati"), Now));
Assert.IsFalse(new SiteCookie("e", "5", "0.0.1", hostOnly: false).Matches(new Uri("http://127.0.0.1/"), Now), "Never a suffix of an IP address.");
Assert.IsFalse(SiteCookie.ForHost("f", string.Empty, "www.instagram.com").Matches(Graph, Now), "An empty cookie is not sent.");
Assert.IsFalse(SiteCookie.ForHost("g", "7", "www.instagram.com", expires: Now).Matches(Graph, Now), "Expired.");
}
[TestMethod]
public void TheCookiesOfARequestComeLongerPathsFirstThenInTheStoredOrder()
{
var values = new SiteSessionValues(
[
SiteCookie.ForHost("csrftoken", "radice", "www.instagram.com"),
SiteCookie.ForHost("zeta", "z", "www.instagram.com"),
SiteCookie.ForHost("csrftoken", "api", "www.instagram.com", "/api/"),
new SiteCookie("mid", "m", "instagram.com", hostOnly: false),
SiteCookie.ForHost("altrove", "x", "www.instagram.com", "/accounts/"),
SiteCookie.ForHost("estraneo", "x", "www.facebook.com"),
],
"agente");
CollectionAssert.AreEqual(
new[] { "csrftoken=api", "csrftoken=radice", "zeta=z", "mid=m" },
values.CookiesFor(Graph, Now).Select(c => $"{c.Name}={c.Value}").ToArray());
Assert.AreEqual("api", values.CookieFor("csrftoken", Graph, Now), "The one with the longest path, as x-csrftoken takes it.");
Assert.AreEqual("radice", values.CookieFor("csrftoken", new Uri("https://www.instagram.com/marta/"), Now));
Assert.IsNull(values.CookieFor("altrove", Graph, Now));
}
[TestMethod]
public void AQuotedValueIsKeptAsTheBrowserKeepsItAndTheExpiryIsRead()
{
// RFC 6265 §5.2: the quotes are part of the value; sent back without them the cookie would not be the browser's.
var rur = SiteCookies.Parse("rur=\"CLN\\05412\\0541795\"; Domain=.instagram.com; Path=/; Max-Age=3600", Graph, Now)!.Cookie;
Assert.AreEqual("\"CLN\\05412\\0541795\"", rur.Value);
Assert.AreEqual(Now.AddHours(1), rur.Expires, "Max-Age from now.");
Assert.AreEqual(new DateTimeOffset(2027, 11, 16, 10, 0, 0, TimeSpan.Zero), SiteCookies.Parse("a=b; expires=Tue, 16 Nov 2027 10:00:00 GMT", Graph, Now)!.Cookie.Expires);
Assert.IsNull(SiteCookies.Parse("a=b; Path=/", Graph, Now)!.Cookie.Expires, "No expiry: it lasts as the session.");
Assert.IsNull(SiteCookies.Parse("a=b; Max-Age=0", Graph, Now)!.Cookie.Expires, "A deletion has no expiry.");
}
[TestMethod]
public async Task NewCookiesKeepTheOrderOfTheSiteAndExpiredOnesAreNotSent()
{
var session = new InMemorySiteSession(new SiteSessionValues(
[Cookie("csrftoken", "c1"), Cookie("sessionid", "s1"), Cookie("vecchio", "v1", Now.AddMinutes(1))],
"agente"));
var capture = session.Read()!.Capture;
// Ten names, in an order no hash keeps by chance.
var names = new[] { "ig_nrcb", "ps_l", "zz", "aa", "mid", "datr", "ps_n", "wd", "b1", "a9" };
await session.UpdateAsync(
new SiteSessionUpdate(names.Select(n => Cookie(n, "x-" + n, n == "wd" ? Now.AddDays(7) : null)), capture: capture),
CancellationToken.None);
var values = session.Read()!;
CollectionAssert.AreEqual(new[] { "csrftoken", "sessionid", "vecchio" }.Concat(names).ToArray(), values.Cookies.Select(c => c.Name).ToArray());
Assert.AreEqual(capture, values.Capture, "A renewal keeps the capture.");
Assert.AreEqual(Now.AddDays(7), values.Cookies.Single(c => c.Name == "wd").Expires);
Assert.AreEqual("v1", values.CookieFor("vecchio", Graph, Now));
Assert.IsNull(values.CookieFor("vecchio", Graph, Now.AddMinutes(1)), "Expired: the browser would not send it.");
Assert.IsFalse(values.CookiesFor(Graph, Now.AddMinutes(2)).Any(c => c.Name == "vecchio"));
Assert.IsNull(values.CookieFor("wd", Graph, Now.AddDays(8)));
Assert.AreEqual("s1", values.CookieFor("sessionid", Graph, Now.AddYears(5)), "No expiry: as long as the session.");
// Renewed without an expiry: the old expiry goes.
await session.UpdateAsync(new SiteSessionUpdate([Cookie("wd", "x2")], capture: capture), CancellationToken.None);
Assert.IsNull(session.Read()!.Cookies.Single(c => c.Name == "wd").Expires);
}
[TestMethod]
public async Task TheSameNameOnTwoPathsIsTwoCookiesAndADeletionTouchesOnlyItsKey()
{
var session = new InMemorySiteSession(new SiteSessionValues(
[
Cookie("csrftoken", "radice"),
SiteCookie.ForHost("csrftoken", "api", "www.instagram.com", "/api/"),
new SiteCookie("csrftoken", "dominio", "instagram.com", hostOnly: false),
],
"agente"));
Assert.AreEqual(3, session.Read()!.Cookies.Count, "Name, domain, path and host-only make the key.");
// The site renews the one at «/api/» and deletes the host-only one at «/»: the domain cookie stays as it was.
var renewal = SiteCookies.Parse("csrftoken=nuovo; Path=/api/", Graph, Now)!;
var deletion = SiteCookies.Parse("csrftoken=; Path=/; Max-Age=0", Graph, Now)!;
Assert.IsTrue(deletion.Deletes);
await session.UpdateAsync(new SiteSessionUpdate([renewal.Cookie], [deletion.Cookie.Key]), CancellationToken.None);
var cookies = session.Read()!.Cookies;
CollectionAssert.AreEqual(new[] { "/api/ nuovo", "/ dominio" }, cookies.Select(c => $"{c.Path} {c.Value}").ToArray(), "Renewed in place, the deleted one gone.");
Assert.IsFalse(cookies[1].HostOnly);
}
[TestMethod]
public async Task TheLateAnswerOfAReplacedSessionChangesNothing()
{
var session = new InMemorySiteSession(new SiteSessionValues([Cookie("sessionid", "vecchia")], "agente"));
var old = session.Read()!.Capture;
session.Replace(new SiteSessionValues([Cookie("sessionid", "nuova")], "agente"));
Assert.AreNotEqual(old, session.Read()!.Capture, "A new login is a new capture.");
await session.UpdateAsync(new SiteSessionUpdate(cookiesDeleted: [Cookie("sessionid", string.Empty).Key], claim: "vecchio", capture: old), CancellationToken.None);
Assert.AreEqual("nuova", session.Read()!.Cookie("sessionid"));
Assert.AreEqual(SiteSessionValues.InitialClaim, session.Read()!.Field("claim", "Op"), "No claim yet: the page's «0».");
Assert.AreEqual(0, session.Updates);
}
[TestMethod]
[DataRow("sessionid=abc; Domain=facebook.com")]
[DataRow("sessionid=abc; Domain=evilinstagram.com")]
[DataRow("sessionid=abc; Domain=com")]
[DataRow("sessionid=abc; Domain=help.instagram.com")]
[DataRow("sessionid=a\u0001b")]
[DataRow("sessionid=caffè")]
[DataRow("senza-uguale")]
[DataRow("=abc")]
[DataRow("nome con spazio=abc")]
public void ACookieOfAnotherDomainOrNotACookieIsIgnored(string line) =>
Assert.IsNull(SiteCookies.Parse(line, Graph, Now));
[TestMethod]
public void ACookieThatABrowserWouldNotKeepIsRefusedWithoutItsValue()
{
foreach (var make in new Func[]
{
() => SiteCookie.ForHost("a=b", "segreto", "www.instagram.com"),
() => SiteCookie.ForHost("a", "segreto;altro", "www.instagram.com"),
() => SiteCookie.ForHost("a", "segreto\r\nx: y", "www.instagram.com"),
() => SiteCookie.ForHost("a", "segreto", "www.instagram.com", "senza-barra"),
() => SiteCookie.ForHost("a", "segreto", "host con spazi"),
})
{
var refused = Assert.ThrowsExactly(() => make());
Assert.IsFalse(refused.Message.Contains("segreto", StringComparison.Ordinal), refused.Message);
}
}
[TestMethod]
public async Task AnUpdateIsAppliedAtOnceAndTheTextShowsNoValue()
{
var session = new InMemorySiteSession(new SiteSessionValues(
[Cookie("csrftoken", "segreto-1"), Cookie("sessionid", "segreto-2"), Cookie("rur", "segreto-3")],
"Mozilla/5.0 segreto-agente",
new Dictionary { ["claim"] = "0", ["lsd"] = "segreto-4", ["rev"] = "segreto-11", ["entry_nonce"] = "segreto-12" },
new Dictionary { ["Op"] = "segreto-5" }));
var update = new SiteSessionUpdate([Cookie("csrftoken", "segreto-6"), Cookie("nuovo", "segreto-7")], [Cookie("rur", string.Empty).Key], "segreto-8");
await session.UpdateAsync(update, CancellationToken.None);
await session.UpdateAsync(new SiteSessionUpdate(), CancellationToken.None);
var values = session.Read()!;
CollectionAssert.AreEqual(new[] { "csrftoken", "sessionid", "nuovo" }, values.Cookies.Select(c => c.Name).ToArray(), "Renewed in place, new at the end, deleted gone.");
Assert.AreEqual("segreto-6", values.Cookie("csrftoken"));
Assert.AreEqual("segreto-8", values.Field("claim", "Op"));
Assert.AreEqual("segreto-5", values.Field("doc_id", "Op"));
Assert.AreEqual("segreto-11", values.Field("rev", "Op"));
Assert.IsNull(values.Field("doc_id", "Altra"));
Assert.AreEqual("Mozilla/5.0 segreto-agente", values.Field("user_agent", "Op"));
Assert.AreEqual(1, session.Updates, "An empty update writes nothing.");
var texts = new List { session.ToString(), values.ToString(), update.ToString(), $"{values}", $"{update}" };
texts.AddRange(values.Cookies.Select(c => c.ToString()));
texts.AddRange(update.CookiesDeleted.Select(k => k.ToString()));
texts.Add(SiteCookies.Parse("csrftoken=segreto-9; Path=/", Graph, Now)!.ToString());
foreach (var text in texts)
{
Assert.IsFalse(text.Contains("segreto", StringComparison.Ordinal), text);
}
foreach (var text in new[] { session.ToString(), values.ToString(), update.ToString() })
{
Assert.IsFalse(text.Contains("csrftoken", StringComparison.Ordinal), "The session's text has counts only: " + text);
}
Assert.ThrowsExactly(() => new SiteSessionValues([], "agente", new Dictionary { ["password"] = "x" }));
Assert.ThrowsExactly(() => new SiteSessionValues([], "agente", new Dictionary { ["user_agent"] = "x" }), "The user agent is not a page value.");
var empty = new InMemorySiteSession(null);
await empty.UpdateAsync(new SiteSessionUpdate(claim: "x"), CancellationToken.None);
Assert.IsNull(empty.Read(), "No session: an update creates none.");
}
[TestMethod]
public void TheNewPageFieldsAreSessionFieldsAndTheVocabularyIsClosed()
{
foreach (var field in new[] { "rev", "hs", "hsi", "dpr", "ccg", "comet_req", "entry_nonce", "lsd", "fb_dtsg", "app_id", "account_id" })
{
Assert.IsTrue(SiteSessionValues.PageFields.Contains(field), field);
Assert.IsTrue(ValueSource.SessionFields.Contains(field), field);
}
CollectionAssert.AreEquivalent(new[] { "user_agent", "claim", "doc_id" }, ValueSource.SessionFields.Except(SiteSessionValues.PageFields).ToArray());
Assert.IsFalse(ValueSource.SessionFields.Contains("spin_r"), "__spin_* stay pending: who adds them to the request is not shown.");
}
private static SiteCookie Cookie(string name, string value, DateTimeOffset? expires = null) =>
SiteCookie.ForHost(name, value, "www.instagram.com", expires: expires);
}