using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Text; using System.Threading; using System.Threading.Tasks; using RynthCore.Plugin.RynthILT.IltWiki; using RynthCore.Plugin.Shared; using RynthCore.RynthAiTests.Harness; namespace RynthILT.Tests; // The Leaftide wiki quest guide (IltWiki/, 2026-11-27): the address, the sealed login, the MediaWiki // sign-in and the read, against a FAKE wiki (FakeWiki below; nothing here touches the network), and the // controller's opt-in, commands and the guide it hands RynthOracle. Every page below is made up for the // tests: invented quests, people and places, written in the wiki's page layout. No real wiki text. internal static class WikiGuideTests { private const string Api = "https://wiki.test/api.php"; private const string User = "Tester@probe"; private const string Password = "pw-Fake-7f3k-q9zz-Bot"; public static void Register(Runner r) { r.Add("wiki: the address the player types becomes the API address (https only)", Address); r.Add("wiki: robots.txt's Crawl-delay sets the gap between requests", Robots); r.Add("wiki: the login is sealed with DPAPI, opens again, and Sign out deletes it", Sealed); r.Add("wiki: sign-in against a fake wiki (token, POST, cookie, assert=user, User-Agent, gaps)", SignIn); r.Add("wiki: a failed sign-in says why in plain words, without the password", SignInFails); r.Add("wiki: off by default: nothing fetched or saved, RynthOracle sees only the way to sign in", OffByDefault); r.Add("wiki: signing in reads the guide, saves it and hands it to RynthOracle", ReadsGuide); r.Add("wiki: a second read fetches only edited pages; Refresh waits 5 minutes", OnlyEdited); r.Add("wiki: a lost session signs in again once; a refused sign-in ends the read plainly", LostSession); r.Add("wiki: Sign out deletes the login and the guide; RynthOracle's guide goes", SignOut); r.Add("wiki: /ilt wiki commands each answer, and never take a login in chat", Commands); r.Add("wiki: a login saved for another address is never used", OtherAddress); r.Add("wiki: the invented pages read into steps, stamps, loot, kill tasks and contracts", Parsing); } // ── The invented pages ────────────────────────────────────────────────── private const string MothErrand = @"{{Leaftide Content}} {{Quest Summary | Level = 120+ | Recommended Level = 150+ | Quest Type = Solo | Starts With = [[Warden Pellis]] | Starts At = [[Hollow Reach]] | Repeat Timer = 20 Hours }} == Overview == Warden Pellis wants the glow sacs of the lantern moths that swarm the old quarry. == Walkthrough & Notes == # Talk to [[Warden Pellis]] at 12.3N, 45.6E. #* {{stamped|LanternMothErrandStarted}} # Kill lantern moths in the quarry (14.0N 47.2E) and loot a {{Itemlink|Moth Glow Sac}}. # Return the {{Itemlink|Moth Glow Sac}} to Warden Pellis. #* {{stamped|LanternMothErrandDone}} == Rewards == {{Rewards Table | Quest Task = Hand in a glow sac | XP Reward = 5,000,000 | Item Reward = * {{Icon Link|Pellis Lantern}} }} [[Category:Invented Quests]]"; private const string GlimmerBeetles = @"{{Quest Summary | Level = 80+ | Quest Type = Solo/Fellowship | Starts With = [[Huntmaster Orlo]] | Repeat Timer = 7 days | Kill Task = Yes }} == Discord Description == Thin out the glimmer beetles near the salt flats. == Walkthrough & Notes == Speak to Huntmaster Orlo at 3.1s,70.2w to take the task. Kill 50 Glimmer Beetles anywhere on the salt flats. Return to Huntmaster Orlo for the reward. == QB Stamps == {{stamped|GlimmerBeetleTaskTaken}} {{stamped|GlimmerBeetleKills on first completion}} [[Category:Kill Tasks]]"; private const string ThornboundInitiate = @"{{Quest Summary | Level = 50+ | Starts With = [[Sister Wren]] }} == Walkthrough == # Bring Sister Wren three bramble cuttings. [[Category:Society Quests: Initiate Rank]]"; private const string BrambleContract = @"{{Item | Name = Contract for the Bramble Wardens | Description = Starts the Bramble Wardens' errand again. | Recommended Level = 60 }} {{Intro | Related Quests = [[Thornbound Initiate Tasks]]}} == Notes == * Purchased from [[Quartermaster Ivo]] in [[Hollow Reach]]. [[Category:Contracts]]"; private const string MothItem = @"{{Item | Name = Moth Glow Sac}} A pale sac that glows faintly. Not a quest page."; // ── A fake MediaWiki ──────────────────────────────────────────────────── private sealed class FakeWiki : HttpMessageHandler { public readonly Dictionary Pages = new(StringComparer.Ordinal) { ["The Lantern Moth Errand"] = (101, MothErrand), ["Glimmer Beetle Kill Task"] = (102, GlimmerBeetles), ["Thornbound Initiate Tasks"] = (103, ThornboundInitiate), ["Contract for the Bramble Wardens"] = (104, BrambleContract), ["Moth Glow Sac"] = (105, MothItem), }; /// Category -> members (title, ns). public readonly Dictionary> Categories = new(StringComparer.Ordinal) { ["Category:Kill_Tasks"] = new() { ("Glimmer Beetle Kill Task", 0), ("Category:Kill Tasks by Level", 14) }, ["Category:Kill Tasks by Level"] = new() { ("Glimmer Beetle Kill Task", 0) }, ["Category:Society_Quests"] = new() { ("Category:Society Quests: Initiate Rank", 14), ("Category:Society Items", 14) }, ["Category:Society Quests: Initiate Rank"] = new() { ("Thornbound Initiate Tasks", 0) }, ["Category:Society Items"] = new() { ("Moth Glow Sac", 0) }, ["Category:Contracts"] = new() { ("Contract for the Bramble Wardens", 0) }, }; public string User = WikiGuideTests.User; public string Password = WikiGuideTests.Password; public string? Robots = "User-agent: *\nCrawl-Delay: 12\n"; public string? LoginResultOverride; // "Aborted" etc. public string? HtmlInstead; // every API answer is this HTML page public bool Redirect; /// After this many signed-in queries the wiki forgets the session, once (0 = never). public int DropSessionAfter; /// The wiki takes the password once only (it was revoked mid-read). public bool RevokeAfterFirstLogin; public readonly ConcurrentQueue<(string Method, string Url, string Body, string Agent, string Cookie)> Log = new(); public readonly List ContentTitles = new(); public int Logins; private int _sessionNo; private string _session = ""; private string _signedSession = ""; private int _queries; private const string LoginToken = "tok+\\"; private static Dictionary Parse(string query) { var map = new Dictionary(StringComparer.Ordinal); foreach (string part in query.TrimStart('?').Split('&', StringSplitOptions.RemoveEmptyEntries)) { int eq = part.IndexOf('='); string k = Uri.UnescapeDataString((eq < 0 ? part : part[..eq]).Replace('+', ' ')); string v = eq < 0 ? "" : Uri.UnescapeDataString(part[(eq + 1)..].Replace('+', ' ')); map[k] = v; } return map; } private static HttpResponseMessage Json(string json, string? cookie = null) { var r = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(json, Encoding.UTF8, "application/json") }; if (cookie != null) r.Headers.TryAddWithoutValidation("Set-Cookie", cookie); return r; } private static string Esc(string s) => System.Text.Json.JsonEncodedText.Encode(s).ToString(); protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { string body = request.Content == null ? "" : await request.Content.ReadAsStringAsync(cancellationToken); string agent = request.Headers.UserAgent.ToString(); string cookie = request.Headers.TryGetValues("Cookie", out var cs) ? string.Join("; ", cs) : ""; Log.Enqueue((request.Method.Method, request.RequestUri!.ToString(), body, agent, cookie)); Uri u = request.RequestUri!; if (u.AbsolutePath == "/robots.txt") return Robots == null ? new HttpResponseMessage(HttpStatusCode.NotFound) : new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(Robots) }; if (Redirect) { var r = new HttpResponseMessage(HttpStatusCode.Found); r.Headers.Location = new Uri("https://elsewhere.test/"); return r; } if (HtmlInstead != null) return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(HtmlInstead, Encoding.UTF8, "text/html") }; Dictionary q = Parse(request.Method == HttpMethod.Post ? body : u.Query); bool hasSession = _session.Length > 0 && cookie.Contains("wikisession=" + _session, StringComparison.Ordinal); if (q.GetValueOrDefault("meta") == "tokens") { _session = "s" + (++_sessionNo); return Json("{\"batchcomplete\":true,\"query\":{\"tokens\":{\"logintoken\":\"" + Esc(LoginToken) + "\"}}}", "wikisession=" + _session + "; path=/; secure; HttpOnly"); } if (q.GetValueOrDefault("action") == "login") { Logins++; if (!hasSession || q.GetValueOrDefault("lgtoken") != LoginToken) return Json("{\"login\":{\"result\":\"WrongToken\"}}"); if (LoginResultOverride != null) return Json("{\"login\":{\"result\":\"" + LoginResultOverride + "\",\"reason\":\"Main-password logins are switched off here.\"}}"); bool revoked = RevokeAfterFirstLogin && Logins > 1; if (q.GetValueOrDefault("lgname") != User || q.GetValueOrDefault("lgpassword") != Password || revoked) return Json("{\"login\":{\"result\":\"Failed\",\"reason\":\"That login name or password is wrong (fake wiki).\"}}"); _signedSession = _session; _queries = 0; return Json("{\"login\":{\"result\":\"Success\",\"lguserid\":7,\"lgusername\":\"Tester\"}}"); } if (q.GetValueOrDefault("action") != "query") return Json("{\"error\":{\"code\":\"badvalue\",\"info\":\"unknown action\"}}"); bool signed = hasSession && _session == _signedSession && _signedSession.Length > 0; if (signed && DropSessionAfter > 0 && ++_queries > DropSessionAfter) { _signedSession = ""; signed = false; DropSessionAfter = 0; // once: the session lapsed } if (q.GetValueOrDefault("assert") == "user" && !signed) return Json("{\"error\":{\"code\":\"assertuserfailed\",\"info\":\"You are no longer logged in.\"}}"); if (q.GetValueOrDefault("meta") == "userinfo|siteinfo") return Json("{\"query\":{\"userinfo\":{\"id\":7,\"name\":\"Tester\"},\"general\":{\"server\":\"https://wiki.test\",\"articlepath\":\"/$1\"}}}"); if (q.GetValueOrDefault("generator") == "embeddedin") { // Two pages per answer, with a continuation (as a big wiki answers). var quests = Pages.Where(p => p.Value.Text.Contains("{{Quest Summary")).Select(p => p.Key).OrderBy(t => t, StringComparer.Ordinal).ToList(); int from = int.TryParse(q.GetValueOrDefault("geicontinue"), out int f) ? f : 0; var part = quests.Skip(from).Take(2).ToList(); string cont = from + 2 < quests.Count ? ",\"continue\":{\"geicontinue\":\"" + (from + 2) + "\",\"continue\":\"gei||\"}" : ""; return Json("{\"query\":{\"pages\":[" + string.Join(",", part.Select(t => PageInfo(t, 0))) + "]}" + cont + "}"); } if (q.GetValueOrDefault("generator") == "categorymembers") { string cat = q.GetValueOrDefault("gcmtitle") ?? ""; var members = Categories.TryGetValue(cat, out var m) ? m : new List<(string, int)>(); return Json("{\"query\":{\"pages\":[" + string.Join(",", members.Select(x => PageInfo(x.Item1, x.Item2))) + "]}}"); } if (q.GetValueOrDefault("prop") == "revisions") { var titles = (q.GetValueOrDefault("titles") ?? "").Split('|'); lock (ContentTitles) ContentTitles.AddRange(titles); var parts = titles.Where(Pages.ContainsKey).Select(t => "{\"ns\":0,\"title\":\"" + Esc(t) + "\",\"revisions\":[{\"revid\":" + Pages[t].Rev + ",\"slots\":{\"main\":{\"content\":\"" + Esc(Pages[t].Text) + "\"}}}]}"); return Json("{\"query\":{\"pages\":[" + string.Join(",", parts) + "]}}"); } return Json("{\"error\":{\"code\":\"badvalue\",\"info\":\"not faked\"}}"); } private string PageInfo(string title, int ns) => "{\"ns\":" + ns + ",\"title\":\"" + Esc(title) + "\"" + (ns == 0 && Pages.TryGetValue(title, out var p) ? ",\"lastrevid\":" + p.Rev : "") + "}"; } // ── Helpers ───────────────────────────────────────────────────────────── private sealed class Harness { public readonly FakeWiki Wiki = new(); public readonly List<(string Text, bool Ok)> Said = new(); public readonly ConcurrentQueue Waits = new(); public DateTime Now = new(2026, 11, 27, 12, 0, 0, DateTimeKind.Utc); public int Handlers; public int SettingsOpened; public readonly IltWikiGuide Guide; public Harness(string name, bool fresh = true) { string dir = Path.Combine(Program.TempRoot, "wiki-" + name); if (fresh && Directory.Exists(dir)) Directory.Delete(dir, recursive: true); WikiLoginStore.FolderOverride = dir; ServerQuestGuideHost.ResetForTests(); Guide = new IltWikiGuide((t, ok) => Said.Add((t, ok)), null, () => { Handlers++; return Wiki; }, (gap, _) => { Waits.Enqueue(gap); return Task.CompletedTask; }, () => Now) { OpenSettings = () => SettingsOpened++, }; Guide.Load(); } public void Settle() { Check.True(Guide.WaitForTests(), "the background work ended"); Guide.Tick(); } public string AllSaid => string.Join(" / ", Said.Select(s => s.Text)); } private static unsafe ServerQuestGuideClient ReadPublished() { var client = new ServerQuestGuideClient(); client.Use((RynthServerQuestGuideApiV1*)ServerQuestGuideHost.Query(1), "RynthILT"); return client; } /// No file under the wiki folder holds the password (or the login name) in readable form, except none may. private static void NoSecretOnDisk(string what) { string dir = WikiLoginStore.Folder; if (!Directory.Exists(dir)) { Check.True(true, what + ": no files"); return; } foreach (string f in Directory.GetFiles(dir, "*", SearchOption.AllDirectories)) { byte[] bytes = File.ReadAllBytes(f); string utf8 = Encoding.UTF8.GetString(bytes), utf16 = Encoding.Unicode.GetString(bytes); Check.False(utf8.Contains(Password) || utf16.Contains(Password), $"{what}: {Path.GetFileName(f)} doesn't hold the password"); } string logs = Path.Combine(Program.TempRoot, "Logs"); if (Directory.Exists(logs)) foreach (string f in Directory.GetFiles(logs, "*", SearchOption.AllDirectories)) { string text; try { using var fs = new FileStream(f, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); using var sr = new StreamReader(fs); text = sr.ReadToEnd(); } catch (IOException) { continue; } Check.False(text.Contains(Password), $"{what}: the log {Path.GetFileName(f)} doesn't hold the password"); } } // ── Tests ─────────────────────────────────────────────────────────────── private static void Address() { Check.True(WikiAddress.TryNormalize("https://wiki.test/", out string a, out _) && a == Api, "a site becomes its api.php"); Check.True(WikiAddress.TryNormalize("wiki.test", out a, out _) && a == Api, "no scheme: https is assumed"); Check.True(WikiAddress.TryNormalize("https://wiki.test/index.php?title=Main_Page#x", out a, out _) && a == Api, "index.php becomes api.php, query dropped"); Check.True(WikiAddress.TryNormalize("https://wiki.test/w/api.php", out a, out _) && a == "https://wiki.test/w/api.php", "an api.php stays"); Check.False(WikiAddress.TryNormalize("http://wiki.test/", out _, out string e) , "plain http is refused"); Check.True(e.Contains("https"), "and says https"); Check.False(WikiAddress.TryNormalize("https://me:pw@wiki.test/", out _, out _), "a login in the address is refused"); Check.False(WikiAddress.TryNormalize("", out _, out _) || WikiAddress.TryNormalize("ht!tp:/", out _, out _), "empty or junk is refused"); Check.True(WikiAddress.Same("https://WIKI.test/api.php", Api) && !WikiAddress.Same("https://other.test/api.php", Api), "same address, any case"); Check.Eq(WikiAddress.FileKey(Api), "wiki.test", "the cache file key is the host"); Check.Eq(WikiAddress.RobotsOf(Api), "https://wiki.test/robots.txt", "robots.txt beside it"); } private static void Robots() { Check.Eq(WikiClient.CrawlDelay("User-agent: *\nCrawl-Delay: 10\n"), 10.0, "Crawl-Delay for every robot"); Check.Eq(WikiClient.CrawlDelay("User-agent: OtherBot\nCrawl-delay: 99\n\nUser-agent: *\nDisallow: /x\n"), (double?)null, "another robot's delay isn't ours"); Check.Eq(WikiClient.CrawlDelay("User-agent: OtherBot\nUser-agent: *\nCrawl-delay: 3 # comment\n"), 3.0, "a group naming several robots"); Check.Eq(WikiClient.CrawlDelay("login"), (double?)null, "a login page instead: none"); } private static void Sealed() { WikiLoginStore.FolderOverride = Path.Combine(Program.TempRoot, "wiki-sealed"); Check.True(WikiLoginStore.Save(new WikiLogin(Api, User, Password), out string err), "saved: " + err); byte[] raw = File.ReadAllBytes(WikiLoginStore.FilePath); string u8 = Encoding.UTF8.GetString(raw), u16 = Encoding.Unicode.GetString(raw); Check.False(u8.Contains(Password) || u16.Contains(Password) || u8.Contains("Tester") || u8.Contains("wiki.test"), "the file is sealed: no password, name or address readable"); WikiLogin? back = WikiLoginStore.Load(out err); Check.True(back != null && back.Api == Api && back.User == User && back.Password == Password, "it opens again for this Windows user"); Check.False(back!.ToString().Contains(Password), "a login written out never shows the password"); raw[raw.Length / 2] ^= 0x5a; File.WriteAllBytes(WikiLoginStore.FilePath, raw); Check.True(WikiLoginStore.Load(out err) == null && err.Contains("sign in again"), "a damaged file is no login, said plainly"); Check.True(WikiLoginStore.Delete(out _) && !File.Exists(WikiLoginStore.FilePath) && !WikiLoginStore.Exists, "Delete removes it"); } private static void SignIn() { var wiki = new FakeWiki(); var waits = new List(); using var client = new WikiClient(Api, wiki, (g, _) => { waits.Add(g); return Task.CompletedTask; }); WikiSignIn s = client.SignInAsync(User, Password, CancellationToken.None).GetAwaiter().GetResult(); Check.True(s.Ok && s.UserName == "Tester" && s.ArticleBase == "https://wiki.test/", "signed in: " + s.Message); var log = wiki.Log.ToArray(); Check.Eq(log.Length, 4, "robots, token, login, user check"); Check.True(log[0].Url.EndsWith("/robots.txt") && log[1].Url.Contains("meta=tokens") && log[2].Method == "POST" && log[3].Url.Contains("assert=user"), "in that order"); Check.True(log[2].Body.Contains("lgname=Tester%40probe") && log[2].Body.Contains("lgtoken="), "the login POST carries the name and the token"); Check.True(log.All(l => !l.Url.Contains(Password) && !l.Url.Contains("lgpassword")), "the password is never in an address"); Check.True(log.Count(l => l.Body.Contains(Uri.EscapeDataString(Password)) || l.Body.Contains(Password)) == 1, "only the login POST carries the password"); Check.True(log[2].Cookie.Contains("wikisession=") && log[3].Cookie.Contains("wikisession="), "the session cookie goes back"); Check.True(log.All(l => l.Agent == WikiClient.UserAgent), "every request names only the plugin: " + log[0].Agent); Check.True(client.Gap == TimeSpan.FromSeconds(12) && waits.Count == 3 && waits.All(w => w == TimeSpan.FromSeconds(12)), $"robots.txt's 12 s kept between every request ({string.Join(",", waits)})"); var slow = new FakeWiki { Robots = "User-agent: *\nCrawl-delay: 1\n" }; using var c2 = new WikiClient(Api, slow, (_, _) => Task.CompletedTask); c2.SignInAsync(User, Password, CancellationToken.None).GetAwaiter().GetResult(); Check.Eq(c2.Gap, WikiClient.MinGap, "never closer than 5 s"); var none = new FakeWiki { Robots = null }; using var c3 = new WikiClient(Api, none, (_, _) => Task.CompletedTask); c3.SignInAsync(User, Password, CancellationToken.None).GetAwaiter().GetResult(); Check.Eq(c3.Gap, WikiClient.DefaultGap, "no robots.txt: 10 s"); } private static WikiSignIn Try(FakeWiki wiki, string user, string password) { using var client = new WikiClient(Api, wiki, (_, _) => Task.CompletedTask); return client.SignInAsync(user, password, CancellationToken.None).GetAwaiter().GetResult(); } private static void SignInFails() { WikiSignIn s = Try(new FakeWiki(), User, "not-the-password"); Check.True(!s.Ok && s.Message.Contains("turned the sign-in down") && s.Message.Contains("fake wiki"), "wrong password: " + s.Message); Check.False(s.Message.Contains("not-the-password"), "the message never holds the password"); s = Try(new FakeWiki(), "Tester", "not-the-password"); Check.True(s.Message.Contains("YourName@botname"), "a name without @: the bot password hint"); s = Try(new FakeWiki { LoginResultOverride = "Aborted" }, User, Password); Check.True(!s.Ok && s.Message.Contains("Special:BotPasswords"), "a main-password sign-in turned away: " + s.Message); s = Try(new FakeWiki { HtmlInstead = "Login required" }, User, Password); Check.True(!s.Ok && s.Message.Contains("api.php"), "not an API: " + s.Message); s = Try(new FakeWiki { Redirect = true }, User, Password); Check.True(!s.Ok && s.Message.Contains("somewhere else"), "a redirect isn't followed: " + s.Message); } private static void OffByDefault() { var h = new Harness("off"); h.Guide.Tick(); Check.False(h.Guide.SignedIn, "not signed in"); Check.False(h.Guide.OnLogin(iltActive: true), "login on ILT: no read"); h.Guide.Tick(); Check.Eq(h.Handlers, 0, "no connection was made"); Check.False(Directory.Exists(WikiLoginStore.Folder) && Directory.GetFiles(WikiLoginStore.Folder).Length > 0, "nothing saved"); Check.Eq(h.Guide.Address, "", "no wiki address built in"); ServerQuestGuideClient c = ReadPublished(); Check.True(c.Available && c.Guide.IsEmpty && c.Tag == "Leaftide", "RynthOracle sees the Leaftide guide, empty"); Check.True(c.Info!.Takes("settings") && !c.Info.Takes("refresh") && c.Info.Status.Contains("Sign in"), "only the way to sign in: " + c.Info.Status); Check.True(c.Command("settings"), "RynthOracle's Its settings is taken"); h.Guide.Tick(); Check.Eq(h.SettingsOpened, 1, "and opens the ILT settings"); } private static Harness SignedIn(string name) { var h = new Harness(name); Check.True(h.Guide.SignIn("https://wiki.test/", User, Password, fromChat: false), "sign-in started: " + h.Guide.Status); h.Settle(); return h; } private static void ReadsGuide() { var h = SignedIn("reads"); Check.True(h.Guide.SignedIn && h.Guide.User == User, "signed in: " + h.Guide.Status); QuestGuide g = h.Guide.Guide; Check.Eq(g.Quests.Count, 3, "three quest pages (the item page isn't one)"); Check.True(g.Contracts.Count == 1 && g.Contracts[0].Npc == "Quartermaster Ivo", "the contract and who sells it"); Check.True(g.KillTasks.SequenceEqual(new[] { "Glimmer Beetle Kill Task" }), "the kill task list"); Check.True(g.Society.TryGetValue("Thornbound Initiate Tasks", out string? rank) && rank == "Initiate", "the society quest's rank"); Check.False(g.Society.ContainsKey("Moth Glow Sac"), "an items sub-category isn't followed"); Check.Eq(g.Source, "wiki.test", "the source is the wiki's host"); Check.Eq(g.Find("The Lantern Moth Errand")?.Url, "https://wiki.test/The_Lantern_Moth_Errand", "page addresses from the site's article path"); Check.True(File.Exists(IltWikiGuide.GuidePath(Api)) && WikiLoginStore.Exists, "the guide and the sealed login are saved"); Check.True(h.Said.Any(s => s.Ok && s.Text.Contains("signed in as Tester")) && h.Said.Any(s => s.Ok && s.Text.Contains("3 quests")), "the sign-in and the read answered in chat: " + h.AllSaid); Check.False(h.AllSaid.Contains(Password) || h.Guide.Status.Contains(Password) || string.Join(" ", h.Guide.StatusLines()).Contains(Password), "no chat or status line holds the password"); NoSecretOnDisk("after the read"); ServerQuestGuideClient c = ReadPublished(); Check.True(c.Available && c.Guide.Quests.Count == 3 && c.Info!.Takes("refresh") && c.Info.Takes("settings"), "RynthOracle gets the guide, with Refresh"); Check.False(c.Info.Status.Contains(Password), "the published status holds no secret"); // A fresh plugin start reads the saved guide without a request. var again = new Harness("reads", fresh: false); Check.True(again.Guide.SignedIn && again.Guide.Guide.Quests.Count == 3 && again.Handlers == 0, "a restart: signed in, the saved guide, no request"); Check.False(again.Guide.OnLogin(true), "a fresh guide isn't read again at login"); var later = new Harness("reads", fresh: false); later.Now = later.Now.AddHours(25); Check.True(later.Guide.OnLogin(true), "a day old: read again at login"); later.Settle(); Check.True(later.Guide.Status.Contains("3 quests"), "and read: " + later.Guide.Status); Check.False(later.Said.Any(), "the login read is quiet when it works"); var off = new Harness("reads", fresh: false); off.Now = later.Now.AddHours(30); off.Guide.SetDaily(false); Check.False(off.Guide.OnLogin(true), "the switch off: no login read"); off.Guide.SetDaily(true); Check.False(off.Guide.OnLogin(false), "not ILT: no login read"); } private static void OnlyEdited() { var h = SignedIn("edited"); int firstContent = h.Wiki.ContentTitles.Count; Check.True(firstContent == 4, "the first read fetched every listed page (3 quests, 1 contract): " + firstContent); Check.False(h.Guide.Refresh(fromChat: true), "Refresh right after a read waits"); Check.True(h.Said.Last().Text.Contains("again in") && !h.Said.Last().Ok, "and says when: " + h.Said.Last().Text); h.Wiki.Pages["The Lantern Moth Errand"] = (201, MothErrand.Replace("20 Hours", "18 Hours")); h.Now = h.Now.AddMinutes(6); h.Wiki.ContentTitles.Clear(); Check.True(h.Guide.Refresh(fromChat: true), "Refresh after 5 minutes reads"); h.Settle(); // The edited quest, plus the pages that aren't quests (they are checked again each time). Check.True(h.Wiki.ContentTitles.Contains("The Lantern Moth Errand") && !h.Wiki.ContentTitles.Contains("Glimmer Beetle Kill Task") && !h.Wiki.ContentTitles.Contains("Thornbound Initiate Tasks") && !h.Wiki.ContentTitles.Contains("Contract for the Bramble Wardens"), "only the edited page (and non-quest pages) fetched: " + string.Join(", ", h.Wiki.ContentTitles)); Check.Eq(h.Guide.Guide.Find("The Lantern Moth Errand")?.Repeat, "18 Hours", "the edit is in the guide"); Check.Eq(h.Guide.Guide.Find("Glimmer Beetle Kill Task")?.Rev, 102L, "an unchanged page kept from the saved guide"); } private static void LostSession() { var h = new Harness("lost"); h.Wiki.DropSessionAfter = 3; h.Guide.SignIn(Api, User, Password, fromChat: false); h.Settle(); Check.True(h.Guide.Guide.Quests.Count == 3 && h.Wiki.Logins == 2, $"the session ended mid-read; signed in again and finished ({h.Wiki.Logins} sign-ins, {h.Guide.Status})"); var r = new Harness("revoked"); r.Wiki.DropSessionAfter = 3; r.Wiki.RevokeAfterFirstLogin = true; r.Guide.SignIn(Api, User, Password, fromChat: false); r.Settle(); Check.True(r.Guide.Status.Contains("signing in again didn't work") && r.Guide.Status.Contains("fake wiki"), "a revoked bot password ends the read plainly: " + r.Guide.Status); Check.True(r.Guide.Guide.IsEmpty && r.Said.Any(s => !s.Ok), "no guide from it, and chat says so"); Check.False(r.AllSaid.Contains(Password) || r.Guide.Status.Contains(Password), "without the password"); } private static void SignOut() { var h = SignedIn("signout"); Check.True(h.Guide.SignOut(fromChat: true), "signed out"); Check.True(h.Said.Last().Ok && h.Said.Last().Text.Contains("deleted"), "and says so: " + h.Said.Last().Text); Check.False(WikiLoginStore.Exists || File.Exists(IltWikiGuide.GuidePath(Api)), "the sealed login and the saved guide are gone"); Check.True(!h.Guide.SignedIn && h.Guide.Guide.IsEmpty, "nothing in memory either"); h.Guide.Tick(); ServerQuestGuideClient c = ReadPublished(); Check.True(c.Guide.IsEmpty && !c.Info!.Takes("refresh"), "RynthOracle's copy goes"); Check.Eq(h.Guide.Address, Api, "the address stays (it is no secret)"); Check.True(h.Guide.SignOut(fromChat: false), "signing out again is fine"); var restart = new Harness("signout", fresh: false); Check.False(restart.Guide.SignedIn, "a restart stays signed out"); } private static void Commands() { var h = new Harness("commands"); void Run(string line, bool ok, string needle) { h.Said.Clear(); h.Guide.HandleCommand(line.Split(' ', StringSplitOptions.RemoveEmptyEntries)); Check.True(h.Said.Count > 0, $"/ilt wiki {line}: answers"); Check.True(h.Said.All(s => s.Ok == ok), $"/ilt wiki {line}: {(ok ? "worked" : "didn't")} ({h.AllSaid})"); Check.True(h.AllSaid.Contains(needle, StringComparison.OrdinalIgnoreCase), $"/ilt wiki {line}: says '{needle}' ({h.AllSaid})"); } Run("status", true, "Off until you sign in"); Run("", true, "address: not set"); Run("refresh", false, "not signed in"); Run("signin", true, "settings window is open"); Check.Eq(h.SettingsOpened, 1, "signin without a login opens the settings"); h.Said.Clear(); h.Guide.HandleCommand(new[] { "signin", User, Password }); Check.True(h.Said.Count == 1 && !h.Said[0].Ok && h.Said[0].Text.Contains("aren't taken in chat"), "a login typed in chat is refused: " + h.AllSaid); Check.False(h.AllSaid.Contains(Password) || h.AllSaid.Contains(User), "and not repeated"); Check.Eq(h.Handlers, 0, "nothing was sent"); Check.False(WikiLoginStore.Exists, "nothing was saved"); Run("signout", true, "not signed in"); Run("address http://wiki.test/", false, "https"); Run("address wiki.test", true, Api); Run("address", true, Api); Run("auto off", true, "is off"); Check.False(h.Guide.Daily, "the switch is off"); Run("auto on", true, "is on"); Run("help", true, "/ilt wiki signout"); Run("frobnicate", false, "unknown"); var s = SignedIn("commands-signed"); s.Said.Clear(); s.Guide.HandleCommand(new[] { "status" }); Check.True(s.AllSaid.Contains("signed in as " + User) && s.AllSaid.Contains("3 quests"), "status when signed in: " + s.AllSaid); s.Said.Clear(); s.Guide.HandleCommand(new[] { "address", "https://other.test/" }); Check.True(s.Said.Count == 1 && !s.Said[0].Ok && s.Said[0].Text.Contains("sign out first"), "the address can't change while signed in"); s.Now = s.Now.AddMinutes(10); s.Said.Clear(); s.Guide.HandleCommand(new[] { "signin" }); Check.True(s.Said.Any(x => x.Ok && x.Text.Contains("signing in again")), "signin with a saved login signs in again: " + s.AllSaid); s.Settle(); Check.True(s.Guide.Status.Contains("3 quests"), "and reads: " + s.Guide.Status); } private static void OtherAddress() { var h = new Harness("other"); h.Guide.SetAddress("https://wiki.test/", fromChat: false); Check.True(WikiLoginStore.Save(new WikiLogin("https://other.test/api.php", User, Password), out _), "a login for another wiki is on disk"); var again = new Harness("other", fresh: false); Check.False(again.Guide.SignedIn, "it isn't used for this address"); Check.True(again.Guide.Status.Contains("another wiki address"), "and the status says why: " + again.Guide.Status); Check.False(again.Guide.OnLogin(true) || again.Guide.Refresh(fromChat: false), "no read with it"); Check.Eq(again.Handlers, 0, "nothing was sent anywhere"); } private static void Parsing() { GuideQuest q = QuestWikiText.ParseQuest("The Lantern Moth Errand", MothErrand, 101, "https://wiki.test/"); Check.True(q.Level == "120+" && q.StartsWith == "Warden Pellis" && q.StartsAt == "Hollow Reach" && q.IsDaily, "the summary box"); Check.True(q.Overview.StartsWith("Warden Pellis wants"), "the overview"); Check.Eq(q.Steps.Count, 3, "three numbered steps"); Check.True(q.Steps[0].Coords.SequenceEqual(new[] { "12.3N, 45.6E" }) && q.Steps[0].Stamps.SequenceEqual(new[] { "LanternMothErrandStarted" }), "a step's place and stamp"); Check.True(q.Steps[1].Coords.SequenceEqual(new[] { "14.0N, 47.2E" }) && q.Loot.SequenceEqual(new[] { "Moth Glow Sac" }), "the loot is the killed-for item, not the handed-in one"); Check.True(q.Rewards.Contains("For Hand in a glow sac:") && q.Rewards.Contains("XP: 5,000,000"), "the rewards table"); GuideQuest k = QuestWikiText.ParseQuest("Glimmer Beetle Kill Task", GlimmerBeetles, 102, "https://wiki.test/"); Check.True(k.IsKillTaskPage && k.IsWeekly && k.KillTarget == 50, "a weekly kill task of 50"); Check.True(k.Overview.StartsWith("Thin out") && k.Steps.Count == 3, "the Discord description and the paragraph steps"); Check.True(k.Steps[0].Coords.SequenceEqual(new[] { "3.1S, 70.2W" }), "coordinates written '3.1s,70.2w'"); Check.True(k.AllStamps().Contains("GlimmerBeetleTaskTaken") && k.AllStamps().Contains("GlimmerBeetleKills"), "the QB Stamps, cut to the flag"); var (pages, cont) = IltWikiReader.Generated("{\"continue\":{\"gcmcontinue\":\"page|X|9\",\"continue\":\"gcm||\"},\"query\":{\"pages\":[{\"ns\":0,\"title\":\"A\",\"lastrevid\":5},{\"ns\":14,\"title\":\"Category:B\"},{\"ns\":0,\"title\":\"C\",\"missing\":true}]}}"); Check.True(pages.Count == 2 && pages[0] == ("A", 0, 5L) && pages[1].Ns == 14 && cont.Count == 2, "a generator answer: pages, sub-categories, the continuation"); Check.True(IltWikiReader.RankOf("Category:Society Quests: Knight Rank") == "Knight" && IltWikiReader.SkipCategory("Category:Society Items"), "ranks and skipped sub-categories"); } }