Snapshot for release 2026.10.21.1 (internal 32a418d)
This commit is contained in:
commit
6fe5630e8c
202 changed files with 43765 additions and 0 deletions
277
Tools/RynthILT.Tests/AetheriaChunkTests.cs
Normal file
277
Tools/RynthILT.Tests/AetheriaChunkTests.cs
Normal file
|
|
@ -0,0 +1,277 @@
|
|||
using RynthCore.Plugin.RynthILT.Hub;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthILT.Tests;
|
||||
|
||||
// The Lugian-hammer aetheria rules (Hub/IltChunkClap.cs): Infinite Leaftide aetheria goes up to
|
||||
// level 10, and aetheria carrying a C, CD or CDR rating is kept unless its keep switch is off.
|
||||
// The cap covers levelled Coalesced Aetheria; an unlevelled one chunks, as in ub-IT. Corrupted
|
||||
// weapons follow ub-IT's hard rules and its optional keep rules, and /clap needs a colour with its
|
||||
// own trinket.
|
||||
internal static class AetheriaChunkTests
|
||||
{
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("aetheria: the chunk cap runs to one past ILT's level 10", Cap);
|
||||
r.Add("aetheria: C / CD / CDR ratings are kept by default, each with its own switch", Ratings);
|
||||
r.Add("aetheria: rating level - at or above keeps, below chunks (Coalesced too)", RatingLevel);
|
||||
r.Add("aetheria: the level cap applies to levelled Coalesced Aetheria; unlevelled Coalesced chunks (ub-IT)", CoalescedCap);
|
||||
r.Add("aetheria: a failed read is not 'unlevelled': unreadable pieces are kept, levelled Coalesced keeps its cap", UnreadableAetheria);
|
||||
r.Add("aetheria: never-chunk, tinker / imbue, item XP, ratings and the cap each keep a piece", AetheriaRules);
|
||||
r.Add("chunk: kind by class and name; chunks and powder are clap material", Kinds);
|
||||
r.Add("corrupted: ub-IT hard rules (workmanship, cleave 1, or 2 on two-handed non-thrust)", CorruptedHardRules);
|
||||
r.Add("corrupted: ub-IT keep rules, all off by default", CorruptedKeepRules);
|
||||
r.Add("corrupted: a failed read is kept; two-handed cleave 2 chunks and other cleave 2 does not", UnreadableCorrupted);
|
||||
r.Add("chunk: busy blocks peace mode, not combat with chunk-in-combat on (ub-IT v2.0.1059)", BusyGate);
|
||||
r.Add("chunk: a target that leaves the pack counts as chunked; still carried after 10 s times out", WaitOutcome);
|
||||
r.Add("clap: the server's WCIDs, each colour paired with its trinket, Coalesced only unrevealed level 1-3", ClapPairs);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Coalesced Aetheria has its level from loot (ACECustom 1-10, ratings at 6+); it used to skip
|
||||
/// the cap, so a cap of 9 still chunked a level 10 Coalesced piece.
|
||||
/// </summary>
|
||||
private static void CoalescedCap()
|
||||
{
|
||||
Check.True(IltChunkClap.UnderChunkCap(8, 9), "level 8 under a cap of 9");
|
||||
Check.False(IltChunkClap.UnderChunkCap(9, 9), "level 9 is not below 9");
|
||||
Check.False(IltChunkClap.UnderChunkCap(10, 9), "a level 10 Coalesced piece is kept");
|
||||
Check.True(IltChunkClap.UnderChunkCap(10, 11), "11 chunks every level");
|
||||
Check.False(IltChunkClap.UnderChunkCap(0, 11), "revealed aetheria with no level read: never chunked");
|
||||
Check.False(IltChunkClap.UnderChunkCap(9, 9, coalesced: true), "a levelled Coalesced piece keeps the cap");
|
||||
Check.True(IltChunkClap.UnderChunkCap(0, 4, coalesced: true), "an unlevelled Coalesced piece chunks (it used to be kept forever)");
|
||||
Check.True(IltChunkClap.UnderChunkCap(0, 1, coalesced: true), "even with the lowest cap");
|
||||
}
|
||||
|
||||
private static readonly IltChunkClap.AetheriaFacts PlainCoalesced = new(
|
||||
Coalesced: true, MaxLevel: 0, NeverChunk: false, ItemXp: 0, Tinkers: 0, Imbue: 0, Crit: 0, CritDamage: 0, CritDamageResist: 0);
|
||||
|
||||
private static void AetheriaRules()
|
||||
{
|
||||
var g = new IltGearState();
|
||||
Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced), null, "a plain unlevelled Coalesced piece chunks");
|
||||
Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced with { MaxLevel = 3 }), null, "level 3 under the default cap of 4");
|
||||
Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced with { MaxLevel = 4 }), "level at or above the cap", "level 4 at the default cap");
|
||||
Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced with { NeverChunk = true }), "never-chunk flag", "bool 9030");
|
||||
Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced with { Tinkers = 1 }), "tinkered or imbued", "tinkered");
|
||||
Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced with { Imbue = 4 }), "tinkered or imbued", "imbued");
|
||||
Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced with { ItemXp = 100 }), "has item XP", "levelled by use");
|
||||
Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced with { Crit = 2 }), "kept for its C / CD / CDR rating", "a C 2 piece is kept by default");
|
||||
g.KeepAetheriaWithCrit = false;
|
||||
Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced with { Crit = 2 }), null, "C switch off: a C 2 piece chunks");
|
||||
Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced with { Coalesced = false }), "no level read", "revealed aetheria needs a level");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The rules read 0 for "the item has none" and for "the host could not read it". An unlevelled
|
||||
/// Coalesced piece is chunked (ub-IT), but only when its level was truly read as none; a piece whose
|
||||
/// properties could not be read is kept, whatever the numbers say.
|
||||
/// </summary>
|
||||
private static void UnreadableAetheria()
|
||||
{
|
||||
var g = new IltGearState();
|
||||
Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced), null, "read as unlevelled: chunks");
|
||||
Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced with { Unreadable = "no appraisal" }),
|
||||
"item data unreadable (no appraisal)", "the same piece with failed reads: kept");
|
||||
Check.Eq(IltChunkClap.AetheriaSkip(g, PlainCoalesced with { MaxLevel = 2, Unreadable = "no item XP" }),
|
||||
"item data unreadable (no item XP)", "a levelled piece with failed reads: kept");
|
||||
Check.Eq(IltChunkClap.AetheriaSkip(new IltGearState { ChunkAetheriaUnderLevel = 1 }, PlainCoalesced), null, "unlevelled chunks at the lowest cap too");
|
||||
|
||||
// Levelled Coalesced pieces keep the cap.
|
||||
var cap9 = new IltGearState { ChunkAetheriaUnderLevel = 9 };
|
||||
Check.Eq(IltChunkClap.AetheriaSkip(cap9, PlainCoalesced with { MaxLevel = 8 }), null, "levelled 8 under a cap of 9");
|
||||
Check.Eq(IltChunkClap.AetheriaSkip(cap9, PlainCoalesced with { MaxLevel = 9 }), "level at or above the cap", "levelled 9 at a cap of 9");
|
||||
Check.Eq(IltChunkClap.AetheriaSkip(cap9, PlainCoalesced with { MaxLevel = 10 }), "level at or above the cap", "levelled 10 over a cap of 9");
|
||||
Check.Eq(IltChunkClap.AetheriaSkip(new IltGearState { ChunkAetheriaUnderLevel = 11 }, PlainCoalesced with { MaxLevel = 10 }), null, "cap 11 chunks every level");
|
||||
}
|
||||
|
||||
private static void UnreadableCorrupted()
|
||||
{
|
||||
var g = new IltGearState();
|
||||
Check.Eq(IltChunkClap.CorruptedSkip(g, PlainSword with { Unreadable = "no appraisal" }),
|
||||
"item data unreadable (no appraisal)", "failed reads: kept (they would read as a plain weapon)");
|
||||
var keepCb = new IltGearState { KeepCorruptedCrushingBlow = true };
|
||||
Check.Eq(IltChunkClap.CorruptedSkip(keepCb, PlainSword with { Unreadable = "float properties" }),
|
||||
"item data unreadable (float properties)", "a keep rule whose float cannot be read keeps the weapon");
|
||||
var twoHanded = PlainSword with { WieldSkill = 41, Cleaving = 2 };
|
||||
Check.Eq(IltChunkClap.CorruptedSkip(g, twoHanded), null, "two-handed cleave 2 chunks");
|
||||
Check.Eq(IltChunkClap.CorruptedSkip(g, PlainSword with { Cleaving = 2 }), "cleave over the limit", "other cleave 2 is kept");
|
||||
Check.Eq(IltChunkClap.CorruptedSkip(g, twoHanded with { WieldSkill = 0, WeaponType = 11 }), null, "WeaponType two-handed counts");
|
||||
Check.Eq(IltChunkClap.CorruptedSkip(g, twoHanded with { AttackType = 2 }), "cleave over the limit", "two-handed thrust keeps the 1 limit");
|
||||
}
|
||||
|
||||
private static void Kinds()
|
||||
{
|
||||
var gem = RynthCore.Loot.AcObjectClass.Gem;
|
||||
Check.Eq(IltChunkClap.KindOf(gem, "Coalesced Aetheria"), IltChunkClap.ChunkKind.Aetheria, "Coalesced");
|
||||
Check.Eq(IltChunkClap.KindOf(gem, "Blue Aetheria"), IltChunkClap.ChunkKind.Aetheria, "revealed sigil");
|
||||
Check.Eq(IltChunkClap.KindOf(gem, "Red Aetheria Chunk"), IltChunkClap.ChunkKind.None, "chunk");
|
||||
Check.Eq(IltChunkClap.KindOf(gem, "Aetheria Powder"), IltChunkClap.ChunkKind.None, "powder");
|
||||
Check.Eq(IltChunkClap.KindOf(RynthCore.Loot.AcObjectClass.MeleeWeapon, "Corrupted Greatsword"), IltChunkClap.ChunkKind.Corrupted, "melee");
|
||||
Check.Eq(IltChunkClap.KindOf(RynthCore.Loot.AcObjectClass.MissileWeapon, "Corrupted Bow"), IltChunkClap.ChunkKind.Corrupted, "missile");
|
||||
Check.Eq(IltChunkClap.KindOf(RynthCore.Loot.AcObjectClass.WandStaffOrb, "Corrupted Orb"), IltChunkClap.ChunkKind.None, "casters are not chunked (ub-IT)");
|
||||
Check.Eq(IltChunkClap.KindOf(RynthCore.Loot.AcObjectClass.MeleeWeapon, "Greatsword"), IltChunkClap.ChunkKind.None, "not corrupted");
|
||||
}
|
||||
|
||||
private static readonly IltChunkClap.CorruptedFacts PlainSword = new() { Workmanship = 6, AttackType = 4, WieldSkill = 45 };
|
||||
|
||||
private static void CorruptedHardRules()
|
||||
{
|
||||
var g = new IltGearState();
|
||||
Check.Eq(IltChunkClap.CorruptedSkip(g, PlainSword), null, "a plain corrupted sword chunks");
|
||||
Check.Eq(IltChunkClap.CorruptedSkip(g, PlainSword with { Workmanship = 0 }), "no workmanship", "workmanship 0");
|
||||
Check.Eq(IltChunkClap.CorruptedSkip(g, PlainSword with { Tinkers = 1 }), "tinkered or imbued", "tinkered");
|
||||
Check.Eq(IltChunkClap.CorruptedSkip(g, PlainSword with { Imbue = 1 }), "tinkered or imbued", "imbued");
|
||||
Check.Eq(IltChunkClap.CorruptedSkip(g, PlainSword with { NeverChunk = true }), "never-chunk flag", "bool 9030");
|
||||
Check.Eq(IltChunkClap.CorruptedSkip(g, PlainSword with { Cleaving = 1 }), null, "one-handed cleave 1");
|
||||
Check.Eq(IltChunkClap.CorruptedSkip(g, PlainSword with { Cleaving = 2 }), "cleave over the limit", "one-handed cleave 2");
|
||||
|
||||
var twoHanded = PlainSword with { WieldSkill = 41, Cleaving = 2 };
|
||||
Check.Eq(IltChunkClap.CorruptedSkip(g, twoHanded), null, "two-handed cleave 2 chunks (it never did before)");
|
||||
Check.Eq(IltChunkClap.CorruptedSkip(g, twoHanded with { Cleaving = 3 }), "cleave over the limit", "two-handed cleave 3");
|
||||
Check.Eq(IltChunkClap.CorruptedSkip(g, twoHanded with { AttackType = 2 }), "cleave over the limit", "a two-handed thrust weapon keeps the 1 limit");
|
||||
Check.Eq(IltChunkClap.MaxChunkCleave(0, 11, 4), 2, "WeaponType TwoHanded counts too");
|
||||
Check.Eq(IltChunkClap.MaxChunkCleave(45, 0, 4), 1, "one-handed");
|
||||
}
|
||||
|
||||
private static void CorruptedKeepRules()
|
||||
{
|
||||
var g = new IltGearState();
|
||||
var loaded = PlainSword with
|
||||
{
|
||||
CritFrequency = 0.1, CritMultiplier = 1.5, IgnoreArmor = 0.2, Slayer = 5, AttackType = 160,
|
||||
ElementalBonus = 10, MaxDamage = 400, Spells = new[] { 2072 },
|
||||
};
|
||||
Check.Eq(IltChunkClap.CorruptedSkip(g, loaded), null, "every keep rule is off by default");
|
||||
|
||||
Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedCrushingBlow = true }, loaded), "kept: Crushing Blow", "Crushing Blow");
|
||||
Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedBitingStrike = true }, loaded), "kept: Biting Strike", "Biting Strike");
|
||||
Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedArmorCleaving = true }, loaded), "kept: Armor Cleaving", "Armor Cleaving");
|
||||
Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedAnySlayer = true }, loaded), "kept: slayer", "slayer");
|
||||
Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedMultiStrike = true }, loaded), "kept: multi-strike", "multi-strike 160");
|
||||
Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedMultiStrike = true }, PlainSword), null, "a single slash is not multi-strike");
|
||||
Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedElementalBonus = true }, loaded), "kept: elemental bonus", "elemental");
|
||||
Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedMaxDamageAtLeast = 400 }, loaded), "kept: max damage", "max damage at the limit");
|
||||
Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedMaxDamageAtLeast = 401 }, loaded), null, "max damage under the limit");
|
||||
Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedAnySpell = true }, loaded), "kept: has a spell", "any spell");
|
||||
Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedSpellIds = "100, 2072" }, loaded), "kept: listed spell", "listed spell id");
|
||||
Check.Eq(IltChunkClap.CorruptedSkip(new IltGearState { KeepCorruptedSpellIds = "100 200" }, loaded), null, "other spell ids");
|
||||
|
||||
Check.Eq(IltChunkClap.ParseSpellIds("1, 2;3 x -4 0").Count, 3, "positive ids only, any separator");
|
||||
Check.Eq(IltChunkClap.ParseSpellIds(null).Count, 0, "no list");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Silentkelpie 2026-10-18: a Coalesced piece was chunked (Red Aetheria Chunk arrived) with no
|
||||
/// result line, and it was filed as skipped after 10 s instead of counted.
|
||||
/// </summary>
|
||||
private static void WaitOutcome()
|
||||
{
|
||||
Check.Eq(IltChunkClap.WaitOutcome(500, targetStillCarried: true), IltChunkClap.ChunkWait.Waiting, "still carried, within the wait");
|
||||
Check.Eq(IltChunkClap.WaitOutcome(1_100, targetStillCarried: false), IltChunkClap.ChunkWait.Gone, "gone from the pack: chunked");
|
||||
Check.Eq(IltChunkClap.WaitOutcome(12_000, targetStillCarried: false), IltChunkClap.ChunkWait.Gone, "gone beats the timeout");
|
||||
Check.Eq(IltChunkClap.WaitOutcome(10_000, targetStillCarried: true), IltChunkClap.ChunkWait.TimedOut, "still carried at 10 s: timed out");
|
||||
}
|
||||
|
||||
private static void BusyGate()
|
||||
{
|
||||
Check.True(IltChunkClap.AllowsChunkWhileBusy(isBusy: false, isPeace: true, chunkInCombat: false), "idle in peace");
|
||||
Check.False(IltChunkClap.AllowsChunkWhileBusy(isBusy: true, isPeace: true, chunkInCombat: true), "busy in peace waits");
|
||||
Check.True(IltChunkClap.AllowsChunkWhileBusy(isBusy: true, isPeace: false, chunkInCombat: true), "busy swinging with chunk-in-combat");
|
||||
Check.False(IltChunkClap.AllowsChunkWhileBusy(isBusy: true, isPeace: false, chunkInCombat: false), "busy in combat without it");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ACECustom /clap: red (Coalesced 42636 at 1-3, chunk 310147, powder 42644) with Empyrean
|
||||
/// Trinkets (34276); blue (42635, 310149, 300019) with Falatacot (34277). 42635/42636 were taken
|
||||
/// for chunks, and one side alone counted, so auto-clap sent /clap with nothing to pair.
|
||||
/// </summary>
|
||||
private static void ClapPairs()
|
||||
{
|
||||
const string Co = "Coalesced Aetheria";
|
||||
Check.Eq(IltChunkClap.ClapPartOf(42636, Co, 2), IltChunkClap.ClapPart.Red, "red Coalesced level 2");
|
||||
Check.Eq(IltChunkClap.ClapPartOf(42635, Co, 3), IltChunkClap.ClapPart.Blue, "blue Coalesced level 3");
|
||||
Check.Eq(IltChunkClap.ClapPartOf(42636, Co, 0), IltChunkClap.ClapPart.Red, "level not read yet: the server decides");
|
||||
Check.Eq(IltChunkClap.ClapPartOf(42636, Co, 4), IltChunkClap.ClapPart.None, "level 4 Coalesced is not clapped");
|
||||
Check.Eq(IltChunkClap.ClapPartOf(42636, "Aetheria", 1), IltChunkClap.ClapPart.None, "revealed aetheria is not clapped");
|
||||
Check.Eq(IltChunkClap.ClapPartOf(42637, Co, 1), IltChunkClap.ClapPart.None, "yellow has no clap use");
|
||||
Check.Eq(IltChunkClap.ClapPartOf(310147, "Red Aetheria Chunk", 0), IltChunkClap.ClapPart.Red, "red chunk");
|
||||
Check.Eq(IltChunkClap.ClapPartOf(310149, "Blue Aetheria Chunk", 0), IltChunkClap.ClapPart.Blue, "blue chunk");
|
||||
Check.Eq(IltChunkClap.ClapPartOf(310150, "Yellow Aetheria Chunk", 0), IltChunkClap.ClapPart.None, "yellow chunk");
|
||||
Check.Eq(IltChunkClap.ClapPartOf(42644, "Aetheria Powder", 0), IltChunkClap.ClapPart.Red, "red powder");
|
||||
Check.Eq(IltChunkClap.ClapPartOf(300019, "Aetheria Powder", 0), IltChunkClap.ClapPart.Blue, "blue powder");
|
||||
Check.Eq(IltChunkClap.ClapPartOf(34276, "Ancient Empyrean Trinket", 0), IltChunkClap.ClapPart.Empyrean, "Empyrean trinket");
|
||||
Check.Eq(IltChunkClap.ClapPartOf(34277, "Ancient Falatacot Trinket", 0), IltChunkClap.ClapPart.Falatacot, "Falatacot trinket");
|
||||
Check.Eq(IltChunkClap.ClapPartOf(0, "Red Aetheria Chunk", 0), IltChunkClap.ClapPart.Red, "no WCID yet: the chunk name");
|
||||
Check.Eq(IltChunkClap.ClapPartOf(0, Co, 1), IltChunkClap.ClapPart.None, "no WCID yet: a Coalesced piece's colour is unknown");
|
||||
Check.Eq(IltChunkClap.ClapPartOf(273, "Pyreal", 0), IltChunkClap.ClapPart.None, "anything else");
|
||||
|
||||
var R = IltChunkClap.ClapPart.Red; var B = IltChunkClap.ClapPart.Blue;
|
||||
var E = IltChunkClap.ClapPart.Empyrean; var F = IltChunkClap.ClapPart.Falatacot;
|
||||
Check.True(IltChunkClap.CanClap(new[] { R, E }), "red + Empyrean");
|
||||
Check.True(IltChunkClap.CanClap(new[] { B, F }), "blue + Falatacot");
|
||||
Check.False(IltChunkClap.CanClap(new[] { R, F }), "red needs Empyrean, not Falatacot");
|
||||
Check.False(IltChunkClap.CanClap(new[] { B, E }), "blue needs Falatacot, not Empyrean");
|
||||
Check.False(IltChunkClap.CanClap(new[] { E, F }), "trinkets alone");
|
||||
Check.False(IltChunkClap.CanClap(new[] { R, B }), "aetheria alone");
|
||||
Check.False(IltChunkClap.CanClap(System.Array.Empty<IltChunkClap.ClapPart>()), "nothing carried");
|
||||
}
|
||||
|
||||
private static void Cap()
|
||||
{
|
||||
Check.Eq(IltInventory.AetheriaMaxLevel, 10, "ILT max aetheria level");
|
||||
Check.Eq(IltChunkClap.ClampUnderLevel(0), 1, "below 1 clamps to 1");
|
||||
Check.Eq(IltChunkClap.ClampUnderLevel(7), 7, "7 (retail clamp was 6) is allowed");
|
||||
Check.Eq(IltChunkClap.ClampUnderLevel(11), 11, "11 chunks every level");
|
||||
Check.Eq(IltChunkClap.ClampUnderLevel(50), 11, "above 11 clamps to 11");
|
||||
Check.Eq(new IltGearState().ChunkAetheriaUnderLevel, 4, "the default cap is unchanged");
|
||||
}
|
||||
|
||||
private static void Ratings()
|
||||
{
|
||||
var g = new IltGearState();
|
||||
Check.True(g.KeepAetheriaWithCrit && g.KeepAetheriaWithCritDamage && g.KeepAetheriaWithCritDamageResist, "all keep switches on by default");
|
||||
Check.False(IltChunkClap.KeptForRatings(g, 0, 0, 0), "no rating: chunkable");
|
||||
Check.True(IltChunkClap.KeptForRatings(g, 2, 0, 0), "C kept");
|
||||
Check.True(IltChunkClap.KeptForRatings(g, 0, 1, 0), "CD kept");
|
||||
Check.True(IltChunkClap.KeptForRatings(g, 0, 0, 3), "CDR kept");
|
||||
|
||||
g.KeepAetheriaWithCrit = false;
|
||||
Check.False(IltChunkClap.KeptForRatings(g, 2, 0, 0), "C chunkable with its switch off");
|
||||
Check.True(IltChunkClap.KeptForRatings(g, 2, 0, 3), "CDR still keeps a C+CDR sigil");
|
||||
g.KeepAetheriaWithCritDamage = false;
|
||||
g.KeepAetheriaWithCritDamageResist = false;
|
||||
Check.False(IltChunkClap.KeptForRatings(g, 3, 3, 3), "every switch off: ratings don't protect");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The rating level: a C / CD / CDR rating at or above it keeps the piece, a lower one chunks
|
||||
/// (if the level cap allows). The default of 1 keeps any rating, as before.
|
||||
/// </summary>
|
||||
private static void RatingLevel()
|
||||
{
|
||||
var g = new IltGearState();
|
||||
Check.Eq(g.KeepAetheriaRatingAtLeast, 1, "default: any rating keeps");
|
||||
Check.True(IltChunkClap.KeptForRatings(g, 1, 0, 0), "C 1 kept at the default");
|
||||
|
||||
g.KeepAetheriaRatingAtLeast = 2;
|
||||
Check.False(IltChunkClap.KeptForRatings(g, 1, 0, 0), "C 1 below level 2: chunks");
|
||||
Check.True(IltChunkClap.KeptForRatings(g, 2, 0, 0), "C 2 at level 2: kept");
|
||||
Check.True(IltChunkClap.KeptForRatings(g, 3, 0, 0), "C 3 above level 2: kept");
|
||||
Check.True(IltChunkClap.KeptForRatings(g, 1, 0, 2), "CDR 2 keeps a C 1 + CDR 2 piece");
|
||||
Check.False(IltChunkClap.KeptForRatings(g, 1, 1, 1), "every rating below the level: chunks");
|
||||
|
||||
g.KeepAetheriaWithCrit = false;
|
||||
Check.False(IltChunkClap.KeptForRatings(g, 5, 0, 0), "a switch that is off ignores the level");
|
||||
|
||||
Check.Eq(IltChunkClap.ClampRatingLevel(0), 1, "below 1 clamps to 1");
|
||||
Check.Eq(IltChunkClap.ClampRatingLevel(99), IltChunkClap.MaxRatingLevel, "clamped to the maximum");
|
||||
|
||||
var coalescedC1 = PlainCoalesced with { Crit = 1 };
|
||||
var level2 = new IltGearState { KeepAetheriaRatingAtLeast = 2 };
|
||||
Check.Eq(IltChunkClap.AetheriaSkip(level2, coalescedC1), null, "an unlevelled C 1 Coalesced piece chunks at rating level 2");
|
||||
Check.Eq(IltChunkClap.AetheriaSkip(level2, PlainCoalesced with { Crit = 2 }), "kept for its C / CD / CDR rating", "a C 2 one is kept");
|
||||
Check.Eq(IltChunkClap.AetheriaSkip(level2, coalescedC1 with { MaxLevel = 6 }), "level at or above the cap",
|
||||
"a low rating does not override the level cap");
|
||||
}
|
||||
}
|
||||
543
Tools/RynthILT.Tests/AttributeRaiserTests.cs
Normal file
543
Tools/RynthILT.Tests/AttributeRaiserTests.cs
Normal file
|
|
@ -0,0 +1,543 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using RynthCore.Plugin.RynthILT.Hub;
|
||||
using RynthCore.PluginSdk;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthILT.Tests;
|
||||
|
||||
// Server Features gate + the infinite-attribute raiser (2026-10-06; RynthAi's ILT Hub, in RynthILT
|
||||
// since 2026-10-13). The gate decides from RynthILT's server list (world-name patterns) and the
|
||||
// character's "Treat this world as ILT" whether the ILT features ask the server at all; the raiser reads "/xp all" costs and spends unassigned XP with "/attr <abbr> 1"
|
||||
// on the ticked stats, in the chosen order, never below the reserve.
|
||||
internal static class AttributeRaiserTests
|
||||
{
|
||||
private const uint Player = 0x50000C01;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("server features: name patterns (exact, wildcards, case)", Patterns);
|
||||
r.Add("server features: list parsing and the override", ListAndOverride);
|
||||
r.Add("attr raiser: pick by mode (priority, round robin, cheapest)", PickModes);
|
||||
r.Add("attr raiser: pick respects ticks, reserve and unknown costs", PickLimits);
|
||||
r.Add("attr raiser: order repair and stat names from server lines", OrderAndNames);
|
||||
r.Add("attr raiser: a run reads costs, raises in order, stops when nothing is affordable", FullRun);
|
||||
r.Add("attr raiser: off when the world is not in the Server Features list", GatedOff);
|
||||
r.Add("attr raiser: safety (stale costs, another stat's reply, gate off mid-run, held off)", Safety);
|
||||
r.Add("attr raiser: by-hand +1 / +10 priced like UB, refused when unaffordable, costs read on tab open", ByHandPriced);
|
||||
r.Add("aug planner: /aug pulled on tab open, totals, reset targets, copy texts", AugPlanner);
|
||||
r.Add("aug refresh: banner alone does not end /aug; Current updates from level lines", AugRefreshWaitsForLevelLines);
|
||||
r.Add("aug refresh: a probe that left Current empty retries /aug once; a click during the probe runs after it", AugProbeRetry);
|
||||
r.Add("aug lines: separators in the level (4,300 / 4.300 / 4 300 / 4'300) and trailing notes read", AugLineValues);
|
||||
r.Add("aug costs: UB's ILT model (tier starts at its S level) in closed form", AugCostModel);
|
||||
r.Add("aug costs: per-server multipliers and rules, saved and reset", AugCostSettings);
|
||||
}
|
||||
|
||||
/// <summary>UB Augs.cs GetCumulativeCost difference, level by level (the reference the closed form must match).</summary>
|
||||
private static decimal UbLoop(IltAugCostRow r, double[] m, int cur, int tgt)
|
||||
{
|
||||
decimal step = r.Base * (decimal)r.LinearPercent / 100m, total = 0;
|
||||
for (int i = cur + 1; i <= tgt; i++)
|
||||
{
|
||||
decimal b = r.Base + (i - 1) * step;
|
||||
double mult = i < r.S1 ? m[0] : i < r.S2 ? m[1] : i < r.S3 ? m[2] : i < r.S4 ? m[3] : m[4];
|
||||
total += b * (decimal)mult;
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
private static void AugCostModel()
|
||||
{
|
||||
var rows = IltAugCosts.DefaultRows().ToDictionary(x => x.Key);
|
||||
var m = IltAugCosts.DefaultMultipliers;
|
||||
var creature = rows["creature"];
|
||||
Check.Eq(IltAugCosts.LumCost(creature, m, 2748, 2749), 750_000m + 2748 * 975_000m, "level 2749 (S1 - 1) is the last x1 level");
|
||||
Check.Eq(IltAugCosts.LumCost(creature, m, 2749, 2750), (750_000m + 2749 * 975_000m) * 4, "level 2750 (S1) is the first x4 level");
|
||||
Check.Eq(rows["specialization"].S2, 2500, "Specialization uses UB's 1750/2500/3000/3750");
|
||||
Check.Eq(rows["summon"].S1, 1750, "Summon uses UB's 1750/2500/3000/3750");
|
||||
Check.Eq(creature.Cap, 0, "no target cap by default (UB has none)");
|
||||
|
||||
foreach (var (key, cur, tgt) in new[] { ("creature", 0, 6000), ("item", 1200, 3600), ("specialization", 1700, 3800),
|
||||
("duration", 999, 1001), ("summon", 3749, 3751), ("life", 10, 10) })
|
||||
Check.Eq(IltAugCosts.LumCost(rows[key], m, cur, tgt), UbLoop(rows[key], m, cur, tgt), $"{key} {cur}->{tgt} matches UB's loop");
|
||||
var odd = new double[] { 1.5, 2, 3.25, 10, 0 };
|
||||
Check.Eq(IltAugCosts.LumCost(rows["war"], odd, 1500, 4000), UbLoop(rows["war"], odd, 1500, 4000), "custom multipliers match the loop");
|
||||
Check.Eq(IltAugCosts.LumCost(creature, m, 50, 40), 0m, "a target below current costs nothing");
|
||||
Check.True(IltAugCosts.LumCost(creature, m, 0, IltAugCosts.NoCapLimit) > 0, "the largest uncapped target is priced without overflow");
|
||||
}
|
||||
|
||||
private static void AugCostSettings()
|
||||
{
|
||||
string file = IltAugCosts.FilePath;
|
||||
if (File.Exists(file)) File.Delete(file);
|
||||
var settings = new IltSettings();
|
||||
var hub = NewHub("InfiniteLeaftide", settings, "aug-costs", out _);
|
||||
var prog = hub.Progression;
|
||||
prog.ApplyAugLines(new List<string> { "War: 1700" });
|
||||
hub.State.Character.AugTargets["war"] = 1800;
|
||||
|
||||
string Snapshot()
|
||||
{
|
||||
var sb = new System.Text.StringBuilder();
|
||||
prog.AppendSnapshotJson(sb);
|
||||
return "{" + sb + "}";
|
||||
}
|
||||
System.Text.Json.JsonElement Aug(string json) => System.Text.Json.JsonDocument.Parse(json).RootElement.GetProperty("aug");
|
||||
|
||||
var before = Aug(Snapshot());
|
||||
Check.False(before.GetProperty("cfg").GetProperty("custom").GetBoolean(), "a world starts on the defaults");
|
||||
Check.Eq(before.GetProperty("cfg").GetProperty("mults").GetArrayLength(), 5, "five tier multipliers in the snapshot");
|
||||
string lumBefore = before.GetProperty("totLum").GetString() ?? "";
|
||||
|
||||
prog.HandleRemote(new[] { "augmult", "1", "2" });
|
||||
var after = Aug(Snapshot());
|
||||
Check.True(after.GetProperty("cfg").GetProperty("custom").GetBoolean(), "an edit gives the world its own rules");
|
||||
Check.Eq(after.GetProperty("cfg").GetProperty("mults")[1].GetDouble(), 2.0, "multiplier saved");
|
||||
Check.True((after.GetProperty("totLum").GetString() ?? "") != lumBefore, "the plan re-prices with the new multiplier");
|
||||
|
||||
prog.HandleRemote(new[] { "augcfg", "war", "s1", "1800" });
|
||||
prog.HandleRemote(new[] { "augcfg", "war", "base", "1m" });
|
||||
prog.HandleRemote(new[] { "augcfg", "war", "s2", "100" });
|
||||
var war = prog.AugCosts.For("InfiniteLeaftide").Augs.First(x => x.Key == "war");
|
||||
Check.Eq(war.S1, 1800, "S1 edited");
|
||||
Check.Eq(war.Base, 1_000_000L, "base accepts k/m/b suffixes");
|
||||
Check.Eq(war.S2, 1800, "S2 can't go below S1");
|
||||
Check.Eq(prog.AugCosts.For("Aelrynth").Multipliers[1], 4.0, "another world keeps the defaults");
|
||||
|
||||
var reloaded = new IltAugCosts();
|
||||
Check.Eq(reloaded.For("infiniteleaftide").Multipliers[1], 2.0, "rules are saved per world (name ignores case)");
|
||||
|
||||
prog.HandleRemote(new[] { "augcfgreset" });
|
||||
Check.False(prog.AugCosts.IsCustom("InfiniteLeaftide"), "reset drops the world's rules");
|
||||
Check.Eq(new IltAugCosts().For("InfiniteLeaftide").Multipliers[1], 4.0, "and the reset is saved");
|
||||
}
|
||||
|
||||
private static void ByHandPriced()
|
||||
{
|
||||
Check.Eq(IltAttributeRaiser.ProjectCost(1_000, 1), 1_000L, "one level costs the reported cost");
|
||||
// 1000 * (1.077^10 - 1) / 0.077 = 14,281.7 (UB's EstimateMultiLevelCost).
|
||||
Check.Eq(IltAttributeRaiser.ProjectCost(1_000, 10), 14_281L, "ten levels grow 7.7% each");
|
||||
Check.Eq(IltAttributeRaiser.ProjectCost(0, 10), 0L, "unknown cost projects nothing");
|
||||
Check.Eq(IltAttributeRaiser.ProjectCost(long.MaxValue / 2, 10), long.MaxValue, "saturates instead of overflowing");
|
||||
|
||||
var settings = new IltSettings();
|
||||
var hub = NewHub("InfiniteLeaftide", settings, "attr-byhand", out _);
|
||||
var raiser = hub.Progression.Attributes;
|
||||
FakeHost.Quads[(Player, IltInventory.QuadAvailableXp)] = 5_000;
|
||||
// Levels already known (as after the login probe), so the tab doesn't queue /aug ahead of /xp all.
|
||||
hub.Progression.ApplyAugLines(new List<string> { "Creature: 1" });
|
||||
|
||||
// Opening the tab (a snapshot poll) reads the costs once per login.
|
||||
var sb = new System.Text.StringBuilder();
|
||||
hub.Progression.AppendSnapshotJson(sb);
|
||||
Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/xp all")), "the first snapshot reads the costs");
|
||||
Reply(hub, "[XP] Your XP cost for next 1 Coordination level is: 1,000",
|
||||
"[XP] Your XP cost for next 1 Strength level is: 4,000");
|
||||
TickUntil(hub, () => false, 400);
|
||||
int reads = FakeHost.ChatCommands.Count(x => x == "/xp all");
|
||||
hub.Progression.AppendSnapshotJson(new System.Text.StringBuilder());
|
||||
TickUntil(hub, () => false, 400);
|
||||
Check.Eq(FakeHost.ChatCommands.Count(x => x == "/xp all"), reads, "later snapshots don't read again");
|
||||
|
||||
sb.Clear();
|
||||
raiser.AppendJson(sb);
|
||||
string json = sb.ToString();
|
||||
System.Text.Json.JsonDocument.Parse("{" + json + "}").Dispose();
|
||||
Check.True(json.Contains("\"key\":\"coo\"") && json.Contains("\"afford1\":true") && json.Contains("\"cost10\":\"~14.3K\""),
|
||||
$"Coordination: +1 affordable, +10 projected (got {json})");
|
||||
Check.True(json.Contains("\"updated\":\"") && !json.Contains("\"updated\":\"-\""), "the last-updated time is set");
|
||||
|
||||
// +10 Coordination (~14.3K of 5K) is refused; +1 Strength (4K of 5K) goes out.
|
||||
raiser.RaiseManual("coo", 10);
|
||||
var status = new System.Text.StringBuilder();
|
||||
raiser.AppendJson(status);
|
||||
Check.True(status.ToString().Contains("Not enough unassigned XP"), "an unaffordable +10 is refused with the reason");
|
||||
raiser.RaiseManual("str", 1);
|
||||
Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/attr str 1")), "an affordable +1 is sent");
|
||||
Check.False(FakeHost.ChatCommands.Contains("/attr coo 10"), "the refused +10 was never sent");
|
||||
}
|
||||
|
||||
private static void AugPlanner()
|
||||
{
|
||||
var settings = new IltSettings();
|
||||
var hub = NewHub("InfiniteLeaftide", settings, "aug-planner", out _);
|
||||
var prog = hub.Progression;
|
||||
|
||||
prog.AppendSnapshotJson(new System.Text.StringBuilder());
|
||||
Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/aug")), "opening the tab pulls /aug once");
|
||||
prog.ApplyAugLines(new List<string> { "Creature: 100", "Specialize: 2", "Summon: 0" });
|
||||
|
||||
prog.HandleRemote(new[] { "augtarget", "creature", "110" });
|
||||
var sb = new System.Text.StringBuilder();
|
||||
prog.AppendSnapshotJson(sb);
|
||||
string json = sb.ToString();
|
||||
using (var doc = System.Text.Json.JsonDocument.Parse("{" + json + "}"))
|
||||
{
|
||||
var aug = doc.RootElement.GetProperty("aug");
|
||||
Check.Eq(aug.GetProperty("totCur").GetInt64(), 102L, "totals: current");
|
||||
Check.Eq(aug.GetProperty("totTgt").GetInt64(), 112L, "totals: target");
|
||||
Check.Eq(aug.GetProperty("totInc").GetInt64(), 10L, "totals: increase");
|
||||
Check.Eq(aug.GetProperty("totCoins").GetInt64(), 30L, "Creature costs 3 coins a level");
|
||||
var creature = aug.GetProperty("rows").EnumerateArray().First(x => x.GetProperty("key").GetString() == "creature");
|
||||
Check.Eq(creature.GetProperty("inc").GetInt32(), 10, "row: increase");
|
||||
string discord = aug.GetProperty("copyDiscord").GetString() ?? "";
|
||||
Check.True(discord.StartsWith("```", StringComparison.Ordinal) && discord.Contains("TOTALS:") && discord.Contains("Creature"),
|
||||
"Discord copy is a code-block table with totals");
|
||||
Check.True(discord.All(ch => ch < 128), "copy text is ASCII (the engine reads the snapshot as ANSI)");
|
||||
string ingame = aug.GetProperty("copyIngame").GetString() ?? "";
|
||||
Check.True(ingame.Contains("Crit: 100") && ingame.Contains("Spec: 2") && !ingame.Contains("Sum:"),
|
||||
$"in-game copy lists current levels with short names (got '{ingame}')");
|
||||
}
|
||||
|
||||
prog.HandleRemote(new[] { "augreset" });
|
||||
Check.Eq(hub.State.Character.AugTargets["creature"], 100, "reset targets: back to current");
|
||||
Check.Eq(hub.State.Character.AugTargets["summon"], 0, "reset targets: unloaded augs go to 0");
|
||||
Check.Eq(FakeHost.ChatCommands.Count(x => x == "/aug"), 1, "levels loaded: no second automatic /aug");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Refresh current must not finish on the /aug banner alone (chat-hold lag used to leave Current at 0).
|
||||
/// </summary>
|
||||
private static void AugRefreshWaitsForLevelLines()
|
||||
{
|
||||
var settings = new IltSettings();
|
||||
var hub = NewHub("InfiniteLeaftide", settings, "aug-refresh-idle", out _);
|
||||
var prog = hub.Progression;
|
||||
// Seed so EnsureAugs does not queue its own /aug ahead of our Refresh.
|
||||
prog.ApplyAugLines(new List<string> { "Creature: 1" });
|
||||
|
||||
prog.HandleRemote(new[] { "augload" });
|
||||
Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/aug")), "Refresh current sends /aug");
|
||||
Reply(hub, "---------------------------", "Advanced Augmentation Levels:");
|
||||
// Longer than IdleEndMs (2s): without ArmsIdle this used to ApplyAugLines([]) and clear the status.
|
||||
var until = DateTime.UtcNow.AddMilliseconds(2500);
|
||||
while (DateTime.UtcNow < until) { hub.Tick(); Thread.Sleep(25); }
|
||||
Check.True(FakeHost.ChatCommands.Count(x => x == "/aug") == 1, "still waiting on the same /aug (banner did not end it)");
|
||||
|
||||
Reply(hub, "Creature:4,300", "Item:100", "Specialize: 2");
|
||||
Check.True(TickUntil(hub, () =>
|
||||
{
|
||||
var sb = new System.Text.StringBuilder();
|
||||
prog.AppendSnapshotJson(sb);
|
||||
return sb.ToString().Contains("\"cur\":4300", StringComparison.Ordinal);
|
||||
}), "Current updates once Creature:/Item: lines arrive");
|
||||
}
|
||||
|
||||
// Silentkelpie (PR #12): the login probe could end on the banner alone (chat-hold backlog) and leave
|
||||
// Current empty with nothing to retry it; a Refresh current click during the probe was dropped.
|
||||
private static void AugProbeRetry()
|
||||
{
|
||||
var hub = NewHub("InfiniteLeaftide", new IltSettings(), "aug-probe-retry", out _);
|
||||
var prog = hub.Progression;
|
||||
|
||||
// Probe reply: the banner and no level lines. The tap runs ApplyAugLines then AfterExternalAugCapture.
|
||||
prog.ApplyAugLines(new List<string> { "---------------------------", "Advanced Augmentation Levels:" });
|
||||
prog.AfterExternalAugCapture();
|
||||
Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/aug")), "Current still empty: /aug is sent again");
|
||||
prog.AfterExternalAugCapture(); // the retry is in flight, and was the one retry
|
||||
prog.ApplyAugLines(new List<string> { "Advanced Augmentation Levels:" });
|
||||
prog.AfterExternalAugCapture();
|
||||
for (int i = 0; i < 20; i++) { hub.Tick(); Thread.Sleep(25); }
|
||||
Check.Eq(FakeHost.ChatCommands.Count(x => x == "/aug"), 1, "only one retry");
|
||||
|
||||
Reply(hub, "Creature:4,300", "Item:100");
|
||||
Check.True(TickUntil(hub, () =>
|
||||
{
|
||||
var sb = new System.Text.StringBuilder();
|
||||
prog.AppendSnapshotJson(sb);
|
||||
return sb.ToString().Contains("\"cur\":4300", StringComparison.Ordinal);
|
||||
}), "the retry's level lines fill Current");
|
||||
|
||||
// A probe with levels needs no retry.
|
||||
var hub2 = NewHub("InfiniteLeaftide", new IltSettings(), "aug-probe-ok", out _);
|
||||
hub2.Progression.ApplyAugLines(new List<string> { "Creature: 12" });
|
||||
hub2.Progression.AfterExternalAugCapture();
|
||||
for (int i = 0; i < 20; i++) { hub2.Tick(); Thread.Sleep(25); }
|
||||
Check.Eq(FakeHost.ChatCommands.Count(x => x == "/aug"), 0, "levels present: no retry");
|
||||
}
|
||||
|
||||
private static void AugLineValues()
|
||||
{
|
||||
Check.True(IltParse.AugLine.IsMatch("Creature:4,300") && IltParse.AugLine.IsMatch("Creature: 4.300")
|
||||
&& IltParse.AugLine.IsMatch("Creature: 4 300") && IltParse.AugLine.IsMatch("Creature: 4'300"), "the regex matches each grouping");
|
||||
Check.False(IltParse.AugLine.IsMatch("Creature: none") || IltParse.AugLine.IsMatch("Advanced Augmentation Levels:"), "and not a line with no number");
|
||||
Check.Eq(IltParse.ParseAugValue(IltParse.AugLine.Match("Creature:4,300").Groups[2].Value), 4300L, "comma");
|
||||
Check.Eq(IltParse.ParseAugValue(IltParse.AugLine.Match("Creature: 4.300").Groups[2].Value), 4300L, "period");
|
||||
Check.Eq(IltParse.ParseAugValue(IltParse.AugLine.Match("Creature: 4 300").Groups[2].Value), 4300L, "space");
|
||||
Check.Eq(IltParse.ParseAugValue(IltParse.AugLine.Match("Creature: 4'300").Groups[2].Value), 4300L, "apostrophe");
|
||||
Check.Eq(IltParse.ParseAugValue(IltParse.AugLine.Match("Creature: 1,234,567").Groups[2].Value), 1234567L, "two groups");
|
||||
Check.Eq(IltParse.ParseAugValue(IltParse.AugLine.Match("Duration: 5 (adds 3)").Groups[2].Value), 5L, "a trailing note");
|
||||
Check.Eq(IltParse.ParseAugValue(IltParse.AugLine.Match("Specialize: 2").Groups[2].Value), 2L, "plain");
|
||||
Check.Eq(IltParse.ParseAugValue(IltParse.AugLine.Match("Item: 2750").Groups[2].Value), 2750L, "no separator");
|
||||
Check.Eq(IltParse.ParseAugValue(""), 0L, "empty");
|
||||
|
||||
var hub = NewHub("InfiniteLeaftide", new IltSettings(), "aug-values", out _);
|
||||
hub.Progression.ApplyAugLines(new List<string> { "Creature: 2 750", "Item: 1.200", "Life: 300" });
|
||||
var sb = new System.Text.StringBuilder();
|
||||
hub.Progression.AppendSnapshotJson(sb);
|
||||
string snap = sb.ToString();
|
||||
Check.True(snap.Contains("\"cur\":2750", StringComparison.Ordinal) && snap.Contains("\"cur\":1200", StringComparison.Ordinal)
|
||||
&& snap.Contains("\"cur\":300", StringComparison.Ordinal), "the planner takes the grouped levels whole");
|
||||
}
|
||||
|
||||
private static void Patterns()
|
||||
{
|
||||
Check.True(ServerFeatureGate.Matches("InfiniteLeaftide", "InfiniteLeaftide"), "exact");
|
||||
Check.True(ServerFeatureGate.Matches("infiniteleaftide", "InfiniteLeaftide"), "exact ignores case");
|
||||
Check.False(ServerFeatureGate.Matches("InfiniteLeaftide2", "InfiniteLeaftide"), "exact means the whole name");
|
||||
Check.True(ServerFeatureGate.Matches("Leaftide Test", "*Leaftide*"), "contains");
|
||||
Check.True(ServerFeatureGate.Matches("MyLeaftide", "*tide"), "ends with");
|
||||
Check.True(ServerFeatureGate.Matches("Leaftide-PTR", "Leaf*"), "starts with");
|
||||
Check.True(ServerFeatureGate.Matches("Aelrynth Infinite", "Ael*Inf*"), "two wildcards");
|
||||
Check.False(ServerFeatureGate.Matches("Aelrynth", "*Leaftide*"), "no match");
|
||||
Check.False(ServerFeatureGate.Matches("ab", "a*bb"), "the end part must fit after the start");
|
||||
Check.True(ServerFeatureGate.NameMatches("Aelrynth", new[] { "", "InfiniteLeaftide", "aelrynth" }, out string m) && m == "aelrynth",
|
||||
"NameMatches reports the pattern that matched");
|
||||
Check.False(ServerFeatureGate.NameMatches("", ServerFeatureGate.DefaultServerNames, out _), "an unknown world never matches");
|
||||
}
|
||||
|
||||
private static void ListAndOverride()
|
||||
{
|
||||
var list = ServerFeatureGate.ParseList(" InfiniteLeaftide , *Leaftide*;Aelrynth,,aelrynth ");
|
||||
Check.Eq(string.Join("|", list), "InfiniteLeaftide|*Leaftide*|Aelrynth", "trimmed, split on , and ;, de-duplicated ignoring case");
|
||||
Check.Eq(ServerFeatureGate.FormatList(list), "InfiniteLeaftide, *Leaftide*, Aelrynth", "formatted back for the text box");
|
||||
|
||||
var s = new IltSettings();
|
||||
Check.True(s.ServerNames.Contains("InfiniteLeaftide"), "fresh settings start with the defaults");
|
||||
Check.True(ServerFeatureGate.IsEnabled("InfiniteLeaftide", s, forceOn: false), "the default list covers InfiniteLeaftide");
|
||||
Check.False(ServerFeatureGate.IsEnabled("Aelrynth", s, forceOn: false), "another world is off by default");
|
||||
Check.True(ServerFeatureGate.IsEnabled("Aelrynth", s, forceOn: true), "the character's override turns it on anywhere");
|
||||
s.ServerNames = new List<string> { "Aelrynth" };
|
||||
Check.True(ServerFeatureGate.IsEnabled("aelrynth", s, forceOn: false), "a world added to the list is on");
|
||||
Check.False(ServerFeatureGate.IsEnabled("InfiniteLeaftide", s, forceOn: false), "a world removed from the list is off");
|
||||
Check.True(ServerFeatureGate.IsEnabled("InfiniteLeaftide", null, forceOn: false), "no settings yet: the defaults apply");
|
||||
s.ServerNames = new List<string>();
|
||||
Check.True(ServerFeatureGate.IsEnabled("InfiniteLeaftide", s, forceOn: false), "an emptied list falls back to the defaults");
|
||||
}
|
||||
|
||||
private static readonly string[] Order = { "coo", "qui", "str", "end", "foc", "sel", "hea", "sta", "man" };
|
||||
|
||||
private static void PickModes()
|
||||
{
|
||||
var cost = new Dictionary<string, long> { ["coo"] = 500, ["qui"] = 300, ["str"] = 100 };
|
||||
var ticked = new HashSet<string> { "coo", "qui", "str" };
|
||||
int rr = 0;
|
||||
Check.Eq(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.Priority, Order, ticked, cost, 1000, ref rr), "coo",
|
||||
"priority: the first affordable stat in the order");
|
||||
Check.Eq(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.Priority, Order, ticked, cost, 400, ref rr), "qui",
|
||||
"priority: skips a stat it can't afford");
|
||||
Check.Eq(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.Cheapest, Order, ticked, cost, 1000, ref rr), "str",
|
||||
"cheapest: the lowest next-level cost");
|
||||
var tie = new Dictionary<string, long> { ["coo"] = 100, ["str"] = 100 };
|
||||
Check.Eq(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.Cheapest, Order, ticked, tie, 1000, ref rr), "coo",
|
||||
"cheapest: a tie goes to the higher-priority stat");
|
||||
|
||||
rr = 0;
|
||||
var picks = new List<string?>();
|
||||
for (int i = 0; i < 4; i++) picks.Add(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.RoundRobin, Order, ticked, cost, 1000, ref rr));
|
||||
Check.Eq(string.Join(",", picks), "coo,qui,str,coo", "round robin: one each in order, then around again");
|
||||
rr = 0;
|
||||
Check.Eq(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.RoundRobin, Order, ticked, cost, 400, ref rr), "qui",
|
||||
"round robin: an unaffordable stat is passed over");
|
||||
Check.Eq(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.RoundRobin, Order, ticked, cost, 400, ref rr), "str",
|
||||
"round robin: carries on from the last pick");
|
||||
}
|
||||
|
||||
private static void PickLimits()
|
||||
{
|
||||
var cost = new Dictionary<string, long> { ["coo"] = 500, ["qui"] = 300 };
|
||||
int rr = 0;
|
||||
Check.Null(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.Priority, Order, new HashSet<string>(), cost, 10_000, ref rr),
|
||||
"nothing ticked: nothing raised");
|
||||
Check.Eq(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.Priority, Order, new HashSet<string> { "qui" }, cost, 10_000, ref rr), "qui",
|
||||
"an unticked stat is never spent on, even at the top of the order");
|
||||
Check.Null(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.Priority, Order, new HashSet<string> { "coo", "qui" }, cost, 0, ref rr),
|
||||
"no budget (XP at or below the reserve): nothing raised");
|
||||
Check.Null(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.Priority, Order, new HashSet<string> { "str" }, cost, 10_000, ref rr),
|
||||
"a stat whose cost wasn't read is not raised blind");
|
||||
var zero = new Dictionary<string, long> { ["coo"] = 0 };
|
||||
Check.Null(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.Cheapest, Order, new HashSet<string> { "coo" }, zero, 10_000, ref rr),
|
||||
"a zero cost (unparsed) is not raised");
|
||||
}
|
||||
|
||||
private static void OrderAndNames()
|
||||
{
|
||||
var repaired = IltAttributeRaiser.RepairOrder(new List<string> { "sel", "bogus", "Self", "Strength", "hea" });
|
||||
Check.Eq(string.Join(",", repaired), "sel,str,hea,coo,qui,end,foc,sta,man",
|
||||
"saved order kept, duplicates/junk dropped, missing stats appended in the default order");
|
||||
Check.Eq(IltAttributeRaiser.RepairOrder(null).Count, 9, "a missing order becomes the default");
|
||||
Check.Eq(string.Join(",", IltAttributeRaiser.RepairSelection(new List<string> { "Coordination", "coo", "x" })), "coo",
|
||||
"selection: names map to abbreviations, duplicates and junk dropped");
|
||||
|
||||
Check.Eq(IltAttributeRaiser.Find("MaxHealth")?.Abbr, "hea", "cost line 'MaxHealth'");
|
||||
Check.Eq(IltAttributeRaiser.Find("Maximum Stamina")?.Abbr, "sta", "'Maximum Stamina'");
|
||||
Check.Eq(IltAttributeRaiser.Find("Self")?.Abbr, "sel", "Self");
|
||||
Check.Eq(IltAttributeRaiser.Find("qui")?.Abbr, "qui", "abbreviation");
|
||||
Check.Null(IltAttributeRaiser.Find("Luck"), "unknown names are rejected");
|
||||
|
||||
var cost = IltParse.XpCost.Match("[XP] Your XP cost for next 1 Coordination level is: 12,345,678");
|
||||
Check.True(cost.Success && cost.Groups[1].Value == "Coordination" && IltParse.ParseLeadingLong(cost.Groups[2].Value) == 12_345_678,
|
||||
"the /xp all cost line parses");
|
||||
var raised = IltParse.AttrRaised.Match("[ATTR] Quickness attribute raised by 1, costing 9,876!");
|
||||
Check.True(raised.Success && raised.Groups[1].Value == "Quickness" && raised.Groups[2].Value == "1"
|
||||
&& IltParse.ParseLeadingLong(raised.Groups[3].Value) == 9876, "the /attr success line parses");
|
||||
}
|
||||
|
||||
// ── The loop on the fake host ─────────────────────────────────────────────
|
||||
|
||||
private static IltHubController NewHub(string world, IltSettings settings, string folder, out RynthCoreHost host)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.WorldName = world;
|
||||
host = FakeHost.Create(Player);
|
||||
string dir = Path.Combine(Program.TempRoot, folder);
|
||||
Directory.CreateDirectory(dir);
|
||||
// No RynthAi here (the fake host has no GetPluginInterface): RynthILT runs on its own.
|
||||
return new IltHubController(host, dir, settings, new RynthAiClient(host));
|
||||
}
|
||||
|
||||
/// <summary>Ticks the hub until <paramref name="done"/> or the timeout (the chat queue spaces sends by real time).</summary>
|
||||
private static bool TickUntil(IltHubController hub, Func<bool> done, int timeoutMs = 6000)
|
||||
{
|
||||
var until = DateTime.UtcNow.AddMilliseconds(timeoutMs);
|
||||
while (DateTime.UtcNow < until)
|
||||
{
|
||||
hub.Tick();
|
||||
if (done()) return true;
|
||||
Thread.Sleep(25);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static void Reply(IltHubController hub, params string[] lines)
|
||||
{
|
||||
foreach (string l in lines) hub.OnChat(l);
|
||||
}
|
||||
|
||||
private static void FullRun()
|
||||
{
|
||||
var settings = new IltSettings();
|
||||
var hub = NewHub("InfiniteLeaftide", settings, "attr-run", out _);
|
||||
var c = hub.State.Character;
|
||||
c.AttrRaiseStats = new List<string> { "coo", "qui" };
|
||||
c.AttrRaiseMode = (int)IltAttributeRaiser.Mode.Priority;
|
||||
c.AttrKeepXp = 200;
|
||||
FakeHost.Quads[(Player, IltInventory.QuadAvailableXp)] = 2_500;
|
||||
var raiser = hub.Progression.Attributes;
|
||||
|
||||
Check.Null(raiser.Blocker(), "an ILT world with /xp not reported off: the raiser can run");
|
||||
raiser.Start(auto: false);
|
||||
Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/xp all")), "a run starts by reading the costs");
|
||||
Reply(hub, "[XP] Your XP cost for next 1 Strength level is: 50",
|
||||
"[XP] Your XP cost for next 1 Coordination level is: 1,000",
|
||||
"[XP] Your XP cost for next 1 Quickness level is: 1,200");
|
||||
Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/attr coo 1")),
|
||||
"priority: Coordination first (Strength is cheaper but not ticked)");
|
||||
|
||||
FakeHost.Quads[(Player, IltInventory.QuadAvailableXp)] = 1_500;
|
||||
Reply(hub, "[ATTR] Coordination attribute raised by 1, costing 1,000!");
|
||||
Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Count(x => x == "/xp all") >= 2), "costs are read again after each raise");
|
||||
Reply(hub, "[XP] Your XP cost for next 1 Coordination level is: 2,000",
|
||||
"[XP] Your XP cost for next 1 Quickness level is: 1,200");
|
||||
Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/attr qui 1")),
|
||||
"Coordination now costs more than the spendable 1,300: Quickness next");
|
||||
|
||||
FakeHost.Quads[(Player, IltInventory.QuadAvailableXp)] = 300;
|
||||
Reply(hub, "[ATTR] Quickness attribute raised by 1, costing 1,200!");
|
||||
Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Count(x => x == "/xp all") >= 3), "third cost read");
|
||||
Reply(hub, "[XP] Your XP cost for next 1 Coordination level is: 2,000",
|
||||
"[XP] Your XP cost for next 1 Quickness level is: 1,500");
|
||||
Check.True(TickUntil(hub, () => !raiser.Running), "nothing affordable above the reserve: the run ends");
|
||||
Check.Eq(FakeHost.ChatCommands.Count(x => x.StartsWith("/attr", StringComparison.Ordinal)), 2, "exactly two raises sent");
|
||||
string summary = FakeHost.Chat.LastOrDefault(x => x.Contains("Attribute raise")) ?? "";
|
||||
Check.True(summary.Contains("Coordination +1") && summary.Contains("Quickness +1") && summary.Contains("2.2K"),
|
||||
$"the run reports what it raised and spent (got '{summary}')");
|
||||
|
||||
var sb = new System.Text.StringBuilder();
|
||||
raiser.AppendJson(sb);
|
||||
string json = sb.ToString();
|
||||
Check.True(json.StartsWith("\"attr\":{\"off\":false", StringComparison.Ordinal), "the Progression snapshot carries the raiser");
|
||||
Check.True(json.Contains("\"key\":\"coo\"") && json.Contains("\"cost\":\"2.0K\""), "rows carry the last read costs");
|
||||
System.Text.Json.JsonDocument.Parse("{" + json + "}").Dispose(); // throws if the JSON is malformed
|
||||
|
||||
// Panel commands: order, ticks, mode, reserve, a manual +10.
|
||||
raiser.HandleRemote("attrmove", new[] { "attrmove", "qui", "up" });
|
||||
Check.Eq(c.AttrOrder[0], "qui", "attrmove up");
|
||||
raiser.HandleRemote("attron", new[] { "attron", "str", "on" });
|
||||
Check.True(c.AttrRaiseStats.Contains("str"), "attron");
|
||||
raiser.HandleRemote("attrmode", new[] { "attrmode", "2" });
|
||||
Check.Eq(c.AttrRaiseMode, 2, "attrmode");
|
||||
raiser.HandleRemote("attrkeep", new[] { "attrkeep", "1.5b" });
|
||||
Check.Eq(c.AttrKeepXp, 1_500_000_000L, "attrkeep takes k/m/b suffixes");
|
||||
raiser.HandleRemote("attrraise", new[] { "attrraise", "foc", "10" });
|
||||
Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/attr foc 10")), "a manual +10 sends /attr foc 10");
|
||||
}
|
||||
|
||||
private static void Safety()
|
||||
{
|
||||
var settings = new IltSettings();
|
||||
var hub = NewHub("InfiniteLeaftide", settings, "attr-safety", out _);
|
||||
var c = hub.State.Character;
|
||||
var raiser = hub.Progression.Attributes;
|
||||
c.AttrRaiseStats = new List<string> { "coo", "qui" };
|
||||
FakeHost.Quads[(Player, IltInventory.QuadAvailableXp)] = 10_000;
|
||||
|
||||
// A cost seen earlier (passively, here by a hand-typed /xp all) is not trusted by a run:
|
||||
// only the costs in the run's own read count.
|
||||
Reply(hub, "[XP] Your XP cost for next 1 Coordination level is: 100");
|
||||
raiser.Start(auto: false);
|
||||
Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/xp all")), "run reads costs");
|
||||
Reply(hub, "[XP] Your XP cost for next 1 Quickness level is: 500"); // Coordination missing this time
|
||||
Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Any(x => x.StartsWith("/attr", StringComparison.Ordinal))), "a raise is sent");
|
||||
Check.Eq(FakeHost.ChatCommands.First(x => x.StartsWith("/attr", StringComparison.Ordinal)), "/attr qui 1",
|
||||
"Coordination's older cost is not used when this read left it out");
|
||||
|
||||
// A reply about another stat (some other /attr sender) is not taken as our success.
|
||||
Reply(hub, "[ATTR] Strength attribute raised by 1, costing 50!");
|
||||
Check.True(TickUntil(hub, () => !raiser.Running), "a reply about another stat ends the run");
|
||||
Check.Eq(FakeHost.ChatCommands.Count(x => x.StartsWith("/attr", StringComparison.Ordinal)), 1, "and nothing more is raised");
|
||||
Check.False(FakeHost.Chat.Any(x => x.Contains("Attribute raise")), "and no raise is reported");
|
||||
|
||||
// The world leaves Server Features mid-run: the next step stops.
|
||||
FakeHost.ChatCommands.Clear();
|
||||
raiser.Start(auto: false);
|
||||
Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/xp all")), "second run reads costs");
|
||||
settings.ServerNames = new List<string> { "SomewhereElse" };
|
||||
Reply(hub, "[XP] Your XP cost for next 1 Coordination level is: 100");
|
||||
Check.True(TickUntil(hub, () => !raiser.Running), "the run stops once the world is off");
|
||||
Check.False(FakeHost.ChatCommands.Any(x => x.StartsWith("/attr", StringComparison.Ordinal)), "no raise after the gate closed");
|
||||
settings.ServerNames = new List<string>(ServerFeatureGate.DefaultServerNames);
|
||||
|
||||
// Another XP spender running: neither Raise now nor +N starts.
|
||||
bool spending = true;
|
||||
raiser.HoldOff = () => spending;
|
||||
FakeHost.ChatCommands.Clear();
|
||||
raiser.Start(auto: false);
|
||||
raiser.RaiseManual("coo", 1);
|
||||
TickUntil(hub, () => false, 600);
|
||||
Check.False(raiser.Running, "held off: Raise now doesn't start");
|
||||
Check.False(FakeHost.ChatCommands.Any(), "held off: nothing is sent");
|
||||
}
|
||||
|
||||
private static void GatedOff()
|
||||
{
|
||||
var settings = new IltSettings();
|
||||
var hub = NewHub("Aelrynth", settings, "attr-gated", out _);
|
||||
var raiser = hub.Progression.Attributes;
|
||||
hub.State.Character.AttrRaiseStats = new List<string> { "coo" };
|
||||
Check.NotNull(raiser.Blocker(), "a world not in the list: blocked");
|
||||
raiser.Start(auto: false);
|
||||
TickUntil(hub, () => false, 600);
|
||||
Check.False(FakeHost.ChatCommands.Any(), "nothing is sent off a feature world");
|
||||
|
||||
settings.ServerNames.Add("Aelrynth");
|
||||
Check.Null(raiser.Blocker(), "adding the world to the server list unblocks it");
|
||||
settings.ServerNames.Remove("Aelrynth");
|
||||
hub.State.ForceLeaftideFeatures = true;
|
||||
Check.Null(raiser.Blocker(), "so does the character's override");
|
||||
}
|
||||
}
|
||||
146
Tools/RynthILT.Tests/BankCommandTests.cs
Normal file
146
Tools/RynthILT.Tests/BankCommandTests.cs
Normal file
|
|
@ -0,0 +1,146 @@
|
|||
using RynthCore.Plugin.RynthILT.Hub;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthILT.Tests;
|
||||
|
||||
// Banking tab (IltBankCommands): the deposit / withdraw commands match ACECustom's /bank handler
|
||||
// (upstream 2026-10-11), and only the bank's own reply lines count as a deposit / withdraw result.
|
||||
internal static class BankCommandTests
|
||||
{
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("bank: deposit commands (everything, one kind, luminance tokens)", Deposits);
|
||||
r.Add("bank: withdraw commands, trade notes by denomination and count", Withdrawals);
|
||||
r.Add("bank: withdraw input is checked before anything is sent", WithdrawRefusals);
|
||||
r.Add("bank: reply lines are recognised, balance and chat lines are not", Replies);
|
||||
r.Add("bank: one item table matches ACECustom's handler (deposit / withdraw / transfer)", ItemTable);
|
||||
r.Add("bank: transfer commands, trade notes by denomination, quoted names", Transfers);
|
||||
r.Add("bank: transfer replies (notes' equivalent, bound prestige coins) are recognised", TransferReplies);
|
||||
r.Add("bank: only the balance dump is backstop-eaten, and only just after a quiet refresh", LeakedDump);
|
||||
}
|
||||
|
||||
private static int TransferIndex(string code) =>
|
||||
System.Array.FindIndex(IltBankCommands.Transfers, t => t.Code == code);
|
||||
|
||||
private static void ItemTable()
|
||||
{
|
||||
string Codes(System.Collections.Generic.IEnumerable<string> codes) => string.Join(",", codes);
|
||||
// ACECustom HandleBank (upstream 976606695): deposit everything; withdraw all but peas and
|
||||
// luminance tokens; transfer all but those and the bound prestige coins.
|
||||
Check.Eq(Codes(System.Linq.Enumerable.Select(IltBankCommands.Deposits, d => d.Args)), ",p,ps,l,lum,k,mk,e,we,pc,n", "deposits");
|
||||
Check.Eq(Codes(System.Linq.Enumerable.Select(IltBankCommands.Withdrawals, w => w.Code)), "p,l,k,mk,e,we,pc,n", "withdrawals");
|
||||
Check.Eq(Codes(System.Linq.Enumerable.Select(IltBankCommands.Transfers, t => t.Code)), "p,l,k,mk,e,we,n", "transfers");
|
||||
Check.Eq(TransferIndex("pc"), -1, "prestige coins are bound: never offered for transfer");
|
||||
Check.Eq(TransferIndex("ps"), -1, "pyreal peas: deposit only");
|
||||
Check.Eq(IltBanking.Currencies.Length, IltBankCommands.Transfers.Length, "the transfer form uses the table");
|
||||
Check.Eq(IltBanking.Currencies[0].Code, "p", "saved transfer index 0 is still pyreals");
|
||||
Check.Eq(IltBanking.Currencies[5].Code, "we", "saved transfer indexes 0-5 keep their currency");
|
||||
}
|
||||
|
||||
private static void Transfers()
|
||||
{
|
||||
int mmd = System.Array.FindIndex(IltBankCommands.NoteDenominations, n => n.Code == "mmd");
|
||||
Check.Eq(IltBankCommands.Transfer(TransferIndex("p"), 250_000, -1, "Bob", out _), "/bank t p 250000 Bob", "pyreals");
|
||||
Check.Eq(IltBankCommands.Transfer(TransferIndex("mk"), 3, -1, " Bob ", out _), "/bank t mk 3 Bob", "name trimmed");
|
||||
Check.Eq(IltBankCommands.Transfer(TransferIndex("l"), 10, -1, "Some Name", out _), "/bank t l 10 \"Some Name\"",
|
||||
"a name with a space is quoted (the server reads one argument)");
|
||||
Check.Eq(IltBankCommands.Transfer(TransferIndex("n"), 4, mmd, "Bob", out _), "/bank t n mmd 4 Bob", "four 250K notes");
|
||||
Check.True(IltBankCommands.IsNoteTransfer(TransferIndex("n")), "notes transfer by denomination");
|
||||
Check.False(IltBankCommands.IsNoteTransfer(TransferIndex("p")), "pyreals don't");
|
||||
Check.Eq(IltBankCommands.NoteValue(mmd, 4), 1_000_000L, "4 x 250K");
|
||||
|
||||
Check.Eq(IltBankCommands.Transfer(-1, 10, -1, "Bob", out string e1), "", "no currency refused");
|
||||
Check.Eq(e1, "Pick a currency.", "why");
|
||||
Check.Eq(IltBankCommands.Transfer(TransferIndex("p"), 0, -1, "Bob", out _), "", "zero refused");
|
||||
Check.Eq(IltBankCommands.Transfer(TransferIndex("p"), 10, -1, " ", out string e2), "", "no recipient refused");
|
||||
Check.Eq(e2, "Enter a recipient.", "why");
|
||||
Check.Eq(IltBankCommands.Transfer(TransferIndex("p"), 10, -1, "Bob\" x", out _), "", "a quote can't break out of the name");
|
||||
Check.Eq(IltBankCommands.Transfer(TransferIndex("n"), 4, 99, "Bob", out _), "", "bad denomination refused");
|
||||
Check.Eq(IltBankCommands.Transfer(TransferIndex("n"), IltBankCommands.MaxNoteCount + 1, mmd, "Bob", out _), "", "too many notes refused");
|
||||
}
|
||||
|
||||
private static void TransferReplies()
|
||||
{
|
||||
Check.True(IltBankCommands.IsTransferReply("Transferred 1,000,000 Pyreals to Bob"), "result");
|
||||
Check.True(IltBankCommands.IsTransferReply("(Equivalent to 4x MMD notes)"), "trade-note equivalent");
|
||||
Check.True(IltBankCommands.IsTransferReply("[BANK] Prestige Coins are bound to you and cannot be transferred."), "bound coins");
|
||||
Check.True(IltBankCommands.IsTransferReply("[Transfer] This command may only be run once every 5 seconds."), "throttled");
|
||||
Check.True(IltBankCommands.IsTransferReply("Invalid denomination. Use: i(100), v(500)"), "bad denomination");
|
||||
Check.False(IltBankCommands.IsTransferReply("[BANK] Pyreals: 1,000"), "a balance line is not");
|
||||
Check.False(IltBankCommands.IsTransferReply("Bob tells you, \"Transferred 5\""), "a tell is not");
|
||||
}
|
||||
|
||||
private static int DepositIndex(string args) =>
|
||||
System.Array.FindIndex(IltBankCommands.Deposits, d => d.Args == args);
|
||||
|
||||
private static int WithdrawIndex(string code) =>
|
||||
System.Array.FindIndex(IltBankCommands.Withdrawals, w => w.Code == code);
|
||||
|
||||
private static void Deposits()
|
||||
{
|
||||
Check.Eq(IltBankCommands.Deposit(0), "/b d", "Everything is a plain deposit");
|
||||
Check.Eq(IltBankCommands.Deposit(DepositIndex("p")), "/b d p", "pyreals");
|
||||
Check.Eq(IltBankCommands.Deposit(DepositIndex("pc")), "/b d pc", "prestige coins");
|
||||
Check.Eq(IltBankCommands.Deposit(DepositIndex("lum")), "/b lum", "luminance tokens use /b lum");
|
||||
Check.Eq(IltBankCommands.Deposit(-1), "", "unknown index sends nothing");
|
||||
Check.Eq(IltBankCommands.Deposit(IltBankCommands.Deposits.Length), "", "past the end sends nothing");
|
||||
}
|
||||
|
||||
private static void Withdrawals()
|
||||
{
|
||||
Check.Eq(IltBankCommands.Withdraw(WithdrawIndex("p"), 1_500_000, 0, out _), "/b w p 1500000", "pyreals");
|
||||
Check.Eq(IltBankCommands.Withdraw(WithdrawIndex("pc"), 3, 0, out _), "/b w pc 3", "prestige coins");
|
||||
int mmd = System.Array.FindIndex(IltBankCommands.NoteDenominations, n => n.Code == "mmd");
|
||||
Check.Eq(IltBankCommands.Withdraw(WithdrawIndex("n"), 5, mmd, out _), "/b w n mmd 5", "five 250K notes");
|
||||
}
|
||||
|
||||
private static void WithdrawRefusals()
|
||||
{
|
||||
Check.Eq(IltBankCommands.Withdraw(WithdrawIndex("p"), 0, 0, out string e1), "", "zero refused");
|
||||
Check.True(e1.Length > 0, "zero says why");
|
||||
Check.Eq(IltBankCommands.Withdraw(-1, 10, 0, out _), "", "no currency refused");
|
||||
Check.Eq(IltBankCommands.Withdraw(WithdrawIndex("n"), 10, 99, out _), "", "bad denomination refused");
|
||||
Check.Eq(IltBankCommands.Withdraw(WithdrawIndex("n"), IltBankCommands.MaxNoteCount + 1, 0, out string e2), "",
|
||||
"more notes than the server allows refused");
|
||||
Check.True(e2.Contains("50,000"), "says the limit");
|
||||
}
|
||||
|
||||
private static void Replies()
|
||||
{
|
||||
Check.True(IltBankCommands.IsActionReply("Deposited 12,345 pyreals"), "deposit");
|
||||
Check.True(IltBankCommands.IsActionReply("No pyreal peas found to deposit"), "nothing to deposit");
|
||||
Check.True(IltBankCommands.IsActionReply("Withdrew 2 prestige coins"), "withdraw");
|
||||
Check.True(IltBankCommands.IsActionReply("Starting Banked Lum: 5B (5,000,000,000)"), "token deposit start");
|
||||
Check.True(IltBankCommands.IsActionReply("[Withdraw] This command may only be run once every 5 seconds."), "throttled");
|
||||
Check.True(IltBankCommands.IsActionReply("You don't have enough luminance banked. Need 10 but only have 5."), "short");
|
||||
Check.False(IltBankCommands.IsActionReply("[BANK] Pyreals: 1,000"), "a balance line is not an action reply");
|
||||
Check.False(IltBankCommands.IsActionReply("No one is near."), "other 'No ...' lines are not");
|
||||
Check.False(IltBankCommands.IsActionReply("Bob tells you, \"Deposited 5 pyreals\""), "a tell is not");
|
||||
Check.False(IltBankCommands.IsActionReply(""), "empty");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// SilentKelpie's backstop for a quiet refresh whose reply leaked into chat, narrowed: the dump's
|
||||
/// header and "Label: N" lines only, never errors, bound-coin notes or Transferred / Received lines,
|
||||
/// and never a balance read outside the window after a quiet refresh (a macro's or plugin's /bank).
|
||||
/// </summary>
|
||||
private static void LeakedDump()
|
||||
{
|
||||
Check.True(IltBanking.IsBalanceDumpLine("[BANK] Your balances are:"), "header");
|
||||
Check.True(IltBanking.IsBalanceDumpLine("[BANK] Pyreals: 1,000"), "pyreals");
|
||||
Check.True(IltBanking.IsBalanceDumpLine("[BANK] Luminance: 2,500,000"), "luminance");
|
||||
Check.True(IltBanking.IsBalanceDumpLine("[BANK] Weakly Enlightened Coins: 3"), "weakly enlightened coins");
|
||||
Check.True(IltBanking.IsBalanceDumpLine("[BANK] Prestige Coins: 2 (bound to you and cannot be traded)"), "prestige coins");
|
||||
Check.False(IltBanking.IsBalanceDumpLine("[BANK] Too many parameters"), "an error");
|
||||
Check.False(IltBanking.IsBalanceDumpLine("[BANK] Prestige Coins are bound to you and cannot be transferred."), "the bound-coin note");
|
||||
Check.False(IltBanking.IsBalanceDumpLine("Transferred 1,000,000 Pyreals to Bob"), "a transfer reply");
|
||||
Check.False(IltBanking.IsBalanceDumpLine("Received 5 Pyreals from Bob"), "a received line");
|
||||
Check.False(IltBanking.IsBalanceDumpLine("Bob tells you, \"[BANK] Pyreals: 5\""), "a tell quoting a dump");
|
||||
|
||||
const long Win = IltBanking.QuietBalanceWindowMs;
|
||||
Check.True(IltBanking.EatLeakedDump(true, 1_000, 1_000 + Win), "a dump line inside the window is eaten");
|
||||
Check.False(IltBanking.EatLeakedDump(true, 1_000 + Win + 1, 1_000 + Win), "after the window it shows (a macro's /bank)");
|
||||
Check.False(IltBanking.EatLeakedDump(true, 1_000, 0), "no quiet refresh out: it shows (typed /bank, loud refresh, other plugins)");
|
||||
Check.False(IltBanking.EatLeakedDump(false, 1_000, 1_000 + Win), "a non-dump [BANK] line inside the window still shows");
|
||||
}
|
||||
}
|
||||
89
Tools/RynthILT.Tests/BankRosterTests.cs
Normal file
89
Tools/RynthILT.Tests/BankRosterTests.cs
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using RynthCore.Plugin.RynthILT.Hub;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthILT.Tests;
|
||||
|
||||
// The Banking tab's every-character table (Hub/IltBankRoster.cs): SilentKelpie's Banking tab, in
|
||||
// RynthInventory's window until 2026-10-21 (its tests came with it, adapted: the roster is RynthILT's own
|
||||
// characters now, without Global Inventory's "not read yet" rows) and RynthILT's own tab since.
|
||||
internal static class BankRosterTests
|
||||
{
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("bank roster: you first, then by name; the totals add every read balance", Roster);
|
||||
r.Add("bank roster: the Banking tab lists every character RynthILT has run on this server", FromSavedCharacters);
|
||||
}
|
||||
|
||||
private static IltBankState Bank(long py, long lum, long lk, long mk, long ec, long wec, long pc, DateTime updated) => new()
|
||||
{
|
||||
Pyreals = py, Luminance = lum, LegendaryKeys = lk, MythicalKeys = mk,
|
||||
EnlightenedCoins = ec, WeaklyEnlightenedCoins = wec, PrestigeCoins = pc, LastUpdated = updated,
|
||||
};
|
||||
|
||||
private static void Roster()
|
||||
{
|
||||
DateTime t = new(2026, 10, 3, 11, 0, 0, DateTimeKind.Local);
|
||||
var rows = new List<IltBankExport.Row>
|
||||
{
|
||||
new("Willow", false, Bank(1, 1, 0, 0, 0, 0, 0, t.AddDays(-1))),
|
||||
new("Buffy", true, Bank(100, 2000, 1, 0, 3, 0, 0, t)),
|
||||
new("Ghost", false, Bank(50, 0, 2, 1, 0, 4, 5, t.AddDays(-2))),
|
||||
new("buffy", false, Bank(999, 999, 9, 9, 9, 9, 9, t.AddDays(-9))), // a stale saved copy of you
|
||||
new("Never", false, Bank(7, 7, 7, 7, 7, 7, 7, DateTime.MinValue)), // never read: not in the totals
|
||||
};
|
||||
IltBankRosterRow[] roster = IltBankRoster.Build(rows);
|
||||
Check.Eq(string.Join(",", roster.Select(r => r.Name)), "Buffy,Ghost,Never,Willow", "you first, then by name; your saved copy doesn't replace you");
|
||||
Check.True(roster[0].Current && roster[0].Pyreals == 100, "your live balance");
|
||||
IltBankRosterRow total = IltBankRoster.Totals(roster);
|
||||
Check.True(total.Name == "Total" && total.Pyreals == 151 && total.Luminance == 2001 && total.LegendaryKeys == 3 && total.MythicalKeys == 1
|
||||
&& total.EnlightenedCoins == 3 && total.WeaklyEnlightenedCoins == 4 && total.PrestigeCoins == 5,
|
||||
"totals add every balance read (a never-read one isn't counted)");
|
||||
Check.Eq(string.Join(",", IltBankRoster.Others(roster)), "Ghost,Never,Willow", "the transfer form's picker: your other characters");
|
||||
Check.Eq(IltBankRoster.Build(new List<IltBankExport.Row>()).Length, 0, "nothing: an empty roster");
|
||||
Check.Eq(IltBankRoster.Age(DateTime.MinValue, t), "-", "never read");
|
||||
Check.Eq(IltBankRoster.Age(t.AddMinutes(-5), t), "5m ago", "minutes");
|
||||
Check.Eq(IltBankRoster.Age(t.AddHours(-3), t), "3h ago", "hours");
|
||||
Check.Eq(IltBankRoster.Age(t.AddDays(-2), t), "2d ago", "days");
|
||||
}
|
||||
|
||||
private static void FromSavedCharacters()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeAiHub.Reset();
|
||||
FakeHost.WorldName = "InfiniteLeaftide";
|
||||
var host = FakeHost.Create(0x50000D41);
|
||||
string world = Path.Combine(Program.TempRoot, "roster-world");
|
||||
if (Directory.Exists(world)) Directory.Delete(world, recursive: true);
|
||||
// Two other characters RynthILT has run here (their saved hub.json), one that never banked.
|
||||
foreach ((string name, long py, bool banked) in new[] { ("Ghost", 50L, true), ("Willow", 7L, true), ("Nobank", 0L, false) })
|
||||
{
|
||||
string dir = Path.Combine(world, name);
|
||||
Directory.CreateDirectory(dir);
|
||||
var state = new IltHubState();
|
||||
state.Bank.Pyreals = py;
|
||||
if (banked) state.Bank.LastUpdated = DateTime.Now.AddHours(-2);
|
||||
File.WriteAllText(Path.Combine(dir, IltHubStore.StateFile), JsonSerializer.Serialize(state, IltHubJsonContext.Default.IltHubState));
|
||||
}
|
||||
string me = Path.Combine(world, "Buffy");
|
||||
Directory.CreateDirectory(me);
|
||||
var hub = new IltHubController(host, me, new IltSettings(), new RynthAiClient(host));
|
||||
hub.OnLoginComplete("Buffy", forceFromMigration: false);
|
||||
hub.State.Bank.Pyreals = 100;
|
||||
hub.State.Bank.LastUpdated = DateTime.Now;
|
||||
|
||||
hub.Tick();
|
||||
Check.Eq(hub.Banking.Roster.Length, 0, "nothing is read while the table isn't on screen");
|
||||
hub.Banking.MarkRosterWatched();
|
||||
hub.Tick();
|
||||
IltBankRosterRow[] roster = hub.Banking.Roster;
|
||||
Check.Eq(string.Join(",", roster.Select(r => r.Name)), "Buffy,Ghost,Willow", "you and the characters with a saved balance");
|
||||
Check.True(roster[0].Current && roster[0].Pyreals == 100 && roster[1].Pyreals == 50, "live and saved balances");
|
||||
Check.Eq(IltBankRoster.Totals(roster).Pyreals, 157L, "the total");
|
||||
}
|
||||
}
|
||||
252
Tools/RynthILT.Tests/BountyReviewTests.cs
Normal file
252
Tools/RynthILT.Tests/BountyReviewTests.cs
Normal file
|
|
@ -0,0 +1,252 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using RynthCore.Plugin.RynthILT.Bounty;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthILT.Tests;
|
||||
|
||||
// The RynthILT review of SilentKelpie's tracker (2026-10-09). Two promises, checked here on a
|
||||
// fake clock:
|
||||
// * rate: at most one "/bounty list" per MinRefreshSeconds (5 s floor, whatever asks: kills,
|
||||
// award lines every kill, Refresh spam, opening and closing the window), and none while the
|
||||
// window is closed;
|
||||
// * hidden chat: only the reply to the tracker's own read is eaten. A /bounty the player types
|
||||
// is shown, also when it overlaps a read of ours, and our own command coming back through the
|
||||
// engine's chat bar dispatcher is not mistaken for the player's.
|
||||
internal static class BountyReviewTests
|
||||
{
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("review: awards on every kill never read more than once per MinRefreshSeconds", AwardsEveryKill);
|
||||
r.Add("review: Refresh spam and window open/close keep the 5 s floor", RefreshSpamAndToggling);
|
||||
r.Add("review: a long mixed session: every read 5 s apart and only while the window is open", MixedSession);
|
||||
r.Add("review: a /bounty list the player types is shown and stands in for the next read", TypedListShown);
|
||||
r.Add("review: a /bounty the player types during our read: the rest of that read is shown", TypedDuringCapture);
|
||||
r.Add("review: our own /bounty list coming back through the chat bar is not the player's", OwnEcho);
|
||||
r.Add("review: command matching and long lines", Matching);
|
||||
}
|
||||
|
||||
private const string Header = "Bounties:";
|
||||
private const string Line = " Lugian Mines: 1 Ascension Coin every 1 kill - you: 0 of 1 kills.";
|
||||
private const string Footer = "Bounty: type /bounty to see the bounties where you stand.";
|
||||
|
||||
private sealed class Rig
|
||||
{
|
||||
public long Ms = 1_000_000;
|
||||
public readonly List<long> SentAt = new();
|
||||
public readonly List<bool> SentWhileOpen = new();
|
||||
public BountyTracker T = null!;
|
||||
public bool Open;
|
||||
private long _lastPollMs;
|
||||
|
||||
public void Step(long ms)
|
||||
{
|
||||
for (long e = 0; e < ms; e += 250)
|
||||
{
|
||||
Ms += 250;
|
||||
if (Open && Ms - _lastPollMs >= 1000) { T.BuildJson(); _lastPollMs = Ms; }
|
||||
T.Tick();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The server answers our read at once (header, a line, footer).</summary>
|
||||
public void Reply()
|
||||
{
|
||||
T.OnChat(Header);
|
||||
T.OnChat(Line);
|
||||
T.OnChat(Footer);
|
||||
}
|
||||
}
|
||||
|
||||
private static Rig New(int minRefreshSeconds = 5)
|
||||
{
|
||||
var rig = new Rig();
|
||||
rig.T = new BountyTracker(cmd =>
|
||||
{
|
||||
if (cmd != BountyTracker.ListCommand) return;
|
||||
rig.SentAt.Add(rig.Ms);
|
||||
rig.SentWhileOpen.Add(rig.T.WindowOpen);
|
||||
}, _ => { }, _ => { }, string.Empty, () => rig.Ms);
|
||||
rig.T.Command($"set minrefreshseconds {minRefreshSeconds}");
|
||||
return rig;
|
||||
}
|
||||
|
||||
private static long MinGap(List<long> at)
|
||||
{
|
||||
long min = long.MaxValue;
|
||||
for (int i = 1; i < at.Count; i++) min = Math.Min(min, at[i] - at[i - 1]);
|
||||
return min;
|
||||
}
|
||||
|
||||
private static void AwardsEveryKill()
|
||||
{
|
||||
var rig = New(minRefreshSeconds: 10);
|
||||
rig.Open = true;
|
||||
// A 1-kill bounty with no cooldown: every kill prints an award, for two minutes.
|
||||
for (int s = 0; s < 120; s++)
|
||||
{
|
||||
rig.T.OnKill();
|
||||
rig.T.OnChat("Bounty complete! +1 Ascension Coin gained.");
|
||||
rig.T.OnChat("Next bounty requires 1 kill.");
|
||||
rig.Step(1000);
|
||||
if (rig.T.Reading) rig.Reply();
|
||||
}
|
||||
Check.True(rig.SentAt.Count >= 2, $"it still reads ({rig.SentAt.Count} reads)");
|
||||
Check.True(rig.SentAt.Count <= 13, $"at most one read per 10 s over 120 s ({rig.SentAt.Count} reads)");
|
||||
Check.True(MinGap(rig.SentAt) >= 10_000, $"reads at least MinRefreshSeconds apart (min gap {MinGap(rig.SentAt)} ms)");
|
||||
}
|
||||
|
||||
private static void RefreshSpamAndToggling()
|
||||
{
|
||||
var rig = New(minRefreshSeconds: 30);
|
||||
rig.Open = true;
|
||||
rig.Step(500);
|
||||
rig.Reply();
|
||||
Check.Eq(rig.SentAt.Count, 1, "opening reads once");
|
||||
|
||||
// Refresh clicked every half second for 20 s: manual reads keep the 5 s floor.
|
||||
for (int i = 0; i < 40; i++)
|
||||
{
|
||||
rig.T.Command("refresh");
|
||||
rig.Step(500);
|
||||
if (rig.T.Reading) rig.Reply();
|
||||
}
|
||||
Check.True(rig.SentAt.Count <= 5, $"20 s of Refresh spam: at most 4 more reads ({rig.SentAt.Count} in all)");
|
||||
Check.True(MinGap(rig.SentAt) >= 5_000, $"manual reads at least 5 s apart (min gap {MinGap(rig.SentAt)} ms)");
|
||||
|
||||
// Kills while closed, then the window toggled open and shut every 4 s for a minute.
|
||||
int before = rig.SentAt.Count;
|
||||
for (int i = 0; i < 15; i++)
|
||||
{
|
||||
rig.Open = false;
|
||||
rig.T.OnKill();
|
||||
rig.Step(4000);
|
||||
rig.Open = true;
|
||||
rig.Step(1000);
|
||||
if (rig.T.Reading) rig.Reply();
|
||||
}
|
||||
Check.True(rig.SentAt.Count - before <= 3, $"open/close every 5 s for 75 s with MinRefreshSeconds 30: at most 3 reads ({rig.SentAt.Count - before})");
|
||||
Check.True(MinGap(rig.SentAt) >= 5_000, "and never two within 5 s");
|
||||
Check.True(rig.SentWhileOpen.All(o => o), "every read went out with the window open");
|
||||
}
|
||||
|
||||
private static void MixedSession()
|
||||
{
|
||||
var rig = New(minRefreshSeconds: 5);
|
||||
var rnd = new Random(20261009);
|
||||
for (int s = 0; s < 1800; s++) // 30 minutes
|
||||
{
|
||||
if (s % 120 == 0) rig.Open = !rig.Open;
|
||||
int roll = rnd.Next(100);
|
||||
if (roll < 30) rig.T.OnKill();
|
||||
else if (roll < 35) rig.T.OnChat("Bounty complete! +1 Ascension Coin gained.");
|
||||
else if (roll < 37) rig.T.Command("refresh");
|
||||
else if (roll < 38) rig.T.OnChat("Bounty unlocked: Ascension Coin - 1 kill required.");
|
||||
rig.Step(1000);
|
||||
if (rig.T.Reading && rnd.Next(4) != 0) rig.Reply(); // now and then the server says nothing
|
||||
}
|
||||
Check.True(rig.SentAt.Count > 10, $"reads happened ({rig.SentAt.Count})");
|
||||
Check.True(MinGap(rig.SentAt) >= 5_000, $"every read at least 5 s after the last (min gap {MinGap(rig.SentAt)} ms)");
|
||||
Check.True(rig.SentWhileOpen.All(o => o), "every read went out with the window open");
|
||||
}
|
||||
|
||||
private static void TypedListShown()
|
||||
{
|
||||
var rig = New(minRefreshSeconds: 5);
|
||||
rig.Open = true;
|
||||
rig.Step(500);
|
||||
rig.Reply();
|
||||
Check.Eq(rig.SentAt.Count, 1, "first read");
|
||||
rig.Step(10_000);
|
||||
|
||||
// The player types /bounty list: the reply is shown (nothing eaten) and still applied.
|
||||
rig.T.NoteTypedCommand("/bounty list");
|
||||
Check.True(rig.T.Reading, "the typed list is captured (shown)");
|
||||
Check.False(rig.T.OnChat(Header), "typed reply: the header stays in chat");
|
||||
Check.False(rig.T.OnChat(" Lugian Mines: 1 Ascension Coin every 1 kill - you: 0 of 1 kills."), "typed reply: the lines stay in chat");
|
||||
Check.False(rig.T.OnChat(Footer), "typed reply: the footer stays in chat");
|
||||
Check.False(rig.T.Reading, "and the footer ends it");
|
||||
Check.Eq(rig.T.State.Entries.Count, 1, "the typed reply fills the list");
|
||||
|
||||
// It counts as the latest read: a kill right after waits the full interval.
|
||||
rig.T.OnKill();
|
||||
rig.Step(4000);
|
||||
Check.Eq(rig.SentAt.Count, 1, "no read of ours on top of the player's");
|
||||
rig.Step(2000);
|
||||
Check.Eq(rig.SentAt.Count, 2, "the kill's read comes MinRefreshSeconds after the typed one");
|
||||
Check.True(rig.T.OnChat(Header) && rig.T.OnChat(Line) && rig.T.OnChat(Footer), "our own read is eaten again");
|
||||
|
||||
// "/bounty" (where you stand) output is never eaten.
|
||||
rig.T.NoteTypedCommand("/bounty");
|
||||
Check.False(rig.T.OnChat("Bounty: 1 Ascension Coin - 0 of 1 kills."), "a /bounty line stays in chat");
|
||||
Check.False(rig.T.OnChat("Bounty: there is no bounty here."), "'no bounty here' stays in chat");
|
||||
}
|
||||
|
||||
private static void TypedDuringCapture()
|
||||
{
|
||||
var rig = New(minRefreshSeconds: 5);
|
||||
rig.Open = true;
|
||||
rig.Step(500);
|
||||
Check.Eq(rig.SentAt.Count, 1, "our read went out");
|
||||
rig.T.NoteTypedCommand(BountyTracker.ListCommand); // our own echo first (consumed)
|
||||
Check.True(rig.T.OnChat(Header), "our reply's header is eaten");
|
||||
|
||||
// The player types /bounty list while our reply is still coming in.
|
||||
rig.Step(250);
|
||||
rig.T.NoteTypedCommand("/bounty list");
|
||||
Check.False(rig.T.OnChat(Line), "after the player asked, reward lines are shown");
|
||||
Check.False(rig.T.OnChat(Footer), "and so is the footer");
|
||||
Check.False(rig.T.OnChat(Header), "the player's own reply: header shown");
|
||||
Check.False(rig.T.OnChat(Line), "the player's own reply: line shown");
|
||||
Check.False(rig.T.OnChat(Footer), "the player's own reply: footer shown");
|
||||
Check.False(rig.T.OnChat("Bounty complete! +1 Ascension Coin gained."), "award lines are never eaten");
|
||||
|
||||
// On a server without /bounty, the player's typed /bounty during our read: the refusal shows.
|
||||
var rig2 = New();
|
||||
rig2.Open = true;
|
||||
rig2.Step(500);
|
||||
rig2.T.NoteTypedCommand("/bounty");
|
||||
Check.False(rig2.T.OnChat("Unknown command: bounty"), "the refusal of the player's own /bounty stays in chat");
|
||||
}
|
||||
|
||||
private static void OwnEcho()
|
||||
{
|
||||
var rig = New(minRefreshSeconds: 5);
|
||||
rig.Open = true;
|
||||
rig.Step(500);
|
||||
Check.Eq(rig.SentAt.Count, 1, "our read went out");
|
||||
rig.Step(250);
|
||||
rig.T.NoteTypedCommand("/bounty list"); // the engine's dispatcher passing our own line back
|
||||
Check.True(rig.T.OnChat(Header), "our echo is recognised: the reply is still eaten");
|
||||
Check.True(rig.T.OnChat(Line), "reward lines eaten");
|
||||
Check.True(rig.T.OnChat(Footer), "footer eaten");
|
||||
|
||||
// An echo that comes too late is taken for the player's: that read is shown, never eaten wrongly.
|
||||
rig.Step(10_000);
|
||||
Check.Eq(rig.SentAt.Count, 1, "no new read yet (nothing asked)");
|
||||
rig.T.Command("refresh");
|
||||
rig.Step(500);
|
||||
Check.Eq(rig.SentAt.Count, 2, "refresh reads");
|
||||
rig.Step(3000);
|
||||
rig.T.NoteTypedCommand("/bounty list");
|
||||
Check.False(rig.T.OnChat(Header), "a late echo errs on the shown side");
|
||||
}
|
||||
|
||||
private static void Matching()
|
||||
{
|
||||
Check.True(BountyTracker.IsBountyCommand("/bounty"), "/bounty");
|
||||
Check.True(BountyTracker.IsBountyCommand("/bounty list"), "/bounty list");
|
||||
Check.True(BountyTracker.IsBountyCommand("@Bounty all"), "@bounty all");
|
||||
Check.False(BountyTracker.IsBountyCommand("/bountyhunter"), "a longer command is not /bounty");
|
||||
Check.False(BountyTracker.IsBountyCommand("/b hello"), "chat");
|
||||
Check.True(BountyTracker.IsListCommand("/bounty list") && BountyTracker.IsListCommand("/BOUNTY ALL"), "list commands");
|
||||
Check.False(BountyTracker.IsListCommand("/bounty") || BountyTracker.IsListCommand("/bounty list now"), "not list commands");
|
||||
|
||||
var rig = New();
|
||||
rig.Open = true;
|
||||
rig.Step(500);
|
||||
string longLine = " Lugian Mines: 1 Ascension Coin every 1 kill - you: 0 of 1 kills." + new string(' ', 600) + "x";
|
||||
Check.False(rig.T.OnChat(longLine), "a line over 512 characters is never eaten or parsed");
|
||||
}
|
||||
}
|
||||
388
Tools/RynthILT.Tests/BountyTests.cs
Normal file
388
Tools/RynthILT.Tests/BountyTests.cs
Normal file
|
|
@ -0,0 +1,388 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using RynthCore.Plugin.RynthILT.Bounty;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthILT.Tests;
|
||||
|
||||
// ACECustom bounty tracker (2026-10-09). The server keeps the kill counts (BountyProgress is a
|
||||
// server-only property), so the engine's Bounties window has RynthILT read "/bounty list" quietly
|
||||
// and parse it. The line formats below are copied from ACECustom BountyManager (ShowAllBounties /
|
||||
// ShowBounty / Award / NextBountyLine). The tracker runs on a fake clock; the engine's 1 s poll
|
||||
// of RynthPluginGetBountiesJson is simulated by calling BuildJson.
|
||||
internal static class BountyTests
|
||||
{
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("bounty: /bounty list lines (counting, cooldown, QB, layers, commas)", ListLines);
|
||||
r.Add("bounty: /bounty lines, waits and chat events", HereLinesAndEvents);
|
||||
r.Add("bounty: a full read replaces the list, a partial one updates it", ApplyListRules);
|
||||
r.Add("bounty: kills and awards stamp the row; an ended cooldown shows 0 kills; state survives a relog", ChangesAndCooldown);
|
||||
r.Add("bounty: /bounty updates only the one reward it can mean", HereMatching);
|
||||
r.Add("bounty: an open window reads the list quietly, kills and awards re-read it", WindowReadsAndKills);
|
||||
r.Add("bounty: closed window sends nothing; unknown command stops reads; no reply times out", ClosedAndUnsupported);
|
||||
r.Add("bounty: the window's JSON (options, QB filter, closest first) parses in the engine", BridgeJson);
|
||||
}
|
||||
|
||||
// ── Parsing ────────────────────────────────────────────────────────────────
|
||||
|
||||
private static void ListLines()
|
||||
{
|
||||
Check.True(BountyParse.TryParseListLine(" Lugian Mines: 1 Ascension Coin every 100 kills (at most every 5 min) - you: 34 of 100 kills.", out var a),
|
||||
"counting line parses (leading indentation)");
|
||||
Check.Eq(a.Where, "Lugian Mines", "area");
|
||||
Check.Eq(a.Amount, 1L, "amount");
|
||||
Check.Eq(a.Item, "Ascension Coin", "item");
|
||||
Check.Eq(a.KillsRequired, 100, "kills per award");
|
||||
Check.Eq(a.CooldownSeconds, 300, "cooldown");
|
||||
Check.Eq(a.Status.Status, BountyStatus.Counting, "status");
|
||||
Check.Eq(a.Status.Kills, 34, "kills so far");
|
||||
|
||||
Check.True(BountyParse.TryParseListLine("All zones: 3 Pyreal Nugget every 1,000 kills (at most every 2 min 30 sec) - you: unlocks in 1 hr 15 sec, then 1,000 kills required.", out var b),
|
||||
"cooldown line parses");
|
||||
Check.Eq(b.Where, "All zones", "all-zones area");
|
||||
Check.Eq(b.KillsRequired, 1000, "N0 kills");
|
||||
Check.Eq(b.CooldownSeconds, 150, "2 min 30 sec");
|
||||
Check.Eq(b.Status.Status, BountyStatus.Cooldown, "cooldown status");
|
||||
Check.Eq(b.Status.WaitSeconds, 3615, "1 hr 15 sec");
|
||||
Check.Eq(b.Status.KillsRequired, 1000, "kills after the cooldown");
|
||||
|
||||
Check.True(BountyParse.TryParseListLine("Valley of Death: 1,500 Trade Note - Large every 1 kill - you: needs 5,000 QB (you have 3,210).", out var c),
|
||||
"QB line with no cooldown and a hyphenated item parses");
|
||||
Check.Eq(c.Amount, 1500L, "N0 amount");
|
||||
Check.Eq(c.Item, "Trade Note - Large", "item keeps its own ' - '");
|
||||
Check.Eq(c.KillsRequired, 1, "one kill");
|
||||
Check.Eq(c.CooldownSeconds, 0, "no cooldown");
|
||||
Check.Eq(c.Status.Status, BountyStatus.NeedsQb, "QB status");
|
||||
Check.Eq(c.Status.QbRequired, 5000L, "QB needed");
|
||||
Check.Eq(c.Status.QbHave, 3210L, "QB had");
|
||||
|
||||
Check.True(BountyParse.TryParseListLine("Halls of Metos: Lower (layer 2): 2 Ascension Coin every 50 kills - you: 0 of 50 kills.", out var d),
|
||||
"an area with ': ' and a layer parses");
|
||||
Check.Eq(d.Where, "Halls of Metos: Lower (layer 2)", "area keeps its colon and layer");
|
||||
|
||||
Check.False(BountyParse.TryParseListLine("Bounties:", out _), "the header is not a reward");
|
||||
Check.False(BountyParse.TryParseListLine("Bounty: type /bounty to see the bounties where you stand.", out _), "the footer is not a reward");
|
||||
Check.False(BountyParse.TryParseListLine("Bob says, \"Lugian Mines: 1 coin every 100 kills\"", out _), "chat talk is not a reward");
|
||||
Check.True(BountyParse.IsListTerminator("Bounty: type /bounty to see the bounties where you stand."), "footer ends the reply");
|
||||
Check.True(BountyParse.IsListTerminator("Bounty: there are no bounties anywhere right now."), "'none anywhere' ends the reply");
|
||||
Check.True(BountyParse.IsNoBountiesAnywhere("Bounty: there are no bounties anywhere right now."), "'none anywhere' is recognised");
|
||||
Check.False(BountyParse.IsListTerminator("Bounty: there is no bounty here."), "/bounty's 'none here' is not the list's end");
|
||||
Check.True(BountyParse.IsUnknownCommand("Unknown command: bounty"), "ACE's unknown-command reply is recognised");
|
||||
Check.False(BountyParse.IsUnknownCommand("Unknown command: bank"), "another command's reply is not ours");
|
||||
}
|
||||
|
||||
private static void HereLinesAndEvents()
|
||||
{
|
||||
Check.True(BountyParse.TryParseHereLine("Bounty: 1 Ascension Coin - 12 of 100 kills.", out var h1), "plain /bounty line");
|
||||
Check.Eq(h1.Scope, "", "no scope");
|
||||
Check.Eq(h1.Status.Kills, 12, "kills");
|
||||
Check.True(BountyParse.TryParseHereLine("Bounty (all zones): 3 Pyreal Nugget - unlocks in 45 sec, then 1 kill required.", out var h2), "all-zones /bounty line");
|
||||
Check.Eq(h2.Scope, "all zones", "all-zones scope");
|
||||
Check.Eq(h2.Status.WaitSeconds, 45, "45 sec");
|
||||
Check.True(BountyParse.TryParseHereLine("Bounty (Thaelaryn Island): 1 Ascension Coin - needs 500 QB (you have 20).", out var h3), "region /bounty line");
|
||||
Check.Eq(h3.Scope, "Thaelaryn Island", "region scope");
|
||||
Check.False(BountyParse.TryParseHereLine("Bounty: there is no bounty here.", out _), "'none here' is not a reward");
|
||||
Check.False(BountyParse.TryParseHereLine("Bounty: +1 Ascension Coin will follow in a moment.", out _), "held notice is not a reward");
|
||||
|
||||
Check.Eq(BountyParse.ParseWaitSeconds("5 min"), 300, "5 min");
|
||||
Check.Eq(BountyParse.ParseWaitSeconds("2 hr 3 min 4 sec"), 7384, "hr min sec");
|
||||
Check.Eq(BountyParse.ParseWaitSeconds("soon"), 0, "unparseable wait");
|
||||
|
||||
Check.True(BountyParse.TryParseEvent("Bounty unlocked: Ascension Coin - 100 kills required.", out var k1, out string item1, out int n1, out _)
|
||||
&& k1 == BountyEventKind.Unlocked && item1 == "Ascension Coin" && n1 == 100, "unlock event");
|
||||
Check.True(BountyParse.TryParseEvent("Bounty complete! +3 Pyreal Nuggets gained.", out var k2, out string item2, out _, out _)
|
||||
&& k2 == BountyEventKind.Complete && item2 == "Pyreal Nuggets", "award event");
|
||||
Check.True(BountyParse.TryParseEvent("Next bounty unlocks in 2 min 30 sec - 1 kill required.", out var k3, out _, out int n3, out int w3)
|
||||
&& k3 == BountyEventKind.NextCooldown && n3 == 1 && w3 == 150, "next-cooldown event");
|
||||
Check.True(BountyParse.TryParseEvent("Next bounty requires 1,000 kills.", out var k4, out _, out int n4, out _)
|
||||
&& k4 == BountyEventKind.NextReady && n4 == 1000, "next-ready event");
|
||||
Check.True(BountyParse.TryParseEvent("Bounty: Your inventory is full. +1 Ascension Coin gained (3 total). They're safe until you make room.", out var k5, out _, out _, out _)
|
||||
&& k5 == BountyEventKind.Held, "held event");
|
||||
Check.False(BountyParse.TryParseEvent("Bounty: there is no bounty here.", out _, out _, out _, out _), "'none here' is not an event");
|
||||
Check.False(BountyParse.TryParseEvent("Bounty: 1 Ascension Coin - 12 of 100 kills.", out _, out _, out _, out _), "a status line is not an event");
|
||||
Check.False(BountyParse.TryParseEvent("Bounty: type /bounty to see the bounties where you stand.", out _, out _, out _, out _), "the footer is not an event");
|
||||
}
|
||||
|
||||
// ── Applying reads ─────────────────────────────────────────────────────────
|
||||
|
||||
private static BountyListLine L(string line)
|
||||
{
|
||||
Check.True(BountyParse.TryParseListLine(line, out var l), "fixture parses: " + line);
|
||||
return l;
|
||||
}
|
||||
|
||||
private static void ApplyListRules()
|
||||
{
|
||||
var t = New(out _, out _, out _);
|
||||
var t0 = new DateTime(2026, 10, 8, 12, 0, 0, DateTimeKind.Utc);
|
||||
t.ApplyList(new[]
|
||||
{
|
||||
L("Lugian Mines: 1 Ascension Coin every 100 kills - you: 10 of 100 kills."),
|
||||
L("All zones: 3 Pyreal Nugget every 50 kills - you: 0 of 50 kills."),
|
||||
}, complete: true, noneAnywhere: false, t0);
|
||||
Check.Eq(t.State.Entries.Count, 2, "full read: two rewards");
|
||||
Check.Eq(t.State.ListedUtc, t0, "read time stamped");
|
||||
|
||||
// A partial reply (no footer) only updates what it names; the other rows stay.
|
||||
t.ApplyList(new[] { L("Lugian Mines: 1 Ascension Coin every 100 kills - you: 11 of 100 kills.") },
|
||||
complete: false, noneAnywhere: false, t0.AddSeconds(5));
|
||||
Check.Eq(t.State.Entries.Count, 2, "partial read keeps the other row");
|
||||
Check.Eq(t.State.Entries[0].Kills, 11, "partial read updates the named row in place");
|
||||
|
||||
// A full read drops areas that are gone and keeps the server's order.
|
||||
t.ApplyList(new[]
|
||||
{
|
||||
L("Thaelaryn Island: 1 Ascension Coin every 20 kills - you: 4 of 20 kills."),
|
||||
L("Lugian Mines: 1 Ascension Coin every 100 kills - you: 12 of 100 kills."),
|
||||
}, complete: true, noneAnywhere: false, t0.AddSeconds(10));
|
||||
Check.Eq(string.Join(",", t.State.Entries.Select(e => e.Where)), "Thaelaryn Island,Lugian Mines", "server order, removed area gone");
|
||||
|
||||
t.ApplyList(Array.Empty<BountyListLine>(), complete: true, noneAnywhere: true, t0.AddSeconds(20));
|
||||
Check.Eq(t.State.Entries.Count, 0, "'none anywhere' empties the list");
|
||||
Check.True(t.State.NoneAnywhere, "and says so");
|
||||
}
|
||||
|
||||
private static void ChangesAndCooldown()
|
||||
{
|
||||
string file = Path.Combine(Program.TempRoot, "bounty-changes", BountyTracker.FileName);
|
||||
var t = New(out _, out _, out _, file);
|
||||
var t0 = new DateTime(2026, 10, 8, 12, 0, 0, DateTimeKind.Utc);
|
||||
const string Head = "Lugian Mines: 1 Ascension Coin every 3 kills (at most every 5 min) - you: ";
|
||||
t.ApplyList(new[] { L(Head + "1 of 3 kills.") }, true, false, t0);
|
||||
Check.Eq(t.State.Entries[0].ChangedUtc, default(DateTime), "first sighting is not a change");
|
||||
|
||||
t.ApplyList(new[] { L(Head + "2 of 3 kills.") }, true, false, t0.AddSeconds(10));
|
||||
Check.Eq(t.State.Entries[0].ChangedUtc, t0.AddSeconds(10), "a new kill stamps the row");
|
||||
|
||||
t.ApplyList(new[] { L(Head + "unlocks in 5 min, then 3 kills required.") }, true, false, t0.AddSeconds(20));
|
||||
var e = t.State.Entries[0];
|
||||
Check.Eq(e.ChangedUtc, t0.AddSeconds(20), "the award stamps the row");
|
||||
Check.Eq(e.UnlockAtUtc, t0.AddSeconds(320), "unlock time = read time + wait");
|
||||
Check.Eq(BountyTracker.Effective(e, t0.AddSeconds(100)).Status, BountyStatus.Cooldown, "still cooling down");
|
||||
var after = BountyTracker.Effective(e, t0.AddSeconds(321));
|
||||
Check.True(after.Status == BountyStatus.Counting && after.Kills == 0, "after the cooldown: 0 of N kills");
|
||||
Check.True(BountyTracker.Describe(e, t0.AddSeconds(100)).Contains("unlocks in 3 min 40 sec"), "chat text counts the cooldown down");
|
||||
|
||||
// The state survives a relog (the window fills right after login).
|
||||
t.Command("set hideqblocked 1");
|
||||
t.Save();
|
||||
var loaded = New(out _, out _, out _, file);
|
||||
Check.Eq(loaded.State.Entries.Count, 1, "entries saved per character");
|
||||
Check.Eq(loaded.State.Entries[0].UnlockAtUtc, t0.AddSeconds(320), "unlock time saved");
|
||||
Check.True(loaded.State.HideQbLocked, "options saved");
|
||||
}
|
||||
|
||||
private static void HereMatching()
|
||||
{
|
||||
var t = New(out _, out _, out _);
|
||||
var t0 = new DateTime(2026, 10, 8, 12, 0, 0, DateTimeKind.Utc);
|
||||
t.ApplyList(new[]
|
||||
{
|
||||
L("Lugian Mines: 1 Ascension Coin every 100 kills - you: 10 of 100 kills."),
|
||||
L("Halls of Metos: 1 Ascension Coin every 100 kills - you: 50 of 100 kills."),
|
||||
L("Thaelaryn Island: 2 Ascension Coin every 20 kills - you: 4 of 20 kills."),
|
||||
L("All zones: 1 Ascension Coin every 100 kills - you: 0 of 100 kills."),
|
||||
}, true, false, t0);
|
||||
|
||||
Check.True(BountyParse.TryParseHereLine("Bounty (Thaelaryn Island): 2 Ascension Coin - 5 of 20 kills.", out var region), "fixture");
|
||||
Check.True(t.ApplyHere(region, t0.AddSeconds(5)), "a region line names its area");
|
||||
Check.Eq(t.State.Entries[2].Kills, 5, "region row updated");
|
||||
|
||||
Check.True(BountyParse.TryParseHereLine("Bounty (all zones): 1 Ascension Coin - 1 of 100 kills.", out var zones), "fixture");
|
||||
Check.True(t.ApplyHere(zones, t0.AddSeconds(6)), "an all-zones line names its area");
|
||||
Check.Eq(t.State.Entries[3].Kills, 1, "all-zones row updated");
|
||||
|
||||
Check.True(BountyParse.TryParseHereLine("Bounty: 1 Ascension Coin - 11 of 100 kills.", out var plain), "fixture");
|
||||
Check.False(t.ApplyHere(plain, t0.AddSeconds(7)), "two dungeons pay the same reward: left alone");
|
||||
Check.Eq(t.State.Entries[0].Kills, 10, "first dungeon untouched");
|
||||
Check.Eq(t.State.Entries[1].Kills, 50, "second dungeon untouched");
|
||||
}
|
||||
|
||||
// ── The read loop ──────────────────────────────────────────────────────────
|
||||
|
||||
private const string ListReplyCounting = " Lugian Mines: 1 Ascension Coin every 100 kills - you: 34 of 100 kills.";
|
||||
private const string Footer = "Bounty: type /bounty to see the bounties where you stand.";
|
||||
|
||||
private static void WindowReadsAndKills()
|
||||
{
|
||||
var t = New(out var clock, out var sent, out _);
|
||||
t.Command("set minrefreshseconds 5");
|
||||
Run(t, clock, 500, windowOpen: true);
|
||||
Check.Eq(Reads(sent), 1, "opening the window reads /bounty list");
|
||||
Check.True(t.Reading, "a read is in progress");
|
||||
|
||||
Check.True(t.OnChat("Bounties:"), "the header is hidden from chat");
|
||||
Check.True(t.OnChat(ListReplyCounting), "reward lines are hidden from chat");
|
||||
Check.True(t.OnChat(Footer), "the footer is hidden and ends the read");
|
||||
Check.False(t.Reading, "the read is over");
|
||||
Check.Eq(t.State.Entries.Count, 1, "the read fills the list");
|
||||
Check.Eq(t.State.Entries[0].Kills, 34, "with the player's kills");
|
||||
|
||||
// A kill re-reads after the debounce, but not sooner than MinRefreshSeconds after the last read.
|
||||
t.OnKill();
|
||||
Run(t, clock, 3000, windowOpen: true);
|
||||
Check.Eq(Reads(sent), 1, "no re-read inside MinRefreshSeconds");
|
||||
Run(t, clock, 3000, windowOpen: true);
|
||||
Check.Eq(Reads(sent), 2, "a kill re-reads the list");
|
||||
t.OnChat("Bounties:");
|
||||
t.OnChat(" Lugian Mines: 1 Ascension Coin every 100 kills - you: 35 of 100 kills.");
|
||||
t.OnChat(Footer);
|
||||
Check.Eq(t.State.Entries[0].Kills, 35, "the kill shows up");
|
||||
Check.True(t.State.Entries[0].ChangedUtc != default, "and the row is highlighted");
|
||||
|
||||
// Award lines are shown to the player and also trigger a read, once MinRefreshSeconds
|
||||
// have passed since the last one (review 2026-10-09: awards used to skip the interval).
|
||||
Check.False(t.OnChat("Bounty complete! +1 Ascension Coin gained."), "award lines stay in chat");
|
||||
Check.Eq(t.State.LastEvent, "Bounty complete! +1 Ascension Coin gained.", "the window shows the last event");
|
||||
Run(t, clock, 2000, windowOpen: true);
|
||||
Check.Eq(Reads(sent), 2, "the award's re-read waits for MinRefreshSeconds");
|
||||
Run(t, clock, 3000, windowOpen: true);
|
||||
Check.Eq(Reads(sent), 3, "an award re-reads the list");
|
||||
|
||||
// A reply whose footer never comes ends after a quiet moment, as a partial update.
|
||||
t.OnChat("Bounties:");
|
||||
t.OnChat(" Lugian Mines: 1 Ascension Coin every 100 kills (at most every 5 min) - you: unlocks in 5 min, then 100 kills required.");
|
||||
Run(t, clock, 2000, windowOpen: true);
|
||||
Check.False(t.Reading, "a reply without its footer still ends");
|
||||
Check.Eq(t.State.Entries[0].Status, (int)BountyStatus.Cooldown, "and is applied");
|
||||
|
||||
// Lines the player asks for themselves are not hidden but still update the list.
|
||||
Check.False(t.OnChat(" Lugian Mines: 1 Ascension Coin every 100 kills - you: 0 of 100 kills."), "a typed /bounty list line stays in chat");
|
||||
Check.Eq(t.State.Entries[0].Status, (int)BountyStatus.Counting, "and updates the row");
|
||||
|
||||
// Closing the window (the engine stops polling; 3 s grace) stops the reads.
|
||||
Run(t, clock, 5000, windowOpen: false);
|
||||
int before = Reads(sent);
|
||||
t.OnKill();
|
||||
Run(t, clock, 20000, windowOpen: false);
|
||||
Check.Eq(Reads(sent), before, "no reads once the window is closed");
|
||||
}
|
||||
|
||||
private static void ClosedAndUnsupported()
|
||||
{
|
||||
var t = New(out var clock, out var sent, out var chat);
|
||||
t.Command("set minrefreshseconds 5");
|
||||
t.OnKill();
|
||||
Run(t, clock, 10000, windowOpen: false);
|
||||
Check.Eq(Reads(sent), 0, "closed window: kills send nothing");
|
||||
|
||||
Run(t, clock, 500, windowOpen: true);
|
||||
Check.Eq(Reads(sent), 1, "opening the window reads the list");
|
||||
Check.True(t.OnChat("Unknown command: bounty"), "the unknown-command reply to our read is hidden");
|
||||
Check.True(t.Unsupported, "'Unknown command: bounty' marks the server unsupported");
|
||||
|
||||
t.OnKill();
|
||||
Run(t, clock, 10 * 60_000, windowOpen: true);
|
||||
Check.Eq(Reads(sent), 1, "no automatic reads on an unsupported server, periodic included");
|
||||
|
||||
t.HandleChatCommand(new[] { "/ilt", "bountys", "refresh" });
|
||||
Check.False(t.Unsupported, "a manual refresh tries again");
|
||||
Run(t, clock, 500, windowOpen: true);
|
||||
Check.Eq(Reads(sent), 2, "and reads the list");
|
||||
Check.True(chat.Any(c => c.Contains("Reading /bounty list")), "the command answers in chat");
|
||||
|
||||
Run(t, clock, 11000, windowOpen: true);
|
||||
Check.False(t.Reading, "no reply: the read is abandoned");
|
||||
Check.True(t.BuildJson().Contains("no reply to /bounty list"), "and the window says so");
|
||||
|
||||
// With the window closed a manual refresh sends nothing (review 2026-10-09: reads only
|
||||
// while the window is open); the next open reads.
|
||||
Run(t, clock, 5000, windowOpen: false);
|
||||
Check.True(t.Command("refresh").Contains("window is open"), "a closed-window refresh says why it waits");
|
||||
Check.Eq(Reads(sent), 2, "a closed-window refresh sends nothing");
|
||||
Run(t, clock, 500, windowOpen: true);
|
||||
Check.Eq(Reads(sent), 3, "the next open reads");
|
||||
|
||||
chat.Clear();
|
||||
t.HandleChatCommand(new[] { "/ilt", "bounty" });
|
||||
Check.True(chat.Any(c => c.Contains("/rc bounties")), "'/ilt bounty' points at the window");
|
||||
}
|
||||
|
||||
private static void BridgeJson()
|
||||
{
|
||||
var t = New(out _, out _, out _);
|
||||
var now = DateTime.UtcNow;
|
||||
t.ApplyList(new[]
|
||||
{
|
||||
L("Valley of Death: 1,500 Trade Note - Large every 1 kill - you: needs 5,000 QB (you have 3,210)."),
|
||||
L("Lugian Mines: 1 Ascension Coin every 100 kills - you: 10 of 100 kills."),
|
||||
L("Thaelaryn Island: 2 Ascension Coin every 20 kills (at most every 5 min) - you: unlocks in 2 min, then 20 kills required."),
|
||||
L("Halls of Metos: 1 Ascension Coin every 10 kills - you: 9 of 10 kills."),
|
||||
}, true, false, now);
|
||||
|
||||
Check.Eq(t.Command("set minrefreshseconds 1"), "", "option accepted");
|
||||
Check.Eq(t.State.MinRefreshSeconds, BountyTracker.MinRefreshFloorSeconds, "MinRefreshSeconds is clamped to the floor");
|
||||
t.Command("set periodicminutes 999");
|
||||
Check.Eq(t.State.PeriodicRefreshMinutes, BountyTracker.PeriodicCeilingMinutes, "PeriodicRefreshMinutes is clamped");
|
||||
Check.True(t.Command("set nonsense 1").Contains("unknown"), "unknown option is reported");
|
||||
|
||||
using (var doc = JsonDocument.Parse(t.BuildJson()))
|
||||
{
|
||||
var root = doc.RootElement;
|
||||
Check.Eq(root.GetProperty("rows").GetArrayLength(), 4, "all rows by default");
|
||||
Check.Eq(root.GetProperty("rows")[0].GetProperty("where").GetString(), "Valley of Death", "server order by default");
|
||||
Check.Eq(root.GetProperty("minRefreshSeconds").GetInt32(), 5, "camelCase option names");
|
||||
}
|
||||
|
||||
t.Command("set hideqblocked 1");
|
||||
t.Command("set sortbyprogress on");
|
||||
string json = t.BuildJson();
|
||||
using (var doc = JsonDocument.Parse(json))
|
||||
{
|
||||
var rows = doc.RootElement.GetProperty("rows");
|
||||
Check.Eq(rows.GetArrayLength(), 3, "QB-locked row hidden");
|
||||
Check.Eq(doc.RootElement.GetProperty("hiddenCount").GetInt32(), 1, "and counted");
|
||||
Check.Eq(rows[0].GetProperty("where").GetString(), "Halls of Metos", "closest first: 9 of 10");
|
||||
Check.Eq(rows[2].GetProperty("where").GetString(), "Thaelaryn Island", "cooldowns after counting rows");
|
||||
}
|
||||
|
||||
#if ENGINE_BOUNTIES
|
||||
var snap = RynthCore.Engine.UI.Data.BountiesSnapshot.Parse(json);
|
||||
Check.NotNull(snap, "the engine parses the plugin's JSON");
|
||||
Check.True(snap!.HideQbLocked && snap.SortByProgress, "engine sees the options");
|
||||
Check.Eq(snap.MinRefreshSeconds, 5, "engine sees MinRefreshSeconds");
|
||||
Check.Eq(snap.HiddenCount, 1, "engine sees the hidden count");
|
||||
Check.Eq(snap.Rows.Count, 3, "engine sees the rows");
|
||||
var cd = snap.Rows.Single(r => r.Where == "Thaelaryn Island");
|
||||
Check.Eq(cd.Status, (int)RynthCore.Engine.UI.Data.BountyRowStatus.Cooldown, "engine status enum matches the plugin's");
|
||||
Check.True(cd.UnlockInSec > 100 && cd.UnlockInSec <= 120, $"cooldown seconds left ({cd.UnlockInSec})");
|
||||
Check.Eq(cd.CooldownSeconds, 300, "cooldown length");
|
||||
var halls = snap.Rows[0];
|
||||
Check.True(halls.Kills == 9 && halls.KillsRequired == 10 && halls.Amount == 1 && halls.Item == "Ascension Coin", "row fields");
|
||||
#endif
|
||||
}
|
||||
|
||||
// ── Helpers ────────────────────────────────────────────────────────────────
|
||||
|
||||
private sealed class Clock { public long Ms = 1_000_000; }
|
||||
|
||||
private static BountyTracker New(out Clock clock, out List<string> sent, out List<string> chat, string file = "")
|
||||
{
|
||||
var c = new Clock();
|
||||
var s = new List<string>();
|
||||
var ch = new List<string>();
|
||||
if (file.Length > 0) Directory.CreateDirectory(Path.GetDirectoryName(file)!);
|
||||
var t = new BountyTracker(s.Add, ch.Add, _ => { }, file, () => c.Ms);
|
||||
clock = c;
|
||||
sent = s;
|
||||
chat = ch;
|
||||
return t;
|
||||
}
|
||||
|
||||
private static int Reads(List<string> sent) => sent.Count(x => x == BountyTracker.ListCommand);
|
||||
|
||||
/// <summary>Advances the clock in 250 ms steps, ticking; with the window open the engine polls every second.</summary>
|
||||
private static void Run(BountyTracker t, Clock clock, long ms, bool windowOpen)
|
||||
{
|
||||
for (long elapsed = 0; elapsed < ms; elapsed += 250)
|
||||
{
|
||||
clock.Ms += 250;
|
||||
if (windowOpen && elapsed % 1000 == 0) t.BuildJson();
|
||||
t.Tick();
|
||||
}
|
||||
}
|
||||
}
|
||||
379
Tools/RynthILT.Tests/BreedingTests.cs
Normal file
379
Tools/RynthILT.Tests/BreedingTests.cs
Normal file
|
|
@ -0,0 +1,379 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using RynthCore.Plugin.RynthILT;
|
||||
using RynthCore.Plugin.RynthILT.Hub;
|
||||
using RynthCore.Plugin.Shared;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthILT.Tests;
|
||||
|
||||
// The pet breeding tracker (IltBreedingRules / IltBreedingEssence / IltBreedingSupplies / IltPetBreeding):
|
||||
// the server's rules and where each value came from, the parsers for ACECustom's appraisal block,
|
||||
// chat and "@breed-debug" (formats copied from PetDevice_Breeding.cs / PetDevice_Maturity.cs), each
|
||||
// breeding gate, the pair planner's odds, the supply refusals, and the JSON RynthOracle reads.
|
||||
internal static class BreedingTests
|
||||
{
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("breeding: tier table has one WCID per tier in every family, no repeats", TierTable);
|
||||
r.Add("breeding: rules come from the server, else the ILT profile, else ACE", RuleSources);
|
||||
r.Add("breeding: stat mutation odds follow ACE's decay, floor and incense cap", MutationOdds);
|
||||
r.Add("breeding: appraisal text gives the stud's charges, refill window and growth", AppraisalParse);
|
||||
r.Add("breeding: chat lines give charges, the guardian, growth stages and events", ChatParse);
|
||||
r.Add("breeding: @breed-debug reply is captured whole or line by line and parsed", DebugParse);
|
||||
r.Add("breeding: each gate (charges, rest, growth, neutered, shiny, bond, tier, ID)", Gates);
|
||||
r.Add("breeding: pair planner blocks wrong sexes and ranges the inherited mutations", Planner);
|
||||
r.Add("breeding: supplies are refused where the server would refuse them", Supplies);
|
||||
r.Add("breeding: reader JSON round-trips through RynthOracle's view", ReaderJson);
|
||||
r.Add("breeding: saved state survives the hub.json source-generated serializer", StateJson);
|
||||
r.Add("breeding: RynthILT.Data v2 keeps v1 readers working", DataApiVersion);
|
||||
}
|
||||
|
||||
private static IltBreedingRules Rules() => new(new IltBreedingState());
|
||||
|
||||
/// <summary>A healthy adult essence's facts (tier 150, bond 120, appraised).</summary>
|
||||
private static BreedEssenceFacts Facts(int id, bool male, uint wcid = 48946) => new()
|
||||
{
|
||||
Id = id,
|
||||
Name = (male ? "Stud " : "Dam ") + id,
|
||||
Wcid = wcid,
|
||||
HasId = true,
|
||||
Bond = 120,
|
||||
MaleOverride = male,
|
||||
};
|
||||
|
||||
private static void TierTable()
|
||||
{
|
||||
var seen = new HashSet<uint>();
|
||||
foreach (uint[] row in IltBreedingEssence.Families)
|
||||
{
|
||||
Check.Eq(row.Length, IltBreedingEssence.Tiers.Length, "row " + row[0]);
|
||||
foreach (uint w in row) Check.True(seen.Add(w), "WCID " + w + " appears once");
|
||||
}
|
||||
Check.Eq(IltBreedingEssence.Families.Length, 36, "36 combat pet families");
|
||||
Check.Eq(IltBreedingEssence.TierOf(48942), 50, "first fire skeleton is tier 50");
|
||||
Check.Eq(IltBreedingEssence.TierOf(49212), 200, "an out-of-run WCID keeps its slot (tier 200)");
|
||||
Check.Eq(IltBreedingEssence.TierOf(787801072), 300, "the last tier-300 essence");
|
||||
Check.Eq(IltBreedingEssence.TierOf(12345, 125), 125, "unknown WCID: a tier-valued level requirement");
|
||||
Check.Eq(IltBreedingEssence.TierOf(12345, 126), 0, "unknown WCID, odd level: unknown tier");
|
||||
Check.True(IltBreedingEssence.IsCombatEssence(49551), "range end is included");
|
||||
}
|
||||
|
||||
private static void RuleSources()
|
||||
{
|
||||
IltBreedingRules r = Rules();
|
||||
Check.Eq(r.Value(IltBreedingRules.MinTier).Source, BreedRuleSource.AceDefault, "min tier: ACE default");
|
||||
Check.Eq(r.GetInt(IltBreedingRules.MinTier), 100, "min tier 100");
|
||||
Check.Eq(r.Value(IltBreedingRules.MutationDecay).Source, BreedRuleSource.IltProfile, "decay: ILT profile");
|
||||
Check.Near(r.Get(IltBreedingRules.MutationDecay), 0.1, 1e-9, "ILT decay 0.1");
|
||||
Check.Near(r.Get(IltBreedingRules.GuardianEnabled), 1, 1e-9, "ILT runs the mating guardian");
|
||||
|
||||
DateTime t = new(2026, 10, 15, 12, 0, 0, DateTimeKind.Utc);
|
||||
Check.True(r.Learn(IltBreedingRules.MaleCharges, 12, t), "a new value is a change");
|
||||
Check.False(r.Learn(IltBreedingRules.MaleCharges, 12, t), "the same value again isn't");
|
||||
Check.Eq(r.Value(IltBreedingRules.MaleCharges).Source, BreedRuleSource.Server, "learned: seen on server");
|
||||
Check.Eq(r.GetInt(IltBreedingRules.MaleCharges), 12, "learned value wins");
|
||||
Check.False(r.Learn("not_a_rule", 1, t), "unknown keys are ignored");
|
||||
Check.Eq(r.RoomText(), "landblock 0x0106 variant 2", "Seedy Motel room");
|
||||
|
||||
IltBreedingRules frozen = r.Frozen();
|
||||
r.Learn(IltBreedingRules.MaleCharges, 8, t);
|
||||
Check.Eq(frozen.GetInt(IltBreedingRules.MaleCharges), 12, "a frozen copy doesn't follow later learning");
|
||||
|
||||
Check.Eq(r.StageName(2), "Whelp", "default stage names");
|
||||
Check.True(r.LearnStageName(2, "Pup"), "a server's own stage name");
|
||||
Check.Eq(r.StageName(2), "Pup", "seen name wins");
|
||||
for (int i = 0; i < IltBreedingRules.MaxEvents + 5; i++) r.AddEvent("x", "e" + i, t);
|
||||
Check.Eq(r.State.Log.Count, IltBreedingRules.MaxEvents, "event log is capped");
|
||||
Check.Eq(r.State.Log[^1].Text, "e" + (IltBreedingRules.MaxEvents + 4), "newest kept last");
|
||||
}
|
||||
|
||||
private static void MutationOdds()
|
||||
{
|
||||
IltBreedingRules r = Rules();
|
||||
Check.Near(r.StatMutationChance(0, 0), 0.05, 1e-9, "base 5%");
|
||||
Check.Near(r.StatMutationChance(4, 0), 0.05 / 1.4, 1e-9, "decay 0.1 x 4 mutations");
|
||||
Check.Near(r.StatMutationChance(0, 0.10), 0.15, 1e-9, "exquisite incense adds 10%");
|
||||
Check.Near(r.CombinedIncense(0.4, 0.3), 0.5, 1e-9, "both parents' incense capped at 50%");
|
||||
r.Learn(IltBreedingRules.MutationDecay, 10, DateTime.UtcNow);
|
||||
Check.Near(r.StatMutationChance(4, 0), 0.02, 1e-9, "never below the 2% floor");
|
||||
}
|
||||
|
||||
private static void AppraisalParse()
|
||||
{
|
||||
double now = 1_800_000_000;
|
||||
double lastRefill = now - (20 * 3600 + 50 * 60);
|
||||
string desc = "A fire skeleton essence.\nSex: Male (9/12 breeding charges today) - refills in 3h 10m\nBond: Unbound (imprints on first summon)";
|
||||
var seen = IltBreedingRules.FromAppraisal(desc, lastRefill, now);
|
||||
Check.True(seen.Contains((IltBreedingRules.MaleCharges, 12)), "max charges from the stud line");
|
||||
Check.True(seen.Contains((IltBreedingRules.MaleRefillHours, 24)), "refill window from the countdown");
|
||||
|
||||
string growth = "Sex: Female (ready to breed)\nGrowth: Whelp 2/5 - 75 kills to Juvenile, 195 to Adult";
|
||||
Check.True(IltBreedingRules.FromAppraisal(growth, 0, now).Contains((IltBreedingRules.MaturityStages, 5)), "stage count");
|
||||
Check.True(IltBreedingRules.TryParseGrowth(growth, out string name, out int stage, out int stages, out int toNext, out string next, out int toAdult), "growth line");
|
||||
Check.Eq(name, "Whelp", "stage name");
|
||||
Check.Eq(stage, 2, "stage");
|
||||
Check.Eq(stages, 5, "stages");
|
||||
Check.Eq(toNext, 75, "to next");
|
||||
Check.Eq(next, "Juvenile", "next stage");
|
||||
Check.Eq(toAdult, 195, "to adult");
|
||||
|
||||
Check.True(IltBreedingRules.TryParseGrowth("Growth: Young Adult 5/5 - 60 kills to Adult", out name, out stage, out _, out toNext, out next, out toAdult), "last stage");
|
||||
Check.Eq(name, "Young Adult", "two-word stage name");
|
||||
Check.Eq(next, "Adult", "last stage leads to Adult");
|
||||
Check.Eq(toAdult, 60, "last stage: to adult = to next");
|
||||
Check.False(IltBreedingRules.TryParseGrowth("Growth: Adult", out _, out _, out _, out _, out _, out _), "an adult has no countdown");
|
||||
}
|
||||
|
||||
private static void ChatParse()
|
||||
{
|
||||
var a = IltBreedingRules.FromChat("[Breeding] Fire Skeleton Essence spent a breeding charge: 7/12 left today.");
|
||||
Check.True(a.Contains((IltBreedingRules.MaleCharges, 12)), "charge line gives the max");
|
||||
var g = IltBreedingRules.FromChat("The union stirs something... Mating Spirit rises before A and B! Only the two parents can harm it. They have 120s to bring it down together.");
|
||||
Check.True(g.Contains((IltBreedingRules.GuardianEnabled, 1)), "guardian on");
|
||||
Check.True(g.Contains((IltBreedingRules.GuardianSeconds, 120)), "guardian timer");
|
||||
var d = IltBreedingRules.FromChat("[Breeding] Your pet performs the courtship dance, waiting for a partner... (Your partner must have their pet summoned in the same room and *dance* within 5 seconds).");
|
||||
Check.True(d.Contains((IltBreedingRules.DanceWindow, 5)), "dance window");
|
||||
Check.Eq(IltBreedingRules.FromChat("You say, \"hello\"").Count, 0, "ordinary chat says nothing");
|
||||
|
||||
Check.True(IltBreedingRules.TryParseGrownInto("Pup has grown into a Whelp! Its body swells with new strength. (2/5)", out int stage, out string name), "growth line");
|
||||
Check.Eq(stage, 2, "stage number");
|
||||
Check.Eq(name, "Whelp", "stage name");
|
||||
|
||||
Check.Eq(IltPetBreeding.EventKind("The mating ritual has begun between A and B..."), "ritual", "ritual");
|
||||
Check.Eq(IltPetBreeding.EventKind("Congratulations! A baby pet has been born: Pup! Placed in Bob's inventory."), "birth", "birth");
|
||||
Check.Eq(IltPetBreeding.EventKind("A baby pet has been born: Pup! Bob's packs are full, so the baby has been tucked away"), "birth", "deferred birth");
|
||||
Check.Eq(IltPetBreeding.EventKind("Pup has reached adulthood! It stands at its full size"), "adult", "adulthood");
|
||||
Check.Eq(IltPetBreeding.EventKind("Pup has imprinted on you. It is now bound to this character"), "imprint", "imprint");
|
||||
Check.Eq(IltPetBreeding.EventKind("[Breeding] The spectral guardian dissolves back into the ether..."), "guardian", "guardian lost");
|
||||
Check.Eq(IltPetBreeding.EventKind("Bob tells you, \"breed?\""), null, "not a breeding line");
|
||||
}
|
||||
|
||||
private const string DebugReply =
|
||||
"=== PET BREEDING DIAGNOSTICS ===\n" +
|
||||
"Breeding System Enabled: True\n" +
|
||||
"Your Location: Landblock=0x0106, Cell=0x01060186, Variant=2\n" +
|
||||
"Allowed Target: whole landblock 0x106, Variant=2 => Location Match: VALID (Room OK)\n" +
|
||||
"Your Active Pet: Fire Skeleton (WCID 48900) | Device: Fire Skeleton Essence\n" +
|
||||
" Sex: Male (9/10 charges)\n" +
|
||||
"Eligible breeding partners nearby: 1\n" +
|
||||
"================================\n";
|
||||
|
||||
private static void DebugParse()
|
||||
{
|
||||
Check.True(IltBreedingRules.IsDebugLine(DebugReply.TrimEnd('\n')), "whole message is a reply line");
|
||||
Check.True(IltBreedingRules.IsDebugEnd(DebugReply.TrimEnd('\n')), "whole message ends the reply");
|
||||
Check.True(IltBreedingRules.IsDebugEnd("================================"), "rule line alone ends it");
|
||||
Check.False(IltBreedingRules.IsDebugEnd("=== PET BREEDING DIAGNOSTICS ==="), "the header doesn't");
|
||||
Check.False(IltBreedingRules.IsDebugLine("Bob says, \"hi\""), "chat isn't");
|
||||
|
||||
BreedDebugInfo whole = IltBreedingRules.ParseDebug(new[] { DebugReply });
|
||||
BreedDebugInfo split = IltBreedingRules.ParseDebug(DebugReply.Split('\n'));
|
||||
foreach (BreedDebugInfo d in new[] { whole, split })
|
||||
{
|
||||
Check.Eq(d.Enabled, (bool?)true, "enabled");
|
||||
Check.Eq(d.AllowedLandblock, 0x106u, "landblock");
|
||||
Check.Eq(d.AllowedVariant, 2, "variant");
|
||||
Check.Eq(d.AllowedKind, "whole landblock", "kind");
|
||||
Check.Eq(d.LocationOk, (bool?)true, "in the room");
|
||||
Check.Eq(d.Partners, 1, "partners");
|
||||
Check.Eq(d.PetSex, "Male (9/10 charges)", "pet sex line");
|
||||
}
|
||||
var rules = IltBreedingRules.FromChat(DebugReply);
|
||||
Check.True(rules.Contains((IltBreedingRules.Landblock, 0x106)), "room landblock learned");
|
||||
Check.True(rules.Contains((IltBreedingRules.Variant, 2)), "room variant learned");
|
||||
}
|
||||
|
||||
private static void Gates()
|
||||
{
|
||||
IltBreedingRules r = Rules();
|
||||
double now = 1_800_000_000;
|
||||
|
||||
BreedEssence full = IltBreedingEssence.Evaluate(Facts(1, true), r, now);
|
||||
Check.True(full.Ready, "a stud that never bred is full");
|
||||
Check.Eq(full.Charges, 10, "10 charges");
|
||||
Check.Eq(full.Tier, 125, "48946 is tier 125");
|
||||
|
||||
var spent = Facts(2, true);
|
||||
spent.MaleCharges = 0;
|
||||
spent.MaleRefreshUnix = now - 2 * 3600;
|
||||
BreedEssence noCharge = IltBreedingEssence.Evaluate(spent, r, now);
|
||||
Check.Eq(noCharge.Gate, BreedGate.NoCharges, "no charges");
|
||||
Check.Near(noCharge.ReadyAtUnix, now + 22 * 3600, 1, "refills 24h after the last refill");
|
||||
|
||||
spent.MaleRefreshUnix = now - 25 * 3600;
|
||||
Check.True(IltBreedingEssence.Evaluate(spent, r, now).Ready, "refilled once the window passed (the server refills on read)");
|
||||
|
||||
var dam = Facts(3, false);
|
||||
dam.NextBreedUnix = now + 3600 + 300;
|
||||
BreedEssence resting = IltBreedingEssence.Evaluate(dam, r, now);
|
||||
Check.Eq(resting.Gate, BreedGate.Resting, "resting dam");
|
||||
Check.Eq(resting.Status, "Rest 1h 05m", "rest countdown");
|
||||
|
||||
var neut = Facts(4, false);
|
||||
neut.Neutered = true;
|
||||
Check.Eq(IltBreedingEssence.Evaluate(neut, r, now).Gate, BreedGate.Neutered, "neutered");
|
||||
|
||||
var shiny = Facts(5, true);
|
||||
shiny.LongDesc = "Sex: Male (shiny - cannot breed)";
|
||||
Check.Eq(IltBreedingEssence.Evaluate(shiny, r, now).Gate, BreedGate.Shiny, "shiny");
|
||||
|
||||
var baby = Facts(6, false);
|
||||
baby.JuvenileFlag = true;
|
||||
baby.MaturityKills = 130;
|
||||
BreedEssence growing = IltBreedingEssence.Evaluate(baby, r, now);
|
||||
Check.Eq(growing.Gate, BreedGate.Growing, "juvenile");
|
||||
Check.Eq(growing.Stage, 3, "130 kills of 300 over 5 stages: stage 3");
|
||||
Check.Eq(growing.StageName, "Juvenile", "stage 3 name");
|
||||
Check.Eq(growing.KillsToNext, 50, "50 kills to stage 4");
|
||||
|
||||
var weak = Facts(7, true);
|
||||
weak.Bond = 40;
|
||||
Check.Eq(IltBreedingEssence.Evaluate(weak, r, now).Gate, BreedGate.LowBond, "bond under 100");
|
||||
|
||||
BreedEssence low = IltBreedingEssence.Evaluate(Facts(8, true, 48944), r, now);
|
||||
Check.Eq(low.Gate, BreedGate.LowTier, "tier 80 is under the minimum");
|
||||
|
||||
var unread = Facts(9, true);
|
||||
unread.HasId = false;
|
||||
Check.Eq(IltBreedingEssence.Evaluate(unread, r, now).Gate, BreedGate.NeedsId, "not appraised yet");
|
||||
|
||||
var boosted = Facts(10, false);
|
||||
boosted.Incense = 0.05;
|
||||
boosted.Catalyst = true;
|
||||
BreedEssence b = IltBreedingEssence.Evaluate(boosted, r, now);
|
||||
Check.Eq(string.Join("|", b.Boosters), "Refined incense +5%|Chromatic Catalyst", "boosters listed");
|
||||
}
|
||||
|
||||
private static void Planner()
|
||||
{
|
||||
IltBreedingRules r = Rules();
|
||||
double now = 1_800_000_000;
|
||||
var sf = Facts(1, true);
|
||||
sf.MutDamage = 2;
|
||||
sf.MutCrit = 1;
|
||||
sf.Incense = 0.10;
|
||||
var df = Facts(2, false);
|
||||
df.MutDamage = 0;
|
||||
df.MutCrit = 3;
|
||||
BreedEssence stud = IltBreedingEssence.Evaluate(sf, r, now), dam = IltBreedingEssence.Evaluate(df, r, now);
|
||||
|
||||
BreedPairPlan p = IltBreedingPlanner.Plan(stud, dam, r);
|
||||
Check.True(p.CanBreed, "both ready");
|
||||
Check.Eq(p.InheritMin, 1, "lower lines: damage 0 + crit 1");
|
||||
Check.Eq(p.InheritMax, 5, "higher lines: damage 2 + crit 3");
|
||||
Check.Near(p.ChanceBest, 0.15 / 1.1, 1e-9, "best: 1 mutation, incense 10%");
|
||||
Check.Near(p.ChanceWorst, 0.15 / 1.5, 1e-9, "worst: 5 mutations");
|
||||
Check.Near(p.PotencyChance, 0.03, 1e-9, "potency 3%");
|
||||
|
||||
BreedPairPlan wrong = IltBreedingPlanner.Plan(dam, stud, r);
|
||||
Check.False(wrong.CanBreed, "swapped sexes");
|
||||
Check.True(wrong.Blockers.Any(b => b.Contains("must be male")), "says the stud must be male");
|
||||
}
|
||||
|
||||
private static void Supplies()
|
||||
{
|
||||
IltBreedingRules r = Rules();
|
||||
double now = 1_800_000_000;
|
||||
BreedSupplyDef lesser = IltBreedingSupplies.Find(IltBreedingSupplies.LesserIncense)!;
|
||||
BreedSupplyDef exquisite = IltBreedingSupplies.Find(IltBreedingSupplies.ExquisiteIncense)!;
|
||||
BreedSupplyDef draught = IltBreedingSupplies.Find(IltBreedingSupplies.Draught)!;
|
||||
BreedSupplyDef offering = IltBreedingSupplies.Find(IltBreedingSupplies.Offering)!;
|
||||
BreedSupplyDef neuter = IltBreedingSupplies.Find(IltBreedingSupplies.NeuteringKit)!;
|
||||
|
||||
var f = Facts(1, false);
|
||||
f.Incense = 0.05;
|
||||
BreedEssence primed = IltBreedingEssence.Evaluate(f, r, now);
|
||||
Check.NotNull(IltBreedingSupplies.RefuseReason(lesser, primed, r), "weaker incense refused");
|
||||
Check.Null(IltBreedingSupplies.RefuseReason(exquisite, primed, r), "stronger incense taken");
|
||||
Check.True(IltBreedingSupplies.Warning(exquisite, primed).Contains("+5%"), "and warns the +5% is lost");
|
||||
|
||||
var n = Facts(2, false);
|
||||
n.Neutered = true;
|
||||
Check.NotNull(IltBreedingSupplies.RefuseReason(lesser, IltBreedingEssence.Evaluate(n, r, now), r), "no incense on a neutered essence");
|
||||
|
||||
BreedEssence adult = IltBreedingEssence.Evaluate(Facts(3, true), r, now);
|
||||
Check.NotNull(IltBreedingSupplies.RefuseReason(draught, adult, r), "draught: juveniles only");
|
||||
var j = Facts(4, true);
|
||||
j.JuvenileFlag = true;
|
||||
j.MaturityKills = 0;
|
||||
Check.Null(IltBreedingSupplies.RefuseReason(draught, IltBreedingEssence.Evaluate(j, r, now), r), "draught on a juvenile");
|
||||
j.MaturityXpMult = 2.0;
|
||||
Check.NotNull(IltBreedingSupplies.RefuseReason(draught, IltBreedingEssence.Evaluate(j, r, now), r), "not twice");
|
||||
|
||||
Check.Null(IltBreedingSupplies.RefuseReason(offering, adult, r), "offering with the guardian on");
|
||||
r.Learn(IltBreedingRules.GuardianEnabled, 0, DateTime.UtcNow);
|
||||
Check.NotNull(IltBreedingSupplies.RefuseReason(offering, adult, r), "offering refused with the guardian off");
|
||||
Check.NotNull(IltBreedingSupplies.RefuseReason(neuter, adult, r), "the neutering kit is never used from here");
|
||||
Check.Eq(IltBreedingSupplies.PriceText(1_250_000), "1.25M", "price text");
|
||||
}
|
||||
|
||||
private static void ReaderJson()
|
||||
{
|
||||
IltBreedingRules r = Rules();
|
||||
double now = 1_800_000_000;
|
||||
var stud = IltBreedingEssence.Evaluate(Facts(11, true), r, now);
|
||||
var dam = IltBreedingEssence.Evaluate(Facts(12, false), r, now);
|
||||
var events = new[] { new IltBreedingEvent { Utc = new DateTime(2026, 10, 15, 20, 0, 0, DateTimeKind.Utc), Kind = "birth", Text = "A \"baby\" was born" } };
|
||||
var supplies = IltBreedingSupplies.All.Select(s => (s, s.Key == IltBreedingSupplies.RefinedIncense ? 2L : 0L)).ToList();
|
||||
var snap = new BreedingSnapshot(new[] { stud, dam }, supplies, r.All(), events,
|
||||
IltBreedingRules.ParseDebug(new[] { DebugReply }), DateTime.UtcNow, IltTri.On, IltTri.On, IltTri.On,
|
||||
r.RoomText(), 5, "hello", now, true, r.Frozen());
|
||||
|
||||
string json = IltPetBreeding.BuildJson(snap, r, "InfiniteLeaftide");
|
||||
using (JsonDocument.Parse(json)) { } // well-formed
|
||||
IltBreedingView v = IltBreedingView.Parse(json);
|
||||
Check.True(v.Loaded && v.Available, "loaded");
|
||||
Check.Eq(v.Enabled, "on", "enabled");
|
||||
Check.Eq(v.Room, "landblock 0x0106 variant 2", "room");
|
||||
Check.Eq(v.FreeSlots, 5, "free slots");
|
||||
Check.Eq(v.Essences.Count, 2, "two essences");
|
||||
Check.True(v.Essences[0].Male && v.Essences[0].Ready, "stud row");
|
||||
Check.Eq(v.Pairs.Count, 1, "one ready pairing");
|
||||
Check.Near(v.Pairs[0].ChanceBest, 0.05, 1e-6, "pair odds");
|
||||
IltBreedSupplyRow refined = v.Supplies.First(s => s.Key == IltBreedingSupplies.RefinedIncense);
|
||||
Check.Eq(refined.Count, 2L, "supply count");
|
||||
Check.Eq(refined.Targets.Count, 2, "both essences can take it");
|
||||
Check.Eq(v.Supplies.First(s => s.Key == IltBreedingSupplies.LesserIncense).Targets.Count, 0, "none carried: no targets");
|
||||
Check.Eq(v.Rules.Count, IltBreedingRules.Defs.Length, "every rule");
|
||||
Check.Eq(v.Events[0].Text, "A \"baby\" was born", "quotes escaped and read back");
|
||||
Check.Eq(v.Debug?.Match, "valid", "diagnostics");
|
||||
Check.Eq(IltBreedingView.ApplyVerb(" incense2 ", 12), "apply incense2 12", "apply verb");
|
||||
}
|
||||
|
||||
private static void StateJson()
|
||||
{
|
||||
var state = new IltHubState();
|
||||
var rules = new IltBreedingRules(state.Pet.Breeding);
|
||||
rules.Learn(IltBreedingRules.MaleCharges, 12, new DateTime(2026, 10, 15, 0, 0, 0, DateTimeKind.Utc));
|
||||
rules.LearnStageName(1, "Hatchling");
|
||||
rules.AddEvent("birth", "born", DateTime.UtcNow);
|
||||
string json = JsonSerializer.Serialize(state, IltHubJsonContext.Default.IltHubState);
|
||||
IltHubState back = JsonSerializer.Deserialize(json, IltHubJsonContext.Default.IltHubState)!;
|
||||
var again = new IltBreedingRules(back.Pet.Breeding);
|
||||
Check.Eq(again.GetInt(IltBreedingRules.MaleCharges), 12, "learned rule saved");
|
||||
Check.Eq(again.StageName(1), "Hatchling", "stage name saved");
|
||||
Check.Eq(back.Pet.Breeding.Log.Count, 1, "event saved");
|
||||
|
||||
IltHubState old = JsonSerializer.Deserialize("{\"Pet\":{\"PetLog\":[\"a\"]}}", IltHubJsonContext.Default.IltHubState)!;
|
||||
Check.NotNull(old.Pet.Breeding, "a hub.json from before the tracker gets an empty breeding state");
|
||||
}
|
||||
|
||||
private static unsafe void DataApiVersion()
|
||||
{
|
||||
// Version 3 (the Temple guardians) appends after the breeding pair; a v2 reader sees the same breeding layout.
|
||||
Check.Eq(RynthIltDataApiV1.InterfaceVersion, 3u, "version 3");
|
||||
Check.True(RynthIltDataApiV1.V1Size < RynthIltDataApiV1.V2Size && RynthIltDataApiV1.V2Size < (uint)sizeof(RynthIltDataApiV1),
|
||||
"v2 appends to v1, v3 to v2");
|
||||
Check.Eq(RynthIltDataApiV1.V1Size, (uint)(8 + 4 * sizeof(IntPtr)), "v1 = two uints and four function pointers");
|
||||
Check.True(DataInterface.Query(RynthIltDataApiV1.InterfaceName, 1) != IntPtr.Zero, "v1 readers still get the table");
|
||||
Check.True(DataInterface.Query(RynthIltDataApiV1.InterfaceName, 2) != IntPtr.Zero, "v2 readers too");
|
||||
Check.True(DataInterface.Query(RynthIltDataApiV1.InterfaceName, 3) != IntPtr.Zero, "v3 readers too");
|
||||
Check.True(DataInterface.Query(RynthIltDataApiV1.InterfaceName, 4) == IntPtr.Zero, "a future version isn't claimed");
|
||||
var t = (RynthIltDataApiV1*)DataInterface.Query(RynthIltDataApiV1.InterfaceName, 1);
|
||||
Check.True(t->GetPetBreedingJson != null && t->PetBreedingCommand != null, "breeding functions filled");
|
||||
Check.Eq(RynthIltHub.SectionPetBreeding, "pets-breeding", "section id");
|
||||
}
|
||||
}
|
||||
173
Tools/RynthILT.Tests/ChunkTargetTests.cs
Normal file
173
Tools/RynthILT.Tests/ChunkTargetTests.cs
Normal file
|
|
@ -0,0 +1,173 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using RynthCore.Plugin.RynthILT.Hub;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthILT.Tests;
|
||||
|
||||
// The chunk rules end to end: a fake inventory with the Lugian Aetheria Hammer and one candidate,
|
||||
// IltChunkClap.Tick, and whether the hammer was used on the candidate. These cover what the pure
|
||||
// rule tests (AetheriaChunkTests) cannot: the properties as RynthILT reads them from the host, an
|
||||
// item that is not appraised, and a host that cannot tell whether an appraisal arrived. The hammer
|
||||
// destroys what it is used on, so "used on it" is the thing to get right.
|
||||
internal static class ChunkTargetTests
|
||||
{
|
||||
private const uint Player = 0x50000F01;
|
||||
private const uint Hammer = 0x5000A001;
|
||||
private const uint Item = 0x5000A002;
|
||||
private const uint ItemTypeGem = 0x00000800;
|
||||
private const uint ItemTypeMelee = 0x00000001;
|
||||
private const uint ItemTypeMisc = 0x00000080;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("chunk (live path): unlevelled Coalesced chunks only when its level was truly read as none", UnlevelledVsUnreadable);
|
||||
r.Add("chunk (live path): levelled Coalesced Aetheria obeys the cap; other aetheria needs a level", LevelledCap);
|
||||
r.Add("chunk (live path): corrupted two-handed cleave 2 chunks, other corrupted cleave 2 does not", CorruptedCleave);
|
||||
r.Add("chunk (live path): corrupted keep rules and the rating level are off by default and protect when on", KeepRulesLive);
|
||||
r.Add("chunk (live path): a busy client in combat chunks with chunk-in-combat on, not off; peace waits for idle", CombatBusy);
|
||||
}
|
||||
|
||||
/// <summary>One chunk pass on a fake pack. Returns the targets the hammer was used on.</summary>
|
||||
private static List<uint> Pass(string folder, Action<IltGearState> settings, Action<uint> candidate,
|
||||
uint itemType = ItemTypeGem, string name = "Coalesced Aetheria", bool appraised = true,
|
||||
bool hostCanSayAppraised = true, bool busy = false, int combatMode = 1)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.WorldName = "InfiniteLeaftide";
|
||||
FakeHost.ContentsCalls = true;
|
||||
FakeHost.UseOnCalls = true;
|
||||
FakeHost.WeaponCalls = hostCanSayAppraised; // installs HasAppraisalData / RequestId / combat mode
|
||||
FakeHost.BusyCalls = true;
|
||||
FakeHost.BusyStateValue = busy ? 1 : 0;
|
||||
FakeHost.CombatModeValue = combatMode;
|
||||
FakeHost.Names[Hammer] = "Lugian Aetheria Hammer"; FakeHost.ItemTypes[Hammer] = ItemTypeMisc; FakeHost.Containers[Hammer] = Player;
|
||||
FakeHost.Names[Item] = name; FakeHost.ItemTypes[Item] = itemType; FakeHost.Containers[Item] = Player;
|
||||
if (appraised) FakeHost.Appraised.Add(Item);
|
||||
candidate(Item);
|
||||
var host = FakeHost.Create(Player);
|
||||
string dir = Path.Combine(Program.TempRoot, "chunk-" + folder);
|
||||
Directory.CreateDirectory(dir);
|
||||
var hub = new IltHubController(host, dir, new IltSettings(), new RynthAiClient(host));
|
||||
var g = hub.State.Gear;
|
||||
g.AutoChunkAetheria = true;
|
||||
g.AutoChunkCorrupted = true;
|
||||
settings(g);
|
||||
hub.Gear.ChunkClap.Tick(10_000);
|
||||
return FakeHost.UsesOn.Where(u => u.Source == Hammer).Select(u => u.Target).ToList();
|
||||
}
|
||||
|
||||
private static void Ints(uint id, params (uint Key, int Value)[] values)
|
||||
{
|
||||
foreach (var (k, v) in values) FakeHost.Ints[(id, k)] = v;
|
||||
}
|
||||
|
||||
private static void UnlevelledVsUnreadable()
|
||||
{
|
||||
// Truly unlevelled: the appraisal arrived and the item has no level (int 319), no XP, no tinks.
|
||||
Check.Eq(Pass("coal-unlevelled", _ => { }, _ => { }).Count, 1, "appraised, no level: chunked (ub-IT)");
|
||||
// Even with the cap at its lowest.
|
||||
Check.Eq(Pass("coal-unlevelled-cap1", g => g.ChunkAetheriaUnderLevel = 1, _ => { }).Count, 1, "cap 1 does not stop an unlevelled one");
|
||||
// Not appraised yet: nothing is known, so it is asked for, not hammered.
|
||||
var asked = Pass("coal-unappraised", _ => { }, _ => { }, appraised: false);
|
||||
Check.Eq(asked.Count, 0, "not appraised: not chunked");
|
||||
Check.True(FakeHost.IdRequests.Contains(Item), "its appraisal is requested");
|
||||
// The host cannot say whether an appraisal arrived: a level of 0 might be a failed read.
|
||||
Check.Eq(Pass("coal-unreadable", _ => { }, _ => { }, hostCanSayAppraised: false).Count, 0,
|
||||
"host cannot confirm the appraisal: kept, not chunked");
|
||||
// The same unconfirmable host with a read level still keeps (no half-trusted piece is hammered).
|
||||
Check.Eq(Pass("coal-unreadable-lvl", _ => { }, id => Ints(id, (IltInventory.IntItemMaxLevel, 2)), hostCanSayAppraised: false).Count, 0,
|
||||
"host cannot confirm the appraisal: even a read level 2 is kept");
|
||||
// A revealed (non-Coalesced) aetheria with no level is never chunked.
|
||||
Check.Eq(Pass("rev-unlevelled", _ => { }, _ => { }, name: "Blue Aetheria").Count, 0, "revealed aetheria with no level: kept");
|
||||
// Item XP, tinks or the never-chunk flag keep it.
|
||||
Check.Eq(Pass("coal-xp", _ => { }, id => FakeHost.Quads[(id, IltInventory.QuadItemTotalXp)] = 500).Count, 0, "has item XP: kept");
|
||||
Check.Eq(Pass("coal-tinked", _ => { }, id => Ints(id, (IltInventory.IntNumTimesTinkered, 1))).Count, 0, "tinkered: kept");
|
||||
Check.Eq(Pass("coal-never", _ => { }, id => FakeHost.Bools[(id, IltInventory.BoolNeverChunk)] = true).Count, 0, "never-chunk flag: kept");
|
||||
}
|
||||
|
||||
private static void LevelledCap()
|
||||
{
|
||||
Check.Eq(Pass("cap-l3", _ => { }, id => Ints(id, (IltInventory.IntItemMaxLevel, 3))).Count, 1, "level 3 under the default cap of 4");
|
||||
Check.Eq(Pass("cap-l4", _ => { }, id => Ints(id, (IltInventory.IntItemMaxLevel, 4))).Count, 0, "level 4 at the default cap of 4: kept");
|
||||
Check.Eq(Pass("cap9-l8", g => g.ChunkAetheriaUnderLevel = 9, id => Ints(id, (IltInventory.IntItemMaxLevel, 8))).Count, 1, "level 8 under a cap of 9");
|
||||
Check.Eq(Pass("cap9-l9", g => g.ChunkAetheriaUnderLevel = 9, id => Ints(id, (IltInventory.IntItemMaxLevel, 9))).Count, 0, "level 9 at a cap of 9: kept");
|
||||
Check.Eq(Pass("cap9-l10", g => g.ChunkAetheriaUnderLevel = 9, id => Ints(id, (IltInventory.IntItemMaxLevel, 10))).Count, 0, "level 10 over a cap of 9: kept");
|
||||
Check.Eq(Pass("cap11-l10", g => g.ChunkAetheriaUnderLevel = 11, id => Ints(id, (IltInventory.IntItemMaxLevel, 10))).Count, 1, "cap 11 chunks every level");
|
||||
Check.Eq(Pass("rev-l2", _ => { }, id => Ints(id, (IltInventory.IntItemMaxLevel, 2)), name: "Blue Aetheria").Count, 1, "a levelled revealed piece under the cap");
|
||||
}
|
||||
|
||||
private static void CorruptedCleave()
|
||||
{
|
||||
void Weapon(uint id, int cleave, int wieldSkill = 45, int weaponType = 0, int attackType = 4) =>
|
||||
Ints(id, (IltInventory.IntItemWorkmanship, 6), (IltInventory.IntCleaving, cleave), (IltInventory.IntWieldSkillType, wieldSkill),
|
||||
(IltInventory.IntWeaponType, weaponType), (IltInventory.IntAttackType, attackType));
|
||||
Check.Eq(Pass("cor-1h-c1", _ => { }, id => Weapon(id, 1), ItemTypeMelee, "Corrupted Sword").Count, 1, "one-handed cleave 1 chunks");
|
||||
Check.Eq(Pass("cor-1h-c2", _ => { }, id => Weapon(id, 2), ItemTypeMelee, "Corrupted Sword").Count, 0, "one-handed cleave 2 is kept");
|
||||
Check.Eq(Pass("cor-2h-c2", _ => { }, id => Weapon(id, 2, wieldSkill: 41), ItemTypeMelee, "Corrupted Greatsword").Count, 1, "two-handed cleave 2 chunks");
|
||||
Check.Eq(Pass("cor-2h-c3", _ => { }, id => Weapon(id, 3, wieldSkill: 41), ItemTypeMelee, "Corrupted Greatsword").Count, 0, "two-handed cleave 3 is kept");
|
||||
Check.Eq(Pass("cor-2h-thrust", _ => { }, id => Weapon(id, 2, wieldSkill: 41, attackType: 2), ItemTypeMelee, "Corrupted Spear").Count, 0, "two-handed thrust cleave 2 is kept");
|
||||
Check.Eq(Pass("cor-nowork", _ => { }, id => Ints(id, (IltInventory.IntCleaving, 1)), ItemTypeMelee, "Corrupted Sword").Count, 0, "no workmanship read: kept");
|
||||
Check.Eq(Pass("cor-unreadable", _ => { }, id => Weapon(id, 1), ItemTypeMelee, "Corrupted Sword", hostCanSayAppraised: false).Count, 0,
|
||||
"host cannot confirm the appraisal: kept");
|
||||
Check.Eq(Pass("cor-off", g => g.AutoChunkCorrupted = false, id => Weapon(id, 1), ItemTypeMelee, "Corrupted Sword").Count, 0, "auto-chunk corrupted off: not touched");
|
||||
}
|
||||
|
||||
private static void KeepRulesLive()
|
||||
{
|
||||
var def = new IltGearState();
|
||||
Check.True(!def.KeepCorruptedCrushingBlow && !def.KeepCorruptedBitingStrike && !def.KeepCorruptedArmorCleaving
|
||||
&& !def.KeepCorruptedAnySlayer && !def.KeepCorruptedMultiStrike && !def.KeepCorruptedElementalBonus
|
||||
&& !def.KeepCorruptedAnySpell && def.KeepCorruptedMaxDamageAtLeast == 0 && def.KeepCorruptedSpellIds == "",
|
||||
"every corrupted keep rule is off by default");
|
||||
Check.Eq(def.KeepAetheriaRatingAtLeast, 1, "the rating level defaults to 1 (any rating keeps, as before)");
|
||||
|
||||
void Loaded(uint id)
|
||||
{
|
||||
Ints(id, (IltInventory.IntItemWorkmanship, 6), (IltInventory.IntCleaving, 1), (IltInventory.IntAttackType, 160),
|
||||
(IltInventory.IntSlayerCreatureType, 5), (IltInventory.IntElementalDamageBonus, 10), (IltInventory.IntDamage, 400));
|
||||
FakeHost.Doubles[(id, IltInventory.FloatCriticalFrequency)] = 0.1;
|
||||
FakeHost.Doubles[(id, IltInventory.FloatCriticalMultiplier)] = 1.5;
|
||||
FakeHost.Doubles[(id, IltInventory.FloatIgnoreArmor)] = 0.2;
|
||||
FakeHost.SpellIds[id] = new uint[] { 2072 };
|
||||
}
|
||||
int Run(string tag, Action<IltGearState> s) => Pass("keep-" + tag, s, Loaded, ItemTypeMelee, "Corrupted Sword").Count;
|
||||
Check.Eq(Run("none", _ => { }), 1, "a loaded corrupted weapon chunks while every keep rule is off");
|
||||
Check.Eq(Run("crush", g => g.KeepCorruptedCrushingBlow = true), 0, "Crushing Blow on: kept");
|
||||
Check.Eq(Run("bite", g => g.KeepCorruptedBitingStrike = true), 0, "Biting Strike on: kept");
|
||||
Check.Eq(Run("armor", g => g.KeepCorruptedArmorCleaving = true), 0, "Armor Cleaving on: kept");
|
||||
Check.Eq(Run("slayer", g => g.KeepCorruptedAnySlayer = true), 0, "slayer on: kept");
|
||||
Check.Eq(Run("multi", g => g.KeepCorruptedMultiStrike = true), 0, "multi-strike on: kept");
|
||||
Check.Eq(Run("elem", g => g.KeepCorruptedElementalBonus = true), 0, "elemental bonus on: kept");
|
||||
Check.Eq(Run("maxdmg", g => g.KeepCorruptedMaxDamageAtLeast = 400), 0, "max damage 400 on: kept");
|
||||
Check.Eq(Run("maxdmg-hi", g => g.KeepCorruptedMaxDamageAtLeast = 401), 1, "max damage above the weapon's: chunks");
|
||||
Check.Eq(Run("spell", g => g.KeepCorruptedAnySpell = true), 0, "any spell on: kept");
|
||||
Check.Eq(Run("spellid", g => g.KeepCorruptedSpellIds = "2072"), 0, "a listed spell id: kept");
|
||||
Check.Eq(Run("spellid-other", g => g.KeepCorruptedSpellIds = "100"), 1, "another spell id: chunks");
|
||||
|
||||
// The rating level on a live Coalesced piece with a C 1 rating.
|
||||
void C1(uint id) => Ints(id, (IltInventory.IntGearCrit, 1));
|
||||
Check.Eq(Pass("rate-default", _ => { }, C1).Count, 0, "C 1 is kept at the default rating level");
|
||||
Check.Eq(Pass("rate-2", g => g.KeepAetheriaRatingAtLeast = 2, C1).Count, 1, "C 1 chunks once the rating level is 2");
|
||||
Check.Eq(Pass("rate-2-c2", g => g.KeepAetheriaRatingAtLeast = 2, id => Ints(id, (IltInventory.IntGearCrit, 2))).Count, 0, "C 2 is kept at level 2");
|
||||
Check.Eq(Pass("rate-2-off", g => { g.KeepAetheriaRatingAtLeast = 2; g.KeepAetheriaWithCrit = false; }, id => Ints(id, (IltInventory.IntGearCrit, 5))).Count, 1,
|
||||
"the C switch off ignores the rating level");
|
||||
}
|
||||
|
||||
private static void CombatBusy()
|
||||
{
|
||||
Check.Eq(Pass("busy-combat-on", g => g.ChunkInCombat = true, _ => { }, busy: true, combatMode: 2).Count, 1,
|
||||
"busy in combat mode with chunk-in-combat on: chunks");
|
||||
Check.Eq(Pass("busy-combat-off", g => g.ChunkInCombat = false, _ => { }, busy: true, combatMode: 2).Count, 0,
|
||||
"busy in combat mode with chunk-in-combat off: waits");
|
||||
Check.Eq(Pass("idle-combat-on", g => g.ChunkInCombat = true, _ => { }, busy: false, combatMode: 2).Count, 1,
|
||||
"idle in combat mode with chunk-in-combat on: chunks");
|
||||
Check.Eq(Pass("busy-peace", g => g.ChunkInCombat = true, _ => { }, busy: true, combatMode: 1).Count, 0,
|
||||
"busy in peace mode waits for idle even with chunk-in-combat on");
|
||||
Check.Eq(Pass("idle-peace", g => g.ChunkInCombat = false, _ => { }, busy: false, combatMode: 1).Count, 1,
|
||||
"idle in peace mode chunks");
|
||||
}
|
||||
}
|
||||
36
Tools/RynthILT.Tests/ChunkTests.cs
Normal file
36
Tools/RynthILT.Tests/ChunkTests.cs
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
using RynthCore.Plugin.RynthILT.Hub;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthILT.Tests;
|
||||
|
||||
// Lugian-hammer chunking (Hub/IltChunkClap.cs): only the Lugian Aetheria Hammer is the tool, and
|
||||
// ILT's result lines name the item and the tool. Ported from SilentKelpie's fix (2026-10-15).
|
||||
internal static class ChunkTests
|
||||
{
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("chunk: only the Lugian Aetheria Hammer is the tool, never a Lugian Hammer weapon", HammerOnly);
|
||||
r.Add("chunk: ILT's result lines (item and tool named) end the wait; combat lines don't", ResultLines);
|
||||
}
|
||||
|
||||
/// <summary>The Flaming Lugian Hammer (a loot weapon) matched " Lugian Hammer", chunked nothing,
|
||||
/// and all 9 Coalesced Aetheria timed out into the skip list.</summary>
|
||||
private static void HammerOnly()
|
||||
{
|
||||
Check.True(IltChunkClap.IsChunkHammer("Lugian Aetheria Hammer"), "the ILT tool");
|
||||
Check.True(IltChunkClap.IsChunkHammer("lugian aetheria hammer"), "any case");
|
||||
Check.False(IltChunkClap.IsChunkHammer("Flaming Lugian Hammer"), "a loot weapon is not the tool");
|
||||
Check.False(IltChunkClap.IsChunkHammer("Lugian Hammer"), "nor the plain one");
|
||||
Check.False(IltChunkClap.IsChunkHammer("Acid Lugian Hammer"), "nor any variant");
|
||||
}
|
||||
|
||||
private static void ResultLines()
|
||||
{
|
||||
Check.Eq(IltChunkClap.ClassifyChat("You smash the Corrupted Sword with the Lugian Aetheria Hammer."), IltChunkClap.ChunkResult.Done, "ILT corrupted line");
|
||||
Check.Eq(IltChunkClap.ClassifyChat("You smash the aetheria with the hammer."), IltChunkClap.ChunkResult.Done, "aetheria line");
|
||||
Check.Eq(IltChunkClap.ClassifyChat("The aetheria is too powerful to chunk."), IltChunkClap.ChunkResult.Refused, "refused");
|
||||
Check.Eq(IltChunkClap.ClassifyChat("You're too busy!"), IltChunkClap.ChunkResult.Busy, "busy");
|
||||
Check.Eq(IltChunkClap.ClassifyChat("You smash Corrupted Shadow for 147 points of bludgeoning damage!"), IltChunkClap.ChunkResult.None,
|
||||
"a combat line naming a corrupted monster is no result");
|
||||
}
|
||||
}
|
||||
152
Tools/RynthILT.Tests/DataApiTests.cs
Normal file
152
Tools/RynthILT.Tests/DataApiTests.cs
Normal file
|
|
@ -0,0 +1,152 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using RynthCore.Plugin.RynthILT;
|
||||
using RynthCore.Plugin.RynthILT.Hub;
|
||||
using RynthCore.Plugin.Shared;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthILT.Tests;
|
||||
|
||||
// "RynthILT.Data" v1 (Plugins/Shared/RynthIltDataApi.cs, DataInterface.cs): the bank JSON RynthILT
|
||||
// builds (Hub/IltBankExport.cs) read back by the shared reader, the bank verb lines a reader sends
|
||||
// (IltBanking.RunVerb splits them), and the table itself. The charms JSON is MoveTests'
|
||||
// CharmsReaderJson. No plugin in this tree reads the interface yet.
|
||||
internal static class DataApiTests
|
||||
{
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("data: the bank JSON reads back whole: characters (current first), choices, notes, log", BankRoundTrip);
|
||||
r.Add("data: the bank verb lines carry their fields in RunVerb's order", BankVerbs);
|
||||
r.Add("data: bad bank JSON reads as nothing", BankBadJson);
|
||||
r.Add("data: the Temple guardian JSON reads back whole (switches, answer, hand-in, rows)", GuardianRoundTrip);
|
||||
// Last: Release() switches the table off for the rest of the process.
|
||||
r.Add("data: the RynthILT.Data table: query, functions, release", DataTable);
|
||||
}
|
||||
|
||||
private static void BankRoundTrip()
|
||||
{
|
||||
var me = new IltBankState { Pyreals = 1_500_000, Luminance = 42, PrestigeCoins = 3,
|
||||
LastUpdated = new DateTime(2026, 10, 13, 21, 25, 37, DateTimeKind.Utc).ToLocalTime() };
|
||||
var alt = new IltBankState { Pyreals = 7, LegendaryKeys = 2, LastUpdated = DateTime.Now };
|
||||
var tx = new List<IltBankTransaction>();
|
||||
for (int i = 0; i < IltBankExport.MaxTransactions + 5; i++)
|
||||
tx.Add(new IltBankTransaction { Timestamp = new DateTime(2026, 10, 1).AddMinutes(i), Type = i % 2 == 0 ? "Sent" : "Received",
|
||||
Currency = "Pyreals", Amount = i, OtherPlayer = "Bob \"the\" Builder" });
|
||||
string json = IltBankExport.Build(true, 1, "InfiniteLeaftide", "Zed",
|
||||
new[] { new IltBankExport.Row("Alt", false, alt), new IltBankExport.Row("Zed", true, me) },
|
||||
"Deposited 5 Pyreals", tx);
|
||||
Check.True(json.All(c => c >= 0x20 && c <= 0x7E), "plain printable ASCII");
|
||||
|
||||
IltBankView v = IltBankView.Parse(json);
|
||||
Check.True(v.Loaded && v.Available, "loaded, ILT");
|
||||
Check.Eq(v.Enabled, 1, "the server has /bank");
|
||||
Check.Eq(v.World, "InfiniteLeaftide", "world");
|
||||
Check.Eq(v.Character, "Zed", "character");
|
||||
Check.Eq(v.Result, "Deposited 5 Pyreals", "last result");
|
||||
Check.Eq(v.Characters.Count, 2, "both characters");
|
||||
Check.True(v.Characters[0].Current && v.Characters[0].Name == "Zed", "the current character first");
|
||||
Check.Eq(v.Characters[0].Pyreals, 1_500_000L, "pyreals");
|
||||
Check.Eq(v.Characters[0].PrestigeCoins, 3L, "prestige coins");
|
||||
Check.Eq(v.Characters[0].UpdatedUtc, new DateTime(2026, 10, 13, 21, 25, 37, DateTimeKind.Utc), "updated, in UTC");
|
||||
Check.Eq(v.Characters[1].LegendaryKeys, 2L, "the other character's keys");
|
||||
|
||||
Check.Eq(v.Deposits.Count, IltBankCommands.Deposits.Length, "every deposit choice");
|
||||
Check.Eq(v.Withdrawals.Count, IltBankCommands.Withdrawals.Length, "every withdraw choice");
|
||||
Check.Eq(v.Transfers.Count, IltBankCommands.Transfers.Length, "every transfer choice");
|
||||
Check.True(v.Transfers.Single(t => t.Notes).Label == "Trade notes", "only trade notes count notes");
|
||||
Check.Eq(v.Notes.Count, IltBankCommands.NoteDenominations.Length, "every note denomination");
|
||||
Check.Eq(v.Notes[^1].Value, 250_000L, "MMD is 250K");
|
||||
|
||||
Check.Eq(v.Transactions.Count, IltBankExport.MaxTransactions, "the log is capped");
|
||||
Check.Eq(v.Transactions[0].Amount, (long)(IltBankExport.MaxTransactions + 4), "newest first");
|
||||
Check.Eq(v.Transactions[0].Player, "Bob \"the\" Builder", "quotes in a name survive");
|
||||
}
|
||||
|
||||
private static void BankVerbs()
|
||||
{
|
||||
Check.Eq(IltBankView.RefreshVerb(), "refresh", "refresh");
|
||||
Check.Eq(IltBankView.DepositVerb(3), "deposit 3", "deposit");
|
||||
Check.Eq(IltBankView.WithdrawVerb(7, 4, 9), "withdraw 7 4 9", "withdraw: index, amount, note");
|
||||
Check.Eq(IltBankView.TransferVerb(6, 2, 9, " Some Name "), "transfer 6 2 9 Some Name", "transfer: the name last, trimmed");
|
||||
foreach (string verb in new[] { IltBankView.RefreshVerb(), IltBankView.DepositVerb(0), IltBankView.WithdrawVerb(0, 1, -1),
|
||||
IltBankView.TransferVerb(0, 1, -1, "Bob") })
|
||||
Check.True(verb.All(c => c >= 0x20 && c <= 0x7E), "ASCII verb (DataInterface refuses anything else): " + verb);
|
||||
}
|
||||
|
||||
private static void BankBadJson()
|
||||
{
|
||||
Check.True(ReferenceEquals(IltBankView.Parse(null), IltBankView.None), "null");
|
||||
Check.True(ReferenceEquals(IltBankView.Parse("{not json"), IltBankView.None), "broken");
|
||||
Check.True(ReferenceEquals(IltBankView.Parse("[1,2]"), IltBankView.None), "not an object");
|
||||
IltBankView empty = IltBankView.Parse("{}");
|
||||
Check.True(empty.Loaded && !empty.Available && empty.Enabled == -1 && empty.Characters.Count == 0, "missing fields read as nothing known");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Version 3: the guardian JSON RynthILT builds (IltGuardian.BuildJson) read back by the reader
|
||||
/// RynthOracle's Quests tab uses, quotes and all.
|
||||
/// </summary>
|
||||
private static void GuardianRoundTrip()
|
||||
{
|
||||
var rows = new[]
|
||||
{
|
||||
new IltTempleAttrStatus("Strength", "Fiun \"Big\" Strongarm", 3, "Ready", "", true, true),
|
||||
new IltTempleAttrStatus("Focus", "Fiun Thinker", 1, "Cooldown", "in 5h 2m", false, false),
|
||||
};
|
||||
string json = IltGuardian.BuildJson("InfiniteLeaftide", chat: true, auto: false, buy: true, cooldownHours: 20,
|
||||
answer: "Pyreal", npc: "Guardian of Attribute Enlightenment", answerAgeSec: 42, heard: "What is \"coin\"?",
|
||||
running: true, status: "handing Pyreal to Guardian...", syncedUtc: new DateTime(2026, 10, 18, 19, 5, 0, DateTimeKind.Utc), rows);
|
||||
Check.True(json.All(c => c >= 0x20 && c <= 0x7E), "plain printable ASCII");
|
||||
|
||||
IltGuardianView v = IltGuardianView.Parse(json);
|
||||
Check.True(v.Loaded && v.Available && v.World == "InfiniteLeaftide", "loaded, the world");
|
||||
Check.True(v.Chat && !v.Auto && v.Buy && v.CooldownHours == 20, "the switches");
|
||||
Check.True(v.Answer == "Pyreal" && v.Npc == "Guardian of Attribute Enlightenment" && v.AnswerAgeSec == 42 && v.Heard == "What is \"coin\"?",
|
||||
"the last answer");
|
||||
Check.True(v.Running && v.Status.StartsWith("handing Pyreal"), "the hand-in");
|
||||
Check.Eq(v.SyncedUtc, new DateTime(2026, 10, 18, 19, 5, 0, DateTimeKind.Utc), "the /qb read time");
|
||||
Check.Eq(v.Rows.Count, 2, "both rows");
|
||||
Check.True(v.Rows[0].Npc == "Fiun \"Big\" Strongarm" && v.Rows[0].Count == 3 && v.Rows[0].Ready && v.Rows[0].Exact, "an exact, ready row");
|
||||
Check.True(v.Rows[1].Eta == "in 5h 2m" && !v.Rows[1].Ready && !v.Rows[1].Exact, "an estimated row on cooldown");
|
||||
|
||||
IltGuardianView none = IltGuardianView.Parse(IltGuardian.BuildJson("x", false, false, false, 1, "", "", -1, "", false, "idle",
|
||||
DateTime.MinValue, Array.Empty<IltTempleAttrStatus>()));
|
||||
Check.True(none.Answer.Length == 0 && none.AnswerAgeSec == -1 && none.SyncedUtc == DateTime.MinValue && none.Rows.Count == 0,
|
||||
"no answer, no /qb read, no rows");
|
||||
}
|
||||
|
||||
private static unsafe void DataTable()
|
||||
{
|
||||
Check.Eq(DataInterface.Query("RynthILT.Hub", 1), IntPtr.Zero, "another interface's name: not ours");
|
||||
Check.Eq(DataInterface.Query(RynthIltDataApiV1.InterfaceName, 4), IntPtr.Zero, "a newer version than we have: none");
|
||||
var t = (RynthIltDataApiV1*)DataInterface.Query(RynthIltDataApiV1.InterfaceName, 1);
|
||||
Check.True(t != null, "v1 is served");
|
||||
Check.Eq(t->Version, 3u, "Version 3 (v1 and v2 readers take it: it starts with their tables)");
|
||||
Check.Eq(t->StructSize, (uint)sizeof(RynthIltDataApiV1), "StructSize");
|
||||
Check.Eq(sizeof(RynthIltDataApiV1), 8 + 8 * IntPtr.Size, "header + 8 functions (v1's 4, the breeding pair, the guardian pair)");
|
||||
Check.Eq(RynthIltDataApiV1.V1Size, (uint)(8 + 4 * IntPtr.Size), "a v1 table ends before the breeding pair");
|
||||
Check.Eq(RynthIltDataApiV1.V2Size, (uint)(8 + 6 * IntPtr.Size), "a v2 table ends before the guardian pair (readers still see breeding on it)");
|
||||
Check.True(t->GetCharmsJson != null && t->GetBankJson != null && t->ToggleCharm != null && t->BankCommand != null
|
||||
&& t->GetPetBreedingJson != null && t->PetBreedingCommand != null
|
||||
&& t->GetGuardianJson != null && t->GuardianCommand != null, "every function is filled in");
|
||||
Check.Eq((IntPtr)t, DataInterface.Query(RynthIltDataApiV1.InterfaceName, 1), "the same table each time");
|
||||
|
||||
// No plugin instance here (not logged in): nothing to report, every action refused.
|
||||
byte* buf = stackalloc byte[64];
|
||||
Check.Eq(t->GetCharmsJson(buf, 64), 0, "no charms before login");
|
||||
Check.Eq(t->GetBankJson(buf, 64), 0, "no bank before login");
|
||||
Check.Eq(t->ToggleCharm(1234), 0, "no toggle before login");
|
||||
byte* verb = stackalloc byte[] { (byte)'r', (byte)'e', (byte)'f', (byte)'r', (byte)'e', (byte)'s', (byte)'h', 0 };
|
||||
Check.Eq(t->BankCommand(verb), 0, "no bank command before login");
|
||||
Check.Eq(t->GetPetBreedingJson(buf, 64), 0, "no breeding JSON before login");
|
||||
Check.Eq(t->PetBreedingCommand(verb), 0, "no breeding command before login");
|
||||
Check.Eq(t->GetGuardianJson(buf, 64), 0, "no guardian JSON before login");
|
||||
Check.Eq(t->GuardianCommand(verb), 0, "no guardian command before login");
|
||||
|
||||
DataInterface.Release();
|
||||
Check.Eq(t->Version, 0u, "Release zeroes Version (readers re-query)");
|
||||
Check.Eq(DataInterface.Query(RynthIltDataApiV1.InterfaceName, 1), IntPtr.Zero, "and nothing is served after shutdown");
|
||||
Check.Eq(t->GetBankJson(buf, 64), 0, "the old table stays callable and answers nothing");
|
||||
}
|
||||
}
|
||||
76
Tools/RynthILT.Tests/FakeAiHub.cs
Normal file
76
Tools/RynthILT.Tests/FakeAiHub.cs
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using RynthCore.Plugin.Shared;
|
||||
|
||||
namespace RynthILT.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// A stand-in for RynthAi's "RynthAi.Hub" table (Plugins/Shared/RynthAiHubApi.cs), so the tests can
|
||||
/// check what RynthILT asks of RynthAi (RynthAiClient.UseTableForTests takes it). Only the functions
|
||||
/// the moved features use answer anything; the rest are absent (null), as an old RynthAi's would be.
|
||||
/// Reset() before each test that uses it.
|
||||
/// </summary>
|
||||
internal static unsafe class FakeAiHub
|
||||
{
|
||||
/// <summary>BackAwayFrom calls (object, radius, hold), and what it answers.</summary>
|
||||
public static readonly List<(uint Id, float Radius, int HoldMs)> BackAways = new();
|
||||
public static int BackAwayResult = RynthAiHub.BackAwayStarted;
|
||||
/// <summary>SetPlayerCounter: the last value reported per counter id.</summary>
|
||||
public static readonly Dictionary<uint, long> Counters = new();
|
||||
/// <summary>SessionStats: the shared session's start (0 = no session: SessionStats answers 0).</summary>
|
||||
public static long SessionStartTicks;
|
||||
|
||||
private static RynthAiHubApiV1* _table;
|
||||
|
||||
public static void Reset()
|
||||
{
|
||||
BackAways.Clear();
|
||||
BackAwayResult = RynthAiHub.BackAwayStarted;
|
||||
Counters.Clear();
|
||||
SessionStartTicks = 0;
|
||||
}
|
||||
|
||||
public static IntPtr Table
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_table == null)
|
||||
{
|
||||
var t = (RynthAiHubApiV1*)NativeMemory.AllocZeroed((nuint)sizeof(RynthAiHubApiV1));
|
||||
t->StructSize = (uint)sizeof(RynthAiHubApiV1);
|
||||
t->BackAwayFrom = &BackAwayFrom;
|
||||
t->SetPlayerCounter = &SetPlayerCounter;
|
||||
t->SessionStats = &SessionStats;
|
||||
t->Version = RynthAiHubApiV1.InterfaceVersion;
|
||||
_table = t;
|
||||
}
|
||||
return (IntPtr)_table;
|
||||
}
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int SessionStats(SessionStatsV1* s)
|
||||
{
|
||||
if (SessionStartTicks == 0 || s == null) return 0;
|
||||
*s = default;
|
||||
s->StartUtcTicks = SessionStartTicks;
|
||||
s->SessionSeconds = 60;
|
||||
return 1;
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int SetPlayerCounter(uint id, long value)
|
||||
{
|
||||
Counters[id] = value;
|
||||
return 1;
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int BackAwayFrom(uint id, float radius, int holdMs)
|
||||
{
|
||||
BackAways.Add((id, radius, holdMs));
|
||||
return BackAwayResult;
|
||||
}
|
||||
}
|
||||
215
Tools/RynthILT.Tests/FeatureCatalogTests.cs
Normal file
215
Tools/RynthILT.Tests/FeatureCatalogTests.cs
Normal file
|
|
@ -0,0 +1,215 @@
|
|||
using System;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using RynthCore.Plugin.RynthILT;
|
||||
using RynthCore.Plugin.RynthILT.Hub;
|
||||
using RynthCore.Plugin.Shared;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthILT.Tests;
|
||||
|
||||
// Leaftide feature list (IltFeatureCatalog): every feature the player asked RynthILT to cover is
|
||||
// listed and the states follow the server bits. Also the NUL-terminated copy RynthILT's interfaces
|
||||
// ("RynthServer.Profile", "RynthILT.Data") hand their JSON out with.
|
||||
internal static class FeatureCatalogTests
|
||||
{
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("features: banking, guardian, attributes, augs, paragon x3, split arrows, T11 and fellowship are listed", Listed);
|
||||
r.Add("features: state follows the server bit on ILT, built-ins are on, nothing is known off ILT", States);
|
||||
r.Add("features: profile JSON is valid ASCII with features and the fellowship rules", ProfileJson);
|
||||
r.Add("features: the interface copies the JSON only when it fits, NUL-terminated", InterfaceWrite);
|
||||
r.Add("features: the /qb list rides the profile JSON on ILT worlds only", QuestBonusJson);
|
||||
r.Add("features: the RynthILT.Server table: query, filled in, release", ServerTable);
|
||||
r.Add("features: the ILT profile is on with the world; a refusal in chat turns a feature off", ProfileOnWithTheWorld);
|
||||
r.Add("features: probed features read checking; options ILT runs off are off until chat shows them", ProbedAndOffInIlt);
|
||||
r.Add("features: charms are on with the ILT world unless refused; rows describe themselves", Charms);
|
||||
}
|
||||
|
||||
/// <summary>ACECustom options Infinite Leaftide runs with off (ServerConfig defaults, PROD_DEPLOY_PLAN.md).</summary>
|
||||
private static readonly string[] OffInIlt = { "pet_strain", "pet_refill", "defense_scaling" };
|
||||
|
||||
/// <summary>Features the login probe (or the /myquests tracker) answers.</summary>
|
||||
private static readonly string[] Probed =
|
||||
{
|
||||
"bank", "attributes", "augmentations", "enlightenment", "clap", "pets", "shinies",
|
||||
"fellowship_blackjack", "quests", "quest_bonus", "powerball", "blackjack",
|
||||
};
|
||||
|
||||
private static void ProfileOnWithTheWorld()
|
||||
{
|
||||
// The features the player asked about, plus the pet switches prod runs on (bond, potency).
|
||||
foreach (string key in new[] { "bank_notes", "t11", "t11_craft_gate", "split_arrows", "charms", "pet_breeding",
|
||||
"pet_maturity", "pet_bond", "pet_potency", "monster_capture", "universal_mastery",
|
||||
"missile_power", "t11_hit_gate", "fship" })
|
||||
{
|
||||
IltFeatureInfo f = IltFeatureCatalog.Find(key)!;
|
||||
Check.Eq(f.Known, IltKnown.Profile, key + " is on in the ILT profile");
|
||||
Check.Eq(IltFeatureCatalog.StateOf(f, true, _ => IltTri.Unknown), IltTri.On, key + " on with the ILT world");
|
||||
Check.Eq(IltFeatureCatalog.StateOf(f, false, _ => IltTri.On), IltTri.Unknown, key + " unknown off ILT");
|
||||
}
|
||||
IltFeatureInfo mastery = IltFeatureCatalog.Find("universal_mastery")!;
|
||||
Check.Eq(IltFeatureCatalog.StateOf(mastery, true, k => k == IltFeature.UniversalMastery ? IltTri.Off : IltTri.Unknown),
|
||||
IltTri.Off, "a refusal in chat turns a profile feature off");
|
||||
Check.Null(IltFeatureCatalog.Find("fellowship_additive"), "upstream ACE's additive fellowship option isn't an ILT feature");
|
||||
}
|
||||
|
||||
private static void ProbedAndOffInIlt()
|
||||
{
|
||||
foreach (string key in Probed)
|
||||
{
|
||||
IltFeatureInfo f = IltFeatureCatalog.Find(key)!;
|
||||
Check.Eq(f.Known, IltKnown.Checked, key + " is answered by the login probe");
|
||||
Check.Eq(IltFeatureCatalog.StateText(IltFeatureCatalog.StateOf(f, true, _ => IltTri.Unknown)), "checking", key + " reads 'checking' until then");
|
||||
}
|
||||
foreach (string key in OffInIlt)
|
||||
{
|
||||
IltFeatureInfo f = IltFeatureCatalog.Find(key)!;
|
||||
Check.Eq(f.Known, IltKnown.ProfileOff, key + " is off in the ILT profile");
|
||||
Check.Eq(IltFeatureCatalog.StateOf(f, true, _ => IltTri.Unknown), IltTri.Off, key + " off with the ILT world");
|
||||
Check.Eq(IltFeatureCatalog.StateOf(f, true, _ => IltTri.On), IltTri.On, key + " on once the server shows it");
|
||||
Check.True(IltFeatureCatalog.Describe(key).Tooltip.Contains("Off in ILT"), key + "'s tooltip says it's off in ILT");
|
||||
}
|
||||
|
||||
// ACECustom's three refill messages (PetDevice.TryApplyPyrealAutoRefillBeforeSummon) prove the refill is on.
|
||||
Check.True(IltServerOptions.IsPyrealRefillLine("You restore one charge on your summoning essence at no cost."), "free refill");
|
||||
Check.True(IltServerOptions.IsPyrealRefillLine("You spend 1,000 pyreals to restore one charge on your summoning essence."), "paid refill");
|
||||
Check.True(IltServerOptions.IsPyrealRefillLine("You need 1,000 pyreals to auto-replenish your summoning essence. You do not have enough pyreals."), "refill too dear");
|
||||
Check.False(IltServerOptions.IsPyrealRefillLine("Your summoning essence is empty."), "an empty essence says nothing about the refill");
|
||||
}
|
||||
|
||||
private static void Charms()
|
||||
{
|
||||
Check.Eq(IltFeatureCatalog.CharmStateOf(true, IltTri.Unknown), IltTri.On, "a charm is on with the ILT world");
|
||||
Check.Eq(IltFeatureCatalog.CharmStateOf(true, IltTri.Off), IltTri.Off, "a refused charm is off");
|
||||
Check.Eq(IltFeatureCatalog.CharmStateOf(false, IltTri.On), IltTri.Unknown, "nothing is claimed off ILT");
|
||||
|
||||
var (label, group, tooltip) = IltFeatureCatalog.Describe(IltFeature.Charm("Mana Barrier"));
|
||||
Check.Eq(label, "Mana Barrier", "a charm row shows the charm's name");
|
||||
Check.Eq(group, IltFeatureCatalog.GroupCharms, "charms have their own section");
|
||||
Check.True(tooltip.Contains("Mana absorbs"), "the tooltip carries the charm's effect");
|
||||
Check.Eq(IltFeatureCatalog.Describe("something_new").Group, IltFeatureCatalog.GroupOther, "an unknown bit goes to Other");
|
||||
}
|
||||
|
||||
private static readonly string[] Requested =
|
||||
{
|
||||
"bank", "guardian", "attributes", "augmentations", "paragon_armor", "paragon_weapons",
|
||||
"paragon_jewelry", "split_arrows", "t11", "fellowship_large", "zone_share", "fellowship_blackjack",
|
||||
};
|
||||
|
||||
private static void Listed()
|
||||
{
|
||||
foreach (string key in Requested)
|
||||
Check.NotNull(IltFeatureCatalog.Find(key), "listed: " + key);
|
||||
Check.Null(IltFeatureCatalog.Find("no_such_feature"), "an unknown key is not found");
|
||||
|
||||
var seen = new System.Collections.Generic.HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (IltFeatureInfo f in IltFeatureCatalog.All)
|
||||
{
|
||||
Check.True(seen.Add(f.Key), "keys are unique: " + f.Key);
|
||||
Check.True(Array.IndexOf(IltFeatureCatalog.Groups, f.Group) >= 0, $"{f.Key} is in a known section ({f.Group})");
|
||||
Check.True(f.Label.Length > 0 && f.Where.Length > 0 && f.Description.Length > 0, f.Key + " has a label, a place and a description");
|
||||
}
|
||||
}
|
||||
|
||||
private static void States()
|
||||
{
|
||||
IltFeatureInfo bank = IltFeatureCatalog.Find("bank")!;
|
||||
IltFeatureInfo guardian = IltFeatureCatalog.Find("guardian")!;
|
||||
Check.Eq(IltFeatureCatalog.StateOf(bank, true, _ => IltTri.On), IltTri.On, "bank on when the server answers /bank");
|
||||
Check.Eq(IltFeatureCatalog.StateOf(bank, true, _ => IltTri.Off), IltTri.Off, "bank off when the server says so");
|
||||
Check.Eq(IltFeatureCatalog.StateOf(bank, true, _ => IltTri.Unknown), IltTri.Unknown, "bank unknown before the check");
|
||||
Check.Eq(IltFeatureCatalog.StateOf(guardian, true, _ => IltTri.Off), IltTri.On, "a built-in feature is on with the ILT world");
|
||||
Check.Eq(IltFeatureCatalog.StateOf(guardian, false, _ => IltTri.On), IltTri.Unknown, "nothing is claimed off ILT");
|
||||
Check.Eq(IltFeatureCatalog.StateText(IltTri.Unknown), "checking", "unknown reads 'checking'");
|
||||
Check.Eq(IltFeatureCatalog.FellowshipMax(true), 29, "ILT fellowships hold 29");
|
||||
Check.Eq(IltFeatureCatalog.FellowshipMax(false), 9, "retail fellowships hold 9");
|
||||
}
|
||||
|
||||
private static void ProfileJson()
|
||||
{
|
||||
string json = IltFeatureCatalog.BuildProfileJson(true, "Infinite \"Leaftide\"", false, "probe",
|
||||
new DateTime(2026, 10, 13, 21, 25, 37, DateTimeKind.Utc),
|
||||
key => key == IltFeature.FBlackjack ? IltTri.Off : IltTri.On);
|
||||
bool ascii = true;
|
||||
foreach (char c in json) if (c < 0x20 || c > 0x7E) ascii = false;
|
||||
Check.True(ascii, "plain printable ASCII");
|
||||
|
||||
using JsonDocument doc = JsonDocument.Parse(json);
|
||||
JsonElement root = doc.RootElement;
|
||||
Check.True(root.GetProperty("ilt").GetBoolean(), "ilt");
|
||||
Check.Eq(root.GetProperty("world").GetString(), "Infinite \"Leaftide\"", "quotes in the world name survive");
|
||||
Check.Eq(root.GetProperty("checked").GetString(), "2026-10-13T21:25:37Z", "checked time in UTC");
|
||||
Check.Eq(root.GetProperty("features").GetArrayLength(), IltFeatureCatalog.All.Length, "every feature in the JSON");
|
||||
JsonElement fel = root.GetProperty("fellowship");
|
||||
Check.Eq(fel.GetProperty("maxMembers").GetInt32(), 29, "fellowship size");
|
||||
Check.Eq(fel.GetProperty("zoneShare").GetInt32(), 1, "Zone Share on (built in)");
|
||||
Check.Eq(fel.GetProperty("blackjack").GetInt32(), 0, "Fellowship Blackjack off (server bit)");
|
||||
|
||||
string off = IltFeatureCatalog.BuildProfileJson(false, "", false, "", DateTime.MinValue, _ => IltTri.On);
|
||||
using JsonDocument d2 = JsonDocument.Parse(off);
|
||||
Check.Eq(d2.RootElement.GetProperty("fellowship").GetProperty("maxMembers").GetInt32(), 9, "off ILT: retail size");
|
||||
Check.Eq(d2.RootElement.GetProperty("checked").GetString(), "", "never checked: empty time");
|
||||
}
|
||||
|
||||
private static void QuestBonusJson()
|
||||
{
|
||||
var qb = new IltQuestBonusInfo(false, 2, 41, "2 completed, 1 incomplete",
|
||||
new[] { "flag\"one", "flagTwo" }, new[] { "flagThree" });
|
||||
string json = IltFeatureCatalog.BuildProfileJson(true, "Infinite Leaftide", false, "probe", DateTime.MinValue, _ => IltTri.On, qb);
|
||||
using JsonDocument doc = JsonDocument.Parse(json);
|
||||
JsonElement q = doc.RootElement.GetProperty("questBonus");
|
||||
Check.False(q.GetProperty("disabled").GetBoolean(), "enabled");
|
||||
Check.Eq(q.GetProperty("generation").GetInt32(), 2, "generation");
|
||||
Check.Eq(q.GetProperty("count").GetInt64(), 41L, "count");
|
||||
Check.Eq(q.GetProperty("status").GetString(), "2 completed, 1 incomplete", "status");
|
||||
Check.Eq(q.GetProperty("completed").GetArrayLength(), 2, "completed flags");
|
||||
Check.Eq(q.GetProperty("completed")[0].GetString(), "flag\"one", "quotes in a flag survive");
|
||||
Check.Eq(q.GetProperty("incomplete")[0].GetString(), "flagThree", "incomplete flags");
|
||||
Check.True(doc.RootElement.TryGetProperty("fellowship", out _), "the fellowship rules are still there");
|
||||
|
||||
string off = IltFeatureCatalog.BuildProfileJson(false, "", false, "", DateTime.MinValue, _ => IltTri.On, qb);
|
||||
using JsonDocument d2 = JsonDocument.Parse(off);
|
||||
Check.False(d2.RootElement.TryGetProperty("questBonus", out _), "off ILT: no /qb list");
|
||||
}
|
||||
|
||||
private static unsafe void ServerTable()
|
||||
{
|
||||
Check.Eq(ServerInterface.Query("RynthILT.Hub", 1), IntPtr.Zero, "another interface's name: not ours");
|
||||
Check.Eq(ServerInterface.Query(RynthIltServerApiV1.InterfaceName, 2), IntPtr.Zero, "a newer version than we have: none");
|
||||
var t = (RynthIltServerApiV1*)ServerInterface.Query(RynthIltServerApiV1.InterfaceName, 1);
|
||||
Check.True(t != null && t->Version == 1 && t->StructSize == (uint)sizeof(RynthIltServerApiV1) && t->GetProfileJson != null,
|
||||
"v1 is served and filled in");
|
||||
|
||||
// Before login the profile is the not-ILT default; the copy is NUL-terminated and valid JSON.
|
||||
byte* buf = stackalloc byte[262144];
|
||||
int n = t->GetProfileJson(buf, 262144);
|
||||
Check.True(n > 0 && n < 262144 && buf[n] == 0, "the default profile fits and is NUL-terminated");
|
||||
using JsonDocument doc = JsonDocument.Parse(Encoding.UTF8.GetString(buf, n));
|
||||
Check.False(doc.RootElement.GetProperty("ilt").GetBoolean(), "not an ILT world before login");
|
||||
Check.Eq(t->GetProfileJson(buf, 8), n, "too small: the length comes back");
|
||||
|
||||
ServerInterface.Release();
|
||||
Check.Eq(t->Version, 0u, "Release zeroes Version (readers re-query)");
|
||||
Check.Eq(t->GetProfileJson(buf, 64), 0, "answers 0 after release");
|
||||
Check.Eq(ServerInterface.Query(RynthIltServerApiV1.InterfaceName, 1), IntPtr.Zero, "not served after release");
|
||||
}
|
||||
|
||||
private static unsafe void InterfaceWrite()
|
||||
{
|
||||
const string json = "{\"ilt\":true}";
|
||||
byte* small = stackalloc byte[4];
|
||||
small[0] = 0x55;
|
||||
Check.Eq(ProfileInterface.Write(json, small, 4), json.Length, "too small: the length is returned");
|
||||
Check.Eq(small[0], (byte)0x55, "too small: nothing written");
|
||||
|
||||
byte* exact = stackalloc byte[json.Length];
|
||||
Check.Eq(ProfileInterface.Write(json, exact, json.Length), json.Length, "no room for the NUL: too small");
|
||||
|
||||
byte* big = stackalloc byte[64];
|
||||
int n = ProfileInterface.Write(json, big, 64);
|
||||
Check.Eq(n, json.Length, "fits: the length without the NUL");
|
||||
Check.Eq(big[n], (byte)0, "NUL-terminated");
|
||||
Check.Eq(Encoding.UTF8.GetString(big, n), json, "the JSON copied whole");
|
||||
}
|
||||
}
|
||||
97
Tools/RynthILT.Tests/FellowshipCommandTests.cs
Normal file
97
Tools/RynthILT.Tests/FellowshipCommandTests.cs
Normal file
|
|
@ -0,0 +1,97 @@
|
|||
using System;
|
||||
using System.Linq;
|
||||
using RynthCore.Plugin.RynthILT.IltFellowship;
|
||||
using RynthCore.Plugin.Shared;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthILT.Tests;
|
||||
|
||||
// ILT's fellowship commands (IltFellowship/IltFellowshipCommands.cs, ACECustom /fship) and the
|
||||
// "servercommands" format they are kept in (Plugins/Shared/ServerCommandShare.cs), checked together.
|
||||
internal static class FellowshipCommandTests
|
||||
{
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("ilt fellowship: the /fship list round-trips through the servercommands format", RoundTrip);
|
||||
r.Add("ilt fellowship: chat lines quote multi-word names and need a name for create", Compose);
|
||||
r.Add("ilt fellowship: bad commands and payloads are dropped", Rejects);
|
||||
r.Add("ilt fellowship: RynthCore's verdict decides, else the world name", Active);
|
||||
}
|
||||
|
||||
private static void RoundTrip()
|
||||
{
|
||||
ServerCommandSet? set = ServerCommandShare.Parse(IltFellowshipCommands.Payload(active: true));
|
||||
Check.True(set != null, "parsed");
|
||||
Check.Eq(set!.Section, "fellowship", "section");
|
||||
Check.Eq(set.ServerId, "ilt", "server id");
|
||||
Check.Eq(set.ServerName, "Infinite Leaftide", "server name");
|
||||
Check.Eq(set.Commands.Count, IltFellowshipCommands.Commands.Count, "every command survives");
|
||||
for (int i = 0; i < set.Commands.Count; i++)
|
||||
Check.Eq(set.Commands[i], IltFellowshipCommands.Commands[i], "command " + i);
|
||||
Check.True(set.Commands.All(c => c.Command.StartsWith("/fship", StringComparison.Ordinal)), "all /fship");
|
||||
|
||||
ServerCommandSet? off = ServerCommandShare.Parse(IltFellowshipCommands.Payload(active: false));
|
||||
Check.True(off != null, "the clear parses");
|
||||
Check.Eq(off!.Commands.Count, 0, "the clear has no commands");
|
||||
}
|
||||
|
||||
private static void Compose()
|
||||
{
|
||||
ServerCommand create = Find("Create"), invite = Find("Invite"), dismiss = Find("Dismiss"), list = Find("List nearby");
|
||||
Check.True(ServerCommandShare.Compose(create, "") == null, "create needs a name");
|
||||
Check.True(ServerCommandShare.Compose(create, " ") == null, "blank is no name");
|
||||
Check.Eq(ServerCommandShare.Compose(create, "Leaf"), "/fship create Leaf", "one word");
|
||||
Check.Eq(ServerCommandShare.Compose(create, " Leaf Hunters "), "/fship create \"Leaf Hunters\"", "quoted, spaces collapsed");
|
||||
Check.Eq(ServerCommandShare.Compose(invite, ""), "/fship add", "no name: the selected player");
|
||||
Check.Eq(ServerCommandShare.Compose(invite, "Raw Cigam"), "/fship add \"Raw Cigam\"", "multi-word player");
|
||||
Check.Eq(ServerCommandShare.Compose(dismiss, "Bo\"b\t"), "/fship remove Bob", "quotes and control characters dropped");
|
||||
Check.Eq(ServerCommandShare.Compose(list, "ignored"), "/fship list", "no argument taken");
|
||||
Check.True(dismiss.Confirm && Find("Disband").Confirm && Find("Leave").Confirm && Find("Invite landblock").Confirm, "risky ones ask");
|
||||
Check.False(invite.Confirm || list.Confirm || create.Confirm, "the rest don't");
|
||||
string longName = new string('x', 200);
|
||||
Check.Eq(ServerCommandShare.CleanArgument(longName).Length, ServerCommandShare.MaxArgument, "argument capped");
|
||||
}
|
||||
|
||||
private static void Rejects()
|
||||
{
|
||||
Check.True(ServerCommandShare.Parse(null) == null, "null");
|
||||
Check.True(ServerCommandShare.Parse("") == null, "empty");
|
||||
Check.True(ServerCommandShare.Parse("C\tX\t/fship\t\t\n") == null, "no S line");
|
||||
Check.True(ServerCommandShare.Parse("S\t\tilt\tILT\n") == null, "no section");
|
||||
|
||||
string payload = "S\tfellowship\tilt\tILT\n" +
|
||||
"C\tNo slash\tfship list\t\t\n" +
|
||||
"C\tSpace\t/ fship\t\t\n" +
|
||||
"C\tQuote\t/fship add \"x\"\t\t\n" +
|
||||
"C\t\t/fship list\t\tno label\n" +
|
||||
"C\tLong\t/" + new string('a', ServerCommandShare.MaxCommand + 5) + "\t\t\n" +
|
||||
"C\tShort\t/fship\t\n" +
|
||||
"C\tGood\t/fship list\tzqA\ttip\n";
|
||||
ServerCommandSet? set = ServerCommandShare.Parse(payload);
|
||||
Check.True(set != null, "parsed");
|
||||
Check.Eq(set!.Commands.Count, 1, "only the good command");
|
||||
Check.Eq(set.Commands[0].Flags, "A", "unknown flags dropped");
|
||||
|
||||
var many = Enumerable.Range(0, 40).Select(i => new ServerCommand("B" + i, "/fship list", "", ""));
|
||||
string built = ServerCommandShare.Build(new ServerCommandSet("fellowship", "ilt", "ILT", many.ToList()));
|
||||
Check.Eq(ServerCommandShare.Parse(built)!.Commands.Count, ServerCommandShare.MaxCommands, "capped");
|
||||
|
||||
string tabbed = ServerCommandShare.Build(new ServerCommandSet("fellowship", "ilt", "ILT",
|
||||
new[] { new ServerCommand("A\tB", "/fship list", "", "line one\nline two") }));
|
||||
ServerCommand c = ServerCommandShare.Parse(tabbed)!.Commands[0];
|
||||
Check.Eq(c.Label, "A B", "tab in a field becomes a space");
|
||||
Check.Eq(c.Tooltip, "line one line two", "newline in a field becomes a space");
|
||||
}
|
||||
|
||||
private static void Active()
|
||||
{
|
||||
Check.True(IltFellowshipCommands.IsActive(true, "Coldeve"), "RynthCore says ILT");
|
||||
Check.False(IltFellowshipCommands.IsActive(false, "InfiniteLeaftide"), "RynthCore says not ILT");
|
||||
Check.True(IltFellowshipCommands.IsActive(null, "InfiniteLeaftide"), "no verdict yet: the world name");
|
||||
Check.False(IltFellowshipCommands.IsActive(null, "Coldeve"), "no verdict, another world");
|
||||
Check.False(IltFellowshipCommands.IsActive(null, null), "nothing known");
|
||||
}
|
||||
|
||||
private static ServerCommand Find(string label) =>
|
||||
IltFellowshipCommands.Commands.First(c => c.Label == label);
|
||||
}
|
||||
128
Tools/RynthILT.Tests/IltSettingsTests.cs
Normal file
128
Tools/RynthILT.Tests/IltSettingsTests.cs
Normal file
|
|
@ -0,0 +1,128 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using RynthCore.Plugin.RynthILT.IltSettingsView;
|
||||
using RynthCore.Plugin.Shared;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthILT.Tests;
|
||||
|
||||
// RynthILT's copy of the ILT settings (IltSettingsView/IltSettingsModel.cs): RynthCore's server
|
||||
// list (plugin API v86, GetServerStateJson: verdict, override, reason), the Hub's feature read, the
|
||||
// engine verdict the Hub follows (IltEngineVerdict), and the RynthCore commands the view sends.
|
||||
internal static class IltSettingsTests
|
||||
{
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("ilt settings: RynthCore's server list gives the ILT verdict, override and reason", ServerList);
|
||||
r.Add("ilt settings: a list without ILT, or no list at all, reads as such", NoIlt);
|
||||
r.Add("ilt settings: the Hub's feature read is published whole", FeatureRead);
|
||||
r.Add("ilt settings: the Hub follows RynthCore's ILT verdict once one arrives", EngineVerdict);
|
||||
r.Add("ilt settings: override and world-name commands are checked before sending", Commands);
|
||||
r.Add("ilt settings: logout clears the copy", ClearOnLogout);
|
||||
}
|
||||
|
||||
// GetServerStateJson as RynthCore writes it (UI/Sections/ServerStateJson.cs, schema 1).
|
||||
private const string State =
|
||||
"{\"schema\":1,\"revision\":3,\"host\":\"infiniteleaftide.online\",\"world\":\"InfiniteLeaftide\",\"pick\":\"auto\"," +
|
||||
"\"active\":\"ilt\",\"activeName\":\"Infinite Leaftide\",\"activePlugin\":\"RynthILT\",\"servers\":[" +
|
||||
"{\"id\":\"ilt\",\"name\":\"Infinite Leaftide\",\"active\":true,\"detected\":false,\"force\":\"on\",\"builtIn\":true," +
|
||||
"\"plugin\":\"RynthILT\",\"reason\":\"forced on for this character\"}," +
|
||||
"{\"id\":\"aelrynth\",\"name\":\"Aelrynth\",\"active\":false,\"detected\":false,\"force\":\"auto\",\"builtIn\":true," +
|
||||
"\"plugin\":\"\",\"reason\":\"not detected\"}]}";
|
||||
|
||||
private const string NoIltState =
|
||||
"{\"schema\":1,\"revision\":1,\"active\":\"\",\"servers\":[" +
|
||||
"{\"id\":\"aelrynth\",\"name\":\"Aelrynth\",\"active\":true,\"detected\":true,\"force\":\"auto\"}]}";
|
||||
|
||||
private static void ServerList()
|
||||
{
|
||||
IltEngineView? v = IltSettingsModel.FromServerState(EngineServerState.Parse(State));
|
||||
Check.True(v?.Server != null, "the ILT server is there");
|
||||
Check.Eq(v!.Server!.Name, "Infinite Leaftide", "name");
|
||||
Check.True(v.Server.Active, "active");
|
||||
Check.False(v.Server.Detected, "not detected (forced)");
|
||||
Check.Eq(v.Server.Force, "on", "override");
|
||||
Check.Eq(v.Server.Reason, "forced on for this character", "reason");
|
||||
|
||||
IltEngineView? odd = IltSettingsModel.FromServerState(EngineServerState.Parse(
|
||||
"{\"schema\":1,\"servers\":[{\"id\":\"ILT\",\"force\":\"WEIRD\"}]}"));
|
||||
Check.True(odd?.Server != null, "the id ignores case");
|
||||
Check.Eq(odd!.Server!.Force, "auto", "an unknown override shows as auto");
|
||||
Check.Eq(odd.Server.Name, "Infinite Leaftide", "a missing name gets the server's");
|
||||
Check.False(odd.Server.Active, "a missing flag is off");
|
||||
}
|
||||
|
||||
private static void NoIlt()
|
||||
{
|
||||
IltEngineView? none = IltSettingsModel.FromServerState(EngineServerState.Parse(NoIltState));
|
||||
Check.True(none != null && none.Server == null, "a list without ILT says so (not 'waiting')");
|
||||
Check.True(IltSettingsModel.FromServerState(null) == null, "no list: nothing");
|
||||
Check.True(EngineServerState.Parse("") == null && EngineServerState.Parse("{\"schema\":2}") == null, "empty or another schema: no list");
|
||||
|
||||
var model = new IltSettingsModel();
|
||||
model.ApplyServerState(EngineServerState.Parse(State));
|
||||
model.ApplyServerState(null);
|
||||
Check.True(model.Engine?.Server?.Active == true, "no answer keeps the last list");
|
||||
}
|
||||
|
||||
private static void FeatureRead()
|
||||
{
|
||||
var model = new IltSettingsModel();
|
||||
var read = new IltFeatureView("Infinite Leaftide", "probe", "12:00:00", Checking: true, IltLike: true,
|
||||
new[] { new KeyValuePair<string, int>("bank", 1) });
|
||||
model.PublishFeatures(read);
|
||||
Check.True(ReferenceEquals(model.Features, read), "published as is");
|
||||
model.PublishFeatures(null);
|
||||
Check.True(model.Features == null, "cleared while there is no Hub");
|
||||
Check.Eq(IltSettingsModel.StateText(1), "on", "1 is on");
|
||||
Check.Eq(IltSettingsModel.StateText(0), "off", "0 is off (not unknown)");
|
||||
Check.Eq(IltSettingsModel.StateText(-1), "unknown", "-1 is unknown");
|
||||
}
|
||||
|
||||
private static void EngineVerdict()
|
||||
{
|
||||
var model = new IltSettingsModel();
|
||||
try
|
||||
{
|
||||
IltEngineVerdict.Attach(model);
|
||||
Check.False(IltEngineVerdict.Pushed, "nothing sent yet");
|
||||
Check.True(IltEngineVerdict.Active == null, "no verdict: RynthILT's own list decides");
|
||||
model.ApplyServerState(EngineServerState.Parse(State));
|
||||
Check.True(IltEngineVerdict.Pushed, "sent");
|
||||
Check.True(IltEngineVerdict.Active == true, "RynthCore says ILT");
|
||||
model.ApplyServerState(EngineServerState.Parse(NoIltState));
|
||||
Check.True(IltEngineVerdict.Pushed && IltEngineVerdict.Active == null, "a list without ILT gives no ILT verdict");
|
||||
model.Clear();
|
||||
Check.False(IltEngineVerdict.Pushed, "logout forgets it");
|
||||
}
|
||||
finally { IltEngineVerdict.Attach(null); }
|
||||
Check.True(IltEngineVerdict.Active == null, "detached");
|
||||
}
|
||||
|
||||
private static void Commands()
|
||||
{
|
||||
Check.Eq(IltSettingsModel.ForceCommand("on"), "/rc server ilt on", "on");
|
||||
Check.Eq(IltSettingsModel.ForceCommand("auto"), "/rc server ilt auto", "auto");
|
||||
Check.Eq(IltSettingsModel.ForceCommand("maybe"), "", "unknown mode sends nothing");
|
||||
Check.Eq(IltSettingsModel.NamesListCommand, "/rc server names ilt", "the names are listed by RynthCore");
|
||||
|
||||
Check.Eq(IltSettingsModel.NamesCommand(true, " *Frost* ", out _), "/rc server names ilt add *Frost*", "add, trimmed");
|
||||
Check.Eq(IltSettingsModel.NamesCommand(false, "Infinite Leaftide", out _), "/rc server names ilt remove Infinite Leaftide", "remove");
|
||||
Check.Eq(IltSettingsModel.NamesCommand(true, "", out string e1), "", "empty refused");
|
||||
Check.True(e1.Length > 0, "with a reason");
|
||||
Check.Eq(IltSettingsModel.NamesCommand(true, new string('a', IltSettingsModel.MaxPattern + 1), out _), "", "too long refused");
|
||||
Check.Eq(IltSettingsModel.NamesCommand(true, "x\n/rc reload", out _), "", "a line break can't start a second command");
|
||||
Check.Eq(IltSettingsModel.NamesCommand(true, "a/b", out _), "", "no '/'");
|
||||
}
|
||||
|
||||
private static void ClearOnLogout()
|
||||
{
|
||||
var model = new IltSettingsModel();
|
||||
model.ApplyServerState(EngineServerState.Parse(State));
|
||||
model.PublishFeatures(new IltFeatureView("w", "", "", false, true, Array.Empty<KeyValuePair<string, int>>()));
|
||||
Check.True(model.Engine != null && model.Features != null, "both copies");
|
||||
model.Clear();
|
||||
Check.True(model.Engine == null && model.Features == null, "cleared");
|
||||
}
|
||||
}
|
||||
615
Tools/RynthILT.Tests/MoveTests.cs
Normal file
615
Tools/RynthILT.Tests/MoveTests.cs
Normal file
|
|
@ -0,0 +1,615 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Runtime.InteropServices;
|
||||
using RynthCore.Loot;
|
||||
using RynthCore.Plugin.RynthILT;
|
||||
using RynthCore.Plugin.RynthILT.Hub;
|
||||
using RynthCore.Plugin.Shared;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthILT.Tests;
|
||||
|
||||
// The ILT Hub's move out of RynthAi into RynthILT (2026-10-13): the saved data carried over from
|
||||
// RynthAi's folders (copied, never moved), the RynthILT.Hub interface table RynthAi's Mini Remote
|
||||
// reads, which "/ra" verbs RynthILT takes from RynthAi, and the host-backed object view that
|
||||
// replaced RynthAi's WorldObjectCache.
|
||||
internal static class MoveTests
|
||||
{
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("move: a character's RynthAi ILT Hub files are copied, the RynthAi copies left alone", MigratesCharacter);
|
||||
r.Add("move: migration never overwrites RynthILT's files and runs once", MigrationIdempotent);
|
||||
r.Add("move: the pre-per-server ACEmulator folder is found too", MigratesFromAceEmulatorFolder);
|
||||
r.Add("move: shared Hub profiles and aug costs are copied once", MigratesShared);
|
||||
r.Add("move: a migration copy that fails is reported (log + chat) and the shared ones retried", MigrationFailuresReported);
|
||||
r.Add("move: a failed Hub save is reported once and retried", StoreSaveFailureReported);
|
||||
r.Add("move: an unfinished copy blocks the character's Hub writes until the retry copies the original", PendingMigrationNeverShadowed);
|
||||
r.Add("move: an old ilt-hub.json loads into RynthILT's state (ILT parts kept)", LegacyStateLoads);
|
||||
r.Add("move: RynthAi's \"/ra\" verbs RynthILT takes (and the ones it leaves)", VerbRouting);
|
||||
r.Add("move: item classes from the client's item type (the gear tools' checks)", Classification);
|
||||
r.Add("move: the interface structs have the agreed layout", InterfaceLayout);
|
||||
r.Add("move: server-list status lines", DescribeLines);
|
||||
r.Add("move: off ILT nothing is sent, no tab or section shows; on ILT the login probe runs", DormantOffIlt);
|
||||
r.Add("move: the charms JSON for RynthILT.Data readers carries the Guardian Hands", CharmsReaderJson);
|
||||
r.Add("move: Character redirects to RynthOracle; Charms and Banking stay RynthILT's tabs", MovedSections);
|
||||
r.Add("sections: RynthILT's manifest (rates, /fship, /qb, and the ILT tabs it shows) is valid schema-1 JSON the engine places", SectionsManifest);
|
||||
// Last: Release() switches the table off for the rest of the process.
|
||||
r.Add("move: the RynthILT.Hub table: query, functions, release", HubTable);
|
||||
}
|
||||
|
||||
private static string Root(string name)
|
||||
{
|
||||
string dir = Path.Combine(Program.TempRoot, "move-" + name);
|
||||
if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true);
|
||||
Directory.CreateDirectory(dir);
|
||||
IltMigration.LegacyProfilesBase = Path.Combine(dir, "RynthAi", "SettingsProfiles");
|
||||
IltMigration.LegacySharedRoot = Path.Combine(dir, "RynthAi");
|
||||
return dir;
|
||||
}
|
||||
|
||||
private const string LegacyHubJson = """
|
||||
{
|
||||
"SchemaVersion": 1,
|
||||
"ForceLeaftideFeatures": false,
|
||||
"UbSidecarsImported": true,
|
||||
"Bank": { "Pyreals": 1234567, "Luminance": 89, "EnlightenedCoins": 42, "AutoRefreshSeconds": 300 },
|
||||
"Pet": { "HealingEnabled": true, "HealPetName": "Healing Buddy", "PetLog": ["Fire Banshee"], "ShinyLog": [] },
|
||||
"Character": {
|
||||
"QuestFilter": "temple", "QbFilter": "wait", "QuestFavorites": ["foo"],
|
||||
"AttrOrder": ["qui","coo","str","end","foc","sel","hea","sta","man"], "AttrRaiseStats": ["qui"],
|
||||
"AugTargets": { "war": 1800 }
|
||||
},
|
||||
"Gear": { "AutoClap": true, "LastUsdPath": "C:\\vt\\x.usd", "LastEquipProfile": "Melee" },
|
||||
"Guardian": { "AutoHandIn": true, "TurnInCounts": { "Strength": 3 } }
|
||||
}
|
||||
""";
|
||||
|
||||
private static string MakeLegacyChar(string world, string charName, bool withProfile = true)
|
||||
{
|
||||
string dir = Path.Combine(IltMigration.LegacyProfilesBase, IltMigration.RynthAiSafeName(world), IltMigration.RynthAiSafeName(charName));
|
||||
Directory.CreateDirectory(Path.Combine(dir, "ilt-hub-profiles"));
|
||||
File.WriteAllText(Path.Combine(dir, "ilt-hub.json"), LegacyHubJson);
|
||||
File.WriteAllText(Path.Combine(dir, "ilt-hub-transactions.json"), "[{\"Type\":\"Received\",\"Currency\":\"Pyreals\",\"Amount\":5}]");
|
||||
File.WriteAllText(Path.Combine(dir, "ilt-hub-profiles", "farm.json"), "{\"SchemaVersion\":1}");
|
||||
if (withProfile)
|
||||
{
|
||||
File.WriteAllText(Path.Combine(dir, "active_profile.txt"), "Melee");
|
||||
File.WriteAllText(Path.Combine(dir, "Melee.json"),
|
||||
"{\"MetaDebug\":false,\"FeatureServerNames\":[\"InfiniteLeaftide\",\"*Leaftide*\",\"MyShard\"],\"ForceServerFeatures\":true}");
|
||||
File.WriteAllText(Path.Combine(dir, "Default.json"), "{\"FeatureServerNames\":[\"Unused\"]}");
|
||||
}
|
||||
return dir;
|
||||
}
|
||||
|
||||
private static void MigratesCharacter()
|
||||
{
|
||||
string root = Root("char");
|
||||
string legacy = MakeLegacyChar("Infinite Leaftide", "Sir Tester");
|
||||
string before = File.ReadAllText(Path.Combine(legacy, "ilt-hub.json"));
|
||||
var settings = new IltSettings();
|
||||
string dest = Path.Combine(root, "RynthILT", "Infinite Leaftide", "Sir Tester");
|
||||
|
||||
var done = IltMigration.MigrateCharacter(dest, "Infinite Leaftide", "Sir Tester", settings, out bool force);
|
||||
Check.True(File.Exists(Path.Combine(dest, IltHubStore.StateFile)), "ilt-hub.json -> hub.json");
|
||||
Check.Eq(File.ReadAllText(Path.Combine(dest, IltHubStore.StateFile)), before, "copied byte for byte");
|
||||
Check.True(File.Exists(Path.Combine(dest, IltHubStore.TransactionsFile)), "transactions copied");
|
||||
Check.True(File.Exists(Path.Combine(dest, IltHubStore.ProfilesFolder, "farm.json")), "per-character Hub profiles copied");
|
||||
Check.True(File.Exists(Path.Combine(legacy, "ilt-hub.json")) && File.Exists(Path.Combine(legacy, "ilt-hub-transactions.json")),
|
||||
"RynthAi's files are still there (copy, not move)");
|
||||
Check.True(settings.ServerNames.Contains("MyShard"), "the active profile's server names are added");
|
||||
Check.False(settings.ServerNames.Contains("Unused"), "only the ACTIVE profile is read");
|
||||
Check.Eq(settings.ServerNames.Count(n => n.Equals("InfiniteLeaftide", StringComparison.OrdinalIgnoreCase)), 1, "no duplicates");
|
||||
Check.True(force, "\"Force enable\" carries over as Treat this world as ILT");
|
||||
Check.True(done.Count >= 4, "the log line lists what was carried over: " + string.Join(", ", done));
|
||||
}
|
||||
|
||||
private static void MigrationIdempotent()
|
||||
{
|
||||
string root = Root("idem");
|
||||
string legacy = MakeLegacyChar("InfiniteLeaftide", "Again", withProfile: false);
|
||||
string dest = Path.Combine(root, "RynthILT", "InfiniteLeaftide", "Again");
|
||||
Directory.CreateDirectory(dest);
|
||||
File.WriteAllText(Path.Combine(dest, IltHubStore.TransactionsFile), "[]"); // RynthILT already has one
|
||||
var settings = new IltSettings();
|
||||
|
||||
IltMigration.MigrateCharacter(dest, "InfiniteLeaftide", "Again", settings, out bool force);
|
||||
Check.Eq(File.ReadAllText(Path.Combine(dest, IltHubStore.TransactionsFile)), "[]", "an existing RynthILT file is never overwritten");
|
||||
Check.True(File.Exists(Path.Combine(dest, IltHubStore.StateFile)), "the missing hub.json is still copied");
|
||||
Check.False(force, "no profile, no override");
|
||||
|
||||
File.WriteAllText(Path.Combine(legacy, "ilt-hub.json"), "{\"Bank\":{\"Pyreals\":1}}");
|
||||
var second = IltMigration.MigrateCharacter(dest, "InfiniteLeaftide", "Again", settings, out _);
|
||||
Check.Eq(second.Count, 0, "once hub.json exists the character is never migrated again");
|
||||
Check.False(File.ReadAllText(Path.Combine(dest, IltHubStore.StateFile)).Contains("\"Pyreals\":1}"), "later RynthAi edits don't overwrite RynthILT's state");
|
||||
|
||||
var none = IltMigration.MigrateCharacter(Path.Combine(root, "RynthILT", "X", "Nobody"), "X", "Nobody", settings, out _);
|
||||
Check.Eq(none.Count, 0, "a character RynthAi never saw: nothing to do");
|
||||
Check.False(Directory.Exists(Path.Combine(root, "RynthILT", "X", "Nobody")), "and no folder is made for it");
|
||||
}
|
||||
|
||||
private static void MigratesFromAceEmulatorFolder()
|
||||
{
|
||||
string root = Root("ace");
|
||||
MakeLegacyChar("ACEmulator", "Old Timer", withProfile: false);
|
||||
var settings = new IltSettings();
|
||||
string dest = Path.Combine(root, "RynthILT", "InfiniteLeaftide", "Old Timer");
|
||||
Check.NotNull(IltMigration.FindLegacyCharFolder("InfiniteLeaftide", "Old Timer"), "the world folder is missing, ACEmulator\\<char> is used");
|
||||
IltMigration.MigrateCharacter(dest, "InfiniteLeaftide", "Old Timer", settings, out _);
|
||||
Check.True(File.Exists(Path.Combine(dest, IltHubStore.StateFile)), "copied from the ACEmulator folder");
|
||||
Check.Eq(IltMigration.RynthAiSafeName("Sir O'Neil-Smith"), "Sir_O'Neil-Smith", "RynthAi's folder names keep ' and - only");
|
||||
}
|
||||
|
||||
private static void MigratesShared()
|
||||
{
|
||||
string root = Root("shared");
|
||||
Directory.CreateDirectory(Path.Combine(IltMigration.LegacySharedRoot, "IltHubProfiles"));
|
||||
File.WriteAllText(Path.Combine(IltMigration.LegacySharedRoot, "IltHubProfiles", "team.json"), "{}");
|
||||
File.WriteAllText(Path.Combine(IltMigration.LegacySharedRoot, "ilt-aug-costs.json"), "{\"x\":1}");
|
||||
var settings = new IltSettings();
|
||||
string dest = Path.Combine(root, "RynthILT");
|
||||
|
||||
var done = IltMigration.MigrateShared(settings, dest);
|
||||
Check.True(File.Exists(Path.Combine(dest, "Profiles", "team.json")), "shared profiles copied");
|
||||
Check.True(File.Exists(Path.Combine(dest, "ilt-aug-costs.json")), "aug costs copied");
|
||||
Check.True(settings.SharedFilesMigrated, "marked done in the settings");
|
||||
Check.Eq(done.Count, 2, "both reported");
|
||||
File.Delete(Path.Combine(dest, "ilt-aug-costs.json"));
|
||||
Check.Eq(IltMigration.MigrateShared(settings, dest).Count, 0, "once only");
|
||||
Check.False(File.Exists(Path.Combine(dest, "ilt-aug-costs.json")), "a file deleted afterwards isn't brought back");
|
||||
}
|
||||
|
||||
// A copy that fails (here: the RynthAi file held open by another program) is never silent: it
|
||||
// is logged and queued for chat with the reason, the rest still copies, and the shared files
|
||||
// aren't marked done so the next login tries again.
|
||||
private static void MigrationFailuresReported()
|
||||
{
|
||||
string root = Root("fail");
|
||||
DataWriteGuard.Reset();
|
||||
string legacy = MakeLegacyChar("InfiniteLeaftide", "Locked Out");
|
||||
string dest = Path.Combine(root, "RynthILT", "InfiniteLeaftide", "Locked Out");
|
||||
var settings = new IltSettings();
|
||||
List<string> done;
|
||||
using (new FileStream(Path.Combine(legacy, "ilt-hub-transactions.json"), FileMode.Open, FileAccess.Read, FileShare.None))
|
||||
done = IltMigration.MigrateCharacter(dest, "InfiniteLeaftide", "Locked Out", settings, out _);
|
||||
Check.True(File.Exists(Path.Combine(dest, IltHubStore.StateFile)), "the other files are still copied");
|
||||
Check.False(File.Exists(Path.Combine(dest, IltHubStore.TransactionsFile)), "the held file isn't");
|
||||
Check.True(done.Any(l => l.Contains("NOT copied") && l.Contains(legacy)), "the log line says so and where the originals are: " + string.Join(", ", done));
|
||||
Check.Eq(DataWriteGuard.PendingCount, 1, "one chat line queued (shown on ILT)");
|
||||
var lines = new List<string>();
|
||||
DataWriteGuard.DrainChat(lines.Add);
|
||||
Check.True(lines.Count == 1 && lines[0].StartsWith("[RynthILT]", StringComparison.Ordinal)
|
||||
&& lines[0].Contains("ilt-hub-transactions.json") && lines[0].Contains("another program"),
|
||||
"it names the file and the reason: " + string.Join(" | ", lines));
|
||||
|
||||
DataWriteGuard.Reset();
|
||||
Directory.CreateDirectory(Path.Combine(IltMigration.LegacySharedRoot, "IltHubProfiles"));
|
||||
File.WriteAllText(Path.Combine(IltMigration.LegacySharedRoot, "IltHubProfiles", "team.json"), "{}");
|
||||
string aug = Path.Combine(IltMigration.LegacySharedRoot, "ilt-aug-costs.json");
|
||||
File.WriteAllText(aug, "{\"x\":1}");
|
||||
string sharedDest = Path.Combine(root, "RynthILT");
|
||||
using (new FileStream(aug, FileMode.Open, FileAccess.Read, FileShare.None))
|
||||
done = IltMigration.MigrateShared(settings, sharedDest);
|
||||
Check.False(settings.SharedFilesMigrated, "a failed shared copy isn't marked done");
|
||||
Check.True(done.Any(l => l.Contains("NOT copied")), "and is reported: " + string.Join(", ", done));
|
||||
Check.True(DataWriteGuard.PendingCount >= 1, "in chat too");
|
||||
done = IltMigration.MigrateShared(settings, sharedDest);
|
||||
Check.True(File.Exists(Path.Combine(sharedDest, "ilt-aug-costs.json")), "the next login copies it");
|
||||
Check.True(settings.SharedFilesMigrated, "then it is marked done");
|
||||
Check.Eq(done.Count, 1, "only the missing file is copied the second time: " + string.Join(", ", done));
|
||||
DataWriteGuard.Reset();
|
||||
}
|
||||
|
||||
// A character whose ilt-hub.json couldn't be copied (held open by another program): the Hub
|
||||
// runs from the RynthAi original read-only (or the defaults), writes no hub.json, bank log or
|
||||
// per-character profile there, the pending mark survives a restart, and the next attempt copies
|
||||
// the original byte for byte - never shadowed by a fresh file.
|
||||
private static void PendingMigrationNeverShadowed()
|
||||
{
|
||||
string root = Root("pending");
|
||||
DataWriteGuard.Reset();
|
||||
string legacy = MakeLegacyChar("InfiniteLeaftide", "Held Open");
|
||||
string legacyHub = Path.Combine(legacy, "ilt-hub.json");
|
||||
string dest = Path.Combine(root, "RynthILT", "InfiniteLeaftide", "Held Open");
|
||||
string hubJson = Path.Combine(dest, IltHubStore.StateFile);
|
||||
var settings = new IltSettings();
|
||||
|
||||
// Held open by another program: neither copied nor readable.
|
||||
using (var held = new FileStream(legacyHub, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
|
||||
{
|
||||
var done = IltMigration.MigrateCharacter(dest, "InfiniteLeaftide", "Held Open", settings, out _);
|
||||
Check.False(File.Exists(hubJson), "the held ilt-hub.json isn't copied");
|
||||
Check.True(IltMigration.IsPending(settings, dest), "the character is marked pending");
|
||||
Check.True(done.Any(l => l.Contains("NOT copied")), "and the log says so: " + string.Join(", ", done));
|
||||
|
||||
var store = new IltHubStore(default, dest)
|
||||
{
|
||||
WritesBlocked = () => IltMigration.IsPending(settings, dest),
|
||||
LegacyFolder = legacy,
|
||||
};
|
||||
IltHubState state = store.LoadState();
|
||||
Check.Eq(state.Bank.Pyreals, 0L, "unreadable: the Hub runs from the defaults");
|
||||
state.Bank.Pyreals = 1;
|
||||
store.SaveStateIfDirty(state);
|
||||
Check.False(File.Exists(hubJson), "no hub.json is written while the copy is unfinished");
|
||||
Check.False(store.SaveProfile(state, "mine", shared: false, out string why), "nor a per-character profile");
|
||||
Check.True(why.Contains("RynthAi"), "with the reason: " + why);
|
||||
Check.True(store.SaveProfile(state, "team-" + Guid.NewGuid().ToString("N"), shared: true, out _), "shared profiles still save");
|
||||
|
||||
// A second login while still held: still pending, still nothing written.
|
||||
IltMigration.MigrateCharacter(dest, "InfiniteLeaftide", "Held Open", settings, out _);
|
||||
Check.True(IltMigration.IsPending(settings, dest) && !File.Exists(hubJson), "still pending, still no hub.json");
|
||||
}
|
||||
|
||||
// Readable again but not yet retried: a Hub started now reads the original, still writes nothing.
|
||||
var readOnly = new IltHubStore(default, dest)
|
||||
{
|
||||
WritesBlocked = () => IltMigration.IsPending(settings, dest),
|
||||
LegacyFolder = legacy,
|
||||
};
|
||||
IltHubState fromLegacy = readOnly.LoadState();
|
||||
Check.Eq(fromLegacy.Bank.Pyreals, 1234567L, "the Hub runs from the RynthAi original, read only");
|
||||
fromLegacy.Bank.Pyreals = 2;
|
||||
readOnly.SaveStateIfDirty(fromLegacy);
|
||||
Check.False(File.Exists(hubJson), "and still writes no hub.json");
|
||||
|
||||
// The mark is in settings.json, so a client restart still knows the copy is unfinished.
|
||||
IltSettingsStore.Save(settings);
|
||||
IltSettings reloaded = IltSettingsStore.Load();
|
||||
Check.True(IltMigration.IsPending(reloaded, dest), "pending survives a restart");
|
||||
|
||||
var finished = IltMigration.MigrateCharacter(dest, "InfiniteLeaftide", "Held Open", reloaded, out bool force);
|
||||
Check.True(File.Exists(hubJson), "the next attempt copies it");
|
||||
Check.Eq(File.ReadAllText(hubJson), File.ReadAllText(legacyHub), "byte for byte: the original, not a fresh file");
|
||||
Check.False(IltMigration.IsPending(reloaded, dest), "no longer pending");
|
||||
Check.True(force, "the profile's Force enable still carries over on the retry");
|
||||
Check.True(finished.Any(l => l.Contains("complete")), "the log says it finished: " + string.Join(", ", finished));
|
||||
|
||||
var after = new IltHubStore(default, dest) { WritesBlocked = () => IltMigration.IsPending(reloaded, dest) };
|
||||
IltHubState loaded = after.LoadState();
|
||||
Check.Eq(loaded.Bank.Pyreals, 1234567L, "the restarted Hub loads the copied file");
|
||||
loaded.Bank.Pyreals = 7;
|
||||
after.SaveStateIfDirty(loaded);
|
||||
Check.True(File.ReadAllText(hubJson).Contains("\"Pyreals\": 7"), "and saves normally from then on");
|
||||
File.Delete(Path.Combine(IltSettingsStore.Folder, IltSettingsStore.FileName));
|
||||
DataWriteGuard.Reset();
|
||||
}
|
||||
|
||||
// RynthILT's own saves report a failure (DataWriteGuard) and try again on the next save.
|
||||
private static void StoreSaveFailureReported()
|
||||
{
|
||||
string root = Root("storefail");
|
||||
DataWriteGuard.Reset();
|
||||
string blocker = Path.Combine(root, "NotAFolder");
|
||||
File.WriteAllText(blocker, "a file where the character folder should be");
|
||||
var store = new IltHubStore(default, blocker);
|
||||
var state = new IltHubState();
|
||||
store.SaveStateIfDirty(state);
|
||||
Check.Eq(DataWriteGuard.PendingCount, 1, "the failed Hub save is queued for chat");
|
||||
store.SaveStateIfDirty(state);
|
||||
Check.Eq(DataWriteGuard.PendingCount, 1, "once per folder, not every retry");
|
||||
File.Delete(blocker);
|
||||
store.SaveStateIfDirty(state);
|
||||
Check.True(File.Exists(Path.Combine(blocker, IltHubStore.StateFile)), "the next save retries and works");
|
||||
DataWriteGuard.Reset();
|
||||
}
|
||||
|
||||
private static void LegacyStateLoads()
|
||||
{
|
||||
string root = Root("state");
|
||||
string dir = Path.Combine(root, "char");
|
||||
Directory.CreateDirectory(dir);
|
||||
File.WriteAllText(Path.Combine(dir, IltHubStore.StateFile), LegacyHubJson);
|
||||
var store = new IltHubStore(default, dir);
|
||||
var s = store.LoadState();
|
||||
Check.Eq(s.Bank.Pyreals, 1234567L, "bank balances");
|
||||
Check.Eq(s.Bank.AutoRefreshSeconds, 300, "bank settings");
|
||||
Check.Eq(s.Pet.PetLog.FirstOrDefault(), "Fire Banshee", "the /pets log (an ILT part of the Pet section)");
|
||||
Check.Eq(s.Character.QbFilter, "wait", "the /qb filter");
|
||||
Check.Eq(s.Character.AttrOrder.FirstOrDefault(), "qui", "the attribute raiser's order");
|
||||
Check.Eq(s.Character.AugTargets["war"], 1800, "aug targets");
|
||||
Check.True(s.Gear.AutoClap && s.Gear.LastEquipProfile == "Melee", "gear settings");
|
||||
Check.True(s.Guardian.AutoHandIn && s.Guardian.TurnInCounts["Strength"] == 3, "guardian settings");
|
||||
Check.True(s.UbSidecarsImported, "the UB import isn't redone");
|
||||
|
||||
store.SaveStateIfDirty(s);
|
||||
string saved = File.ReadAllText(Path.Combine(dir, IltHubStore.StateFile));
|
||||
Check.False(saved.Contains("HealPetName"), "the Pets tab's settings (RynthAi's now) aren't written back here");
|
||||
Check.False(saved.Contains("QuestFavorites"), "nor the Quests tab's");
|
||||
}
|
||||
|
||||
private static void VerbRouting()
|
||||
{
|
||||
static bool Takes(string line) => RynthILTPlugin.IsIltVerb(line.Split(' ', StringSplitOptions.RemoveEmptyEntries));
|
||||
Check.True(Takes("hub bank"), "hub bank");
|
||||
Check.True(Takes("hub attr run"), "hub attr run");
|
||||
Check.True(Takes("hub refresh"), "hub refresh");
|
||||
Check.True(Takes("hub help"), "hub help (RynthILT prints the whole list)");
|
||||
Check.True(Takes("hub open banking show"), "hub open <ILT tab>");
|
||||
Check.True(Takes("hub open guardian"), "hub open guardian (the engine panel)");
|
||||
Check.True(Takes("hub open bounties"), "hub open bounties");
|
||||
Check.False(Takes("hub open pets"), "hub open pets is RynthAi's");
|
||||
Check.False(Takes("hub open quests hide"), "hub open quests is RynthAi's");
|
||||
Check.True(Takes("hub tab gear"), "hub tab <ILT tab>");
|
||||
Check.False(Takes("hub tab quests"), "hub tab quests is RynthAi's");
|
||||
Check.False(Takes("hub tab remote"), "the Remote tab is RynthAi's");
|
||||
Check.False(Takes("hub"), "bare /ra hub toggles RynthAi's Mini Remote");
|
||||
Check.True(Takes("guardian handin"), "guardian");
|
||||
Check.True(Takes("bounty show") && Takes("bounties") && Takes("bountys"), "bounty, bounties, bountys");
|
||||
Check.True(Takes("rates reset"), "rates reset (the Mini Remote's Reset XP)");
|
||||
Check.False(Takes("quests refresh"), "/ra quests is RynthAi's");
|
||||
Check.False(Takes("pets show"), "/ra pets is RynthAi's");
|
||||
Check.False(Takes("start"), "anything else is RynthAi's");
|
||||
// The VTank hotkey verbs (RynthAi 2026-10-13, RynthAiPlugin.VTankHotkeys.cs) stay RynthAi's.
|
||||
foreach (string vt in new[] { "vtkeys", "targetlock", "recharge", "lootthis", "meleelow", "navprio", "lootprio", "navlootprio", "setmetastate Default", "testitem", "propertydump" })
|
||||
Check.False(Takes(vt), $"{vt} is RynthAi's (VTank hotkeys)");
|
||||
}
|
||||
|
||||
private static void Classification()
|
||||
{
|
||||
Check.Eq(IltObjects.ClassifyByItemType(0x00000800), AcObjectClass.Gem, "gem (aetheria)");
|
||||
Check.Eq(IltObjects.ClassifyByItemType(0x00000001), AcObjectClass.MeleeWeapon, "melee weapon");
|
||||
Check.Eq(IltObjects.ClassifyByItemType(0x00000100), AcObjectClass.MissileWeapon, "missile weapon");
|
||||
Check.Eq(IltObjects.ClassifyByItemType(0x00008000), AcObjectClass.WandStaffOrb, "caster");
|
||||
Check.Eq(IltObjects.ClassifyByItemType(0x40000000), AcObjectClass.Salvage, "salvage (white quartz)");
|
||||
Check.Eq(IltObjects.ClassifyByItemType(0x00001000), AcObjectClass.SpellComponent, "spell component");
|
||||
Check.Eq(IltObjects.ClassifyByItemType(0x00000200), AcObjectClass.Container, "pack");
|
||||
Check.Eq(IltObjects.ClassifyByItemType(0x00000010), AcObjectClass.Monster, "creature");
|
||||
Check.Eq(IltObjects.ClassifyByItemType(0x00000002 | 0x00000004), AcObjectClass.Armor, "armor wins over clothing");
|
||||
Check.Eq(IltObjects.ClassifyByItemType(0), AcObjectClass.Unknown, "no type yet");
|
||||
}
|
||||
|
||||
private static unsafe void InterfaceLayout()
|
||||
{
|
||||
Check.Eq(sizeof(ServerHubTabV1), 24 + 32 + 4 + 4 + 4, "ServerHubTabV1: id, label, width, height, flags");
|
||||
Check.Eq((int)Marshal.OffsetOf<ServerHubTabV1>(nameof(ServerHubTabV1.Flags)), 64, "ServerHubTabV1.Flags offset");
|
||||
// RynthILT.Hub grew on 2026-10-20 (append-only): readers accept any table at least BaseStructSize
|
||||
// long (the first release's 9 functions) and check the appended ones with Has.
|
||||
Check.Eq((int)RynthServerHubApiV1.BaseStructSize, 8 + 9 * IntPtr.Size, "RynthServerHubApiV1.BaseStructSize: the first release's 9 functions");
|
||||
Check.Eq(RynthServerHubApiV1.AllowSummonOnEmptyOffset, 8 + 9 * IntPtr.Size, "AllowSummonOnEmpty right after Command");
|
||||
Check.Eq((int)Marshal.OffsetOf<RynthServerHubApiV1>(nameof(RynthServerHubApiV1.AllowSummonOnEmpty)), RynthServerHubApiV1.AllowSummonOnEmptyOffset,
|
||||
"AllowSummonOnEmptyOffset is where the field really is");
|
||||
Check.Eq((int)Marshal.OffsetOf<RynthServerHubApiV1>(nameof(RynthServerHubApiV1.GetSubTabs)), RynthServerHubApiV1.GetSubTabsOffset,
|
||||
"GetSubTabsOffset is where the field really is");
|
||||
Check.Eq((int)Marshal.OffsetOf<RynthServerHubApiV1>(nameof(RynthServerHubApiV1.GetSetting)), RynthServerHubApiV1.GetSettingOffset,
|
||||
"GetSettingOffset is where the field really is");
|
||||
Check.Eq((int)Marshal.OffsetOf<RynthServerHubApiV1>(nameof(RynthServerHubApiV1.SetSetting)), RynthServerHubApiV1.SetSettingOffset,
|
||||
"SetSettingOffset is where the field really is");
|
||||
// SessionStatsMore was appended (2026-10-13); readers accept any table at least
|
||||
// BaseStructSize long, so an older RynthAi still connects.
|
||||
// VaultedDungeonsEnabled was appended (2026-10-18): the Vaulted Dungeons master switch.
|
||||
// BackAwayFrom was appended (2026-10-20): the generic back-away RynthILT's Handler ring evade asks for.
|
||||
// SetPlayerCounter too (2026-10-20): the T11 wield counters RynthILT reads from /aug.
|
||||
Check.Eq(sizeof(RynthAiHubApiV1), 8 + 14 * IntPtr.Size, "RynthAiHubApiV1: header + 14 functions");
|
||||
Check.Eq((int)Marshal.OffsetOf<RynthAiHubApiV1>(nameof(RynthAiHubApiV1.SetPlayerCounter)), RynthAiHubApiV1.SetPlayerCounterOffset,
|
||||
"SetPlayerCounterOffset is where the field really is");
|
||||
Check.Eq((int)Marshal.OffsetOf<RynthAiHubApiV1>(nameof(RynthAiHubApiV1.BackAwayFrom)), RynthAiHubApiV1.BackAwayFromOffset,
|
||||
"BackAwayFromOffset is where the field really is");
|
||||
Check.Eq((int)RynthAiHubApiV1.BaseStructSize, 8 + 10 * IntPtr.Size, "RynthAiHubApiV1.BaseStructSize: the first release's 10 functions");
|
||||
Check.Eq(RynthAiHubApiV1.SessionStatsMoreOffset, (int)RynthAiHubApiV1.BaseStructSize, "SessionStatsMore right after the base table");
|
||||
Check.Eq(RynthAiHubApiV1.VaultedDungeonsEnabledOffset, 8 + 11 * IntPtr.Size, "VaultedDungeonsEnabled right after SessionStatsMore");
|
||||
Check.Eq((int)Marshal.OffsetOf<RynthAiHubApiV1>(nameof(RynthAiHubApiV1.VaultedDungeonsEnabled)), RynthAiHubApiV1.VaultedDungeonsEnabledOffset,
|
||||
"VaultedDungeonsEnabledOffset is where the field really is");
|
||||
Check.Eq(sizeof(QuestFlagV1), 24, "QuestFlagV1");
|
||||
Check.Eq(sizeof(QuestStatusV1), 16, "QuestStatusV1");
|
||||
Check.Eq(RynthIltHub.InterfaceName, "RynthILT.Hub", "interface name");
|
||||
// The hub split into the neutral RynthServer.Hub (RynthServerHubApi.cs) on 2026-10-21: the ids are
|
||||
// the wire format and kept their values.
|
||||
Check.Eq(RynthServerHubApiV1.InterfaceName, "RynthServer.Hub", "the neutral interface name");
|
||||
Check.Eq(string.Join(",", RynthServerHub.SectionRemoteBank, RynthServerHub.SectionRemoteGuardian, RynthServerHub.SectionRemoteStats,
|
||||
RynthServerHub.SectionRemoteOptions, RynthServerHub.SectionPetCharms, RynthServerHub.SectionPetCapture,
|
||||
RynthServerHub.SectionPetLogs, RynthServerHub.SectionServerStatus, RynthServerHub.SectionServerMenu),
|
||||
"remote-bank,remote-guardian,remote-stats,remote-options,pets-charms,pets-capture,pets-logs,ilt-status,server-menu",
|
||||
"section ids unchanged");
|
||||
Check.Eq(string.Join(",", RynthServerHub.TabParentPets, RynthServerHub.TextSessionReport, RynthServerHub.TextServerId,
|
||||
RynthServerHub.FeatureQuests, RynthServerHub.SettingVaultedDungeons),
|
||||
"pets,session-report,server-id,quests,vaulted-dungeons", "tab, text, feature and setting ids unchanged");
|
||||
Check.Eq((RynthServerHub.TabShown, RynthServerHub.TabAvailable), (1u, 2u), "tab flags unchanged");
|
||||
Check.Eq(RynthAiHubApiV1.InterfaceName, "RynthAi.Hub", "RynthAi's interface name");
|
||||
}
|
||||
|
||||
private static void DescribeLines()
|
||||
{
|
||||
var s = new IltSettings();
|
||||
Check.True(ServerFeatureGate.Describe("InfiniteLeaftide", s, false).Contains("ON - matches 'InfiniteLeaftide'"), "on by name");
|
||||
Check.True(ServerFeatureGate.Describe("Aelrynth", s, true).Contains("Treat this world as ILT"), "on by the override");
|
||||
Check.True(ServerFeatureGate.Describe("Aelrynth", s, false).Contains("OFF"), "off");
|
||||
Check.True(ServerFeatureGate.Describe("", s, false).Contains("not logged in"), "before login");
|
||||
}
|
||||
|
||||
private static IltHubController NewHub(string world, string folder)
|
||||
{
|
||||
RynthCore.RynthAiHostTests.Fakes.FakeHost.Reset();
|
||||
RynthCore.RynthAiHostTests.Fakes.FakeHost.WorldName = world;
|
||||
var host = RynthCore.RynthAiHostTests.Fakes.FakeHost.Create(0x50000F01);
|
||||
string dir = Path.Combine(Program.TempRoot, "move-" + folder);
|
||||
Directory.CreateDirectory(dir);
|
||||
return new IltHubController(host, dir, new IltSettings(), new RynthAiClient(host));
|
||||
}
|
||||
|
||||
private static void TickFor(IltHubController hub, int ms)
|
||||
{
|
||||
var until = DateTime.UtcNow.AddMilliseconds(ms);
|
||||
while (DateTime.UtcNow < until) { hub.Tick(); System.Threading.Thread.Sleep(50); }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The charms JSON behind "RynthILT.Data" is valid JSON; on ILT it has a "hands" array (empty
|
||||
/// with no hand carried) that the shared reader parses, off ILT it has none and still parses.
|
||||
/// </summary>
|
||||
private static void CharmsReaderJson()
|
||||
{
|
||||
var on = NewHub("InfiniteLeaftide", "charms-on");
|
||||
string json = on.CharmsTab.BuildReaderJson();
|
||||
using (var doc = System.Text.Json.JsonDocument.Parse(json))
|
||||
Check.True(doc.RootElement.TryGetProperty("hands", out var hands) && hands.GetArrayLength() == 0,
|
||||
"on ILT: an empty hands array with no Guardian Hand carried");
|
||||
Check.True(json.All(c => c < 128), "ASCII only");
|
||||
var view = IltCharmsView.Parse(json);
|
||||
Check.True(view.Loaded && view.Hands.Count == 0, "the shared reader takes it");
|
||||
|
||||
var withHands = IltCharmsView.Parse("{\"available\":true,\"charms\":[],\"hands\":[" +
|
||||
"{\"id\":1234,\"name\":\"Guardian Hand\",\"active\":\"on\",\"server\":\"off\"},{\"id\":0,\"name\":\"no id\"}]}");
|
||||
Check.Eq(withHands.Hands.Count, 1, "a hand without an id is skipped (nothing to toggle)");
|
||||
Check.True(withHands.Hands[0] == new IltHandRow(1234, "Guardian Hand", "on", "off"), "id, name, active, server");
|
||||
|
||||
var off = NewHub("Aeshnidae", "charms-off");
|
||||
string offJson = off.CharmsTab.BuildReaderJson();
|
||||
using (var doc = System.Text.Json.JsonDocument.Parse(offJson))
|
||||
Check.False(doc.RootElement.TryGetProperty("hands", out _), "off ILT: no hands");
|
||||
Check.True(IltCharmsView.Parse(offJson).Hands.Count == 0, "and the reader shows none");
|
||||
}
|
||||
|
||||
/// <summary>The Character tab moved out (2026-10-13); every other ILT tab is still RynthILT's.</summary>
|
||||
private static void MovedSections()
|
||||
{
|
||||
Check.Eq(IltSections.MovedCommand(IltSection.Character), IltSections.OracleCharacterCommand, "Character -> RynthOracle Character");
|
||||
foreach (var kept in new[] { IltSection.Banking, IltSection.Gear, IltSection.Charms, IltSection.Games })
|
||||
{
|
||||
Check.True(IltSections.MovedCommand(kept) == null, $"{IltSections.Label(kept)} is still RynthILT's");
|
||||
Check.True(IltSections.IsTab(kept), $"{IltSections.Label(kept)} is a Mini Remote tab");
|
||||
}
|
||||
Check.True(IltSections.MovedCommand(IltSection.VaultedDungeons) == null && IltSections.IsTab(IltSection.VaultedDungeons),
|
||||
"Vaulted Dungeons is a RynthILT tab (shown only with the master switch, VaultedDungeonsTests)");
|
||||
Check.True(IltSections.Tabs.SequenceEqual(new[] { IltSection.Banking, IltSection.Gear, IltSection.Charms, IltSection.Games, IltSection.VaultedDungeons }),
|
||||
"the tab list is Banking, Gear, Charms, Games, Vaulted Dungeons");
|
||||
Check.False(IltSections.IsTab(IltSection.Character) || IltSections.IsTab(IltSection.Guardian), "Character and the Guardian aren't tabs");
|
||||
Check.True(IltSections.TryParse("char", out IltSection c) && c == IltSection.Character, "old Character names still parse (for the redirect)");
|
||||
Check.Eq(IltSections.OracleCharacterCommand, "/ro character", "Oracle command");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// RynthILT's RynthPluginGetSectionsJson: schema 1 (UI/Sections/SectionManifest.cs in RynthCore),
|
||||
/// every view an ILT one, each surface one RenderEmbed answers.
|
||||
/// </summary>
|
||||
private static void SectionsManifest()
|
||||
{
|
||||
// No Hub (before the character's name is known): the always-there views only.
|
||||
string bare = IltSectionsManifest.Build(IltSectionsManifest.TabsOf(null));
|
||||
using var doc = System.Text.Json.JsonDocument.Parse(bare);
|
||||
var root = doc.RootElement;
|
||||
Check.Eq(root.GetProperty("version").GetInt32(), 1, "schema 1");
|
||||
var sections = root.GetProperty("sections");
|
||||
Check.Eq(sections.GetArrayLength(), 2, "two sections of RynthILT's own");
|
||||
Check.Eq(sections[0].GetProperty("id").GetString(), "quests", "a Quests section (the /qb list)");
|
||||
Check.Eq(sections[1].GetProperty("id").GetString(), "games", "and Games (moved from RynthAi with the tabs)");
|
||||
var surfaces = new System.Collections.Generic.List<string>();
|
||||
foreach (var c in root.GetProperty("contributions").EnumerateArray())
|
||||
{
|
||||
Check.Eq(c.GetProperty("server").GetString(), "ilt", "an Infinite Leaftide view");
|
||||
surfaces.Add(c.GetProperty("surface").GetString() ?? "");
|
||||
}
|
||||
Check.True(surfaces.SequenceEqual(new[] { RynthILTPlugin.RatesSurface, RynthILTPlugin.FellowshipSurface, RynthILTPlugin.QuestBonusSurface,
|
||||
RynthILTPlugin.DynamicStampsSurface }),
|
||||
"rates, fellowship, quest bonus, Dynamic Stamps (from RynthOracle 2026-10-21): " + string.Join(",", surfaces));
|
||||
Check.True(surfaces.All(s => s.StartsWith("section:ilt-", StringComparison.Ordinal) && s.Length <= 64), "short section:ilt-* surfaces");
|
||||
Check.True(bare.All(ch => ch < 128), "ASCII only");
|
||||
|
||||
// The Mini Remote ILT tabs the Hub shows (RynthAi listed them until 2026-10-20): Gear not reported yet,
|
||||
// Games hidden, Charms and Banking shown.
|
||||
var tabs = new[]
|
||||
{
|
||||
new IltSectionsManifest.Tab("banking", 560, 520, Shown: true, Available: true),
|
||||
new IltSectionsManifest.Tab("gear", 560, 520, Shown: true, Available: false),
|
||||
new IltSectionsManifest.Tab("charms", 560, 520, Shown: true, Available: true),
|
||||
new IltSectionsManifest.Tab("games", 520, 440, Shown: false, Available: false),
|
||||
new IltSectionsManifest.Tab("character", 520, 440, Shown: true, Available: true),
|
||||
};
|
||||
string json = IltSectionsManifest.Build(tabs);
|
||||
var m = RynthCore.Engine.UI.Sections.SectionManifestParser.Parse("RynthILT", json, out string error);
|
||||
Check.Eq(error, string.Empty, "the engine's parser takes it");
|
||||
Check.Eq(m.Contributions.Length, 7, "rates, fellowship, /qb, Dynamic Stamps, Banking, Gear, Charms");
|
||||
var stamps = m.Contributions.Single(c => c.Surface == RynthILTPlugin.DynamicStampsSurface);
|
||||
Check.True(stamps.Section == "quests" && stamps.Primary && stamps.Server == "ilt" && stamps.Label == "Dynamic Stamps",
|
||||
"Dynamic Stamps: a page of RynthILT's Quests section, on ILT only");
|
||||
var gear = m.Contributions.Single(c => c.Surface == "section:gear");
|
||||
Check.True(gear.Section == "inventory" && !gear.Enabled && gear.Note.Length > 0, "Gear in Inventory, disabled with a note until reported");
|
||||
Check.True(m.Contributions.Any(c => c.Surface == "section:charms" && c.Enabled) && m.Contributions.Any(c => c.Surface == "section:banking" && c.Enabled),
|
||||
"Charms and Banking stay RynthILT's tabs");
|
||||
Check.False(m.Contributions.Any(c => c.Surface == "section:games"), "a hidden tab isn't listed");
|
||||
Check.False(m.Contributions.Any(c => c.Surface == "section:character"), "Character moved out: never placed");
|
||||
var iltOn = new RynthCore.Engine.UI.Sections.ServerState("ilt", "Infinite Leaftide", true, true, RynthCore.Engine.UI.Sections.ServerForce.Auto, true, "");
|
||||
var on = RynthCore.Engine.UI.Sections.SectionCatalog.Build(new[] { m }, _ => false, new[] { iltOn });
|
||||
Check.True(on.Single(v => v.Id == "inventory").Panes.Any(p => p.Title == "Charms" && p.Contribution?.Plugin == "RynthILT"),
|
||||
"on ILT the engine shows RynthILT's Charms in Inventory (drawn by RynthILT)");
|
||||
var off = RynthCore.Engine.UI.Sections.SectionCatalog.Build(new[] { m }, _ => false, new[] { iltOn with { Active = false } });
|
||||
Check.False(off.Single(v => v.Id == "inventory").Panes.Any(p => p.Title == "Charms"), "off ILT: none");
|
||||
Check.True(IltSectionsManifest.TryTabOf("section:banking", out IltSection bank) && bank == IltSection.Banking, "section:banking draws Banking");
|
||||
Check.False(IltSectionsManifest.TryTabOf("section:bank", out _), "only the tab's own id");
|
||||
Check.False(IltSectionsManifest.TryTabOf("section:pets", out _), "pets is RynthAi's");
|
||||
Check.False(IltSectionsManifest.TryTabOf("section:ilt-rates", out _), "not a tab");
|
||||
Check.True(RynthILTPlugin.IsParsedRemoteAction("servermenu") && RynthILTPlugin.IsParsedRemoteAction("ServerMenu")
|
||||
&& !RynthILTPlugin.IsParsedRemoteAction("prog"), "RynthCore's servermenu push is answered, never queued as a verb");
|
||||
}
|
||||
|
||||
private static void DormantOffIlt()
|
||||
{
|
||||
var off = NewHub("Aeshnidae", "dormant");
|
||||
off.OnLoginComplete("Tester", forceFromMigration: false);
|
||||
foreach (string line in new[] { "Your Pet Log:", "[BANK] Pyreals: 5", "Guardian of Strength tells you, \"x\"" }) off.OnChat(line);
|
||||
TickFor(off, 6800); // past the 6 s login delay
|
||||
Check.Eq(RynthCore.RynthAiHostTests.Fakes.FakeHost.ChatCommands.Count, 0, "off ILT: no probe, no command at all");
|
||||
Check.False(off.Options.IsIltLikeWorld, "not an ILT world");
|
||||
foreach (var s in IltSections.Tabs) Check.False(off.TabShown(s), $"no {IltSections.Label(s)} tab");
|
||||
Check.False(off.RenderSection(RynthServerHub.SectionRemoteBank) || off.RenderSection(RynthIltHub.SectionQuestBonus)
|
||||
|| off.RenderSection(RynthServerHub.SectionPetLogs) || off.RenderSection(RynthServerHub.SectionRemoteGuardian)
|
||||
|| off.RenderSection(RynthServerHub.SectionServerMenu), "no ILT section draws (checked before any ImGui call)");
|
||||
Check.True(off.BuildProgressionJson().StartsWith("{\"available\":false"), "Progression: not available");
|
||||
off.OnLogout();
|
||||
|
||||
var on = NewHub("InfiniteLeaftide", "awake");
|
||||
on.OnLoginComplete("Tester", forceFromMigration: false);
|
||||
TickFor(on, 6800);
|
||||
Check.True(on.Options.IsIltLikeWorld, "InfiniteLeaftide is ILT");
|
||||
Check.True(RynthCore.RynthAiHostTests.Fakes.FakeHost.ChatCommands.Count > 0, "on ILT the login probe asks the server");
|
||||
Check.False(RynthCore.RynthAiHostTests.Fakes.FakeHost.ChatCommands.Any(c => c.Contains("/ilt features", StringComparison.OrdinalIgnoreCase)),
|
||||
"the server is never asked for a feature list (the ILT profile is Rynth-side)");
|
||||
// Character moved out of the Mini Remote (RynthOracle's Character tab, Session Stats);
|
||||
// Charms and Banking are Infinite Leaftide's own screens and stay RynthILT's tabs.
|
||||
Check.False(on.TabShown(IltSection.Character), "Character is no Mini Remote tab any more");
|
||||
Check.Eq(on.TabShown(IltSection.Gear), on.Available, "Gear shows once the server features are known");
|
||||
Check.Eq(on.TabShown(IltSection.Charms), on.Available, "Charms too");
|
||||
on.OnLogout();
|
||||
|
||||
var forced = NewHub("Aeshnidae", "forced");
|
||||
forced.OnLoginComplete("Tester", forceFromMigration: true);
|
||||
Check.True(forced.Options.IsIltLikeWorld, "a migrated \"Force enable\" makes the world ILT for this character");
|
||||
forced.OnLogout();
|
||||
}
|
||||
|
||||
private static unsafe void HubTable()
|
||||
{
|
||||
Check.Eq(HubInterface.Query("RynthAi.Hub", 1), IntPtr.Zero, "another interface's name: not ours");
|
||||
Check.Eq(HubInterface.Query(RynthIltHub.InterfaceName, 2), IntPtr.Zero, "a newer version than we have: none");
|
||||
var t = (RynthServerHubApiV1*)HubInterface.Query(RynthIltHub.InterfaceName, 1);
|
||||
Check.True(t != null, "v1 is served");
|
||||
Check.Eq(t->Version, 1u, "Version 1");
|
||||
Check.Eq(t->StructSize, (uint)sizeof(RynthServerHubApiV1), "StructSize");
|
||||
Check.True(t->IsServerWorld != null && t->GetFeature != null && t->GetRates != null && t->GetForceServer != null && t->SetForceServer != null
|
||||
&& t->GetTabs != null && t->RenderTab != null && t->RenderSection != null && t->Command != null
|
||||
&& t->AllowSummonOnEmpty != null && t->GetSubTabs != null && t->GetSetting != null && t->SetSetting != null,
|
||||
"every function is filled in");
|
||||
Check.True(RynthServerHubApiV1.Has(t, RynthServerHubApiV1.GetSubTabsOffset), "the appended functions are inside StructSize");
|
||||
Check.Eq((IntPtr)t, HubInterface.Query(RynthIltHub.InterfaceName, 1), "the same table each time");
|
||||
Check.Eq((IntPtr)t, HubInterface.Query(RynthServerHubApiV1.InterfaceName, 1),
|
||||
"and under the server-neutral name RynthAi asks the active server's owner for (RynthServer.Hub)");
|
||||
|
||||
// No plugin instance here (not logged in): every function answers "nothing".
|
||||
Check.Eq(t->IsServerWorld(), 0, "not ILT before login");
|
||||
byte* key = stackalloc byte[] { (byte)'b', (byte)'a', (byte)'n', (byte)'k', 0 };
|
||||
Check.Eq(t->GetFeature(key), -1, "feature unknown before login");
|
||||
Check.Eq(t->GetTabs(null, 0), 0, "no tabs before login");
|
||||
Check.Eq(t->Command(key), 0, "no command taken before login");
|
||||
Check.Eq(t->AllowSummonOnEmpty(), 0, "no summon from empty before login");
|
||||
byte* pets = stackalloc byte[] { (byte)'p', (byte)'e', (byte)'t', (byte)'s', 0 };
|
||||
Check.Eq(t->GetSubTabs(pets, null, 0), 0, "no Pets sub-tabs before login");
|
||||
Check.Eq(t->GetSetting(pets), -1, "no setting offered before login");
|
||||
Check.Eq(t->SetSetting(pets, 1), 0, "and none taken");
|
||||
|
||||
HubInterface.Release();
|
||||
Check.Eq(t->Version, 0u, "Release zeroes Version (callers re-query)");
|
||||
Check.Eq(HubInterface.Query(RynthIltHub.InterfaceName, 1), IntPtr.Zero, "and nothing is served after shutdown");
|
||||
Check.Eq(t->IsServerWorld(), 0, "the old table stays callable and answers nothing");
|
||||
}
|
||||
}
|
||||
189
Tools/RynthILT.Tests/PetAutomationTests.cs
Normal file
189
Tools/RynthILT.Tests/PetAutomationTests.cs
Normal file
|
|
@ -0,0 +1,189 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using RynthCore.Plugin.RynthILT.Hub;
|
||||
using RynthCore.Plugin.Shared;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthILT.Tests;
|
||||
|
||||
// ACECustom's parts of RynthAi's Pets tab moved to RynthILT on 2026-10-20 (Hub/IltPetAutomation.cs):
|
||||
// the pet charms, the summon-from-empty refill gate RynthAi's PetManager asks through RynthILT.Hub,
|
||||
// siphon-lens auto-capture and the Breeding sub-tab offer. Their settings are copied once from the
|
||||
// character's RynthAi miniremote.json (IltMigration.ImportRynthAiSettings).
|
||||
internal static class PetAutomationTests
|
||||
{
|
||||
private const uint Player = 0x50000A01;
|
||||
private const uint Lens = 0x80000A02;
|
||||
private const uint Mob = 0x80000A03;
|
||||
private const uint Charm = 0x80000A04;
|
||||
private const uint Lb = 0xA9B40000;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("pets (RynthILT): summon from empty needs the opt-in, an active refill charm and the server's word; never off ILT", RefillGate);
|
||||
r.Add("pets (RynthILT): auto-capture uses the lens on a weak creature in range only, and only when switched on", Capture);
|
||||
r.Add("pets (RynthILT): the Breeding sub-tab is offered on ILT unless the server reports breeding off", BreedingSubTab);
|
||||
r.Add("pets (RynthILT): off ILT the Pets sections draw nothing and nothing ticks", DormantOffIlt);
|
||||
r.Add("migration: the Pets tab's ACECustom options come over from RynthAi's miniremote.json once", ImportsPetSettings);
|
||||
}
|
||||
|
||||
private static IltHubController NewHub(string world, string folder, Action? setup = null)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.WorldName = world;
|
||||
FakeHost.ContentsCalls = true;
|
||||
FakeHost.WeaponCalls = true; // UseObject, RequestId, appraisal state
|
||||
FakeHost.LiveObjectsCalls = true;
|
||||
FakeHost.Names[Player] = "Petter";
|
||||
FakeHost.Positions[Player] = (Lb | 0x1C, 96f, 96f, 0f);
|
||||
setup?.Invoke();
|
||||
var host = FakeHost.Create(Player);
|
||||
string dir = Path.Combine(Program.TempRoot, "pets-" + folder);
|
||||
if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true);
|
||||
Directory.CreateDirectory(dir);
|
||||
var hub = new IltHubController(host, dir, new IltSettings(), new RynthAiClient(host));
|
||||
hub.OnLoginComplete("Petter", forceFromMigration: false);
|
||||
return hub;
|
||||
}
|
||||
|
||||
private static void Carry(uint id, string name, uint wcid)
|
||||
{
|
||||
FakeHost.Names[id] = name;
|
||||
FakeHost.ItemTypes[id] = 0x80; // misc
|
||||
FakeHost.Containers[id] = Player;
|
||||
FakeHost.Wcids[id] = wcid;
|
||||
}
|
||||
|
||||
private static void RefillGate()
|
||||
{
|
||||
var hub = NewHub("InfiniteLeaftide", "refill", () => FakeHost.Bools[(Player, IltInventory.BoolPyrealRefillActive)] = true);
|
||||
var pets = hub.PetAutomation;
|
||||
Check.False(pets.ComputeAllowSummonOnEmpty(), "not opted in: no summon from empty");
|
||||
hub.State.Pet.RefillFromEmpty = true;
|
||||
Check.True(pets.ComputeAllowSummonOnEmpty(), "opted in, and the server stamped the refill bool (active and confirmed)");
|
||||
|
||||
var charmOnly = NewHub("InfiniteLeaftide", "refill-charm", () =>
|
||||
{
|
||||
Carry(Charm, "Summon Essence Refill Charm", IltInventory.WcidSummonRefillCharm);
|
||||
FakeHost.Strings[(Charm, IltInventory.StrUse)] = "Toggles the refill. Status: ON";
|
||||
});
|
||||
charmOnly.State.Pet.RefillFromEmpty = true;
|
||||
Check.True(charmOnly.PetAutomation.RefillCharmActive(), "the carried charm reads ON");
|
||||
Check.False(charmOnly.PetAutomation.ComputeAllowSummonOnEmpty(), "but the server hasn't confirmed pet_refill: never spend");
|
||||
charmOnly.Options.Set(IltFeature.PetRefill, IltTri.On);
|
||||
Check.True(charmOnly.PetAutomation.ComputeAllowSummonOnEmpty(), "confirmed: summon from empty");
|
||||
charmOnly.Tick();
|
||||
Check.True(charmOnly.PetAutomation.AllowSummonOnEmpty, "the tick caches it for RynthAi (RynthILT.Hub AllowSummonOnEmpty)");
|
||||
|
||||
var off = NewHub("Aeshnidae", "refill-off", () => FakeHost.Bools[(Player, IltInventory.BoolPyrealRefillActive)] = true);
|
||||
off.State.Pet.RefillFromEmpty = true;
|
||||
Check.False(off.PetAutomation.ComputeAllowSummonOnEmpty(), "off ILT: never");
|
||||
off.Tick();
|
||||
Check.False(off.PetAutomation.AllowSummonOnEmpty, "and nothing cached for RynthAi");
|
||||
}
|
||||
|
||||
private static void Capture()
|
||||
{
|
||||
var hub = NewHub("InfiniteLeaftide", "capture", () =>
|
||||
{
|
||||
Carry(Lens, "Flawed Siphon Lens", PetCaptureRules.Lenses[0].Wcid);
|
||||
FakeHost.Names[Mob] = "Drudge Skulker";
|
||||
FakeHost.ItemTypes[Mob] = 0x10; // creature
|
||||
FakeHost.Positions[Mob] = (Lb | 0x1C, 96f, 99f, 0f); // 3 m
|
||||
FakeHost.TargetVitals[Mob] = (100, 100);
|
||||
});
|
||||
var pets = hub.PetAutomation;
|
||||
long now = Environment.TickCount64; // the chat replies time their back-off on the real clock
|
||||
pets.TickCapture(now);
|
||||
Check.Eq(FakeHost.Uses.Count, 0, "switched off: no lens used");
|
||||
Check.Eq(pets.CaptureStatus, "off", "status off");
|
||||
|
||||
hub.State.Pet.AutoCapture = true;
|
||||
pets.TickCapture(now);
|
||||
Check.Eq(FakeHost.Uses.Count, 0, "a full-health creature: no lens");
|
||||
Check.True(pets.CaptureStatus.Contains("Drudge Skulker") && pets.CaptureStatus.Contains("need"), "it says what it waits for");
|
||||
|
||||
FakeHost.TargetVitals[Mob] = (15, 100);
|
||||
pets.TickCapture(now + 1000);
|
||||
Check.Eq(FakeHost.Uses.Count, 1, "15%: the lens is used");
|
||||
Check.Eq(FakeHost.Uses[0], Lens, "the chosen lens");
|
||||
pets.TickCapture(now + 1500);
|
||||
Check.Eq(FakeHost.Uses.Count, 1, "the cooldown holds the next use back");
|
||||
pets.OnChat("The creature is too strong to be siphoned.");
|
||||
Check.True(pets.CaptureStatus.StartsWith("refused"), "a refusal is noted");
|
||||
|
||||
FakeHost.Positions[Mob] = (Lb | 0x1C, 96f, 110f, 0f); // 14 m
|
||||
pets.TickCapture(now + 60_000);
|
||||
Check.Eq(FakeHost.Uses.Count, 1, "out of range: no lens");
|
||||
|
||||
hub.Options.Set(RynthIltHub.FeatureMonsterCapture, IltTri.Off);
|
||||
FakeHost.Positions[Mob] = (Lb | 0x1C, 96f, 99f, 0f);
|
||||
pets.TickCapture(now + 120_000);
|
||||
Check.Eq(FakeHost.Uses.Count, 1, "the server reports monster capture off: no lens");
|
||||
Check.True(pets.CaptureStatus.Contains("disabled"), "and says so");
|
||||
}
|
||||
|
||||
private static void BreedingSubTab()
|
||||
{
|
||||
var on = NewHub("InfiniteLeaftide", "breed-on");
|
||||
var tabs = on.SubTabs(RynthServerHub.TabParentPets);
|
||||
Check.Eq(tabs.Length, 1, "one Pets sub-tab on ILT");
|
||||
Check.Eq(tabs[0].Id, RynthIltHub.SectionPetBreeding, "Breeding, drawn as the pets-breeding section");
|
||||
Check.Eq(on.SubTabs("crafting").Length, 0, "nothing for another tab");
|
||||
on.Options.Set(RynthIltHub.FeaturePetBreeding, IltTri.Off);
|
||||
Check.Eq(on.SubTabs(RynthServerHub.TabParentPets).Length, 0, "the server reports breeding off: none");
|
||||
|
||||
var off = NewHub("Aeshnidae", "breed-off");
|
||||
Check.Eq(off.SubTabs(RynthServerHub.TabParentPets).Length, 0, "off ILT: none");
|
||||
}
|
||||
|
||||
private static void DormantOffIlt()
|
||||
{
|
||||
var off = NewHub("Aeshnidae", "dormant", () =>
|
||||
{
|
||||
Carry(Lens, "Flawed Siphon Lens", PetCaptureRules.Lenses[0].Wcid);
|
||||
FakeHost.Names[Mob] = "Drudge Skulker";
|
||||
FakeHost.ItemTypes[Mob] = 0x10;
|
||||
FakeHost.Positions[Mob] = (Lb | 0x1C, 96f, 99f, 0f);
|
||||
FakeHost.TargetVitals[Mob] = (1, 100);
|
||||
});
|
||||
off.State.Pet.AutoCapture = true;
|
||||
for (int i = 0; i < 5; i++) { off.Tick(); System.Threading.Thread.Sleep(60); }
|
||||
Check.Eq(FakeHost.Uses.Count, 0, "off ILT the capture never ticks (no lens used)");
|
||||
Check.False(off.RenderSection(RynthServerHub.SectionPetCharms) || off.RenderSection(RynthServerHub.SectionPetCapture),
|
||||
"the Pets sections draw nothing (checked before any ImGui call)");
|
||||
}
|
||||
|
||||
private static void ImportsPetSettings()
|
||||
{
|
||||
string legacy = Path.Combine(IltMigration.LegacyProfilesBase, "InfiniteLeaftide", "Petter");
|
||||
Directory.CreateDirectory(legacy);
|
||||
File.WriteAllText(Path.Combine(legacy, "Default.json"), "{}");
|
||||
File.WriteAllText(Path.Combine(legacy, IltMigration.LegacyMiniRemoteFile),
|
||||
"{ \"Pet\": { \"HealingEnabled\": true, \"UsePyrealRefillPath\": true, \"AutoCaptureEnabled\": true, \"CaptureLensIndex\": 3 } }");
|
||||
var state = new IltHubState();
|
||||
Check.False(state.Pet.RefillFromEmpty || state.Pet.AutoCapture, "RynthILT's defaults: both off");
|
||||
var lines = IltMigration.ImportRynthAiSettings(state, "InfiniteLeaftide", "Petter");
|
||||
Check.True(state.RynthAiSettingsImported, "marked done");
|
||||
Check.True(state.Pet.RefillFromEmpty, "summon from empty came over");
|
||||
Check.True(state.Pet.AutoCapture, "auto-capture came over");
|
||||
Check.Eq(state.Pet.CaptureLens, 3, "the lens came over");
|
||||
Check.True(lines.Any(l => l.Contains("auto-capture on")), "and the log line says so");
|
||||
|
||||
state.Pet.AutoCapture = false; // changed in RynthILT afterwards
|
||||
Check.Eq(IltMigration.ImportRynthAiSettings(state, "InfiniteLeaftide", "Petter").Count, 0, "the second login does nothing");
|
||||
Check.False(state.Pet.AutoCapture, "RynthILT's own change stays");
|
||||
|
||||
var fresh = new IltHubState();
|
||||
IltMigration.ImportRynthAiSettings(fresh, "InfiniteLeaftide", "Nobody");
|
||||
Check.True(fresh.RynthAiSettingsImported && !fresh.Pet.AutoCapture && !fresh.Pet.RefillFromEmpty,
|
||||
"a character without RynthAi files keeps the defaults (and is marked done)");
|
||||
|
||||
File.WriteAllText(Path.Combine(legacy, IltMigration.LegacyMiniRemoteFile), "{ broken");
|
||||
var broken = new IltHubState();
|
||||
IltMigration.ImportRynthAiSettings(broken, "InfiniteLeaftide", "Petter");
|
||||
Check.True(broken.RynthAiSettingsImported && !broken.Pet.AutoCapture, "an unreadable miniremote.json: defaults, no exception");
|
||||
}
|
||||
}
|
||||
109
Tools/RynthILT.Tests/PetCaptureRulesTests.cs
Normal file
109
Tools/RynthILT.Tests/PetCaptureRulesTests.cs
Normal file
|
|
@ -0,0 +1,109 @@
|
|||
// ACECustom MonsterCapture health / range / lens table — matches Source/ACE.Server/Entity/MonsterCapture.cs.
|
||||
// Moved from RynthCore.RynthAiTests with the rules (RynthILT's IltPetCaptureRules since 2026-10-20).
|
||||
using RynthCore.Plugin.RynthILT.Hub;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthILT.Tests;
|
||||
|
||||
internal static class PetCaptureRulesTests
|
||||
{
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("pet capture: health gate matches ACECustom (≤20% or under 20 HP)", HealthGate);
|
||||
r.Add("pet capture: Asheron's Lens bypasses the health gate", AsheronsBypass);
|
||||
r.Add("pet capture: range is 5 m; dead creatures are never capturable", RangeAndDead);
|
||||
r.Add("pet capture: lens WCIDs match PetGuideController", LensWcids);
|
||||
r.Add("pet capture: a creature is left alone after 5 tries with no capture, then retried after the block", ThrottlePerTarget);
|
||||
r.Add("pet capture: 15 lens uses with no capture anywhere trip the backstop; a success resets it", ThrottleBackstop);
|
||||
}
|
||||
|
||||
private static void HealthGate()
|
||||
{
|
||||
// Full health — refuse.
|
||||
Check.False(PetCaptureRules.IsWeakEnough(100, 100), "100/100 too strong");
|
||||
Check.False(PetCaptureRules.IsWeakEnough(21, 100), "21% and ≥20 HP too strong");
|
||||
|
||||
// Fraction gate.
|
||||
Check.True(PetCaptureRules.IsWeakEnough(20, 100), "20% exactly is allowed");
|
||||
Check.True(PetCaptureRules.IsWeakEnough(1, 100), "1% allowed");
|
||||
|
||||
// Absolute HP gate (high % but under 20 HP).
|
||||
Check.True(PetCaptureRules.IsWeakEnough(15, 50), "15/50 = 30% but under 20 HP");
|
||||
Check.True(PetCaptureRules.IsWeakEnough(19, 19), "19/19 under 20 HP");
|
||||
|
||||
// Ratio-only path (no absolute HP): only the fraction half.
|
||||
Check.True(PetCaptureRules.IsWeakEnoughRatio(0.20f), "ratio 0.20");
|
||||
Check.False(PetCaptureRules.IsWeakEnoughRatio(0.21f), "ratio 0.21");
|
||||
Check.False(PetCaptureRules.IsWeakEnoughRatio(0f), "ratio 0 = dead");
|
||||
Check.False(PetCaptureRules.IsWeakEnough(0, 100), "0 current = dead");
|
||||
}
|
||||
|
||||
private static void AsheronsBypass()
|
||||
{
|
||||
var asheron = PetCaptureRules.LensAt(4);
|
||||
Check.Eq(asheron.Wcid, 78780012u, "Asheron's WCID");
|
||||
Check.True(asheron.BypassesHealthGate, "bypasses health");
|
||||
Check.True(PetCaptureRules.CanAttempt(asheron, 100, 100), "full health ok for Asheron's");
|
||||
Check.False(PetCaptureRules.CanAttempt(asheron, 0, 100), "still not when dead");
|
||||
|
||||
var flawed = PetCaptureRules.LensAt(0);
|
||||
Check.False(PetCaptureRules.CanAttempt(flawed, 100, 100), "Flawed refuses full health");
|
||||
Check.True(PetCaptureRules.CanAttempt(flawed, 10, 100), "Flawed at 10%");
|
||||
}
|
||||
|
||||
private static void RangeAndDead()
|
||||
{
|
||||
Check.Eq(PetCaptureRules.CaptureRangeM, 5.0f, "5 m range");
|
||||
Check.True(PetCaptureRules.InRange(0), "at feet");
|
||||
Check.True(PetCaptureRules.InRange(5.0), "at 5 m");
|
||||
Check.False(PetCaptureRules.InRange(5.01), "past 5 m");
|
||||
Check.False(PetCaptureRules.InRange(-1), "unknown distance");
|
||||
}
|
||||
|
||||
private static void LensWcids()
|
||||
{
|
||||
Check.Eq(PetCaptureRules.Lenses.Length, 5, "five selectable lenses");
|
||||
Check.Eq(PetCaptureRules.LensAt(0).Wcid, 78780001u, "Flawed");
|
||||
Check.Eq(PetCaptureRules.LensAt(1).Wcid, 78780002u, "Pristine");
|
||||
Check.Eq(PetCaptureRules.LensAt(2).Wcid, 78780003u, "Perfect");
|
||||
Check.Eq(PetCaptureRules.LensAt(3).Wcid, 78780010u, "Resonance");
|
||||
Check.Eq(PetCaptureRules.LensAt(4).Wcid, 78780012u, "Asheron's");
|
||||
Check.Eq(PetCaptureRules.LensNames.Length, PetCaptureRules.Lenses.Length, "combo labels match");
|
||||
}
|
||||
|
||||
private static void ThrottlePerTarget()
|
||||
{
|
||||
var t = new PetCaptureThrottle();
|
||||
long now = 1000;
|
||||
for (int i = 0; i < PetCaptureThrottle.MaxTriesPerTarget; i++)
|
||||
{
|
||||
Check.True(t.MayAttempt(7, now), $"try {i + 1} allowed");
|
||||
t.RecordAttempt(7, now);
|
||||
now += 2500;
|
||||
}
|
||||
Check.False(t.MayAttempt(7, now), "5 tries used: blocked");
|
||||
Check.True(t.BlockedSecondsLeft(7, now) > 0, "block time left reported");
|
||||
Check.True(t.MayAttempt(8, now), "another creature is not blocked");
|
||||
Check.False(t.MayAttempt(7, now + PetCaptureThrottle.TargetBlockMs - 3000), "still blocked just before the block ends");
|
||||
Check.True(t.MayAttempt(7, now + PetCaptureThrottle.TargetBlockMs + 1), "block served: tries again");
|
||||
t.RecordAttempt(7, now + PetCaptureThrottle.TargetBlockMs + 1);
|
||||
Check.True(t.MayAttempt(7, now + PetCaptureThrottle.TargetBlockMs + 2), "a fresh set of tries after the block");
|
||||
}
|
||||
|
||||
private static void ThrottleBackstop()
|
||||
{
|
||||
var t = new PetCaptureThrottle();
|
||||
long now = 0;
|
||||
for (int i = 0; i < PetCaptureThrottle.MaxTriesWithoutSuccess; i++)
|
||||
{
|
||||
Check.False(t.Exhausted, $"not exhausted before use {i + 1}");
|
||||
t.RecordAttempt(100 + i, now); // a new creature each time: per-target never trips
|
||||
now += 2500;
|
||||
}
|
||||
Check.True(t.Exhausted, "15 uses over many creatures, no capture: exhausted");
|
||||
Check.False(t.MayAttempt(999, now), "nothing more is allowed");
|
||||
t.RecordSuccess();
|
||||
Check.False(t.Exhausted, "a capture reply resets the backstop");
|
||||
Check.True(t.MayAttempt(100, now), "and the per-target blocks");
|
||||
}
|
||||
}
|
||||
98
Tools/RynthILT.Tests/ProfileTests.cs
Normal file
98
Tools/RynthILT.Tests/ProfileTests.cs
Normal file
|
|
@ -0,0 +1,98 @@
|
|||
using System;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using RynthCore.Plugin.RynthILT;
|
||||
using RynthCore.Plugin.RynthILT.Hub;
|
||||
using RynthCore.Plugin.Shared;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthILT.Tests;
|
||||
|
||||
// RynthILT's "RynthServer.Profile" (ProfileInterface.cs): the same interface and JSON the server
|
||||
// plugins serve, for "ilt", carrying Infinite Leaftide's tinkering salvage (Hub/IltSalvage.cs).
|
||||
// The JSON is read back with the shared reader RynthAi's Crafting tab uses (EngineServerState.cs:
|
||||
// ServerSalvageView.ParseList), so the rows it plans with are the ones checked here. 2026-10-15.
|
||||
internal static unsafe class ProfileTests
|
||||
{
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("profile: RynthILT serves RynthServer.Profile for ilt", Interface);
|
||||
r.Add("profile: ILT's salvage reaches the Crafting tab's reader (Leather after the cap, jewelry stack)", Salvage);
|
||||
r.Add("profile: ILT's trinkets reach the Crafting tab's reader (RynthAi's TinkerCatalog rule until 2026-10-20)", Trinkets);
|
||||
}
|
||||
|
||||
private static void Interface()
|
||||
{
|
||||
Check.Eq(ProfileInterface.Query("RynthILT.Hub", 1), IntPtr.Zero, "another interface's name: not this table");
|
||||
Check.Eq(ProfileInterface.Query(RynthServerProfileApiV1.InterfaceName, 2), IntPtr.Zero, "a newer version than we have: none");
|
||||
var t = (RynthServerProfileApiV1*)ProfileInterface.Query(RynthServerProfileApiV1.InterfaceName, 1);
|
||||
Check.True(t != null, "the table");
|
||||
Check.Eq(t->Version, RynthServerProfileApiV1.InterfaceVersion, "version");
|
||||
Check.Eq(t->StructSize, (uint)sizeof(RynthServerProfileApiV1), "struct size");
|
||||
Check.True(t->GetProfileJson != null, "GetProfileJson");
|
||||
|
||||
string json = ProfileInterface.CurrentJson(true, "InfiniteLeaftide");
|
||||
using JsonDocument doc = JsonDocument.Parse(json);
|
||||
JsonElement root = doc.RootElement;
|
||||
Check.Eq(root.GetProperty("schema").GetInt32(), RynthServerProfile.Schema, "schema");
|
||||
Check.Eq(root.GetProperty("id").GetString(), "ilt", "the engine's ILT id");
|
||||
Check.Eq(root.GetProperty("name").GetString(), "Infinite Leaftide", "name");
|
||||
Check.Eq(root.GetProperty("plugin").GetString(), "RynthILT", "plugin");
|
||||
Check.True(root.GetProperty("active").GetBoolean(), "active");
|
||||
Check.Eq(root.GetProperty("world").GetString(), "InfiniteLeaftide", "world");
|
||||
Check.Eq(root.GetProperty("hosts")[0].GetString(), "infiniteleaftide.online", "hosts from the csproj");
|
||||
Check.Eq(ProfileInterface.CurrentJson(true, "InfiniteLeaftide"), json, "unchanged state: the same JSON");
|
||||
Check.False(JsonDocument.Parse(ProfileInterface.CurrentJson(false, null)).RootElement.GetProperty("active").GetBoolean(),
|
||||
"before the Hub is up: not active");
|
||||
}
|
||||
|
||||
private static void Trinkets()
|
||||
{
|
||||
var rule = ServerTrinketRule.Parse(ProfileInterface.CurrentJson(true, "InfiniteLeaftide"));
|
||||
Check.True(rule != ServerTrinketRule.None, "the profile carries a trinket rule");
|
||||
foreach (string t in new[] { "Ornate Compass", "Tinker's Goggles", "Jade Scarab", "Pocket Watch", "Puzzle Box", "Spinning Top" })
|
||||
Check.True(rule.IsTrinket(t), t + " is a trinket");
|
||||
foreach (string j in new[] { "Yellow Topaz Ring", "Gold Necklace", "Silver Bracelet" })
|
||||
Check.False(rule.IsTrinket(j), j + " is Jewelry");
|
||||
}
|
||||
|
||||
private static void Salvage()
|
||||
{
|
||||
var rows = ServerSalvageView.ParseList(ProfileInterface.CurrentJson(true, "InfiniteLeaftide"));
|
||||
Check.Eq(rows.Count, IltSalvage.Rows.Length, "every row arrives");
|
||||
for (int i = 0; i < rows.Count; i++)
|
||||
{
|
||||
var a = IltSalvage.Rows[i];
|
||||
var b = rows[i];
|
||||
bool same = a.Bench == b.Bench && a.Material == b.Material && a.Kind == b.Kind && a.Effect == b.Effect
|
||||
&& a.UsesTinkSlot == b.UsesTinkSlot && a.NameMatch == b.NameMatch && a.AppliedInt == b.AppliedInt
|
||||
&& a.Prepared == b.Prepared && a.Order == b.Order && a.AfterCap == b.AfterCap
|
||||
&& a.StackGroup == b.StackGroup && a.StackCap == b.StackCap;
|
||||
Check.True(same, $"row {i} ({a.Bench} {a.Material}) round-trips");
|
||||
}
|
||||
|
||||
const int Leather = 52, Steel = 64, Serpentine = 71, Silver = 63, Diamond = 20, BlackGarnet = 15;
|
||||
foreach (string bench in new[] { "melee", "missile", "caster" })
|
||||
{
|
||||
var leather = rows.Single(r => r.Bench == bench && r.Material == Leather);
|
||||
Check.True(leather.AfterCap, bench + " Leather: after the cap");
|
||||
Check.False(leather.UsesTinkSlot, bench + " Leather: no tink slot");
|
||||
Check.Eq(leather.Kind, "once", bench + " Leather: once");
|
||||
Check.Eq(leather.Order, 995, bench + " Leather: last");
|
||||
}
|
||||
Check.Eq(rows.Count(r => r.AfterCap), 3, "only the weapon Leathers wait for the cap");
|
||||
|
||||
var stack = rows.Where(r => r.StackGroup.Length > 0).ToList();
|
||||
Check.Eq(string.Join(",", stack.Select(r => r.Bench + ":" + r.Material)), $"jewelry:{Serpentine},jewelry:{Steel}", "Serpentine + Steel stack");
|
||||
Check.True(stack.All(r => r.StackGroup == "jewelry-stack" && r.StackCap == 10 && r.Kind == "tink" && !r.UsesTinkSlot),
|
||||
"one group, cap 10, repeatable, no tink slot");
|
||||
|
||||
Check.Eq(rows.Single(r => r.Bench == "jewelry" && r.Material == Silver).AppliedInt, 374, "jewelry Silver flag int");
|
||||
var diamond = rows.Single(r => r.Bench == "trinkets" && r.Material == Diamond);
|
||||
Check.True(diamond.Prepared && diamond.AppliedInt == 384 && diamond.Order == 10, "trinket Diamond: prepared, flag 384, first");
|
||||
Check.Eq(rows.Count(r => r.Prepared), 4, "the four trinket tiers are prepared");
|
||||
Check.True(rows.Where(r => r.Material == BlackGarnet).All(r => r.NameMatch == "Abyssal" && r.UsesTinkSlot),
|
||||
"Abyssal-Touched Gems by bag name, using a tink slot");
|
||||
Check.False(rows.Any(r => r.Bench is "armor" or "items"), "no armor or item rows");
|
||||
}
|
||||
}
|
||||
64
Tools/RynthILT.Tests/Program.cs
Normal file
64
Tools/RynthILT.Tests/Program.cs
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthILT.Tests;
|
||||
|
||||
// Offline tests for the RynthILT plugin: the ACECustom bounty tracker (parsing, merging, the
|
||||
// quiet /bounty list read loop on a fake clock, persistence, the bridge JSON) and the ILT Hub
|
||||
// (attribute raiser, aug costs, bank commands, sigil chain, and the move out of RynthAi: data
|
||||
// migration, the RynthILT.Hub table, verb routing, the object view) and its RynthServer.Profile
|
||||
// (ILT's tinkering salvage). Each test prints PASS / FAIL.
|
||||
//
|
||||
// Run: dotnet run -c Release (all tests)
|
||||
// dotnet run -c Release -- window (tests whose name contains "window")
|
||||
internal static class Program
|
||||
{
|
||||
/// <summary>Scratch folder next to the exe for files tests write. Emptied at start.</summary>
|
||||
public static string TempRoot { get; } = Path.Combine(AppContext.BaseDirectory, "scratch");
|
||||
|
||||
private static int Main(string[] args)
|
||||
{
|
||||
if (Directory.Exists(TempRoot)) Directory.Delete(TempRoot, recursive: true);
|
||||
Directory.CreateDirectory(TempRoot);
|
||||
|
||||
// SAFETY: every file the ILT Hub would write under %APPDATA%\RynthCore\RynthILT or read from
|
||||
// the RynthAi folder points at the scratch folder before any test runs.
|
||||
RynthCore.Plugin.RynthILT.Hub.IltAugCosts.FilePath = Path.Combine(TempRoot, "ilt-aug-costs.json");
|
||||
RynthCore.Plugin.RynthILT.Hub.IltHubStore.SharedRoot = Path.Combine(TempRoot, "RynthILT");
|
||||
RynthCore.Plugin.RynthILT.Hub.IltSettingsStore.Folder = Path.Combine(TempRoot, "RynthILT");
|
||||
RynthCore.Plugin.RynthILT.Hub.IltMigration.LegacyProfilesBase = Path.Combine(TempRoot, "RynthAi", "SettingsProfiles");
|
||||
RynthCore.Plugin.RynthILT.Hub.IltMigration.LegacySharedRoot = Path.Combine(TempRoot, "RynthAi");
|
||||
RynthCore.Plugin.RynthILT.RynthLog.Init(default, Path.Combine(TempRoot, "Logs"));
|
||||
RynthCore.Plugin.Shared.DataWriteGuard.PluginName = "RynthILT"; // as RynthILTPlugin.Initialize sets it
|
||||
|
||||
var runner = new Runner();
|
||||
BountyTests.Register(runner);
|
||||
BountyReviewTests.Register(runner);
|
||||
AttributeRaiserTests.Register(runner);
|
||||
SigilChainTests.Register(runner);
|
||||
BankCommandTests.Register(runner);
|
||||
MoveTests.Register(runner);
|
||||
ChunkTests.Register(runner);
|
||||
ProfileTests.Register(runner);
|
||||
FeatureCatalogTests.Register(runner);
|
||||
IltSettingsTests.Register(runner);
|
||||
FellowshipCommandTests.Register(runner);
|
||||
AetheriaChunkTests.Register(runner);
|
||||
ChunkTargetTests.Register(runner);
|
||||
RingChainTests.Register(runner);
|
||||
VaultedDungeonsTests.Register(runner);
|
||||
PetCaptureRulesTests.Register(runner);
|
||||
PetAutomationTests.Register(runner);
|
||||
RingEvadeTests.Register(runner);
|
||||
VaultedSwitchTests.Register(runner);
|
||||
T11Tests.Register(runner);
|
||||
RemoteTabTests.Register(runner);
|
||||
StampTests.Register(runner);
|
||||
BankRosterTests.Register(runner);
|
||||
// Before DataApiTests: its last test releases the RynthILT.Data table, which the breeding version test queries.
|
||||
BreedingTests.Register(runner);
|
||||
DataApiTests.Register(runner);
|
||||
return runner.Run("RynthILT tests", args.Length > 0 ? args[0] : null);
|
||||
}
|
||||
}
|
||||
94
Tools/RynthILT.Tests/RemoteTabTests.cs
Normal file
94
Tools/RynthILT.Tests/RemoteTabTests.cs
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using RynthCore.Plugin.RynthILT.Hub;
|
||||
using RynthCore.Plugin.Shared;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthILT.Tests;
|
||||
|
||||
// The ILT parts of RynthAi's Remote tab moved to RynthILT on 2026-10-20: the coin / pyreal lines under
|
||||
// RynthAi's Stats ("remote-stats"), the session report's tail (GetText "session-report"), the Bank and
|
||||
// Guardian sections' switches (RynthILT's own now, drawn in RynthAi's Options popup, "remote-options"),
|
||||
// and the coin session restarting with RynthAi's shared session instead of RynthAi sending "rates reset".
|
||||
internal static class RemoteTabTests
|
||||
{
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("remote tab (RynthILT): its texts for RynthAi (server id, the session report's coins) and none off ILT", Texts);
|
||||
r.Add("remote tab (RynthILT): Bank / Guardian follow RynthILT's own switches; the stats and options draw nothing off ILT", Switches);
|
||||
r.Add("remote tab (RynthILT): the coins start over when RynthAi's shared session restarts", FollowsSession);
|
||||
r.Add("migration: RynthAi's huds.json Bank / Guardian switches come over once", ImportsSwitches);
|
||||
}
|
||||
|
||||
private static IltHubController NewHub(string world, string folder)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeAiHub.Reset();
|
||||
FakeHost.WorldName = world;
|
||||
var host = FakeHost.Create(0x50000D21);
|
||||
var ai = new RynthAiClient(host);
|
||||
ai.UseTableForTests(FakeAiHub.Table);
|
||||
string dir = Path.Combine(Program.TempRoot, "remote-" + folder);
|
||||
if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true);
|
||||
Directory.CreateDirectory(dir);
|
||||
var hub = new IltHubController(host, dir, new IltSettings(), ai);
|
||||
hub.OnLoginComplete("Remoter", forceFromMigration: false);
|
||||
return hub;
|
||||
}
|
||||
|
||||
private static void Texts()
|
||||
{
|
||||
var on = NewHub("InfiniteLeaftide", "texts-on");
|
||||
Check.Eq(on.GetText(RynthServerHub.TextServerId), "ilt", "its tabs belong to RynthCore's 'ilt'");
|
||||
string tail = on.GetText(RynthServerHub.TextSessionReport);
|
||||
Check.True(tail.StartsWith(", Coins ") && tail.Contains("/h, Pyr "), "the session report's tail: coins and pyreals per hour");
|
||||
Check.Eq(on.GetText("no-such-text"), string.Empty, "an unknown id: nothing");
|
||||
|
||||
var off = NewHub("Aeshnidae", "texts-off");
|
||||
Check.Eq(off.GetText(RynthServerHub.TextSessionReport), string.Empty, "off ILT: no coins in RynthAi's report");
|
||||
}
|
||||
|
||||
private static void Switches()
|
||||
{
|
||||
var on = NewHub("InfiniteLeaftide", "switches");
|
||||
Check.True(on.State.Remote.ShowBank && on.State.Remote.ShowGuardian, "both on by default");
|
||||
on.State.Remote.ShowBank = false;
|
||||
on.State.Remote.ShowGuardian = false;
|
||||
Check.False(on.RenderSection(RynthServerHub.SectionRemoteBank), "Bank switched off: nothing drawn");
|
||||
Check.False(on.RenderSection(RynthServerHub.SectionRemoteGuardian), "Guardian switched off: nothing drawn");
|
||||
|
||||
var off = NewHub("Aeshnidae", "switches-off");
|
||||
Check.False(off.RenderSection(RynthServerHub.SectionRemoteStats) || off.RenderSection(RynthServerHub.SectionRemoteOptions)
|
||||
|| off.RenderSection(RynthServerHub.SectionRemoteBank) || off.RenderSection(RynthServerHub.SectionRemoteGuardian),
|
||||
"off ILT: none of the Remote tab's ILT parts draws (checked before any ImGui call)");
|
||||
}
|
||||
|
||||
private static void FollowsSession()
|
||||
{
|
||||
var hub = NewHub("InfiniteLeaftide", "session");
|
||||
long t1 = DateTime.UtcNow.AddMinutes(-10).Ticks;
|
||||
FakeAiHub.SessionStartTicks = t1;
|
||||
long now = Environment.TickCount64;
|
||||
hub.Rates.Tick(now);
|
||||
DateTime first = hub.Rates.SessionStartUtc;
|
||||
System.Threading.Thread.Sleep(30);
|
||||
hub.Rates.Tick(now + 100);
|
||||
Check.Eq(hub.Rates.SessionStartUtc, first, "the same shared session: no restart");
|
||||
FakeAiHub.SessionStartTicks = DateTime.UtcNow.Ticks; // RynthAi's Reset XP
|
||||
hub.Rates.Tick(now + 200);
|
||||
Check.True(hub.Rates.SessionStartUtc > first, "RynthAi's session restarted: the coins start over too");
|
||||
}
|
||||
|
||||
private static void ImportsSwitches()
|
||||
{
|
||||
string legacy = Path.Combine(IltMigration.LegacyProfilesBase, "InfiniteLeaftide", "Remoter");
|
||||
Directory.CreateDirectory(legacy);
|
||||
File.WriteAllText(Path.Combine(legacy, "Default.json"), "{}");
|
||||
File.WriteAllText(Path.Combine(legacy, IltMigration.LegacyHudsFile), "{ \"ShowMiniRemote\": true, \"MiniShowBank\": false }");
|
||||
var state = new IltHubState();
|
||||
IltMigration.ImportRynthAiSettings(state, "InfiniteLeaftide", "Remoter");
|
||||
Check.False(state.Remote.ShowBank, "Bank was hidden in RynthAi: hidden here");
|
||||
Check.True(state.Remote.ShowGuardian, "Guardian wasn't in the file: the default (shown)");
|
||||
}
|
||||
}
|
||||
93
Tools/RynthILT.Tests/RingChainTests.cs
Normal file
93
Tools/RynthILT.Tests/RingChainTests.cs
Normal file
|
|
@ -0,0 +1,93 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using RynthCore.Plugin.RynthILT.Hub;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthILT.Tests;
|
||||
|
||||
// The Rings inscription chain's pure parts (Hub/IltRingChain.cs, SilentKelpie's RynthAi
|
||||
// Crafting > Rings moved to RynthILT): ingredient names, the craft queue and the scroll pairing.
|
||||
internal static class RingChainTests
|
||||
{
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("rings: ingredients match by name, with alternates and an exclude", Ingredients);
|
||||
r.Add("rings: the queue runs every Step 1, then Step 2, then the glyphs, capped per recipe", Queue);
|
||||
r.Add("rings: scrolls are known by their glyph and paired with targets the UB-IT way", Scrolls);
|
||||
r.Add("rings: the recipe list holds the three steps and eight glyphs", RecipeList);
|
||||
}
|
||||
|
||||
private static IltRingRecipe Recipe(string id) => IltRingChain.Recipes.Single(r => r.Id == id);
|
||||
|
||||
private static void Ingredients()
|
||||
{
|
||||
var step1 = Recipe("ring2_step1_quill_trophy");
|
||||
Check.True(IltRingChain.Matches("Quill of Infliction", step1.Tool), "the quill");
|
||||
Check.True(IltRingChain.Matches("infliction quill", step1.Tool), "an alternate name, any case");
|
||||
Check.False(IltRingChain.Matches("Enlightened Quill of Infliction", step1.Tool), "the enlightened quill is Step 2's, not Step 1's");
|
||||
Check.True(IltRingChain.Matches("Empyrean Trophy", step1.Target), "a trophy");
|
||||
Check.False(IltRingChain.Matches("Trophy Scroll", step1.Target), "plain 'Trophy' isn't enough (scrolls carry the word)");
|
||||
Check.False(IltRingChain.Matches(null, step1.Tool), "no name");
|
||||
Check.False(IltRingChain.Matches("", step1.Tool), "empty name");
|
||||
|
||||
var step2 = Recipe("ring2_step2_ink");
|
||||
Check.True(IltRingChain.Matches("Enlightened Quill of Infliction", step2.Tool), "Step 2 takes Step 1's quill");
|
||||
Check.False(IltRingChain.Matches("Enlightened Infliction Quill of Partition", step2.Tool), "but not the partition quill");
|
||||
|
||||
var flame = Recipe("ring2_glyph_flame");
|
||||
Check.True(IltRingChain.Matches("Enlightened Infliction Quill of Partition", flame.Tool), "Step 3 takes the partition quill");
|
||||
Check.True(IltRingChain.Matches("Glyph of Flame", flame.Target), "the full glyph name");
|
||||
Check.False(IltRingChain.Matches("Glyph of Frost", flame.Target), "another glyph is not");
|
||||
}
|
||||
|
||||
private static void Queue()
|
||||
{
|
||||
var runs = new Dictionary<string, int>
|
||||
{
|
||||
["ring2_glyph_frost"] = 1,
|
||||
["ring2_step2_ink"] = 2,
|
||||
["ring2_step1_quill_trophy"] = 2,
|
||||
["ring2_glyph_bludgeoning"] = 1,
|
||||
};
|
||||
List<IltRingRecipe> q = IltRingChain.Expand(id => runs.TryGetValue(id, out int n) ? n : 0);
|
||||
Check.Eq(string.Join(",", q.Select(r => r.Id)),
|
||||
"ring2_step1_quill_trophy,ring2_step1_quill_trophy,ring2_step2_ink,ring2_step2_ink,ring2_glyph_bludgeoning,ring2_glyph_frost",
|
||||
"tier order, then the definition order within a tier");
|
||||
Check.Eq(IltRingChain.Expand(_ => 0).Count, 0, "nothing queued");
|
||||
Check.Eq(IltRingChain.Expand(id => id == "ring2_step2_ink" ? -5 : 0).Count, 0, "negative runs count as none");
|
||||
Check.Eq(IltRingChain.Expand(id => id == "ring2_step2_ink" ? 500 : 0).Count, IltRingChain.MaxRuns, "capped at MaxRuns");
|
||||
}
|
||||
|
||||
private static void Scrolls()
|
||||
{
|
||||
Check.True(IltRingChain.IsInscriptionScroll("Inscription of Halo of Frost"), "an inscription scroll");
|
||||
Check.False(IltRingChain.IsInscriptionScroll("Scroll of Frost Bolt"), "a spell scroll is not");
|
||||
Check.False(IltRingChain.IsInscriptionScroll(null), "no name");
|
||||
Check.Eq(IltRingChain.GlyphOf("Inscription of Halo of Frost")?.Id, "ring2_glyph_frost", "known by its scroll name");
|
||||
Check.Eq(IltRingChain.GlyphOf("Inscription of Cassius' Ring of Fire")?.Id, "ring2_glyph_flame", "apostrophes too");
|
||||
Check.True(IltRingChain.GlyphOf("Inscription of Something New") == null, "an unknown scroll has no glyph");
|
||||
|
||||
var scrolls = new[]
|
||||
{
|
||||
(Id: 50, Name: "Inscription of Something New"),
|
||||
(Id: 40, Name: "Inscription of Halo of Frost"),
|
||||
(Id: 30, Name: "Inscription of Tectonic Rifts"),
|
||||
(Id: 20, Name: "Inscription of Halo of Frost"),
|
||||
};
|
||||
var pairs = IltRingChain.PairScrolls(scrolls, new[] { 900, 700, 800, 700 });
|
||||
// Scrolls by glyph id (bludgeoning < frost; unknown last), then by id; targets by id, once each.
|
||||
Check.Eq(string.Join(" ", pairs.Select(p => p.Scroll + ">" + p.Target)), "30>700 20>800 40>900", "pairing order");
|
||||
Check.Eq(IltRingChain.PairScrolls(scrolls.Take(1), new[] { 1, 2, 3 }).Count, 1, "one scroll per target, no more pairs than scrolls");
|
||||
Check.Eq(IltRingChain.PairScrolls(scrolls, Array.Empty<int>()).Count, 0, "no targets, no pairs");
|
||||
}
|
||||
|
||||
private static void RecipeList()
|
||||
{
|
||||
Check.Eq(IltRingChain.Recipes.Length, 10, "Step 1, Step 2 and eight glyphs");
|
||||
Check.Eq(IltRingChain.Recipes.Count(r => r.Tier == 3), 8, "eight glyphs");
|
||||
Check.True(IltRingChain.Recipes.Select(r => r.Id).Distinct().Count() == IltRingChain.Recipes.Length, "ids are unique");
|
||||
foreach (var r in IltRingChain.Recipes.Where(r => r.Tier == 3))
|
||||
Check.True(r.ScrollMarkers.Length > 0, r.Id + " knows its scroll's name");
|
||||
}
|
||||
}
|
||||
134
Tools/RynthILT.Tests/RingEvadeTests.cs
Normal file
134
Tools/RynthILT.Tests/RingEvadeTests.cs
Normal file
|
|
@ -0,0 +1,134 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using RynthCore.Plugin.RynthILT.Hub;
|
||||
using RynthCore.Plugin.Shared;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthILT.Tests;
|
||||
|
||||
// The Empyrean Handler's lethal ring (Hub/IltRingEvade.cs), RynthAi's CombatManager's until 2026-10-20
|
||||
// (Silentkelpie's PR 12). The line "The handler briefly channels infused Empyrean hatred to release a
|
||||
// lethal ring." on an ILT world, with a Handler near, makes RynthILT ask RynthAi to back away from it
|
||||
// (RynthAi.Hub BackAwayFrom, 12 yards, a 750 ms jump). The setting (on by default) is RynthILT's now,
|
||||
// copied once from the RynthAi profile.
|
||||
internal static class RingEvadeTests
|
||||
{
|
||||
private const uint Player = 0x50000B01;
|
||||
private const uint Handler = 0x80000B02;
|
||||
private const uint Lb = 0xA9B40000;
|
||||
private const string RingLine = "The handler briefly channels infused Empyrean hatred to release a lethal ring.";
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("ring evade (RynthILT): the Handler's line, and not a player's copy of it", ChannelLine);
|
||||
r.Add("ring evade (RynthILT): on ILT with a Handler near, RynthAi is asked to back away (once per cooldown)", AsksRynthAi);
|
||||
r.Add("ring evade (RynthILT): not with the setting off, no Handler near, off ILT, or without RynthAi", NotThese);
|
||||
r.Add("migration: the RynthAi profile's Handler ring evade comes over once (on by default)", ImportsSetting);
|
||||
}
|
||||
|
||||
private static IltHubController NewHub(string world, string folder, bool handler = true, bool withAi = true, string handlerName = "Empyrean Handler")
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeAiHub.Reset();
|
||||
FakeHost.WorldName = world;
|
||||
FakeHost.ContentsCalls = true;
|
||||
FakeHost.LiveObjectsCalls = true;
|
||||
FakeHost.Names[Player] = "Evader";
|
||||
FakeHost.Positions[Player] = (Lb | 0x1C, 96f, 96f, 0f);
|
||||
if (handler)
|
||||
{
|
||||
FakeHost.Names[Handler] = handlerName;
|
||||
FakeHost.ItemTypes[Handler] = 0x10;
|
||||
FakeHost.Positions[Handler] = (Lb | 0x1C, 96f, 101f, 0f);
|
||||
}
|
||||
var host = FakeHost.Create(Player);
|
||||
var ai = new RynthAiClient(host);
|
||||
if (withAi) ai.UseTableForTests(FakeAiHub.Table);
|
||||
string dir = Path.Combine(Program.TempRoot, "ring-" + folder);
|
||||
if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true);
|
||||
Directory.CreateDirectory(dir);
|
||||
var hub = new IltHubController(host, dir, new IltSettings(), ai);
|
||||
hub.OnLoginComplete("Evader", forceFromMigration: false);
|
||||
return hub;
|
||||
}
|
||||
|
||||
private static void ChannelLine()
|
||||
{
|
||||
Check.True(IltRingEvade.IsChannelLine(RingLine, ChatSource.Emote), "the Handler's emote");
|
||||
Check.True(IltRingEvade.IsChannelLine("handler briefly channels infused Empyrean hatred to release a lethal ring.", 0x00),
|
||||
"mid-line on a system line (a client that strips 'The ')");
|
||||
Check.False(IltRingEvade.IsChannelLine("Someone says, \"" + RingLine + "\"", ChatSource.Speech), "a player saying it");
|
||||
Check.False(IltRingEvade.IsChannelLine("Bob tells you, \"" + RingLine + "\"", 0x00), "a tell repeating it");
|
||||
Check.False(IltRingEvade.IsChannelLine("The handler waves.", ChatSource.Emote), "another Handler emote");
|
||||
}
|
||||
|
||||
private static void AsksRynthAi()
|
||||
{
|
||||
var hub = NewHub("InfiniteLeaftide", "asks");
|
||||
hub.OnChat(RingLine, ChatSource.Emote);
|
||||
Check.Eq(FakeAiHub.BackAways.Count, 1, "one back-away request");
|
||||
var (id, radius, hold) = FakeAiHub.BackAways[0];
|
||||
Check.Eq(id, Handler, "away from the Handler");
|
||||
Check.Eq(radius, IltRingEvade.DangerYards, "12 yards (RynthAi widens it to Ring Range)");
|
||||
Check.Eq(hold, IltRingEvade.JumpHoldMs, "a 750 ms jump");
|
||||
Check.True(hub.RingEvade.LastOutcome.Contains("backs away"), "logged");
|
||||
hub.OnChat(RingLine, ChatSource.Emote);
|
||||
Check.Eq(FakeAiHub.BackAways.Count, 1, "a second line inside the cooldown asks nothing");
|
||||
|
||||
var outside = NewHub("InfiniteLeaftide", "outside");
|
||||
FakeAiHub.BackAwayResult = RynthAiHub.BackAwayOutside;
|
||||
outside.OnChat(RingLine, ChatSource.Emote);
|
||||
Check.Eq(FakeAiHub.BackAways.Count, 1, "RynthAi decides the radius");
|
||||
Check.True(outside.RingEvade.LastOutcome.Contains("outside"), "and its answer is logged");
|
||||
|
||||
var notFighting = NewHub("InfiniteLeaftide", "notnow");
|
||||
FakeAiHub.BackAwayResult = RynthAiHub.BackAwayNotNow;
|
||||
notFighting.OnChat(RingLine, ChatSource.Emote);
|
||||
Check.True(notFighting.RingEvade.LastOutcome.Contains("isn't fighting"), "RynthAi not fighting: it says so");
|
||||
}
|
||||
|
||||
private static void NotThese()
|
||||
{
|
||||
var off = NewHub("InfiniteLeaftide", "setting-off");
|
||||
off.State.Combat.HandlerRingEvade = false;
|
||||
off.OnChat(RingLine, ChatSource.Emote);
|
||||
Check.Eq(FakeAiHub.BackAways.Count, 0, "setting off: nothing asked");
|
||||
|
||||
var none = NewHub("InfiniteLeaftide", "none", handlerName: "Drudge Skulker");
|
||||
none.OnChat(RingLine, ChatSource.Emote);
|
||||
Check.Eq(FakeAiHub.BackAways.Count, 0, "no Empyrean Handler near: nothing asked");
|
||||
|
||||
var said = NewHub("InfiniteLeaftide", "said");
|
||||
said.OnChat("Someone says, \"" + RingLine + "\"", ChatSource.Speech);
|
||||
Check.Eq(FakeAiHub.BackAways.Count, 0, "a player's copy: nothing asked");
|
||||
|
||||
var retail = NewHub("Aeshnidae", "retail");
|
||||
retail.OnChat(RingLine, ChatSource.Emote);
|
||||
Check.Eq(FakeAiHub.BackAways.Count, 0, "off ILT: nothing asked");
|
||||
|
||||
var noAi = NewHub("InfiniteLeaftide", "noai", withAi: false);
|
||||
noAi.OnChat(RingLine, ChatSource.Emote);
|
||||
Check.True(noAi.RingEvade.LastOutcome.Contains("RynthAi"), "without RynthAi: said in the log, no crash");
|
||||
}
|
||||
|
||||
private static void ImportsSetting()
|
||||
{
|
||||
Check.True(new IltHubState().Combat.HandlerRingEvade, "on by default");
|
||||
string legacy = Path.Combine(IltMigration.LegacyProfilesBase, "InfiniteLeaftide", "Evader");
|
||||
Directory.CreateDirectory(legacy);
|
||||
File.WriteAllText(Path.Combine(legacy, "active_profile.txt"), "Farm");
|
||||
File.WriteAllText(Path.Combine(legacy, "Farm.json"), "{ \"HandlerRingEvade\": false, \"MonsterRange\": 30 }");
|
||||
var state = new IltHubState();
|
||||
IltMigration.ImportRynthAiSettings(state, "InfiniteLeaftide", "Evader");
|
||||
Check.False(state.Combat.HandlerRingEvade, "the active profile had it off: off here too");
|
||||
|
||||
string legacy2 = Path.Combine(IltMigration.LegacyProfilesBase, "InfiniteLeaftide", "Oldie");
|
||||
Directory.CreateDirectory(legacy2);
|
||||
File.WriteAllText(Path.Combine(legacy2, "Default.json"), "{ \"MonsterRange\": 30 }");
|
||||
var old = new IltHubState();
|
||||
IltMigration.ImportRynthAiSettings(old, "InfiniteLeaftide", "Oldie");
|
||||
Check.True(old.Combat.HandlerRingEvade, "a profile from before the setting: on (the default)");
|
||||
}
|
||||
}
|
||||
71
Tools/RynthILT.Tests/RynthILT.Tests.csproj
Normal file
71
Tools/RynthILT.Tests/RynthILT.Tests.csproj
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!--
|
||||
Tests for the RynthILT plugin: the ACECustom bounty tracker (Bounty/, ported from SilentKelpie's
|
||||
rynth/RynthSuite PR #11 with his BountyTests) and the ILT Hub moved out of RynthAi 2026-10-13
|
||||
(the attribute raiser and aug costs, bank commands and the sigil chain, which ran in
|
||||
RynthCore.RynthAiHostTests before, plus the move itself: data migration, the RynthILT.Hub
|
||||
interface table, which "/ra" verbs RynthILT takes, the host-backed object view).
|
||||
|
||||
Like RynthCore.RynthAiHostTests this references the plugin project itself, so it is a
|
||||
net10.0-windows x86 exe and needs the x86 .NET runtime (C:\Program Files (x86)\dotnet). The
|
||||
plugin grants InternalsVisibleTo to this assembly name. The fake engine host is the RynthAi
|
||||
host tests' FakeHost (linked; RYNTHILT_TESTS leaves out its RynthAi-only helpers). File tests
|
||||
use a scratch folder next to the exe, never %APPDATA%\RynthCore or C:\Games.
|
||||
Run: dotnet run -c Release (exit 0 = pass, 1 = fail; an argument filters by test name)
|
||||
-->
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0-windows</TargetFramework>
|
||||
<PlatformTarget>x86</PlatformTarget>
|
||||
<RuntimeIdentifier>win-x86</RuntimeIdentifier>
|
||||
<SelfContained>false</SelfContained>
|
||||
<Nullable>enable</Nullable>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<InvariantGlobalization>true</InvariantGlobalization>
|
||||
<RootNamespace>RynthILT.Tests</RootNamespace>
|
||||
<AssemblyName>RynthILT.Tests</AssemblyName>
|
||||
<Platforms>x86</Platforms>
|
||||
<DefineConstants>$(DefineConstants);RYNTHILT_TESTS</DefineConstants>
|
||||
<NoWarn>$(NoWarn);CS1591</NoWarn>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\Plugins\RynthCore.Plugin.RynthILT\RynthCore.Plugin.RynthILT.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- The RynthAi test tools' check/runner harness and fake engine host (no plugin code in them). -->
|
||||
<Compile Include="$(RynthSuiteRoot)Tools\RynthCore.RynthAiTests\Harness\Check.cs" Link="Harness\Check.cs" />
|
||||
<Compile Include="$(RynthSuiteRoot)Tools\RynthCore.RynthAiTests\Harness\Runner.cs" Link="Harness\Runner.cs" />
|
||||
<Compile Include="$(RynthSuiteRoot)Tools\RynthCore.RynthAiHostTests\Fakes\FakeHost.cs" Link="Fakes\FakeHost.cs" />
|
||||
<!-- The shared reader RynthAi's Crafting tab uses on RynthILT's RynthServer.Profile JSON (ProfileTests),
|
||||
Plugins\Shared\EngineServerState.cs, comes with the plugin now (it reads RynthCore's server list). -->
|
||||
</ItemGroup>
|
||||
|
||||
<!-- The engine's Bounties snapshot reader (self-contained DTOs), so BountyTests checks the plugin's
|
||||
JSON against the engine's own reader. Optional, so this builds before the engine side is
|
||||
merged: without the file the round-trip check is compiled out (ENGINE_BOUNTIES). -->
|
||||
<PropertyGroup Condition="Exists('..\..\..\RynthCore\src\RynthCore.Engine\UI\Data\BountiesSnapshotJson.cs')">
|
||||
<DefineConstants>$(DefineConstants);ENGINE_BOUNTIES</DefineConstants>
|
||||
</PropertyGroup>
|
||||
<ItemGroup Condition="Exists('..\..\..\RynthCore\src\RynthCore.Engine\UI\Data\BountiesSnapshotJson.cs')">
|
||||
<Compile Include="..\..\..\RynthCore\src\RynthCore.Engine\UI\Data\BountiesSnapshotJson.cs" Link="Engine\BountiesSnapshotJson.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<!-- The engine's Mini Remote sections manifest parser and catalog (pure; the RynthAi host tests link the same
|
||||
files), so the sections test checks RynthILT's RynthPluginGetSectionsJson against the engine's reader. -->
|
||||
<ItemGroup>
|
||||
<Compile Include="..\..\..\RynthCore\src\RynthCore.Engine\UI\Sections\ServerForce.cs" Link="Engine\ServerForce.cs" />
|
||||
<Compile Include="..\..\..\RynthCore\src\RynthCore.Engine\UI\Sections\SectionManifest.cs" Link="Engine\SectionManifest.cs" />
|
||||
<Compile Include="..\..\..\RynthCore\src\RynthCore.Engine\UI\Sections\SectionCatalog.cs" Link="Engine\SectionCatalog.cs" />
|
||||
<Compile Include="..\..\..\RynthCore\src\RynthCore.Engine\Compatibility\IltDetect.cs" Link="Engine\IltDetect.cs" />
|
||||
<Compile Include="..\..\..\RynthCore\src\RynthCore.Engine\Compatibility\AelrynthWire.cs" Link="Engine\AelrynthWire.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<!-- The engine supplies cimgui; never copy ImGui.NET's own next to the test exe either. -->
|
||||
<Target Name="RemoveBundledImGuiNative" AfterTargets="Build">
|
||||
<Delete Files="$(OutputPath)cimgui.dll" Condition="Exists('$(OutputPath)cimgui.dll')" />
|
||||
</Target>
|
||||
|
||||
</Project>
|
||||
83
Tools/RynthILT.Tests/SigilChainTests.cs
Normal file
83
Tools/RynthILT.Tests/SigilChainTests.cs
Normal file
|
|
@ -0,0 +1,83 @@
|
|||
using RynthCore.Plugin.RynthILT.Hub;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthILT.Tests;
|
||||
|
||||
// Enlightenment 301-325 sigil craft chain (2026-10-07). Each target level T costs T - 5 sigils and
|
||||
// T x 2B luminance (ACECustom tier 5). Sigil = Lifeblood Elixir + Ascension Coin; Ascension Coin =
|
||||
// E-coin + Ancient Yalani Trinket; Elixir = Lifebloom Resin + Necrolytic Extract; Resin = Life
|
||||
// Splitter + Plant. Stock is used from the top of the chain down.
|
||||
internal static class SigilChainTests
|
||||
{
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("sigil chain: 301-325 tier rates and sigil counts", TierRates);
|
||||
r.Add("sigil chain: shortfall uses stock top-down", ShortfallTopDown);
|
||||
r.Add("sigil chain: fulfillable count and shared e-coin pool", FulfillableAndCoins);
|
||||
r.Add("sigil chain: item names (plural stacks, Plant exact)", Names);
|
||||
}
|
||||
|
||||
private static void TierRates()
|
||||
{
|
||||
var t301 = IltProgression.EnlStepCost(301);
|
||||
Check.Eq(t301.Item, "Enlightenment Sigils", "301 takes sigils");
|
||||
Check.Eq(t301.Count, 296, "301 takes T - 5 sigils");
|
||||
Check.Eq(t301.Lum, 301 * 2_000_000_000m, "301 costs T x 2B luminance (no step multiplier yet)");
|
||||
Check.Eq(IltProgression.EnlStepCost(325).Lum, 325 * 2_000_000_000m, "325 still has no step multiplier");
|
||||
Check.Eq(IltProgression.EnlStepCost(326).Item, "Enlightenment Crests", "326 moves to crests");
|
||||
Check.Eq(IltSigilChain.SigilsForRange(300, 302), 296L + 297L, "range 300 -> 302 sums both levels");
|
||||
Check.Eq(IltSigilChain.SigilsForRange(324, 330), 320L, "range clamps at 325");
|
||||
Check.Eq(IltSigilChain.SigilsForRange(200, 300), 0L, "no sigils below 301");
|
||||
}
|
||||
|
||||
private static void ShortfallTopDown()
|
||||
{
|
||||
var empty = IltSigilChain.Shortfall(10, new IltSigilStock());
|
||||
Check.Eq(empty.CoinsShort, 10L, "empty pack: one e-coin per sigil");
|
||||
Check.Eq(empty.PlantsShort, 10L, "empty pack: one plant per sigil");
|
||||
Check.True(!empty.Covered, "empty pack is not covered");
|
||||
|
||||
var stock = new IltSigilStock
|
||||
{
|
||||
Sigils = 2, AscensionCoins = 3, LifebloodElixirs = 1, LifebloomResins = 4,
|
||||
EnlightenedCoins = 100, YalaniTrinkets = 1, NecrolyticExtracts = 2, LifeSplitters = 0, Plants = 5,
|
||||
};
|
||||
var s = IltSigilChain.Shortfall(10, stock);
|
||||
Check.Eq(s.SigilsToCraft, 8L, "2 finished sigils used first");
|
||||
Check.Eq(s.AscensionToCraft, 5L, "3 Ascension Coins on hand");
|
||||
Check.Eq(s.ElixirsToCraft, 7L, "1 Elixir on hand");
|
||||
Check.Eq(s.CoinsShort, 0L, "100 e-coins cover 5 crafts");
|
||||
Check.Eq(s.TrinketsShort, 4L, "1 trinket on hand");
|
||||
Check.Eq(s.ExtractsShort, 5L, "2 extracts on hand");
|
||||
Check.Eq(s.ResinsToCraft, 3L, "4 resins on hand");
|
||||
Check.Eq(s.SplittersShort, 3L, "no splitters");
|
||||
Check.Eq(s.PlantsShort, 0L, "5 plants cover 3 resins");
|
||||
|
||||
Check.True(IltSigilChain.Shortfall(5, new IltSigilStock { Sigils = 9 }).Covered, "finished sigils cover the demand");
|
||||
}
|
||||
|
||||
private static void FulfillableAndCoins()
|
||||
{
|
||||
var stock = new IltSigilStock
|
||||
{
|
||||
Sigils = 1, AscensionCoins = 1, EnlightenedCoins = 10, YalaniTrinkets = 2,
|
||||
LifebloomResins = 1, LifeSplitters = 10, Plants = 10, NecrolyticExtracts = 4,
|
||||
};
|
||||
Check.Eq(IltSigilChain.Fulfillable(stock), 4L, "1 finished + min(3 coins, 4 elixirs)");
|
||||
|
||||
IltSigilChain.EcoinDemand(50, 30, 2, 20, out long fromCoins, out long still, out long need);
|
||||
Check.Eq(fromCoins, 1L, "20 coins left after Ascension crafts make 1 token");
|
||||
Check.Eq(still, 1L, "one token still short");
|
||||
Check.Eq(need, 20L, "one more token's worth of coins");
|
||||
IltSigilChain.EcoinDemand(10, 25, 0, 20, out _, out _, out need);
|
||||
Check.Eq(need, 15L, "Ascension crafts alone exceed the pool");
|
||||
}
|
||||
|
||||
private static void Names()
|
||||
{
|
||||
Check.True(IltSigilChain.NameIs("Ascension Coins", IltSigilChain.AscensionCoin), "plural stack name");
|
||||
Check.True(IltSigilChain.NameIs(" plant ", IltSigilChain.Plant), "case and spaces ignored");
|
||||
Check.True(!IltSigilChain.NameIs("Plant Fiber", IltSigilChain.Plant), "Plant must be the whole name");
|
||||
Check.True(!IltSigilChain.NameIs("Lifebloom Resin", IltSigilChain.LifebloodElixir), "Lifebloom is not Lifeblood");
|
||||
}
|
||||
}
|
||||
258
Tools/RynthILT.Tests/StampTests.cs
Normal file
258
Tools/RynthILT.Tests/StampTests.cs
Normal file
|
|
@ -0,0 +1,258 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using RynthCore.Plugin.RynthILT;
|
||||
using RynthCore.Plugin.RynthILT.Hub;
|
||||
using RynthCore.Plugin.RynthOracle.Data;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthILT.Tests;
|
||||
|
||||
// Infinite Leaftide's Dynamic Stamps (Hub/IltDynamicStampList.cs, Hub/IltDynamicStamps.cs): SilentKelpie's
|
||||
// (RynthSuite PR 12), rows of RynthOracle's Quests list until 2026-10-21 and RynthILT's own page since.
|
||||
// The list and its matching rules (the tests that came with it from RynthOracle.Tests), the page's
|
||||
// filters, where its flags come from, and what its buttons send (RynthNav, RynthAi's /ub give).
|
||||
internal static class StampTests
|
||||
{
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("stamps: the shipped list (243 stamps in 17 areas) and how a stamp is matched", ShippedList);
|
||||
r.Add("stamps: the loader skips bad and repeated rows", Loader);
|
||||
r.Add("stamps: the page's filters (area, missing / had, search)", Filters);
|
||||
r.Add("stamps: flags come from any /myquests reply; only RynthILT's own reply is hidden", Flags);
|
||||
r.Add("stamps: off ILT the page is dormant (no flags read)", Dormant);
|
||||
r.Add("stamps: Go / Route / Arrow ask RynthNav; Chat prints the stamp", Nav);
|
||||
r.Add("stamps: Give Parchment needs RynthAi, sends /ub give 1, then reads the flags again", Give);
|
||||
r.Add("stamps: a Parchment in the packs is found while the page is on screen", Parchment);
|
||||
}
|
||||
|
||||
private const uint Player = 0x50000D31;
|
||||
private static readonly long Yesterday = DateTimeOffset.UtcNow.AddDays(-1).ToUnixTimeSeconds();
|
||||
|
||||
private static IltHubController NewHub(string world, string folder, bool withAi = false)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeAiHub.Reset();
|
||||
FakeHost.WorldName = world;
|
||||
FakeHost.PluginCommandCalls = true;
|
||||
FakeHost.ContentsCalls = true;
|
||||
FakeHost.Containers[0x7000A001] = Player;
|
||||
FakeHost.Names[0x7000A001] = "Pyreal";
|
||||
var host = FakeHost.Create(Player);
|
||||
var ai = new RynthAiClient(host);
|
||||
if (withAi) ai.UseTableForTests(FakeAiHub.Table);
|
||||
string dir = Path.Combine(Program.TempRoot, "stamps-" + folder);
|
||||
if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true);
|
||||
Directory.CreateDirectory(dir);
|
||||
var hub = new IltHubController(host, dir, new IltSettings(), ai);
|
||||
hub.OnLoginComplete("Stamper", forceFromMigration: false);
|
||||
return hub;
|
||||
}
|
||||
|
||||
private static void ShippedList()
|
||||
{
|
||||
var all = DynamicStampList.All;
|
||||
Check.Eq(all.Count, 243, "243 stamps from the ExtraDyn sheet");
|
||||
Check.True(DynamicStampList.Areas.Count == 17 && DynamicStampList.Areas[0] == "Facility Hub" && DynamicStampList.Areas[^1] == "Candeth Keep",
|
||||
"areas: " + string.Join(",", DynamicStampList.Areas));
|
||||
Check.True(all.All(s => s.Stamp.StartsWith("dynamic_") && s.Stamp == s.Stamp.ToLowerInvariant()), "every stamp is a lower-case dynamic_ flag");
|
||||
Check.Eq(all.Select(s => s.Stamp).Distinct().Count(), all.Count, "no stamp listed twice");
|
||||
Check.True(all.All(s => s.Label.Length > 0), "every row names an NPC or a place");
|
||||
|
||||
DynamicStamp felscuda = all.First(s => s.Npc == "Felscuda");
|
||||
Check.True(felscuda.Stamp == "dynamic_1_&9jiytb!" && felscuda.Place == "Folthid Cellar" && felscuda.Reward == "Healing Rabbit Pie"
|
||||
&& felscuda.Note == "8.8S, 53.1E", $"Felscuda row: {felscuda.Place} / {felscuda.Reward} / {felscuda.Note}");
|
||||
|
||||
// /myquests keys flags as \S+ lower case, so the stamps' ! & # ^ $ survive.
|
||||
var f = new QuestFlagStore();
|
||||
long t = 900_000;
|
||||
f.OnChatLine($"Dynamic_1_&9jiyTB! - 1 solves ({Yesterday})\"Dynamic\" 1 0", t);
|
||||
f.OnChatLine($"Dynamic_1_ANND! - 1 solves ({Yesterday})\"Dynamic\" 1 0", t + 1); // the sheet lost the closing !
|
||||
f.OnChatLine($"Dynamic_1_ZZZnewNPC! - 1 solves ({Yesterday})\"Dynamic\" 1 0", t + 2); // not on the sheet
|
||||
f.OnChatLine($"rtwcompleted_1013 - 1 solves ({Yesterday})\"RTW\" -1 72000", t + 3);
|
||||
f.Tick(t + 5_000);
|
||||
Check.True(felscuda.Have(f), "Felscuda's stamp read from /myquests");
|
||||
DynamicStamp annd = all.First(s => s.Stamp == "dynamic_1_annd");
|
||||
Check.True(annd.Have(f) && annd.MatchedFlag(f) == "dynamic_1_annd!", "a stamp the sheet lost its ! on still matches");
|
||||
Check.False(all.First(s => s.Npc == "Raxanza Folthid").Have(f), "an NPC not done is missing");
|
||||
List<string> extra = DynamicStampList.Unlisted(f);
|
||||
Check.True(extra.Count == 1 && extra[0] == "dynamic_1_zzznewnpc!", "unlisted: only the stamp the sheet doesn't have: " + string.Join(",", extra));
|
||||
DynamicStamp shortStamp = all.First(s => s.Stamp == "dynamic_1_s");
|
||||
var sf = new QuestFlagStore();
|
||||
sf.OnChatLine($"Dynamic_1_SomethingElse! - 1 solves ({Yesterday})\"Dynamic\" 1 0", t);
|
||||
sf.Tick(t + 5_000);
|
||||
Check.False(shortStamp.Have(sf), "a cut-short stem under 14 characters isn't matched by prefix");
|
||||
|
||||
// RynthNav targets, best first (RynthNav takes the first on its map).
|
||||
Check.Eq(string.Join(" | ", felscuda.NavCandidates()), "8.8S, 53.1E | Folthid Cellar | Felscuda | Facility Hub", "Felscuda nav");
|
||||
var gerent = new DynamicStamp { Area = "Graveyard", Place = "Gerent's Compound at 87.2S, 17.5W", Npc = "Gerent" };
|
||||
Check.Eq(string.Join(" | ", gerent.NavCandidates()), "87.2S, 17.5W | Gerent's Compound | Gerent | Graveyard", "coordinates inside the place, 'at' dropped");
|
||||
var lost = new DynamicStamp { Area = "Odd Stamps", Place = "Lost Wish Cottages (Arwic) 42.6n 62.4e", Npc = "Bob" };
|
||||
Check.Eq(string.Join(" | ", lost.NavCandidates()), "42.6N, 62.4E | Lost Wish Cottages (Arwic) | Lost Wish Cottages | Arwic",
|
||||
"lower-case n/e, a bracketed town, no grouping area, a 3-letter NPC left out");
|
||||
var mhoire = new DynamicStamp { Area = "Looking Around", Place = "Mhoire Castle - Great Hall" };
|
||||
Check.Eq(string.Join(" | ", mhoire.NavCandidates()), "Mhoire Castle - Great Hall | Mhoire Castle | Great Hall", "a place's parts");
|
||||
Check.True(all.Count(s => s.NavCandidates().Count > 0) >= 200, "most stamps have somewhere to go: " + all.Count(s => s.NavCandidates().Count > 0));
|
||||
}
|
||||
|
||||
private static void Loader()
|
||||
{
|
||||
var stamps = DynamicStampList.Parse(new StringReader(
|
||||
"Area,Place,Npc,Reward,Stamp,Note\n"
|
||||
+ "\"A\",\"P\",\"Npc1\",\"R\",\"Dynamic_1_Abc!\",\"8.8S, 53.1E\"\n"
|
||||
+ "\"A\",\"P\",\"Dup\",\"R\",\"dynamic_1_abc!\",\"\"\n" // the same stamp again: skipped
|
||||
+ "\"A\",\"P\",\"NotDyn\",\"R\",\"something_else\",\"\"\n" // not a dynamic_ flag: skipped
|
||||
+ "\"A\",\"P\",\"Short\"\n" // no stamp column: skipped
|
||||
+ "\n"
|
||||
+ "\"B\",\"\",\"\",\"\",\"Dynamic_2_x\",\"\"\n"));
|
||||
Check.True(stamps.Count == 2 && stamps[0].Stamp == "dynamic_1_abc!" && stamps[1].Stamp == "dynamic_2_x",
|
||||
"bad and repeated rows skipped, the rest kept: " + string.Join(",", stamps.Select(s => s.Stamp)));
|
||||
Check.True(stamps[0].Npc == "Npc1" && stamps[0].Note == "8.8S, 53.1E" && stamps[1].Label == "", "fields read, a missing NPC and place leave an empty label");
|
||||
Check.Eq(DynamicStampList.Parse(new StringReader("")).Count, 0, "an empty file is an empty list");
|
||||
}
|
||||
|
||||
private static void Filters()
|
||||
{
|
||||
var f = new QuestFlagStore();
|
||||
f.OnChatLine($"Dynamic_1_&9jiyTB! - 1 solves ({Yesterday})\"Dynamic\" 1 0", 0);
|
||||
f.Tick(5_000);
|
||||
List<DynamicStampText.Row> rows = DynamicStampText.Rows(DynamicStampList.All, f);
|
||||
Check.Eq(rows.Count, 243, "a row per listed stamp");
|
||||
Check.Eq(rows.Count(r => r.Have), 1, "one had");
|
||||
Check.Eq(DynamicStampText.Filter(rows, "", null, DynamicStampText.Show.All).Count, 243, "no filter: everything");
|
||||
Check.Eq(DynamicStampText.Filter(rows, "", null, DynamicStampText.Show.Have).Single().Stamp.Npc, "Felscuda", "Had: Felscuda's");
|
||||
Check.Eq(DynamicStampText.Filter(rows, "", null, DynamicStampText.Show.Missing).Count, 242, "Missing: the rest");
|
||||
string area = DynamicStampList.Areas[0];
|
||||
int inArea = DynamicStampList.All.Count(s => s.Area == area);
|
||||
Check.Eq(DynamicStampText.Filter(rows, null, area, DynamicStampText.Show.All).Count, inArea, "the area picker narrows to " + area);
|
||||
Check.Eq(DynamicStampText.Filter(rows, "felscuda rabbit", null, DynamicStampText.Show.All).Single().Stamp.Npc, "Felscuda",
|
||||
"every search word, in the NPC and the reward, any case");
|
||||
Check.Eq(DynamicStampText.Filter(rows, "felscuda nothinglikethis", null, DynamicStampText.Show.All).Count, 0, "a word nowhere: nothing");
|
||||
}
|
||||
|
||||
private static void Flags()
|
||||
{
|
||||
IltHubController hub = NewHub("InfiniteLeaftide", "flags");
|
||||
IltDynamicStamps stamps = hub.DynamicStamps;
|
||||
long now = IltHubContext.NowMs;
|
||||
|
||||
// A reply another plugin (or the player) asked for: read, and shown.
|
||||
bool eaten = hub.OnChat($"Dynamic_1_&9jiyTB! - 1 solves ({Yesterday})\"Dynamic\" 1 0");
|
||||
Check.False(eaten, "a reply RynthILT didn't ask for shows in chat");
|
||||
stamps.Tick(now + 5_000);
|
||||
Check.True(stamps.Flags.TryGet("dynamic_1_&9jiytb!", out _), "the flag is read from it");
|
||||
|
||||
// Its own request: the reply is hidden.
|
||||
hub.Tick();
|
||||
stamps.RequestFlags();
|
||||
Check.True(FakeHost.ChatCommands.Contains("/myquests"), "Read quest flags sends /myquests");
|
||||
stamps.NoteTypedMyQuests(); // the engine's dispatcher hands it back through the chat bar
|
||||
Check.True(stamps.Flags.AwaitingOurs, "waiting for its own reply");
|
||||
Check.True(hub.OnChat($"Dynamic_1_ANND! - 1 solves ({Yesterday})\"Dynamic\" 1 0"), "its own reply is hidden");
|
||||
stamps.Tick(IltHubContext.NowMs + 5_000);
|
||||
Check.False(stamps.Flags.AwaitingOurs, "done waiting once the reply went quiet");
|
||||
Check.True(stamps.Flags.TryGet("dynamic_1_annd!", out _), "and read");
|
||||
|
||||
// The page's snapshot follows the flags while it is on screen.
|
||||
stamps.MarkWatched();
|
||||
stamps.Tick(IltHubContext.NowMs);
|
||||
IltDynamicStamps.Snapshot s = stamps.Current;
|
||||
Check.True(s.Built && s.Rows.Count == 243, "the snapshot lists every stamp");
|
||||
Check.Eq(s.Have, 1, "one listed stamp had (the other read reply replaced the first)");
|
||||
Check.True(s.LastReadUtc != DateTime.MinValue, "when the flags were read");
|
||||
|
||||
hub.OnLogout();
|
||||
Check.False(stamps.Current.Built || stamps.Flags.Flags.Count > 0, "logout forgets the flags and the snapshot");
|
||||
}
|
||||
|
||||
private static void Dormant()
|
||||
{
|
||||
IltHubController hub = NewHub("Aeshnidae", "dormant");
|
||||
hub.OnChat($"Dynamic_1_&9jiyTB! - 1 solves ({Yesterday})\"Dynamic\" 1 0");
|
||||
hub.DynamicStamps.Tick(IltHubContext.NowMs + 5_000);
|
||||
Check.Eq(hub.DynamicStamps.Flags.Flags.Count, 0, "off ILT no chat reaches the page");
|
||||
Check.False(hub.Options.IsIltLikeWorld, "(not an ILT world)");
|
||||
}
|
||||
|
||||
private static void Nav()
|
||||
{
|
||||
IltHubController hub = NewHub("InfiniteLeaftide", "nav");
|
||||
IltDynamicStamps stamps = hub.DynamicStamps;
|
||||
DynamicStamp felscuda = DynamicStampList.All.First(s => s.Npc == "Felscuda");
|
||||
Check.Eq(DynamicStampText.NavLine("route", felscuda), "route 8.8S, 53.1E || Folthid Cellar || Felscuda || Facility Hub", "the RynthNav line");
|
||||
Check.Eq(DynamicStampText.NavLine("go", new DynamicStamp { Stamp = "dynamic_x" }), "", "nowhere to go: no line");
|
||||
|
||||
stamps.Nav("route", felscuda);
|
||||
stamps.Nav("go", felscuda);
|
||||
stamps.Nav("arrow", felscuda);
|
||||
Check.Eq(FakeHost.PluginCommands.Count, 3, "three RynthNav commands");
|
||||
Check.True(FakeHost.PluginCommands.All(c => c.Plugin == "RynthNav" && c.Action == "rnav"), "to RynthNav's rnav");
|
||||
Check.True(FakeHost.PluginCommands[1].Value.StartsWith("go 8.8S, 53.1E || "), "go with every candidate");
|
||||
Check.True(stamps.Status.Contains("arrow"), "the status says what happened: " + stamps.Status);
|
||||
FakeHost.PluginCommandDelivered = false;
|
||||
stamps.Nav("go", felscuda);
|
||||
Check.True(stamps.Status.Contains("RynthNav isn't loaded"), "without RynthNav: said so");
|
||||
|
||||
FakeHost.Chat.Clear();
|
||||
stamps.Print(felscuda);
|
||||
Check.True(FakeHost.Chat.Count >= 2 && FakeHost.Chat[0].Contains("Felscuda") && FakeHost.Chat[0].Contains("missing")
|
||||
&& FakeHost.Chat[1].Contains("Folthid Cellar") && FakeHost.Chat[1].Contains("Healing Rabbit Pie"),
|
||||
"Chat prints the stamp, its status, place and reward: " + string.Join(" | ", FakeHost.Chat));
|
||||
}
|
||||
|
||||
private static void Give()
|
||||
{
|
||||
// Without RynthAi: the reason, nothing sent.
|
||||
Check.True(DynamicStampText.GiveUnavailableReason(false, false)!.Contains("Needs RynthAi"), "no RynthAi: says it needs it");
|
||||
Check.True(DynamicStampText.GiveUnavailableReason(true, true)!.Contains("Unrecognized /ub command"), "rejected: says why");
|
||||
Check.Null(DynamicStampText.GiveUnavailableReason(true, false), "RynthAi there: Give works");
|
||||
Check.Eq(DynamicStampText.GiveCommand("Parchment\nof /quit", "Felscuda"), "/ub give 1 Parchmentof /quit to Felscuda",
|
||||
"control characters are stripped from the command");
|
||||
Check.True(DynamicStampText.IsGiveRejection("[RynthAi] Unrecognized /ub command.") && !DynamicStampText.IsGiveRejection("[RynthAi] ok"),
|
||||
"RynthAi's rejection line");
|
||||
|
||||
DynamicStamp felscuda = DynamicStampList.All.First(s => s.Npc == "Felscuda");
|
||||
IltHubController none = NewHub("InfiniteLeaftide", "give-none");
|
||||
none.DynamicStamps.Give(felscuda, "Parchment of Learning");
|
||||
Check.False(FakeHost.ChatCommands.Any(c => c.StartsWith("/ub give")), "without RynthAi nothing is sent");
|
||||
|
||||
IltHubController hub = NewHub("InfiniteLeaftide", "give", withAi: true);
|
||||
IltDynamicStamps stamps = hub.DynamicStamps;
|
||||
stamps.Give(felscuda, "Parchment of Learning");
|
||||
Check.True(FakeHost.ChatCommands.Contains("/ub give 1 Parchment of Learning to Felscuda"), "Give sends /ub give 1: " + string.Join("|", FakeHost.ChatCommands));
|
||||
Check.True(stamps.Status.Contains("Giving Parchment of Learning to Felscuda"), "and says so");
|
||||
|
||||
// The stamp is a quest flag: /myquests is read again once the NPC had time to answer.
|
||||
stamps.Tick(IltHubContext.NowMs + 1_000);
|
||||
Check.False(FakeHost.ChatCommands.Contains("/myquests"), "not straight away");
|
||||
stamps.Tick(IltHubContext.NowMs + IltDynamicStamps.HandInRefreshMs + 1_000);
|
||||
Check.True(FakeHost.ChatCommands.Contains("/myquests"), "a /myquests after the hand-in");
|
||||
|
||||
// The loaded RynthAi answers "Unrecognized /ub command": Give turns itself off.
|
||||
hub.OnChat("[RynthAi] Unrecognized /ub command.");
|
||||
stamps.Rebuild();
|
||||
Check.True(stamps.Current.GiveReason != null && stamps.Current.GiveReason.Contains("Unrecognized"), "rejected right after the send: Give is off");
|
||||
int sends = FakeHost.ChatCommands.Count(c => c.StartsWith("/ub give"));
|
||||
stamps.Give(felscuda, "Parchment of Learning");
|
||||
Check.Eq(FakeHost.ChatCommands.Count(c => c.StartsWith("/ub give")), sends, "no further /ub give goes out");
|
||||
}
|
||||
|
||||
private static void Parchment()
|
||||
{
|
||||
IltHubController hub = NewHub("InfiniteLeaftide", "parchment", withAi: true);
|
||||
IltDynamicStamps stamps = hub.DynamicStamps;
|
||||
stamps.Tick(IltHubContext.NowMs);
|
||||
Check.False(stamps.Current.Built, "nothing is built while the page isn't on screen");
|
||||
stamps.MarkWatched();
|
||||
stamps.Tick(IltHubContext.NowMs);
|
||||
Check.True(stamps.Current.Built && stamps.Current.Parchment == null, "on screen: built; no Parchment carried");
|
||||
Check.Null(stamps.Current.GiveReason, "RynthAi is there: Give would work");
|
||||
|
||||
FakeHost.Containers[0x7000A002] = Player;
|
||||
FakeHost.Names[0x7000A002] = "Parchment of Learning";
|
||||
stamps.Tick(IltHubContext.NowMs + 2_000);
|
||||
Check.Eq(stamps.Current.Parchment, "Parchment of Learning", "a Parchment in the main pack is found");
|
||||
}
|
||||
}
|
||||
113
Tools/RynthILT.Tests/T11Tests.cs
Normal file
113
Tools/RynthILT.Tests/T11Tests.cs
Normal file
|
|
@ -0,0 +1,113 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using RynthCore.Loot.T11;
|
||||
using RynthCore.Plugin.RynthILT;
|
||||
using RynthCore.Plugin.RynthILT.Hub;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthILT.Tests;
|
||||
|
||||
// T11 (ACECustom tier 11+ gear) moved from RynthAi on 2026-10-20 (Hub/IltT11.cs): RynthILT reads the
|
||||
// "/aug" reply's wield counters, applies its item-aug override and reports them to RynthAi's loot rules
|
||||
// (RynthAi.Hub SetPlayerCounter); "/ilt t11" (and RynthAi's "/ra t11", passed on) shows and sets them.
|
||||
internal static class T11Tests
|
||||
{
|
||||
private const uint Player = 0x50000E01;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("t11 (RynthILT): the /aug reply's counters go to RynthAi, with the item-aug override applied", ReportsCounters);
|
||||
r.Add("t11 (RynthILT): /ilt t11 and /ra t11 are RynthILT's verbs; augs sets the override", Commands);
|
||||
r.Add("t11 (RynthILT): off ILT nothing is read or reported", DormantOffIlt);
|
||||
r.Add("migration: the RynthAi profile's T11 item-aug override comes over once", ImportsOverride);
|
||||
}
|
||||
|
||||
private static IltHubController NewHub(string world, string folder)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeAiHub.Reset();
|
||||
FakeHost.WorldName = world;
|
||||
var host = FakeHost.Create(Player);
|
||||
var ai = new RynthAiClient(host);
|
||||
ai.UseTableForTests(FakeAiHub.Table);
|
||||
string dir = Path.Combine(Program.TempRoot, "t11-" + folder);
|
||||
if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true);
|
||||
Directory.CreateDirectory(dir);
|
||||
var hub = new IltHubController(host, dir, new IltSettings(), ai);
|
||||
hub.OnLoginComplete("Augger", forceFromMigration: false);
|
||||
return hub;
|
||||
}
|
||||
|
||||
private static void ReportsCounters()
|
||||
{
|
||||
var hub = NewHub("InfiniteLeaftide", "report");
|
||||
hub.T11.Tick(Environment.TickCount64);
|
||||
Check.Eq(FakeAiHub.Counters[(uint)T11Counter.ItemAugmentations], -1L, "unknown before /aug (reported as -1)");
|
||||
Check.Eq(hub.T11.LastReported, T11Catalog.CounterNames.Length, "every counter is reported");
|
||||
|
||||
hub.OnChat("Advanced Augmentation Levels:");
|
||||
hub.OnChat("Item:2,400");
|
||||
hub.OnChat("Triune Weave: 5 (adds 5 to your aug counts)");
|
||||
hub.T11.Tick(Environment.TickCount64);
|
||||
Check.Eq(FakeAiHub.Counters[(uint)T11Counter.ItemAugmentations], 2400L, "Item: 2,400 reported");
|
||||
Check.Eq(FakeAiHub.Counters[(uint)T11Counter.TriuneWeave], 5L, "Triune Weave: 5 reported");
|
||||
|
||||
hub.State.T11.ItemAugsOverride = 2500;
|
||||
hub.T11.Tick(Environment.TickCount64);
|
||||
Check.Eq(FakeAiHub.Counters[(uint)T11Counter.ItemAugmentations], 2500L, "the override replaces /aug's item count");
|
||||
hub.State.T11.ItemAugsOverride = -1;
|
||||
hub.T11.Tick(Environment.TickCount64);
|
||||
Check.Eq(FakeAiHub.Counters[(uint)T11Counter.ItemAugmentations], 2400L, "auto again: /aug's count");
|
||||
|
||||
hub.OnLogout();
|
||||
hub.T11.Tick(Environment.TickCount64);
|
||||
Check.Eq(FakeAiHub.Counters[(uint)T11Counter.ItemAugmentations], -1L, "after logout: unknown again");
|
||||
}
|
||||
|
||||
private static void Commands()
|
||||
{
|
||||
Check.True(RynthILTPlugin.IsIltVerb(new[] { "t11" }), "/ra t11 is RynthILT's (RynthAi passes it on)");
|
||||
Check.True(RynthILTPlugin.IsIltVerb(new[] { "t11", "augs", "5" }), "with its arguments");
|
||||
Check.True(RynthILTPlugin.IsIltVerb(new[] { "ub", "qblist" }) && RynthILTPlugin.IsIltVerb(new[] { "ub", "augs" }),
|
||||
"ub-IT's /ub qblist and /ub augs (ACECustom commands RynthAi passes on) are RynthILT's");
|
||||
Check.False(RynthILTPlugin.IsIltVerb(new[] { "ub", "wear" }) || RynthILTPlugin.IsIltVerb(new[] { "ub" }), "no other /ub verb");
|
||||
|
||||
var hub = NewHub("InfiniteLeaftide", "cmd");
|
||||
FakeHost.Chat.Clear();
|
||||
hub.T11.HandleCommand(new[] { "augs", "3,000" });
|
||||
Check.Eq(hub.State.T11.ItemAugsOverride, 3000, "augs 3,000 fixes the override");
|
||||
Check.Eq(FakeAiHub.Counters[(uint)T11Counter.ItemAugmentations], 3000L, "and reports it at once");
|
||||
hub.T11.HandleCommand(new[] { "augs", "auto" });
|
||||
Check.Eq(hub.State.T11.ItemAugsOverride, -1, "augs auto clears it");
|
||||
FakeHost.Chat.Clear();
|
||||
hub.T11.HandleCommand(Array.Empty<string>());
|
||||
Check.True(FakeHost.Chat.Any(l => l.Contains("=== T11 loot")), "no argument: the status");
|
||||
Check.True(FakeHost.Chat.Any(l => l.Contains("Item Augmentations") || l.Contains("unknown")), "lists the counters");
|
||||
FakeHost.Chat.Clear();
|
||||
hub.T11.HandleCommand(new[] { "augs", "-5" });
|
||||
Check.True(FakeHost.Chat.Any(l => l.Contains("Usage")), "a bad count: usage");
|
||||
}
|
||||
|
||||
private static void DormantOffIlt()
|
||||
{
|
||||
var off = NewHub("Aeshnidae", "off");
|
||||
off.OnChat("Advanced Augmentation Levels:");
|
||||
off.OnChat("Item:2,400");
|
||||
for (int i = 0; i < 3; i++) off.Tick();
|
||||
Check.Eq(FakeAiHub.Counters.Count, 0, "off ILT: no counter is reported to RynthAi");
|
||||
Check.True(off.T11.Player.Get(T11Counter.ItemAugmentations) == null, "nor read");
|
||||
}
|
||||
|
||||
private static void ImportsOverride()
|
||||
{
|
||||
string legacy = Path.Combine(IltMigration.LegacyProfilesBase, "InfiniteLeaftide", "Augger");
|
||||
Directory.CreateDirectory(legacy);
|
||||
File.WriteAllText(Path.Combine(legacy, "Default.json"), "{ \"T11ItemAugsOverride\": 2750 }");
|
||||
var state = new IltHubState();
|
||||
Check.Eq(state.T11.ItemAugsOverride, -1, "automatic by default");
|
||||
IltMigration.ImportRynthAiSettings(state, "InfiniteLeaftide", "Augger");
|
||||
Check.Eq(state.T11.ItemAugsOverride, 2750, "the RynthAi profile's override came over");
|
||||
}
|
||||
}
|
||||
527
Tools/RynthILT.Tests/VaultedDungeonsTests.cs
Normal file
527
Tools/RynthILT.Tests/VaultedDungeonsTests.cs
Normal file
|
|
@ -0,0 +1,527 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using RynthCore.Plugin.RynthILT.Hub;
|
||||
using RynthCore.Plugin.Shared;
|
||||
using RynthCore.PluginSdk;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthILT.Tests;
|
||||
|
||||
// The Vaulted Dungeons keeper (Hub/IltVaultedDungeons.cs, Silentkelpie's, taken in with the owner's
|
||||
// safety rules): ILT only, a master switch (RynthAi's setting, off by default) that gates everything,
|
||||
// no resume of Active from the saved file, a recall that waits out combat / buffing, /rc quit once per
|
||||
// activation and never while gated, and a no-kill timer that restarts on kills and captures.
|
||||
// The clock, the master switch, RynthAi's activity and the gem use are the module's test seams.
|
||||
internal static class VaultedDungeonsTests
|
||||
{
|
||||
private const uint Player = 0x50000C01;
|
||||
private const uint Quarry = 0x01F7; // dungeon 1: Tyrant's Quarry
|
||||
private const uint Elsewhere = 0x0001;
|
||||
private const string Luminance = "You've banked 1,234 Luminance.";
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("vaulted: not an ILT world -> inert (no tick work, no recall, no quit, a 'not available' reply)", NotIlt);
|
||||
r.Add("vaulted: master off -> inert even with a saved Active, Auto Start and Kill Client", MasterOff);
|
||||
r.Add("vaulted: master on + explicit start -> recalls at 1 s then every 5 s outside, stops inside; a saved Active is not resumed", ExplicitStartRecalls);
|
||||
r.Add("vaulted: Auto Start On Arrival is honoured only with the master on", AutoStart);
|
||||
r.Add("vaulted: Kill Client fires once per activation and restarts on luminance, a killing blow and a capture", QuitOnceAndResets);
|
||||
r.Add("vaulted: Kill Client is never sent once the master goes off, even between the timer and the send", QuitNeverWhenGated);
|
||||
r.Add("vaulted: a busy bot (combat, buffing, server wait, client busy) defers the recall; the warning keeps its cadence", BusyDefers);
|
||||
r.Add("vaulted: turning the master off mid-run stops it at once and says so once; turning it on starts Off", MasterOffMidRun);
|
||||
r.Add("vaulted: the tab and /ra hub open vaulted follow ILT + the master; settings file format kept", TabAndFile);
|
||||
r.Add("vaulted: capture lines are the Pets tab's own success replies", CaptureLines);
|
||||
r.Add("vaulted: settings go through the source-generated JSON context (NativeAOT has no reflection serializer)", SourceGeneratedContext);
|
||||
}
|
||||
|
||||
// ── Rig ──────────────────────────────────────────────────────────────────
|
||||
|
||||
private sealed class Rig
|
||||
{
|
||||
public IltHubController Hub = null!;
|
||||
public IltVaultedDungeons V = null!;
|
||||
public string Dir = "";
|
||||
public long T = 1_000_000;
|
||||
public bool Master;
|
||||
public RynthAiActivity? Act = RynthAiActivity.None;
|
||||
public int MasterCalls, AllowCalls = int.MaxValue;
|
||||
public readonly List<string> GemsUsed = new();
|
||||
public bool HasGem = true;
|
||||
|
||||
public int Quits => FakeHost.ChatCommands.Count(c => c == "/rc quit");
|
||||
public int ChatCount(string part) => FakeHost.Chat.Count(c => c.Contains(part, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
public void Step(long ms) { T += ms; V.Tick(T); }
|
||||
public void Inside() => FakeHost.PlayerPose = ((Quarry << 16) | 0x0100u, 0, 0, 0);
|
||||
public void Outside() => FakeHost.PlayerPose = ((Elsewhere << 16) | 0x0100u, 0, 0, 0);
|
||||
public string SettingsFile => Path.Combine(Dir, "VaultedDungeons", "settings.json");
|
||||
public void WriteSettings(string json)
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(SettingsFile)!);
|
||||
File.WriteAllText(SettingsFile, json);
|
||||
}
|
||||
}
|
||||
|
||||
private static Rig NewRig(string world, string folder, bool master, bool busyCalls = false)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.WorldName = world;
|
||||
FakeHost.BusyCalls = busyCalls;
|
||||
var host = FakeHost.Create(Player);
|
||||
var rig = new Rig { Master = master, Dir = Path.Combine(Program.TempRoot, folder) };
|
||||
Directory.CreateDirectory(rig.Dir);
|
||||
rig.Hub = new IltHubController(host, rig.Dir, new IltSettings(), new RynthAiClient(host));
|
||||
rig.V = rig.Hub.VaultedDungeons;
|
||||
rig.V.Clock = () => rig.T;
|
||||
rig.V.MasterEnabled = () => { rig.MasterCalls++; return rig.Master && rig.MasterCalls <= rig.AllowCalls; };
|
||||
rig.V.Activity = () => rig.Act;
|
||||
rig.V.UseGem = name => { if (!rig.HasGem) return false; rig.GemsUsed.Add(name); return true; };
|
||||
rig.Outside();
|
||||
return rig;
|
||||
}
|
||||
|
||||
/// <summary>Dungeon 1 (Tyrant's Quarry), the primary gem, the given extras. "active": true is on disk to prove it is ignored.</summary>
|
||||
private static string Settings(string extras = "")
|
||||
=> "{ \"active\": true, \"dungeon\": 1, \"gem\": 1" + (extras.Length > 0 ? ", " + extras : "") + " }";
|
||||
|
||||
// ── ILT only ─────────────────────────────────────────────────────────────
|
||||
|
||||
private static void NotIlt()
|
||||
{
|
||||
var rig = NewRig("Aelrynth", "vd-notilt", master: true);
|
||||
rig.WriteSettings(Settings("\"autoStart\": true, \"quit\": true, \"quitMinutes\": 1"));
|
||||
string before = File.ReadAllText(rig.SettingsFile);
|
||||
|
||||
rig.Outside();
|
||||
for (int i = 0; i < 20; i++) rig.Step(1000);
|
||||
rig.Inside();
|
||||
for (int i = 0; i < 10; i++) rig.Step(30_000);
|
||||
Check.False(rig.V.IsActive, "not running on another world, though the master is on and Auto Start was saved");
|
||||
Check.Eq(rig.GemsUsed.Count, 0, "no recall gem");
|
||||
Check.Eq(rig.Quits, 0, "no /rc quit");
|
||||
Check.Eq(FakeHost.ChatCommands.Count, 0, "no command of any kind (no /vt, /ub or /rc)");
|
||||
Check.Eq(rig.ChatCount("[Vaulted Dungeons]"), 0, "and not a word in chat");
|
||||
Check.Eq(File.ReadAllText(rig.SettingsFile), before, "the settings file wasn't even read or rewritten");
|
||||
|
||||
rig.V.HandleCommand(new[] { "on" });
|
||||
Check.False(rig.V.IsActive, "/ilt vaulted on is refused");
|
||||
Check.Eq(rig.ChatCount("Not available on this server"), 1, "with the 'not available on this server' reply");
|
||||
FakeHost.Chat.Clear();
|
||||
rig.V.HandleCommand(new[] { "status" });
|
||||
Check.Eq(rig.ChatCount("Not available on this server"), 1, "status says the same");
|
||||
Check.False(rig.Hub.TabShown(IltSection.VaultedDungeons), "no tab");
|
||||
Check.False(rig.Hub.SectionAvailable(IltSection.VaultedDungeons), "not available");
|
||||
|
||||
// The controller doesn't tick it either (and the module would refuse anyway).
|
||||
rig.Hub.Tick();
|
||||
Check.Eq(rig.GemsUsed.Count, 0, "the controller's tick does nothing here");
|
||||
}
|
||||
|
||||
// ── Master switch ────────────────────────────────────────────────────────
|
||||
|
||||
private static void MasterOff()
|
||||
{
|
||||
var rig = NewRig("InfiniteLeaftide", "vd-masteroff", master: false);
|
||||
rig.WriteSettings(Settings("\"autoStart\": true, \"quit\": true, \"quitMinutes\": 1, \"disableMeta\": true"));
|
||||
string before = File.ReadAllText(rig.SettingsFile);
|
||||
|
||||
rig.Outside();
|
||||
for (int i = 0; i < 20; i++) rig.Step(1000);
|
||||
rig.Inside();
|
||||
for (int i = 0; i < 10; i++) rig.Step(30_000); // five minutes inside: a one-minute Kill Client would have fired
|
||||
Check.False(rig.V.IsActive, "off: a saved Active and Auto Start start nothing");
|
||||
Check.Eq(rig.GemsUsed.Count, 0, "no recall gem");
|
||||
Check.Eq(rig.Quits, 0, "no /rc quit");
|
||||
Check.Eq(FakeHost.ChatCommands.Count, 0, "no arrival commands (/vt opt set ...) either");
|
||||
Check.Eq(rig.ChatCount("[Vaulted Dungeons]"), 0, "silent");
|
||||
Check.Eq(File.ReadAllText(rig.SettingsFile), before, "settings untouched");
|
||||
Check.True(rig.Hub.Options.IsIltLikeWorld, "(it is an ILT world: the master switch is what holds it)");
|
||||
Check.False(rig.Hub.TabShown(IltSection.VaultedDungeons), "the tab is hidden");
|
||||
Check.False(rig.Hub.SectionAvailable(IltSection.VaultedDungeons), "and not available");
|
||||
|
||||
rig.V.HandleCommand(new[] { "on" });
|
||||
Check.False(rig.V.IsActive, "/ilt vaulted on is refused");
|
||||
Check.Eq(rig.ChatCount("Settings > Navigation"), 1, "and says where the switch is");
|
||||
rig.V.HandleCommand(new[] { "toggle" });
|
||||
Check.False(rig.V.IsActive, "toggle too");
|
||||
|
||||
// Through the controller, the real wiring: nothing either.
|
||||
for (int i = 0; i < 5; i++) rig.Hub.Tick();
|
||||
Check.Eq(rig.GemsUsed.Count, 0, "the controller's tick does nothing while off");
|
||||
|
||||
// The lines that restart the timer are ignored too (nothing is running).
|
||||
rig.V.OnChat(Luminance);
|
||||
rig.V.OnKillNotification();
|
||||
Check.Eq(rig.Quits, 0, "still nothing");
|
||||
}
|
||||
|
||||
// ── Recalls ──────────────────────────────────────────────────────────────
|
||||
|
||||
private static void ExplicitStartRecalls()
|
||||
{
|
||||
var rig = NewRig("InfiniteLeaftide", "vd-recall", master: true);
|
||||
rig.WriteSettings(Settings()); // "active": true on disk: ignored
|
||||
rig.Outside();
|
||||
rig.Step(0);
|
||||
Check.False(rig.V.IsActive, "a saved Active is not resumed after login");
|
||||
for (int i = 0; i < 10; i++) rig.Step(1000);
|
||||
Check.Eq(rig.GemsUsed.Count, 0, "so nothing is recalled until the player starts it");
|
||||
|
||||
rig.V.HandleCommand(new[] { "on" });
|
||||
Check.True(rig.V.IsActive, "an explicit start");
|
||||
rig.Step(0); // first tick outside: the clock starts
|
||||
rig.Step(500);
|
||||
Check.Eq(rig.GemsUsed.Count, 0, "0.5 s out: too early");
|
||||
rig.Step(500); // 1 s
|
||||
Check.Eq(rig.GemsUsed.Count, 1, "the first recall comes 1 s after leaving");
|
||||
Check.Eq(rig.GemsUsed[0], "Primary Portal Recall Gem", "the chosen gem");
|
||||
rig.Step(4000);
|
||||
Check.Eq(rig.GemsUsed.Count, 1, "4 s later: not yet");
|
||||
rig.Step(1000); // 5 s since the last use
|
||||
Check.Eq(rig.GemsUsed.Count, 2, "then every 5 s");
|
||||
rig.Step(5000);
|
||||
Check.Eq(rig.GemsUsed.Count, 3, "again");
|
||||
|
||||
rig.Inside();
|
||||
rig.Step(1000);
|
||||
for (int i = 0; i < 12; i++) rig.Step(1000);
|
||||
Check.Eq(rig.GemsUsed.Count, 3, "inside the dungeon: no more gems");
|
||||
|
||||
FakeHost.Portaling = true;
|
||||
rig.Outside();
|
||||
rig.Step(10_000);
|
||||
Check.Eq(rig.GemsUsed.Count, 3, "portal space: nothing used");
|
||||
FakeHost.Portaling = false;
|
||||
rig.Step(0);
|
||||
rig.Step(1000);
|
||||
Check.Eq(rig.GemsUsed.Count, 4, "out again: 1 s, then a recall");
|
||||
|
||||
rig.HasGem = false;
|
||||
rig.Step(5000);
|
||||
Check.Eq(rig.GemsUsed.Count, 4, "no gem in the pack: none used");
|
||||
Check.True(rig.ChatCount("No Primary Portal Recall Gem") >= 1, "and it says so");
|
||||
}
|
||||
|
||||
private static void AutoStart()
|
||||
{
|
||||
// Master on: arriving in the chosen dungeon switches it on, and the arrival commands go out.
|
||||
var on = NewRig("InfiniteLeaftide", "vd-auto-on", master: true);
|
||||
on.WriteSettings(Settings("\"autoStart\": true, \"disableMeta\": true"));
|
||||
on.Inside();
|
||||
on.Step(0);
|
||||
Check.True(on.V.IsActive, "Auto Start On Arrival switches the keeper on (master on)");
|
||||
Check.True(FakeHost.ChatCommands.Contains("/vt opt set EnableMeta False"), "and runs the arrival commands");
|
||||
|
||||
// Auto Start off, master on: a relog inside does not resume a saved Active.
|
||||
var manual = NewRig("InfiniteLeaftide", "vd-auto-off", master: true);
|
||||
manual.WriteSettings(Settings("\"disableMeta\": true"));
|
||||
manual.Inside();
|
||||
manual.Step(0);
|
||||
Check.False(manual.V.IsActive, "no Auto Start: not resumed");
|
||||
Check.Eq(FakeHost.ChatCommands.Count, 0, "and the arrival commands wait for an Active keeper");
|
||||
|
||||
// Master off, Auto Start saved: nothing; then the master comes on while inside.
|
||||
var gated = NewRig("InfiniteLeaftide", "vd-auto-gated", master: false);
|
||||
gated.WriteSettings(Settings("\"autoStart\": true"));
|
||||
gated.Inside();
|
||||
gated.Step(0);
|
||||
Check.False(gated.V.IsActive, "master off: Auto Start does nothing");
|
||||
gated.Master = true;
|
||||
gated.Step(1000);
|
||||
Check.True(gated.V.IsActive, "with the master on, Auto Start (the player's own saved choice) applies");
|
||||
}
|
||||
|
||||
// ── Kill Client ──────────────────────────────────────────────────────────
|
||||
|
||||
private static Rig QuitRig(string folder, int minutes = 2)
|
||||
{
|
||||
var rig = NewRig("InfiniteLeaftide", folder, master: true);
|
||||
rig.WriteSettings(Settings("\"quit\": true, \"quitMinutes\": " + minutes));
|
||||
rig.Inside();
|
||||
rig.Step(0);
|
||||
rig.V.HandleCommand(new[] { "on" });
|
||||
rig.Step(0); // inside: the no-kill clock starts here
|
||||
return rig;
|
||||
}
|
||||
|
||||
private static void QuitOnceAndResets()
|
||||
{
|
||||
// Luminance line.
|
||||
var rig = QuitRig("vd-quit-lum");
|
||||
rig.Step(119_000);
|
||||
Check.Eq(rig.Quits, 0, "just under 2 minutes: no quit");
|
||||
rig.V.OnChat(Luminance);
|
||||
rig.Step(119_000);
|
||||
Check.Eq(rig.Quits, 0, "the luminance line restarted the timer");
|
||||
rig.Step(2_000);
|
||||
Check.Eq(rig.Quits, 1, "2 minutes after the last kill: /rc quit");
|
||||
for (int i = 0; i < 10; i++) rig.Step(60_000);
|
||||
Check.Eq(rig.Quits, 1, "and only once");
|
||||
// A kill after the quit went out doesn't arm a second one (once per activation).
|
||||
rig.V.OnChat(Luminance);
|
||||
for (int i = 0; i < 10; i++) rig.Step(60_000);
|
||||
Check.Eq(rig.Quits, 1, "still once");
|
||||
|
||||
// The player's own killing blow.
|
||||
rig = QuitRig("vd-quit-kill");
|
||||
rig.Step(110_000);
|
||||
rig.V.OnKillNotification();
|
||||
rig.Step(110_000);
|
||||
Check.Eq(rig.Quits, 0, "a killing blow restarted the timer");
|
||||
rig.Step(15_000);
|
||||
Check.Eq(rig.Quits, 1, "and it fires after the next idle stretch");
|
||||
|
||||
// A pet capture.
|
||||
rig = QuitRig("vd-quit-capture");
|
||||
rig.Step(110_000);
|
||||
rig.V.OnChat("You have successfully siphoned the essence of the Olthoi Warrior.");
|
||||
rig.Step(110_000);
|
||||
Check.Eq(rig.Quits, 0, "a capture restarted the timer");
|
||||
rig.V.OnChat("The echo resonates perfectly.");
|
||||
rig.Step(110_000);
|
||||
Check.Eq(rig.Quits, 0, "so does the other success reply");
|
||||
rig.Step(15_000);
|
||||
Check.Eq(rig.Quits, 1, "then it fires");
|
||||
|
||||
// Lines that are not kills don't restart it.
|
||||
rig = QuitRig("vd-quit-noise");
|
||||
rig.Step(110_000);
|
||||
rig.V.OnChat("You hit the Olthoi Warrior for 50 points of damage.");
|
||||
rig.V.OnChat("The essence is not ready yet.");
|
||||
rig.V.OnChat("Bob says, \"You've banked 5 Luminance.\""); // a player's chat, not the system line
|
||||
rig.Step(15_000);
|
||||
Check.Eq(rig.Quits, 1, "damage lines, a refused capture and someone else's chat don't count");
|
||||
|
||||
// The minutes are the player's setting: 1 minute here.
|
||||
rig = QuitRig("vd-quit-1m", minutes: 1);
|
||||
rig.Step(59_000);
|
||||
Check.Eq(rig.Quits, 0, "1 minute setting: not yet");
|
||||
rig.Step(2_000);
|
||||
Check.Eq(rig.Quits, 1, "fires at 1 minute");
|
||||
|
||||
// Off -> on again is a new activation: one more quit may be sent.
|
||||
rig.V.HandleCommand(new[] { "off" });
|
||||
rig.V.HandleCommand(new[] { "on" });
|
||||
rig.Step(0);
|
||||
rig.Step(61_000);
|
||||
Check.Eq(rig.Quits, 2, "a new activation gets its own single quit");
|
||||
}
|
||||
|
||||
private static void QuitNeverWhenGated()
|
||||
{
|
||||
// The master goes off, the timer would have fired: nothing is sent, and it stopped.
|
||||
var rig = QuitRig("vd-quit-gated");
|
||||
rig.Step(100_000);
|
||||
rig.Master = false;
|
||||
rig.Step(30_000);
|
||||
Check.Eq(rig.Quits, 0, "master off before the timer: no /rc quit");
|
||||
Check.False(rig.V.IsActive, "and the keeper is off");
|
||||
rig.Step(600_000);
|
||||
Check.Eq(rig.Quits, 0, "ever");
|
||||
|
||||
// The master goes off between the timer firing and the send (asked again right before sending).
|
||||
rig = QuitRig("vd-quit-race");
|
||||
rig.Step(100_000);
|
||||
rig.AllowCalls = rig.MasterCalls + 1; // true at the top of the next tick, false when it re-checks
|
||||
rig.Step(21_000); // the timer fires in this tick
|
||||
Check.Eq(rig.Quits, 0, "master off between the timer firing and the send: not sent");
|
||||
Check.False(rig.V.IsActive, "the keeper stopped");
|
||||
Check.Eq(rig.ChatCount("Stopped"), 1, "said once");
|
||||
|
||||
// Not an ILT world any more (the world name changes): same.
|
||||
rig = QuitRig("vd-quit-world");
|
||||
rig.Step(100_000);
|
||||
FakeHost.WorldName = "Aelrynth";
|
||||
rig.Step(30_000);
|
||||
Check.Eq(rig.Quits, 0, "world no longer ILT: no /rc quit");
|
||||
Check.False(rig.V.IsActive, "stopped");
|
||||
|
||||
// Not Active: the timer has nothing to do (the player turned it off).
|
||||
rig = QuitRig("vd-quit-off");
|
||||
rig.V.HandleCommand(new[] { "off" });
|
||||
for (int i = 0; i < 10; i++) rig.Step(60_000);
|
||||
Check.Eq(rig.Quits, 0, "Off: no quit");
|
||||
}
|
||||
|
||||
// ── Combat / buff guard ──────────────────────────────────────────────────
|
||||
|
||||
private static void BusyDefers()
|
||||
{
|
||||
var rig = NewRig("InfiniteLeaftide", "vd-busy", master: true, busyCalls: true);
|
||||
rig.WriteSettings(Settings());
|
||||
rig.Outside();
|
||||
rig.Step(0);
|
||||
rig.V.HandleCommand(new[] { "on" });
|
||||
rig.Act = RynthAiActivity.MacroRunning | RynthAiActivity.Combat;
|
||||
rig.Step(0);
|
||||
rig.Step(1000);
|
||||
rig.Step(4000);
|
||||
Check.Eq(rig.GemsUsed.Count, 0, "in combat: the recall is deferred");
|
||||
Check.Eq(rig.ChatCount("Waiting to use the Primary Portal Recall Gem"), 1, "and says why, once");
|
||||
rig.Step(20_000);
|
||||
Check.Eq(rig.ChatCount("Waiting to use"), 1, "no repeat inside the 30 s warning cadence");
|
||||
rig.Step(10_000);
|
||||
Check.Eq(rig.ChatCount("Waiting to use"), 2, "the warning comes again after 30 s");
|
||||
Check.Eq(rig.GemsUsed.Count, 0, "still nothing used");
|
||||
|
||||
rig.Act = RynthAiActivity.MacroRunning; // clear
|
||||
rig.Step(100);
|
||||
Check.Eq(rig.GemsUsed.Count, 1, "the first clear tick recalls (it was due all along)");
|
||||
|
||||
// Buffing, the server wait, looting, salvaging, crafting and RynthAi not answering all defer too.
|
||||
foreach (RynthAiActivity? busy in new RynthAiActivity?[]
|
||||
{ RynthAiActivity.Buffing, RynthAiActivity.ServerAction, RynthAiActivity.Looting, RynthAiActivity.Salvaging, RynthAiActivity.Crafting, null })
|
||||
{
|
||||
int before = rig.GemsUsed.Count;
|
||||
rig.Act = busy;
|
||||
rig.Step(6000);
|
||||
Check.Eq(rig.GemsUsed.Count, before, $"busy ({(busy.HasValue ? busy.Value.ToString() : "RynthAi not ready")}): deferred");
|
||||
rig.Act = RynthAiActivity.None;
|
||||
rig.Step(100);
|
||||
Check.Eq(rig.GemsUsed.Count, before + 1, "and used once it is clear");
|
||||
}
|
||||
|
||||
// The client's own busy hourglass.
|
||||
FakeHost.BusyStateValue = 1;
|
||||
int n = rig.GemsUsed.Count;
|
||||
rig.Step(6000);
|
||||
Check.Eq(rig.GemsUsed.Count, n, "the client is busy: deferred");
|
||||
FakeHost.BusyStateValue = 0;
|
||||
rig.Step(100);
|
||||
Check.Eq(rig.GemsUsed.Count, n + 1, "used when it clears");
|
||||
|
||||
// Busy never blocks the Kill Client (it is not a game action that can be lost).
|
||||
var q = NewRig("InfiniteLeaftide", "vd-busy-quit", master: true);
|
||||
q.WriteSettings(Settings("\"quit\": true, \"quitMinutes\": 1"));
|
||||
q.Inside();
|
||||
q.Step(0);
|
||||
q.V.HandleCommand(new[] { "on" });
|
||||
q.Step(0);
|
||||
q.Act = RynthAiActivity.Combat;
|
||||
q.Step(61_000);
|
||||
Check.Eq(q.Quits, 1, "a busy bot still gets its Kill Client");
|
||||
}
|
||||
|
||||
// ── Master off mid-run ───────────────────────────────────────────────────
|
||||
|
||||
private static void MasterOffMidRun()
|
||||
{
|
||||
var rig = NewRig("InfiniteLeaftide", "vd-midrun", master: true);
|
||||
rig.WriteSettings(Settings("\"quit\": true, \"quitMinutes\": 1"));
|
||||
rig.Outside();
|
||||
rig.Step(0);
|
||||
rig.V.HandleCommand(new[] { "on" });
|
||||
rig.Step(0);
|
||||
rig.Step(1000);
|
||||
Check.Eq(rig.GemsUsed.Count, 1, "running: a recall went out");
|
||||
|
||||
rig.Master = false;
|
||||
rig.Step(10);
|
||||
Check.False(rig.V.IsActive, "the master went off: stopped on that very tick");
|
||||
Check.Eq(rig.ChatCount("Stopped"), 1, "and it said so");
|
||||
for (int i = 0; i < 20; i++) rig.Step(5000);
|
||||
Check.Eq(rig.GemsUsed.Count, 1, "no more recalls");
|
||||
Check.Eq(rig.ChatCount("Stopped"), 1, "and the notice wasn't repeated");
|
||||
Check.Eq(rig.Quits, 0, "no quit");
|
||||
|
||||
rig.Master = true;
|
||||
rig.Step(10);
|
||||
Check.False(rig.V.IsActive, "turned back on: it starts Off, nothing resumes by itself");
|
||||
rig.Step(10_000);
|
||||
Check.Eq(rig.GemsUsed.Count, 1, "nothing recalled");
|
||||
rig.V.HandleCommand(new[] { "on" });
|
||||
rig.Step(0);
|
||||
rig.Step(1000);
|
||||
Check.Eq(rig.GemsUsed.Count, 2, "until the player starts it again");
|
||||
|
||||
// The Mini Remote button path (posted to the pump) re-checks the switch as well.
|
||||
rig.V.HandleCommand(new[] { "off" });
|
||||
rig.Master = false;
|
||||
rig.Hub.Context.Post(() => rig.V.HandleCommand(new[] { "on" }));
|
||||
rig.Hub.Tick();
|
||||
Check.False(rig.V.IsActive, "an On click that lands after the switch went off is refused");
|
||||
}
|
||||
|
||||
// ── Tab, commands, file ──────────────────────────────────────────────────
|
||||
|
||||
private static void TabAndFile()
|
||||
{
|
||||
var rig = NewRig("InfiniteLeaftide", "vd-tab", master: true);
|
||||
Check.True(rig.Hub.TabShown(IltSection.VaultedDungeons), "ILT + master on: the tab is shown");
|
||||
Check.True(IltSections.Tabs.Contains(IltSection.VaultedDungeons), "it is one of the tab-bar tabs");
|
||||
Check.True(IltSections.IsTab(IltSection.VaultedDungeons), "a Mini Remote tab");
|
||||
Check.Eq(IltSections.TabId(IltSection.VaultedDungeons), "vaulted", "tab id");
|
||||
Check.True(IltSections.TryParse("vaulted", out var s) && s == IltSection.VaultedDungeons, "/ra hub open vaulted parses");
|
||||
Check.True(IltSections.TryParse("vaulted-dungeons", out s) && s == IltSection.VaultedDungeons, "and the long names");
|
||||
Check.True(RynthCore.Plugin.RynthILT.RynthILTPlugin.IsIltVerb(new[] { "hub", "open", "vaulted" }), "RynthILT takes '/ra hub open vaulted'");
|
||||
rig.Master = false;
|
||||
Check.False(rig.Hub.TabShown(IltSection.VaultedDungeons), "master off: hidden");
|
||||
|
||||
// The file: the format Silentkelpie's keeper wrote, kept. A start is saved.
|
||||
rig = NewRig("InfiniteLeaftide", "vd-file", master: true);
|
||||
rig.WriteSettings("""{ "dungeon": 3, "gem": 2, "quit": true, "quitMinutes": 7, "autoStart": false, "attackPower": 0.5 }""");
|
||||
rig.V.HandleCommand(new[] { "status" });
|
||||
Check.Eq(rig.ChatCount("dungeon=Wailing Cells, gem=Secondary Portal Recall Gem, kill-client=7m"), 1, "dungeon list and gem names as upstream");
|
||||
rig.V.HandleCommand(new[] { "on" });
|
||||
rig.Step(0);
|
||||
string saved = File.ReadAllText(rig.SettingsFile);
|
||||
Check.True(saved.Contains("\"active\": true") && saved.Contains("\"quitMinutes\": 7") && saved.Contains("\"dungeon\": 3"),
|
||||
"saved in the same camelCase layout");
|
||||
|
||||
// A new session (relog) reads it back with Active Off.
|
||||
var again = NewRig("InfiniteLeaftide", "vd-file", master: true);
|
||||
FakeHost.Chat.Clear();
|
||||
again.V.HandleCommand(new[] { "status" });
|
||||
Check.True(again.ChatCount("Off — dungeon=Wailing Cells") == 1 && !again.V.IsActive, "the next session starts Off, with the same choices");
|
||||
}
|
||||
|
||||
// The NativeAOT build (what ships) turns reflection-based System.Text.Json off, so the keeper's
|
||||
// settings must use IltVaultedDungeonsJsonContext. This project runs on the normal runtime where
|
||||
// reflection would still work, so assert the generated metadata exists and that the file layout
|
||||
// is what the context (not an options object) produces.
|
||||
private static void SourceGeneratedContext()
|
||||
{
|
||||
var ctx = IltVaultedDungeonsJsonContext.Default;
|
||||
Check.True(ctx.Cfg != null, "the context has metadata for the settings type (IltVaultedDungeonsJsonContext.Default.Cfg)");
|
||||
Check.True(ctx.GetTypeInfo(typeof(IltVaultedDungeons.Cfg)) != null, "and resolves it by type");
|
||||
|
||||
var cfg = new IltVaultedDungeons.Cfg
|
||||
{
|
||||
Active = true, Dungeon = 3, Gem = 2, Quit = true, QuitMinutes = 7, ShowInDungeon = true,
|
||||
AutoStart = true, DisableMeta = true, DisableNav = false, RepeatAttack = true, SetPower = true, AttackPower = 0.5f,
|
||||
};
|
||||
string json = System.Text.Json.JsonSerializer.Serialize(cfg, ctx.Cfg);
|
||||
Check.True(json.Contains("\"active\": true") && json.Contains("\"quitMinutes\": 7") && json.Contains("\"attackPower\": 0.5"),
|
||||
"serializes indented with camelCase names");
|
||||
Check.True(json.Contains("\n"), "indented");
|
||||
|
||||
var back = System.Text.Json.JsonSerializer.Deserialize(json, ctx.Cfg);
|
||||
Check.True(back != null, "round-trips");
|
||||
Check.True(back!.Active && back.Dungeon == 3 && back.Gem == 2 && back.Quit && back.QuitMinutes == 7 && back.ShowInDungeon
|
||||
&& back.AutoStart && back.DisableMeta && !back.DisableNav && back.RepeatAttack && back.SetPower && back.AttackPower == 0.5f,
|
||||
"every field survives");
|
||||
|
||||
// The shape of the file Silentkelpie's keeper wrote (camelCase, partial) still reads.
|
||||
var upstream = System.Text.Json.JsonSerializer.Deserialize(
|
||||
"""{ "dungeon": 2, "gem": 1, "quit": true, "quitMinutes": 5 }""", ctx.Cfg);
|
||||
Check.True(upstream != null && upstream.Dungeon == 2 && upstream.Gem == 1 && upstream.Quit && upstream.QuitMinutes == 5 && !upstream.Active,
|
||||
"a partial upstream file reads, missing fields keep their defaults");
|
||||
|
||||
bool threw = false;
|
||||
try { System.Text.Json.JsonSerializer.Deserialize("{ not json", ctx.Cfg); } catch (System.Text.Json.JsonException) { threw = true; }
|
||||
Check.True(threw, "a corrupt file still throws, which the keeper's bad-file copy relies on");
|
||||
}
|
||||
|
||||
private static void CaptureLines()
|
||||
{
|
||||
Check.True(PetCaptureLines.IsSuccess("You have successfully siphoned the essence."), "siphoned");
|
||||
Check.True(PetCaptureLines.IsSuccess("The echo resonates perfectly."), "echo");
|
||||
Check.True(PetCaptureLines.IsSuccess("The essence is captured!"), "captured");
|
||||
Check.False(PetCaptureLines.IsSuccess("The creature is too strong to be siphoned."), "a refusal is not a success");
|
||||
Check.False(PetCaptureLines.IsSuccess("siphon failed"), "nor a failure");
|
||||
Check.False(PetCaptureLines.IsSuccess(""), "empty");
|
||||
}
|
||||
}
|
||||
64
Tools/RynthILT.Tests/VaultedSwitchTests.cs
Normal file
64
Tools/RynthILT.Tests/VaultedSwitchTests.cs
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using RynthCore.Plugin.RynthILT.Hub;
|
||||
using RynthCore.Plugin.Shared;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthILT.Tests;
|
||||
|
||||
// The Vaulted Dungeons keeper's master switch moved from RynthAi's profile to RynthILT on 2026-10-20
|
||||
// (IltHubState.VaultedDungeonsEnabled, the ILT settings view). RynthAi mirrors it into the engine's
|
||||
// Settings > Navigation row through RynthILT.Hub GetSetting / SetSetting, which offer it on ILT only.
|
||||
internal static class VaultedSwitchTests
|
||||
{
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("vaulted switch: RynthILT's own (off by default), what the keeper reads, offered to the engine row on ILT only", OwnSwitch);
|
||||
r.Add("migration: the RynthAi profile's Vaulted Dungeons switch comes over once", ImportsSwitch);
|
||||
}
|
||||
|
||||
private static IltHubController NewHub(string world, string folder)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.WorldName = world;
|
||||
var host = FakeHost.Create(0x50000C01);
|
||||
string dir = Path.Combine(Program.TempRoot, "vswitch-" + folder);
|
||||
if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true);
|
||||
Directory.CreateDirectory(dir);
|
||||
var hub = new IltHubController(host, dir, new IltSettings(), new RynthAiClient(host));
|
||||
hub.OnLoginComplete("Vaulter", forceFromMigration: false);
|
||||
return hub;
|
||||
}
|
||||
|
||||
private static void OwnSwitch()
|
||||
{
|
||||
var hub = NewHub("InfiniteLeaftide", "own");
|
||||
Check.False(hub.State.VaultedDungeonsEnabled, "off by default");
|
||||
Check.False(hub.VaultedDungeons.MasterEnabled(), "the keeper reads RynthILT's own switch (no RynthAi needed)");
|
||||
Check.False(hub.SectionAvailable(IltSection.VaultedDungeons), "no tab while off");
|
||||
Check.Eq(hub.GetSetting(RynthServerHub.SettingVaultedDungeons), 0, "offered to the engine row: off");
|
||||
Check.True(hub.SetSetting(RynthServerHub.SettingVaultedDungeons, 1), "the engine row (through RynthAi) sets it");
|
||||
Check.True(hub.State.VaultedDungeonsEnabled && hub.VaultedDungeons.MasterEnabled(), "on");
|
||||
Check.True(hub.SectionAvailable(IltSection.VaultedDungeons), "the tab shows on ILT");
|
||||
Check.Eq(hub.GetSetting("no-such-setting"), -1, "an unknown key isn't offered");
|
||||
Check.False(hub.SetSetting("no-such-setting", 1), "nor taken");
|
||||
|
||||
var off = NewHub("Aeshnidae", "off");
|
||||
Check.Eq(off.GetSetting(RynthServerHub.SettingVaultedDungeons), -1, "off ILT: not offered (the engine row hides)");
|
||||
}
|
||||
|
||||
private static void ImportsSwitch()
|
||||
{
|
||||
string legacy = Path.Combine(IltMigration.LegacyProfilesBase, "InfiniteLeaftide", "Vaulter");
|
||||
Directory.CreateDirectory(legacy);
|
||||
File.WriteAllText(Path.Combine(legacy, "Default.json"), "{ \"EnableVaultedDungeons\": true }");
|
||||
var state = new IltHubState();
|
||||
var lines = IltMigration.ImportRynthAiSettings(state, "InfiniteLeaftide", "Vaulter");
|
||||
Check.True(state.VaultedDungeonsEnabled, "on in the RynthAi profile: on here");
|
||||
Check.True(lines.Exists(l => l.Contains("Vaulted Dungeons master switch on")), "logged");
|
||||
state.VaultedDungeonsEnabled = false;
|
||||
IltMigration.ImportRynthAiSettings(state, "InfiniteLeaftide", "Vaulter");
|
||||
Check.False(state.VaultedDungeonsEnabled, "copied once: RynthILT's later change stays");
|
||||
}
|
||||
}
|
||||
355
Tools/RynthOracle.QuestPackGen/Program.cs
Normal file
355
Tools/RynthOracle.QuestPackGen/Program.cs
Normal file
|
|
@ -0,0 +1,355 @@
|
|||
using System.Globalization;
|
||||
using System.IO.Compression;
|
||||
using System.Text;
|
||||
|
||||
namespace RynthOracle.QuestPackGen;
|
||||
|
||||
/// <summary>
|
||||
/// Generates a server quest pack for RynthOracle from an ACE world-database dump.
|
||||
///
|
||||
/// Every row of the world's `quest` table (the flags /myquests can show: ACE leaves out flags
|
||||
/// without a row) becomes a pack row with its timer (min_Delta, seconds, before the server's
|
||||
/// quest_mindelta_rate), its solve limit, its message, and who sets it (NPCs whose emotes
|
||||
/// stamp, increment or update the flag; else NPCs that check it). The curated text stays
|
||||
/// Advis's: for a flag in the base list the pack leaves Quest, Url and Hint empty (the plugin
|
||||
/// keeps the base row's text and only fills empty fields), and a flag that only another
|
||||
/// server's pack knows takes that pack's text. Base flags missing from the quest table get a
|
||||
/// NotOnServer row, so the plugin hides them on this server (their status can never be read).
|
||||
/// </summary>
|
||||
internal static class Program
|
||||
{
|
||||
// EmoteType (ACE.Entity.Enum.EmoteType)
|
||||
private static readonly HashSet<int> SetTypes = new() { 20, 22, 33, 60, 61, 70, 79, 81, 85, 86 };
|
||||
private static readonly HashSet<int> CheckTypes = new() { 21, 30, 58, 80, 82 };
|
||||
|
||||
private static int Main(string[] args)
|
||||
{
|
||||
try
|
||||
{
|
||||
string server = Arg(args, "-server") ?? "Aelrynth";
|
||||
string resources = Arg(args, "-resources") ?? FindResources();
|
||||
// The server plugins (RynthServers\Plugins, since 2026-10-21; RynthOracle stays in RynthSuite).
|
||||
string pluginsDir = Arg(args, "-plugins") ?? FindServerPlugins();
|
||||
string dump = Arg(args, "-dump") ?? NewestDump();
|
||||
// A server's pack lives in its server plugin (since 2026-10-21): Plugins\RynthCore.Plugin.Rynth<Server>\Resources.
|
||||
string output = Arg(args, "-out") ?? Path.Combine(pluginsDir,
|
||||
"RynthCore.Plugin.Rynth" + server, "Resources", $"quests.{server.ToLowerInvariant()}.csv");
|
||||
Console.WriteLine($"dump: {dump}");
|
||||
Console.WriteLine($"resources: {resources}");
|
||||
Console.WriteLine($"out: {output}");
|
||||
|
||||
var db = WorldDump.Read(dump);
|
||||
Console.WriteLine($"read {db.Quests.Count} quests, {db.Names.Count} weenie names, {db.EmoteOwner.Count} emotes, {db.Actions.Count} quest emote actions");
|
||||
|
||||
Dictionary<string, CuratedRow> baseRows = Curated.Load(Path.Combine(resources, "quests.csv"));
|
||||
var otherPacks = new Dictionary<string, CuratedRow>(StringComparer.OrdinalIgnoreCase);
|
||||
// The other servers' packs, in their server plugins (Plugins\*\Resources\quests.<id>.csv).
|
||||
foreach (string pack in Directory.GetDirectories(pluginsDir, "RynthCore.Plugin.Rynth*")
|
||||
.Select(d => Path.Combine(d, "Resources")).Where(Directory.Exists)
|
||||
.SelectMany(d => Directory.GetFiles(d, "quests.*.csv")))
|
||||
{
|
||||
if (Path.GetFullPath(pack).Equals(Path.GetFullPath(output), StringComparison.OrdinalIgnoreCase)) continue;
|
||||
foreach (var kv in Curated.Load(pack))
|
||||
otherPacks.TryAdd(kv.Key, kv.Value);
|
||||
}
|
||||
|
||||
// Who sets / checks each flag.
|
||||
var setters = new Dictionary<string, SortedSet<string>>(StringComparer.OrdinalIgnoreCase);
|
||||
var checkers = new Dictionary<string, SortedSet<string>>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach ((uint emoteId, int type, string message) in db.Actions)
|
||||
{
|
||||
var map = SetTypes.Contains(type) ? setters : CheckTypes.Contains(type) ? checkers : null;
|
||||
if (map == null || !db.EmoteOwner.TryGetValue(emoteId, out uint wcid)) continue;
|
||||
string flag = QuestName(message);
|
||||
if (flag.Length == 0) continue;
|
||||
string who = db.Names.TryGetValue(wcid, out string? n) && n.Length > 0 ? n
|
||||
: db.ClassNames.TryGetValue(wcid, out string? c) ? c : $"wcid {wcid}";
|
||||
if (!map.TryGetValue(flag, out var set)) map[flag] = set = new SortedSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
set.Add(who);
|
||||
}
|
||||
|
||||
var sb = new StringBuilder();
|
||||
sb.Append("QuestFlag,Server,Quest,Url,Info,Hint,Repeatable,MinDelta,MaxSolves,Source,NotOnServer\n");
|
||||
int fromBase = 0, fromOther = 0, generated = 0, notOn = 0;
|
||||
foreach (var q in db.Quests.OrderBy(q => q.Key, StringComparer.Ordinal))
|
||||
{
|
||||
string flag = q.Key;
|
||||
(uint minDelta, int maxSolves, string message) = q.Value;
|
||||
string name = "", url = "", info = message, hint = "";
|
||||
if (baseRows.ContainsKey(flag)) fromBase++;
|
||||
else if (otherPacks.TryGetValue(flag, out CuratedRow? o))
|
||||
{
|
||||
fromOther++;
|
||||
name = o.Name; url = o.Url; hint = o.Hint;
|
||||
if (o.Info.Length > 0) info = o.Info;
|
||||
}
|
||||
else generated++;
|
||||
|
||||
bool repeatable = minDelta > 0 || maxSolves == -1 || maxSolves > 1;
|
||||
string source = setters.TryGetValue(flag, out var s) ? "set by " + Join(s)
|
||||
: checkers.TryGetValue(flag, out var c) ? "checked by " + Join(c) : "";
|
||||
Row(sb, flag, server, name, url, info, hint, repeatable ? "TRUE" : "FALSE",
|
||||
minDelta.ToString(CultureInfo.InvariantCulture), maxSolves.ToString(CultureInfo.InvariantCulture), source, "");
|
||||
}
|
||||
foreach (string flag in baseRows.Keys.Where(f => !db.Quests.ContainsKey(f)).OrderBy(f => f, StringComparer.Ordinal))
|
||||
{
|
||||
notOn++;
|
||||
Row(sb, flag, server, "", "", "", "", "", "", "", "", "TRUE");
|
||||
}
|
||||
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(output))!);
|
||||
File.WriteAllText(output, sb.ToString(), new UTF8Encoding(false));
|
||||
Console.WriteLine($"wrote {db.Quests.Count} quests: {fromBase} in the base list (Advis's text kept), {fromOther} named from another server's pack, {generated} new; {notOn} base flags not on {server}");
|
||||
return 0;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine("error: " + ex.Message);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>ACE QuestManager.GetQuestName: everything before the first '@', lower case.</summary>
|
||||
private static string QuestName(string message)
|
||||
{
|
||||
int at = message.IndexOf('@');
|
||||
return (at >= 0 ? message[..at] : message).Trim().ToLowerInvariant();
|
||||
}
|
||||
|
||||
private static string Join(SortedSet<string> names) =>
|
||||
names.Count <= 3 ? string.Join(", ", names) : string.Join(", ", names.Take(3)) + $" and {names.Count - 3} more";
|
||||
|
||||
private static void Row(StringBuilder sb, params string[] fields)
|
||||
{
|
||||
for (int i = 0; i < fields.Length; i++)
|
||||
{
|
||||
if (i > 0) sb.Append(',');
|
||||
string f = fields[i].Replace("\r", " ").Replace("\n", " ");
|
||||
if (f.IndexOfAny(new[] { ',', '"' }) >= 0) sb.Append('"').Append(f.Replace("\"", "\"\"")).Append('"');
|
||||
else sb.Append(f);
|
||||
}
|
||||
sb.Append('\n');
|
||||
}
|
||||
|
||||
private static string? Arg(string[] args, string name)
|
||||
{
|
||||
for (int i = 0; i < args.Length - 1; i++)
|
||||
if (args[i].Equals(name, StringComparison.OrdinalIgnoreCase)) return args[i + 1];
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>RynthOracle's Resources: in this tree, or the sibling RynthSuite checkout (RynthServers' layout).</summary>
|
||||
private static string FindResources() =>
|
||||
FindUp(d => new[] { Path.Combine(d, "Plugins", "RynthCore.Plugin.RynthOracle", "Resources"),
|
||||
Path.Combine(d, "RynthSuite", "Plugins", "RynthCore.Plugin.RynthOracle", "Resources") })
|
||||
?? throw new InvalidOperationException("can't find RynthSuite's Plugins\\RynthCore.Plugin.RynthOracle\\Resources; pass -resources");
|
||||
|
||||
/// <summary>The Plugins folder that holds the server plugins (RynthAelrynth's).</summary>
|
||||
private static string FindServerPlugins() =>
|
||||
FindUp(d => new[] { Path.Combine(d, "Plugins") }, p => Directory.Exists(Path.Combine(p, "RynthCore.Plugin.RynthAelrynth")))
|
||||
?? throw new InvalidOperationException("can't find the server plugins (Plugins\\RynthCore.Plugin.RynthAelrynth); pass -plugins");
|
||||
|
||||
private static string? FindUp(Func<string, string[]> candidates, Func<string, bool>? ok = null)
|
||||
{
|
||||
foreach (string start in new[] { Directory.GetCurrentDirectory(), AppContext.BaseDirectory })
|
||||
{
|
||||
var dir = new DirectoryInfo(start);
|
||||
while (dir != null)
|
||||
{
|
||||
foreach (string p in candidates(dir.FullName))
|
||||
if (Directory.Exists(p) && (ok == null || ok(p))) return p;
|
||||
dir = dir.Parent;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static string NewestDump()
|
||||
{
|
||||
const string dir = @"C:\Aeshnidae\backups";
|
||||
string? f = Directory.Exists(dir)
|
||||
? Directory.GetFiles(dir, "aeshnidae_world-*.sql.gz").OrderByDescending(p => p, StringComparer.Ordinal).FirstOrDefault()
|
||||
: null;
|
||||
return f ?? throw new InvalidOperationException($"no aeshnidae_world-*.sql.gz in {dir}; pass -dump");
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed record CuratedRow(string Name, string Url, string Info, string Hint);
|
||||
|
||||
internal static class Curated
|
||||
{
|
||||
public static Dictionary<string, CuratedRow> Load(string path)
|
||||
{
|
||||
var map = new Dictionary<string, CuratedRow>(StringComparer.OrdinalIgnoreCase);
|
||||
if (!File.Exists(path)) return map;
|
||||
using var r = new StreamReader(path);
|
||||
string? header = r.ReadLine();
|
||||
if (header == null) return map;
|
||||
string[] h = CsvLine.Parse(header);
|
||||
int Col(string n) => Array.FindIndex(h, x => x.Trim().Equals(n, StringComparison.OrdinalIgnoreCase));
|
||||
int flag = Col("QuestFlag"), name = Col("Quest"), url = Col("Url"), info = Col("Info"), hint = Col("Hint");
|
||||
if (flag < 0) return map;
|
||||
while (r.ReadLine() is string line)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(line)) continue;
|
||||
string[] f = CsvLine.Parse(line);
|
||||
string F(int i) => i >= 0 && i < f.Length ? f[i].Trim() : "";
|
||||
string key = F(flag).ToLowerInvariant();
|
||||
if (key.Length > 0) map.TryAdd(key, new CuratedRow(F(name), F(url), F(info), F(hint)));
|
||||
}
|
||||
return map;
|
||||
}
|
||||
}
|
||||
|
||||
internal static class CsvLine
|
||||
{
|
||||
public static string[] Parse(string line)
|
||||
{
|
||||
var fields = new List<string>();
|
||||
var sb = new StringBuilder();
|
||||
bool q = false;
|
||||
for (int i = 0; i < line.Length; i++)
|
||||
{
|
||||
char c = line[i];
|
||||
if (q)
|
||||
{
|
||||
if (c == '"') { if (i + 1 < line.Length && line[i + 1] == '"') { sb.Append('"'); i++; } else q = false; }
|
||||
else sb.Append(c);
|
||||
}
|
||||
else if (c == '"') q = true;
|
||||
else if (c == ',') { fields.Add(sb.ToString()); sb.Clear(); }
|
||||
else sb.Append(c);
|
||||
}
|
||||
fields.Add(sb.ToString());
|
||||
return fields.ToArray();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The few world tables the pack needs, read from a mysqldump file (.sql or .sql.gz).</summary>
|
||||
internal sealed class WorldDump
|
||||
{
|
||||
public readonly Dictionary<string, (uint MinDelta, int MaxSolves, string Message)> Quests = new(StringComparer.OrdinalIgnoreCase);
|
||||
public readonly Dictionary<uint, string> ClassNames = new();
|
||||
public readonly Dictionary<uint, string> Names = new(); // PropertyString 1 (Name)
|
||||
public readonly Dictionary<uint, uint> EmoteOwner = new(); // emote id -> wcid
|
||||
public readonly List<(uint EmoteId, int Type, string Message)> Actions = new();
|
||||
|
||||
public static WorldDump Read(string path)
|
||||
{
|
||||
var db = new WorldDump();
|
||||
using Stream file = File.OpenRead(path);
|
||||
using Stream s = path.EndsWith(".gz", StringComparison.OrdinalIgnoreCase) ? new GZipStream(file, CompressionMode.Decompress) : file;
|
||||
using var reader = new StreamReader(s, Encoding.UTF8);
|
||||
|
||||
var columns = new Dictionary<string, List<string>>(StringComparer.Ordinal);
|
||||
string? creating = null;
|
||||
string? inserting = null;
|
||||
while (reader.ReadLine() is string line)
|
||||
{
|
||||
if (line.StartsWith("CREATE TABLE `", StringComparison.Ordinal))
|
||||
{
|
||||
creating = line.Substring(14, line.IndexOf('`', 14) - 14);
|
||||
columns[creating] = new List<string>();
|
||||
continue;
|
||||
}
|
||||
if (creating != null)
|
||||
{
|
||||
string t = line.TrimStart();
|
||||
if (t.StartsWith("`", StringComparison.Ordinal)) columns[creating].Add(t.Substring(1, t.IndexOf('`', 1) - 1));
|
||||
else if (t.StartsWith(")", StringComparison.Ordinal)) creating = null;
|
||||
continue;
|
||||
}
|
||||
if (line.StartsWith("INSERT INTO `", StringComparison.Ordinal))
|
||||
{
|
||||
string table = line.Substring(13, line.IndexOf('`', 13) - 13);
|
||||
inserting = IsWanted(table) ? table : null;
|
||||
int v = line.IndexOf(" VALUES", StringComparison.Ordinal);
|
||||
if (inserting != null && v >= 0) db.Take(inserting, columns, line[(v + 7)..]);
|
||||
if (line.TrimEnd().EndsWith(";", StringComparison.Ordinal)) inserting = null;
|
||||
continue;
|
||||
}
|
||||
if (inserting != null)
|
||||
{
|
||||
db.Take(inserting, columns, line);
|
||||
if (line.TrimEnd().EndsWith(";", StringComparison.Ordinal)) inserting = null;
|
||||
}
|
||||
}
|
||||
return db;
|
||||
}
|
||||
|
||||
private static bool IsWanted(string t) =>
|
||||
t is "quest" or "weenie" or "weenie_properties_string" or "weenie_properties_emote" or "weenie_properties_emote_action";
|
||||
|
||||
private void Take(string table, Dictionary<string, List<string>> columns, string text)
|
||||
{
|
||||
if (!columns.TryGetValue(table, out List<string>? cols)) return;
|
||||
foreach (List<string?> row in Tuples(text))
|
||||
{
|
||||
string? Get(string c) { int i = cols.IndexOf(c); return i >= 0 && i < row.Count ? row[i] : null; }
|
||||
switch (table)
|
||||
{
|
||||
case "quest":
|
||||
string name = (Get("name") ?? "").Trim().ToLowerInvariant();
|
||||
if (name.Length == 0) break;
|
||||
uint.TryParse(Get("min_Delta"), NumberStyles.None, CultureInfo.InvariantCulture, out uint md);
|
||||
int.TryParse(Get("max_Solves"), NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out int ms);
|
||||
Quests[name] = (md, ms, (Get("message") ?? "").Trim());
|
||||
break;
|
||||
case "weenie":
|
||||
if (uint.TryParse(Get("class_Id"), out uint id)) ClassNames[id] = Get("class_Name") ?? "";
|
||||
break;
|
||||
case "weenie_properties_string":
|
||||
if (Get("type") == "1" && uint.TryParse(Get("object_Id"), out uint oid)) Names[oid] = Get("value") ?? "";
|
||||
break;
|
||||
case "weenie_properties_emote":
|
||||
if (uint.TryParse(Get("id"), out uint eid) && uint.TryParse(Get("object_Id"), out uint owner)) EmoteOwner[eid] = owner;
|
||||
break;
|
||||
case "weenie_properties_emote_action":
|
||||
string? msg = Get("message");
|
||||
if (msg == null || !int.TryParse(Get("type"), out int type)) break;
|
||||
if (uint.TryParse(Get("emote_Id"), out uint emote)) Actions.Add((emote, type, msg));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The value tuples in a VALUES list fragment: "(1,'a\'b',NULL),(2,...);".</summary>
|
||||
private static IEnumerable<List<string?>> Tuples(string text)
|
||||
{
|
||||
int i = 0;
|
||||
while (true)
|
||||
{
|
||||
while (i < text.Length && text[i] != '(') i++;
|
||||
if (i >= text.Length) yield break;
|
||||
i++;
|
||||
var row = new List<string?>();
|
||||
var sb = new StringBuilder();
|
||||
bool quoted = false, wasQuoted = false;
|
||||
for (; i < text.Length; i++)
|
||||
{
|
||||
char c = text[i];
|
||||
if (quoted)
|
||||
{
|
||||
if (c == '\\' && i + 1 < text.Length)
|
||||
{
|
||||
char n = text[++i];
|
||||
sb.Append(n switch { 'n' => '\n', 'r' => '\r', 't' => '\t', '0' => '\0', _ => n });
|
||||
}
|
||||
else if (c == '\'') quoted = false;
|
||||
else sb.Append(c);
|
||||
}
|
||||
else if (c == '\'') { quoted = true; wasQuoted = true; }
|
||||
else if (c == ',' || c == ')')
|
||||
{
|
||||
string v = sb.ToString();
|
||||
row.Add(!wasQuoted && v.Trim() == "NULL" ? null : v);
|
||||
sb.Clear();
|
||||
wasQuoted = false;
|
||||
if (c == ')') { i++; break; }
|
||||
}
|
||||
else sb.Append(c);
|
||||
}
|
||||
yield return row;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!--
|
||||
Builds Aelrynth's quest pack for RynthOracle (Plugins\RynthCore.Plugin.RynthAelrynth\Resources\
|
||||
quests.aelrynth.csv: the server plugin's, which offers it to RynthOracle since 2026-10-21) from a
|
||||
world-database BACKUP DUMP (mysqldump .sql or .sql.gz), never from a live database: by default the
|
||||
newest C:\Aeshnidae\backups\aeshnidae_world-*.sql.gz. It reads RynthOracle's retail list and the
|
||||
other server plugins' packs for names. Re-run it after content changes, then rebuild RynthAelrynth.
|
||||
|
||||
Run (from this folder):
|
||||
dotnet run -c Release
|
||||
dotnet run -c Release (two dashes) -dump file.sql.gz -resources oracleResourcesDir -plugins serverPluginsDir -out file.csv -server Aelrynth
|
||||
RynthOracle's retail list is read from the sibling RynthSuite checkout (..\RynthSuite\Plugins\
|
||||
RynthCore.Plugin.RynthOracle\Resources); the packs are this repo's Plugins\*\Resources.
|
||||
-->
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<InvariantGlobalization>true</InvariantGlobalization>
|
||||
<RootNamespace>RynthOracle.QuestPackGen</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
||||
170
Tools/RynthServerPack.Tests/AelrynthTests.cs
Normal file
170
Tools/RynthServerPack.Tests/AelrynthTests.cs
Normal file
|
|
@ -0,0 +1,170 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using RynthCore.Engine.UI.Sections;
|
||||
using RynthCore.Plugin.RynthAelrynth;
|
||||
using RynthCore.Plugin.ServerPack;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthServerPack.Tests;
|
||||
|
||||
// RynthAelrynth's own features (Plugins\RynthCore.Plugin.RynthAelrynth\Aelrynth), moved out of
|
||||
// RynthOracle on 2026-10-20: the /top and /trial reply parser (RynthOracle.Tests' old
|
||||
// AelrynthReplies), the own-reply hiding, the setting taken over from rynthoracle.json and its page.
|
||||
internal static class AelrynthTests
|
||||
{
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("aelrynth: the replies of /top, /top me and /trial parse", Replies);
|
||||
r.Add("aelrynth: replies to RynthAelrynth's own requests are hidden, typed ones show", HideOwnReplies);
|
||||
r.Add("aelrynth: RynthOracle's reply-hiding choice is taken over once", Migration);
|
||||
r.Add("aelrynth: its Leaderboards page is an Aelrynth-only view of the Server section", Pages);
|
||||
r.Add("aelrynth: the difficulty tier (PropertyInt 9051) is published for other plugins, only on Aelrynth", DifficultyTier);
|
||||
}
|
||||
|
||||
private static void Replies()
|
||||
{
|
||||
var a = new AelrynthBoards();
|
||||
long now = 2_000_000;
|
||||
a.RequestTop("", now);
|
||||
Check.True(a.OnChatLine("Leaderboards - 37 characters, refreshed 4 min ago. /top <board> for the top ten, /top me for yourself.", now, out bool ours) && ours, "overview header");
|
||||
a.OnChatLine(" kills Creature kills: Buffy, 1,234,567", now, out _);
|
||||
a.OnChatLine(" pk PK kills: nobody yet", now, out _);
|
||||
Check.True(a.Overview.Count == 2 && a.Overview[0].Key == "kills" && a.Overview[0].Leader == "Buffy" && a.Overview[0].Value == "1,234,567"
|
||||
&& a.Overview[1].Leader == "nobody yet", "overview rows");
|
||||
|
||||
a.RequestTop("kills", now);
|
||||
a.OnChatLine("Creature kills - top 10 of 37:", now, out _);
|
||||
a.OnChatLine(" 1. Buffy 1,234,567 <- you", now, out _);
|
||||
a.OnChatLine(" 2. Dargoth 987,654", now, out _);
|
||||
a.OnChatLine(" 3. Sal 500 12 kills per death", now, out _);
|
||||
Check.True(a.BoardTitle == "Creature kills" && a.BoardRows.Count == 3 && a.BoardRows[0].IsYou && a.BoardRows[1].Value == "987,654"
|
||||
&& a.BoardRows[2].Extra == "12 kills per death", "board rows: " + string.Join(" | ", a.BoardRows.Select(r => $"{r.Rank} {r.Name} {r.Value} [{r.Extra}] {r.IsYou}")));
|
||||
|
||||
a.RequestTop("me", now);
|
||||
a.OnChatLine("Buffy on the boards:", now, out _);
|
||||
a.OnChatLine(" Creature kills #1 of 37, 1,234,567", now, out _);
|
||||
a.OnChatLine(" PK kills -", now, out _);
|
||||
Check.True(a.Standings.Count == 2 && a.Standings[0].Rank == 1 && a.Standings[1].Rank == 0, "/top me");
|
||||
|
||||
Check.False(a.OnChatLine(" 9. Nobody 12", now + 30_000, out _), "an entry long after its header is ignored");
|
||||
|
||||
a.RequestTrial("", now);
|
||||
a.OnChatLine("Trials - a fresh personal copy of a listed dungeon, entered through its portal, is a timed course: ...", now, out _);
|
||||
a.OnChatLine(" The Citadel Below - Trial (02F0): tier 0 12:34 by Buffy | you: tier 0 12:34 | this week: Buffy 12:34 (tier 0)", now, out _);
|
||||
a.OnChatLine(" your next attempt here: in 12 min", now, out _);
|
||||
a.OnChatLine("Trophy: the week's fastest clear of each dungeon, any tier - a trophy and 1,000 experience, Sunday 20:00 (2026-W40). /trial <name> for the top 10 of one dungeon.", now, out _);
|
||||
Check.True(a.Trials.Count == 1 && a.Trials[0].Landblock == "02F0" && a.TrialLines.Count == 3, $"/trial overview ({a.Trials.Count} dungeons, {a.TrialLines.Count} lines)");
|
||||
|
||||
a.RequestTrial("citadel", now);
|
||||
a.OnChatLine("The Citadel Below - Trial (02F0) - top 10, best per character, any tier:", now, out _);
|
||||
a.OnChatLine(" 1. 12:34 Buffy (tier 0, 105 kills, 3 Oct)", now, out _);
|
||||
a.OnChatLine(" you: tier 0 12:34 (105 kills)", now, out _);
|
||||
Check.True(a.TrialRows.Count == 1 && a.TrialRows[0].Name == "Buffy" && a.TrialRows[0].Value == "12:34" && a.TrialNotes.Count == 1, "/trial dungeon top 10");
|
||||
Check.False(a.OnChatLine("Bob tells you, \"hello\"", now, out _), "ordinary chat is never taken");
|
||||
}
|
||||
|
||||
private static void HideOwnReplies()
|
||||
{
|
||||
var f = new AelrynthFeature();
|
||||
long now = 3_000_000;
|
||||
f.Boards.RequestTop("", now);
|
||||
Check.True(f.OnChatLine("Leaderboards - 3 characters, refreshed just now. /top <board> ...", 0, now), "a reply to RynthAelrynth's /top is hidden");
|
||||
Check.True(f.OnChatLine(" kills Creature kills: Buffy, 12", 0, now), "and its rows");
|
||||
Check.False(f.OnChatLine("Leaderboards - 3 characters, refreshed just now. /top <board> ...", 0, now + 60_000), "a typed /top's reply shows");
|
||||
Check.False(f.OnChatLine(" kills Creature kills: Ann, 14", 0, now + 60_000), "and its rows");
|
||||
Check.True(f.Boards.Overview.Count == 1 && f.Boards.Overview[0].Leader == "Ann", "read either way");
|
||||
f.HideOwnReplies = false;
|
||||
f.Boards.RequestTrial("", now);
|
||||
Check.False(f.OnChatLine("Trials - a fresh personal copy of a listed dungeon ...", 0, now), "with hiding off, own replies show too");
|
||||
Check.False(f.OnChatLine("Bob says, \"hi\"", 0, now), "ordinary chat shows");
|
||||
f.Reset();
|
||||
Check.True(f.Boards.Overview.Count == 0 && f.Boards.Trials.Count == 0, "login/logout clears the boards");
|
||||
}
|
||||
|
||||
private static void Migration()
|
||||
{
|
||||
string dir = ServerPackHooksTests.TempDir();
|
||||
try
|
||||
{
|
||||
string oracle = Path.Combine(dir, "rynthoracle.json"), mine = Path.Combine(dir, "rynthaelrynth.json");
|
||||
File.WriteAllText(oracle, "{ \"hideOwnQuestReplies\": false }");
|
||||
var s = new ServerPackSettings(mine);
|
||||
s.Load();
|
||||
Check.True(AelrynthFeature.Migrate(s, oracle), "taken over the first time");
|
||||
var f = new AelrynthFeature();
|
||||
f.LoadSettings(s);
|
||||
Check.False(f.HideOwnReplies, "the player's choice (shown) came over");
|
||||
Check.False(AelrynthFeature.Migrate(s, oracle), "never twice");
|
||||
var fresh = new ServerPackSettings(Path.Combine(dir, "fresh.json"));
|
||||
fresh.Load();
|
||||
AelrynthFeature.Migrate(fresh, Path.Combine(dir, "none.json"));
|
||||
var g = new AelrynthFeature();
|
||||
g.LoadSettings(fresh);
|
||||
Check.True(g.HideOwnReplies, "default: hidden");
|
||||
}
|
||||
finally { try { Directory.Delete(dir, true); } catch { } }
|
||||
}
|
||||
|
||||
private static void Pages()
|
||||
{
|
||||
var pages = ServerPackPages.Validate(AelrynthFeature.PageList.Select(p => new ServerPage(p.Id, p.Label, p.Tooltip, () => { })));
|
||||
Check.Eq(pages.Count, 1, "one page");
|
||||
ServerPackInfo info = new("aelrynth", "Aelrynth", new[] { "aelrynth.com" }, new[] { "Aelrynth*", "Aeshnidae*" });
|
||||
SectionManifest m = SectionManifestParser.Parse("RynthAelrynth", ServerPackModel.BuildSectionsJson(info, "RynthAelrynth", pages), out string error);
|
||||
Check.Eq(error, "", "RynthCore parses the manifest");
|
||||
SectionContribution view = m.Contributions.Single(c => c.Primary);
|
||||
Check.True(view.Server == "aelrynth" && view.Label == "Leaderboards" && view.Surface == "section:server-aelrynth.boards",
|
||||
"Leaderboards, only while Aelrynth is active");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// AelrynthDifficulty (2026-10-21, RynthAi's AwakenedTier before): the tier the server sends as
|
||||
/// PropertyInt 9051 goes into the profile's "values" with the 5% a tier, which RynthAi reads (through
|
||||
/// ServerProfileView.Value) without knowing the server.
|
||||
/// </summary>
|
||||
private static void DifficultyTier()
|
||||
{
|
||||
Check.Eq(AelrynthDifficulty.TierProperty, 9051u, "PropertyInt 9051");
|
||||
Check.Eq((RynthCore.Plugin.Shared.RynthServerProfile.ValueDifficultyTier, RynthCore.Plugin.Shared.RynthServerProfile.ValueDifficultyHealthPercent),
|
||||
("difficultyTier", "difficultyHealthPercent"), "the value names RynthAi reads");
|
||||
var d = new AelrynthDifficulty();
|
||||
var values = new ServerProfileValues();
|
||||
int? property = null;
|
||||
int reads = 0;
|
||||
int? Read() { reads++; return property; }
|
||||
ServerPackInfo info = new("aelrynth", "Aelrynth", new[] { "aelrynth.com" }, new[] { "Aelrynth*", "Aeshnidae*" });
|
||||
string Json() => ServerPackProfile.BuildJson(info, "RynthAelrynth", "0.2.0", true, "Aelrynth", values.Snapshot(out _));
|
||||
double Tier() => RynthCore.Plugin.Shared.ServerProfileView.Value(Json(), "difficultyTier", -1);
|
||||
double Percent() => RynthCore.Plugin.Shared.ServerProfileView.Value(Json(), "difficultyHealthPercent", -1);
|
||||
|
||||
long now = 1_000_000;
|
||||
d.Tick(now, active: true, Read, values);
|
||||
Check.True(d.Tier == null && values.Snapshot(out _).Length == 0, "the server hasn't sent the tier: nothing published (RynthAi stays at tier 0)");
|
||||
|
||||
property = 3;
|
||||
d.Tick(now + 100, active: true, Read, values);
|
||||
Check.Eq(reads, 1, "read at most every ReadMs");
|
||||
d.Tick(now + AelrynthDifficulty.ReadMs, active: true, Read, values);
|
||||
Check.Eq(d.Tier, (int?)3, "tier 3 seen");
|
||||
Check.Eq((Tier(), Percent()), (3.0, 5.0), "published: tier 3, +5% health a tier");
|
||||
|
||||
property = null;
|
||||
d.Tick(now + 2 * AelrynthDifficulty.ReadMs, active: true, Read, values);
|
||||
Check.Eq(Tier(), 3.0, "a failed read keeps the last tier");
|
||||
property = 0;
|
||||
d.Tick(now + 3 * AelrynthDifficulty.ReadMs, active: true, Read, values);
|
||||
Check.Eq((Tier(), Percent()), (0.0, 5.0), "back in real Dereth: tier 0 (still a server with tiers)");
|
||||
property = -2;
|
||||
d.Tick(now + 4 * AelrynthDifficulty.ReadMs, active: true, Read, values);
|
||||
Check.Eq(Tier(), 0.0, "a negative tier reads as 0");
|
||||
|
||||
property = 7;
|
||||
d.Tick(now + 5 * AelrynthDifficulty.ReadMs, active: false, Read, values);
|
||||
Check.True(d.Tier == null && Tier() == -1 && Percent() == -1, "off Aelrynth (RynthCore's verdict): both values taken out");
|
||||
d.Tick(now + 6 * AelrynthDifficulty.ReadMs, active: true, Read, values);
|
||||
Check.Eq(Tier(), 7.0, "and read again once it is Aelrynth");
|
||||
d.Reset();
|
||||
Check.True(d.Tier == null && d.Describe().Contains("not sent"), "login and logout forget the tier (logout clears the values)");
|
||||
}
|
||||
}
|
||||
216
Tools/RynthServerPack.Tests/ConquestTests.cs
Normal file
216
Tools/RynthServerPack.Tests/ConquestTests.cs
Normal file
|
|
@ -0,0 +1,216 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using RynthCore.Engine.UI.Sections;
|
||||
using RynthCore.Plugin.RynthConquest;
|
||||
using RynthCore.Plugin.RynthOracle.Data;
|
||||
using RynthCore.Plugin.ServerPack;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthServerPack.Tests;
|
||||
|
||||
// RynthConquest's own features (Plugins\RynthCore.Plugin.RynthConquest\Conquest), moved out of
|
||||
// RynthOracle on 2026-10-20: the reply parser (RynthOracle.Tests' old ConquestReplies), the
|
||||
// own-reply hiding, the login /augs, the auto-deposit, the settings taken over from rynthoracle.json,
|
||||
// the Void DoT rule it publishes, the custom quest list and its pages.
|
||||
internal static class ConquestTests
|
||||
{
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("conquest: the replies of /b, /augs, /enl augs, /bonus, /fship list and /top parse", Replies);
|
||||
r.Add("conquest: replies to RynthConquest's own requests are hidden, typed ones show", HideOwnReplies);
|
||||
r.Add("conquest: /augs once after login, then never again", LoginAugs);
|
||||
r.Add("conquest: the auto-deposit is off unless turned on, then once per ten-minute mark", AutoDeposit);
|
||||
r.Add("conquest: RynthOracle's settings are taken over once (defaults kept without them)", Migration);
|
||||
r.Add("conquest: the Void DoT rule for RynthOracle's timers", VoidRule);
|
||||
r.Add("conquest: the custom quest worklist and its status", CustomQuests);
|
||||
r.Add("conquest: its pages are Conquest-only views of the Server section", Pages);
|
||||
}
|
||||
|
||||
private static void Replies()
|
||||
{
|
||||
var d = new ConquestData();
|
||||
long now = 1_000_000;
|
||||
d.RequestBank(now);
|
||||
Check.True(d.OnChatLine("[BANK] Your balances:", now, out bool ours) && ours, "bank heading (ours)");
|
||||
d.OnChatLine("[BANK] Pyreals: 1,039,678,533", now, out _);
|
||||
d.OnChatLine("[BANK] Event Tokens [Dragon Coins] (x): 12", now, out _);
|
||||
Check.True(d.Bank.Any(b => b.Name == "Pyreals" && b.Value.Contains("4,158 MMDs")), "pyreals with MMDs");
|
||||
Check.True(d.Bank.Any(b => b.Name == "Dragon Coins (x)"), "event token name");
|
||||
Check.False(d.OnChatLine("Bob says, \"[BANK] Pyreals: 999\"", now, out _), "a pasted balance is ignored");
|
||||
d.OnChatLine("[BANK] Pyreals: 5", now + 60_000, out bool late);
|
||||
Check.False(late, "a reply long after the request isn't ours (shows in chat)");
|
||||
|
||||
d.RequestAugs(now);
|
||||
d.OnChatLine("Creature: 25", now, out _);
|
||||
d.OnChatLine("Duration: 3", now, out _);
|
||||
ConquestAug creature = d.Augs.First(a => a.Name == "Creature");
|
||||
Check.True(creature.Count == 25 && creature.NextLuminanceCost() == 6_229_500, $"Creature 25 next costs 6,229,500 ({creature.NextLuminanceCost()})");
|
||||
Check.True(d.DurationAugs == 3 && Math.Abs(d.VoidDurationMultiplier(5) - 2.15) < 1e-9, "void duration x(1 + 5*0.2 + 3*0.05)");
|
||||
|
||||
d.RequestEnl(now);
|
||||
d.OnChatLine("Enlightenment Augmentations:", now, out _);
|
||||
d.OnChatLine("Skill Credits: 2 (10 max)", now, out _);
|
||||
d.OnChatLine("Damage: 5 (25 max)", now, out _);
|
||||
Check.True(d.EnlAugs.Count == 2 && d.EnlAugs[0].Name == "Damage", "enlightenment augs in display order");
|
||||
|
||||
d.RequestBonus(now);
|
||||
d.OnChatLine("=== XP Bonuses ===", now, out _);
|
||||
d.OnChatLine("Quest Bonus: 14.18% (1,418 quests)", now, out _);
|
||||
d.OnChatLine("Total Bonus (Kills): 0.16%", now, out _);
|
||||
Check.True(d.Bonuses.First(b => b.Name == "Quest").Value == "14.18% (1,418 quests)" && d.Bonuses.First(b => b.Name == "Total (Kills)").Value == "0.16%", "bonuses");
|
||||
|
||||
d.RequestFships(now);
|
||||
d.OnChatLine("Fellowships looking for members:", now, out _);
|
||||
d.OnChatLine("- Heroes (Leader: Bob) [3/14] @ Bur", now, out _);
|
||||
d.OnChatLine("- Quiet (Leader: Ann) [1/14]", now, out _);
|
||||
Check.True(d.Fellowships.Count == 2 && d.Fellowships[0].Location == "Bur" && d.Fellowships[1].MemberCount == 1, "fellowship list");
|
||||
|
||||
ConquestBoard lvl = d.Boards.First(b => b.Key == "level");
|
||||
d.RequestBoard(lvl, now);
|
||||
d.OnChatLine("Top 2 Players by Level:", now, out _);
|
||||
d.OnChatLine("1: 300 - Alpha", now, out _);
|
||||
d.OnChatLine("2: 299 - Beta", now, out _);
|
||||
d.OnChatLine("57: 250 - Me (You)", now, out _);
|
||||
Check.True(lvl.Rows.Count == 2 && lvl.You != null && lvl.You.Rank == 57 && lvl.You.Name == "Me", "Conquest /top board");
|
||||
|
||||
Check.Eq(ConquestData.WithdrawCommand(ConquestData.Withdrawable[ConquestData.DefaultWithdraw], "10"), "/bank withdraw n 10", "withdraw MMDs");
|
||||
Check.Null(ConquestData.WithdrawCommand(ConquestData.Withdrawable[0], "-3"), "withdraw refuses a bad amount");
|
||||
Check.Eq(ConquestData.TransferCommand(ConquestData.Transferable[2], "4", "Some One"), "/bank transfer p 1000000 \"Some One\"", "transfer MMD notes as pyreals");
|
||||
Check.Null(ConquestData.TransferCommand(ConquestData.Transferable[2], "1001", "X"), "transfer cap");
|
||||
}
|
||||
|
||||
private static void HideOwnReplies()
|
||||
{
|
||||
var f = new ConquestFeature();
|
||||
f.Login(0);
|
||||
long now = 100_000;
|
||||
f.Data.RequestBank(now);
|
||||
Check.True(f.OnChatLine("[BANK] Pyreals: 1,000", now), "a reply to RynthConquest's /b is hidden");
|
||||
Check.False(f.OnChatLine("[BANK] Pyreals: 1,000", now + 60_000), "the same reply long after (typed /b) shows");
|
||||
Check.False(f.OnChatLine("Bob says, \"hello\"", now), "ordinary chat shows");
|
||||
f.HideOwnReplies = false;
|
||||
f.Data.RequestBank(now);
|
||||
Check.False(f.OnChatLine("[BANK] Pyreals: 1,000", now), "with hiding off, own replies show too");
|
||||
f.HideOwnReplies = true;
|
||||
|
||||
// /myquests: only RynthConquest's own request's reply is hidden; the flags are read either way.
|
||||
Check.True(f.Flags.Request(_ => true, now), "own /myquests sent");
|
||||
Check.True(f.OnChatLine("assaultonaimaru - 1 solves (1719432000)\"x\" -1 0", now), "its reply is hidden");
|
||||
f.Flags.Tick(now + 2000);
|
||||
Check.True(f.Flags.TryGet("assaultonaimaru", out _), "and read");
|
||||
Check.False(f.OnChatLine("ghostdencompleted - 1 solves (1719432000)\"x\" -1 0", now + 3000), "a reply nobody here asked for shows");
|
||||
Check.True(f.Data.AutoDeposit(now).Length > 0 && f.OnChatLine("Deposited 12 items.", now), "the auto-deposit's reply is hidden");
|
||||
}
|
||||
|
||||
private static void LoginAugs()
|
||||
{
|
||||
var f = new ConquestFeature();
|
||||
f.Login(1000);
|
||||
Check.Null(f.LoginAugsDue(1000 + ConquestFeature.AugsReadDelayMs), "not before the delay");
|
||||
Check.Eq(f.LoginAugsDue(1001 + ConquestFeature.AugsReadDelayMs), "/augs", "/augs after it");
|
||||
Check.Null(f.LoginAugsDue(5_000_000), "only once");
|
||||
f.Login(9_000_000);
|
||||
Check.Eq(f.LoginAugsDue(9_000_001 + ConquestFeature.AugsReadDelayMs), "/augs", "again for the next login");
|
||||
}
|
||||
|
||||
private static void AutoDeposit()
|
||||
{
|
||||
var f = new ConquestFeature();
|
||||
f.Login(0);
|
||||
var at = new DateTime(2026, 10, 20, 14, 0, 5, DateTimeKind.Local);
|
||||
Check.False(f.AutoDeposit, "off by default (as it was in RynthOracle)");
|
||||
Check.Null(f.AutoDepositDue(at, 0), "off: no deposit at :00");
|
||||
f.AutoDeposit = true;
|
||||
Check.Eq(f.AutoDepositDue(at, 0), "/bank deposit", "on: /bank deposit at :00");
|
||||
Check.Null(f.AutoDepositDue(at.AddSeconds(30), 0), "once per mark");
|
||||
Check.Null(f.AutoDepositDue(at.AddMinutes(5), 0), "not at :05");
|
||||
Check.Eq(f.AutoDepositDue(at.AddMinutes(10), 0), "/bank deposit", "again at :10");
|
||||
long block = -1;
|
||||
Check.True(ConquestFeature.DepositDue(new DateTime(2026, 1, 1, 0, 20, 0), ref block), "the schedule: :20");
|
||||
Check.False(ConquestFeature.DepositDue(new DateTime(2026, 1, 1, 0, 21, 0), ref block), "the schedule: not :21");
|
||||
}
|
||||
|
||||
private static void Migration()
|
||||
{
|
||||
string dir = ServerPackHooksTests.TempDir();
|
||||
try
|
||||
{
|
||||
string oracle = Path.Combine(dir, "rynthoracle.json"), mine = Path.Combine(dir, "rynthconquest.json");
|
||||
File.WriteAllText(oracle, "{ \"hideOwnQuestReplies\": false, \"conquestAutoDeposit\": true, \"tabName\": \"Conquest\" }");
|
||||
var s = new ServerPackSettings(mine);
|
||||
s.Load();
|
||||
Check.True(ConquestFeature.Migrate(s, oracle), "taken over the first time");
|
||||
var f = new ConquestFeature();
|
||||
f.LoadSettings(s);
|
||||
Check.True(f.AutoDeposit, "auto-deposit came over (on)");
|
||||
Check.False(f.HideOwnReplies, "hiding came over (off)");
|
||||
|
||||
// Turned off here later: a newer rynthoracle.json never turns it back on.
|
||||
f.AutoDeposit = false;
|
||||
f.SaveSettings(s);
|
||||
var again = new ServerPackSettings(mine);
|
||||
again.Load();
|
||||
Check.False(ConquestFeature.Migrate(again, oracle), "never taken over twice");
|
||||
var g = new ConquestFeature();
|
||||
g.LoadSettings(again);
|
||||
Check.False(g.AutoDeposit, "the player's choice here stands");
|
||||
|
||||
// A new player (no RynthOracle settings): the defaults.
|
||||
string fresh = Path.Combine(dir, "fresh.json");
|
||||
var n = new ServerPackSettings(fresh);
|
||||
n.Load();
|
||||
Check.True(ConquestFeature.Migrate(n, Path.Combine(dir, "missing.json")), "runs (nothing to take)");
|
||||
var h = new ConquestFeature();
|
||||
h.LoadSettings(n);
|
||||
Check.True(!h.AutoDeposit && h.HideOwnReplies, "defaults: auto-deposit off, own replies hidden");
|
||||
Check.True(new ServerPackSettings(fresh) is var reread && Reload(reread) && reread.GetBool(ConquestFeature.MigrationMarker, false),
|
||||
"the marker is saved");
|
||||
}
|
||||
finally { try { Directory.Delete(dir, true); } catch { } }
|
||||
}
|
||||
|
||||
private static bool Reload(ServerPackSettings s) { s.Load(); return true; }
|
||||
|
||||
private static void VoidRule()
|
||||
{
|
||||
var f = new ConquestFeature();
|
||||
f.Login(0);
|
||||
Check.Eq(f.VoidScale, 1.0, "no augs, no Archmage's Endurance: x1");
|
||||
f.ArchmagesEndurance = 5;
|
||||
f.Data.RequestAugs(0);
|
||||
f.Data.OnChatLine("Duration: 3", 0, out _);
|
||||
Check.Near(f.VoidScale, 2.15, 1e-9, "x(1 + 5*0.2 + 3*0.05)");
|
||||
Check.Eq(ConquestFeature.VoidScaleKey, "voidDotDurationScale", "the profile value RynthOracle reads");
|
||||
}
|
||||
|
||||
private static void CustomQuests()
|
||||
{
|
||||
Check.Eq(CustomQuestList.All.Count, 6, "six custom quests (customquests.csv, embedded)");
|
||||
Check.True(CustomQuestList.All.All(q => q.Server == "Conquest" && q.Flag.Length > 0 && q.Flag == q.Flag.ToLowerInvariant()), "Conquest rows, flags in lower case");
|
||||
var flags = new QuestFlagStore();
|
||||
CustomQuest darsh = CustomQuestList.All.First(q => q.Flag == "assaultonaimaru");
|
||||
DateTime now = DateTime.UtcNow;
|
||||
Check.False(darsh.IsComplete(flags, now), "not done without the flag");
|
||||
Check.Eq(darsh.Status(flags, now), "ready", "ready without the flag");
|
||||
long done = DateTimeOffset.UtcNow.ToUnixTimeSeconds() - 60;
|
||||
flags.OnChatLine($"assaultonaimaru - 1 solves ({done})\"x\" -1 3600", 0);
|
||||
flags.Tick(5000);
|
||||
Check.True(darsh.IsComplete(flags, now), "a repeatable on cooldown counts as done");
|
||||
Check.True(darsh.Status(flags, now) is not ("ready" or "completed") && darsh.Status(flags, now).Contains('m'), "its status is the time left: " + darsh.Status(flags, now));
|
||||
}
|
||||
|
||||
private static void Pages()
|
||||
{
|
||||
var pages = ServerPackPages.Validate(ConquestFeature.PageList.Select(p => new ServerPage(p.Id, p.Label, p.Tooltip, () => { })));
|
||||
Check.Eq(pages.Count, ConquestFeature.PageList.Length, "every page is valid");
|
||||
Check.True(pages.Select(p => p.Label).SequenceEqual(new[] { "Conquest", "Leaderboards" }), "the Conquest and Leaderboards pages");
|
||||
ServerPackInfo info = new("conquest", "Conquest", new[] { "acconquest.ddns.net" }, new[] { "Conquest", "ConquestAC" });
|
||||
SectionManifest m = SectionManifestParser.Parse("RynthConquest", ServerPackModel.BuildSectionsJson(info, "RynthConquest", pages), out string error);
|
||||
Check.Eq(error, "", "RynthCore parses the manifest");
|
||||
SectionContribution[] views = m.Contributions.Where(c => c.Primary).ToArray();
|
||||
Check.Eq(views.Length, 2, "two pages in the Mini Remote");
|
||||
Check.True(views.All(c => c.Server == "conquest"), "shown only while Conquest is active");
|
||||
Check.True(views.Select(c => c.Surface).SequenceEqual(new[] { "section:server-conquest.main", "section:server-conquest.boards" }), "their surfaces");
|
||||
}
|
||||
}
|
||||
122
Tools/RynthServerPack.Tests/LevistrasTests.cs
Normal file
122
Tools/RynthServerPack.Tests/LevistrasTests.cs
Normal file
|
|
@ -0,0 +1,122 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Xml.Linq;
|
||||
using RynthCore.App;
|
||||
using RynthCore.PluginSdk.Manifest;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthServerPack.Tests;
|
||||
|
||||
// RynthLevistras (2026-10-21): the Levistras server plugin, and the launcher's server list
|
||||
// (RynthCore.App\KnownServerCatalog.cs), which names a server plugin for every server it offers.
|
||||
internal static class LevistrasTests
|
||||
{
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("levistras: the plugin's detection data matches the launcher's Levistras entry", Detection);
|
||||
r.Add("levistras: its card says bots are forbidden and two accounts", Card);
|
||||
r.Add("levistras: its quest pack is the 464 Levistras rows RynthOracle had", Pack);
|
||||
r.Add("launcher catalog: every server names a plugin that claims its host, port and emulator", Catalog);
|
||||
}
|
||||
|
||||
private static string PluginsDir()
|
||||
{
|
||||
string? dir = AppContext.BaseDirectory;
|
||||
while (dir != null && !Directory.Exists(Path.Combine(dir, "Plugins", "Shared", "ServerPack")))
|
||||
dir = Path.GetDirectoryName(dir);
|
||||
if (dir == null) throw new DirectoryNotFoundException("RynthSuite\\Plugins not found above " + AppContext.BaseDirectory);
|
||||
return Path.Combine(dir, "Plugins");
|
||||
}
|
||||
|
||||
private sealed record Plugin(string Dir, string Id, string Name, string[] Hosts, string[] Worlds, string ServerData);
|
||||
|
||||
/// <summary>The server plugin project named Rynth<name>, or null.</summary>
|
||||
private static Plugin? Load(string pluginName)
|
||||
{
|
||||
string dir = Path.Combine(PluginsDir(), "RynthCore.Plugin." + pluginName);
|
||||
string csproj = Path.Combine(dir, "RynthCore.Plugin." + pluginName + ".csproj");
|
||||
if (!File.Exists(csproj)) return null;
|
||||
XDocument doc = XDocument.Load(csproj);
|
||||
string Prop(string name) => doc.Descendants(name).FirstOrDefault()?.Value.Trim() ?? "";
|
||||
string[] Split(string v) => v.Split('|', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
|
||||
string data = Path.Combine(dir, "ServerData.cs");
|
||||
return new Plugin(dir, Prop("RynthPluginServerId"), Prop("RynthPluginServerName"), Split(Prop("RynthPluginServerHosts")),
|
||||
Split(Prop("RynthPluginServerWorldNames")), File.Exists(data) ? File.ReadAllText(data) : "");
|
||||
}
|
||||
|
||||
/// <summary>The port ServerData.cs sets (9000 when it doesn't say).</summary>
|
||||
private static int PortOf(Plugin p)
|
||||
{
|
||||
Match m = Regex.Match(p.ServerData, @"\bPort\s*=\s*(\d+)");
|
||||
return m.Success ? int.Parse(m.Groups[1].Value) : 9000;
|
||||
}
|
||||
|
||||
private static string EmulatorOf(Plugin p)
|
||||
{
|
||||
Match m = Regex.Match(p.ServerData, @"\bEmulator\s*=\s*""([^""]*)""");
|
||||
return m.Success ? m.Groups[1].Value : "ACE";
|
||||
}
|
||||
|
||||
private static void Detection()
|
||||
{
|
||||
Plugin? p = Load("RynthLevistras");
|
||||
Check.NotNull(p, "RynthLevistras exists");
|
||||
if (p == null) return;
|
||||
Check.Eq(p.Id, "levistras", "id");
|
||||
Check.Eq(p.Name, "Levistras", "name (also its quest pack's tag)");
|
||||
Check.True(p.Hosts.SequenceEqual(new[] { "levistras.acportalstorm.com" }), "host: " + string.Join("|", p.Hosts));
|
||||
Check.True(p.Worlds.Contains("Levistras"), "world name Levistras (the name RynthOracle matched before the move)");
|
||||
|
||||
KnownServer? k = KnownServerCatalog.FindById("levistras");
|
||||
Check.NotNull(k, "the launcher lists Levistras");
|
||||
if (k == null) return;
|
||||
Check.Eq(k.PluginName, "RynthLevistras", "the launcher's entry names RynthLevistras");
|
||||
var server = new RynthPluginServer { Id = p.Id, Hosts = p.Hosts.ToList() };
|
||||
Check.True(server.MatchesHost(k.Host, out _), "the plugin claims the launcher's host " + k.Host);
|
||||
Check.Eq(PortOf(p), k.Port, "port");
|
||||
Check.Eq(EmulatorOf(p), "ACE", "emulator");
|
||||
Check.Eq(k.Emulator, AcEmulatorKind.Ace, "the launcher connects with ACE");
|
||||
}
|
||||
|
||||
private static void Card()
|
||||
{
|
||||
Plugin? p = Load("RynthLevistras");
|
||||
if (p == null) { Check.True(false, "RynthLevistras exists"); return; }
|
||||
Check.True(p.ServerData.Contains("Botting = BottingPolicy.Forbidden"), "botting forbidden (the server card warns, RynthAi's combat isn't for here)");
|
||||
Check.True(p.ServerData.Contains("AccountLimit = \"2 accounts\""), "two accounts");
|
||||
Check.True(p.ServerData.Contains("Ruleset = \"PvE\""), "PvE");
|
||||
}
|
||||
|
||||
private static void Pack()
|
||||
{
|
||||
Plugin? p = Load("RynthLevistras");
|
||||
if (p == null) { Check.True(false, "RynthLevistras exists"); return; }
|
||||
string file = Path.Combine(p.Dir, "Resources", "quests.levistras.csv");
|
||||
Check.True(File.Exists(file), "Resources\\quests.levistras.csv (ServerPlugin.props embeds it as the served pack)");
|
||||
if (!File.Exists(file)) return;
|
||||
string csv = File.ReadAllText(file);
|
||||
Check.Eq(RynthCore.Plugin.ServerPack.ServerPackQuestPack.CountRows(csv), 464, "464 quests");
|
||||
var info = new RynthCore.Plugin.ServerPack.ServerPackInfo(p.Id, p.Name, p.Hosts, p.Worlds);
|
||||
string json = RynthCore.Plugin.ServerPack.ServerPackQuestPack.BuildInfoJson(info, "RynthLevistras", "0.1.0", csv);
|
||||
Check.True(json.Contains("\"server\":\"levistras\"") && json.Contains("\"tag\":\"Levistras\"") && json.Contains("\"rows\":464"),
|
||||
"offered as levistras / Levistras, 464 rows: " + json);
|
||||
Check.True(File.Exists(Path.Combine(p.Dir, "THIRD_PARTY_NOTICES.md")), "the pack's MIT notice (Advis Eveldan's rows) comes with it");
|
||||
}
|
||||
|
||||
private static void Catalog()
|
||||
{
|
||||
foreach (KnownServer k in KnownServerCatalog.All)
|
||||
{
|
||||
Plugin? p = Load(k.PluginName);
|
||||
Check.NotNull(p, $"{k.Id}: the launcher's plugin {k.PluginName} exists");
|
||||
if (p == null) continue;
|
||||
Check.Eq(p.Id, k.Id, $"{k.PluginName}: the same server id as the launcher");
|
||||
var server = new RynthPluginServer { Id = p.Id, Hosts = p.Hosts.ToList() };
|
||||
Check.True(server.MatchesHost(k.Host, out _), $"{k.PluginName} claims the launcher's host {k.Host}");
|
||||
Check.Eq(PortOf(p), k.Port, $"{k.PluginName}: port");
|
||||
Check.Eq(EmulatorOf(p).Equals("GDLE", StringComparison.OrdinalIgnoreCase), k.Emulator == AcEmulatorKind.Gdle, $"{k.PluginName}: emulator");
|
||||
}
|
||||
}
|
||||
}
|
||||
24
Tools/RynthServerPack.Tests/Program.cs
Normal file
24
Tools/RynthServerPack.Tests/Program.cs
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthServerPack.Tests;
|
||||
|
||||
// Offline tests for the server plugins: the shared model and every server plugin's detection data.
|
||||
//
|
||||
// Run: dotnet run -c Release (all tests)
|
||||
// dotnet run -c Release -- host (tests whose name contains "host")
|
||||
internal static class Program
|
||||
{
|
||||
private static int Main(string[] args)
|
||||
{
|
||||
var runner = new Runner();
|
||||
ServerPackModelTests.Register(runner);
|
||||
ServerProjectsTests.Register(runner);
|
||||
ServerPackHooksTests.Register(runner);
|
||||
ConquestTests.Register(runner);
|
||||
AelrynthTests.Register(runner);
|
||||
VaultTests.Register(runner);
|
||||
QuestPackTests.Register(runner);
|
||||
LevistrasTests.Register(runner);
|
||||
return runner.Run("RynthServerPack tests", args.Length > 0 ? args[0] : null);
|
||||
}
|
||||
}
|
||||
154
Tools/RynthServerPack.Tests/QuestPackTests.cs
Normal file
154
Tools/RynthServerPack.Tests/QuestPackTests.cs
Normal file
|
|
@ -0,0 +1,154 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using RynthCore.Plugin.ServerPack;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthServerPack.Tests;
|
||||
|
||||
// "RynthServer.QuestPack" (Plugins\Shared\ServerPack\ServerPackQuestPack.cs): a server plugin's own quest
|
||||
// list for RynthOracle. The info JSON says whose pack it is and how big; junk is no pack at all.
|
||||
internal static class QuestPackTests
|
||||
{
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("quest pack: the info JSON names the server, its tag and the pack's size", InfoJson);
|
||||
r.Add("quest pack: no pack, junk or a header alone is no pack", NoPack);
|
||||
r.Add("quest pack: the info JSON is plain ASCII and escaped", InfoAscii);
|
||||
r.Add("quest pack: the embedded pack is served as it is (RynthConquest's)", Embedded);
|
||||
r.Add("quest packs: Conquest's, Levistras's and Aelrynth's are their own plugins' (none left in RynthOracle)", Projects);
|
||||
}
|
||||
|
||||
private static string PluginsDir()
|
||||
{
|
||||
string? dir = AppContext.BaseDirectory;
|
||||
while (dir != null && !Directory.Exists(Path.Combine(dir, "Plugins", "Shared", "ServerPack")))
|
||||
dir = Path.GetDirectoryName(dir);
|
||||
if (dir == null) throw new DirectoryNotFoundException("RynthSuite\\Plugins not found above " + AppContext.BaseDirectory);
|
||||
return Path.Combine(dir, "Plugins");
|
||||
}
|
||||
|
||||
/// <summary>RynthSuite's Plugins: the sibling checkout this repo builds against (RynthOracle lives there).</summary>
|
||||
private static string SuitePluginsDir()
|
||||
{
|
||||
string? dir = AppContext.BaseDirectory;
|
||||
while (dir != null && !Directory.Exists(Path.Combine(dir, "RynthSuite", "Plugins", "RynthCore.Plugin.RynthOracle")))
|
||||
dir = Path.GetDirectoryName(dir);
|
||||
if (dir == null) throw new DirectoryNotFoundException("the sibling RynthSuite\\Plugins not found above " + AppContext.BaseDirectory);
|
||||
return Path.Combine(dir, "RynthSuite", "Plugins");
|
||||
}
|
||||
|
||||
private static void Embedded()
|
||||
{
|
||||
string csv = ServerPackQuestPack.Csv;
|
||||
Check.Eq(ServerPackQuestPack.CountRows(csv), 546, "RynthConquest's 546 quests are served");
|
||||
var conquest = new ServerPackInfo("conquest", "Conquest", new[] { "acconquest.ddns.net" }, new[] { "Conquest" });
|
||||
using JsonDocument doc = JsonDocument.Parse(ServerPackQuestPack.BuildInfoJson(conquest, "RynthConquest", "0.2.0", csv));
|
||||
Check.Eq(doc.RootElement.GetProperty("rows").GetInt32(), 546, "the info says so");
|
||||
Check.Eq(doc.RootElement.GetProperty("tag").GetString(), "Conquest", "under the tag the master list uses");
|
||||
Check.True(ReferenceEquals(csv, ServerPackQuestPack.Csv), "read once");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The packs that were RynthOracle's (2026-10-21): each in its server's plugin, as
|
||||
/// Resources\quests.<server id>.csv (ServerPlugin.props embeds it), naming only that server; the
|
||||
/// same rows as before; none left in RynthOracle, which keeps only the retail list.
|
||||
/// </summary>
|
||||
private static void Projects()
|
||||
{
|
||||
string plugins = PluginsDir();
|
||||
var expected = new Dictionary<string, (string Dir, string Name, int Rows)>
|
||||
{
|
||||
["conquest"] = ("RynthCore.Plugin.RynthConquest", "Conquest", 546),
|
||||
["levistras"] = ("RynthCore.Plugin.RynthLevistras", "Levistras", 464),
|
||||
["aelrynth"] = ("RynthCore.Plugin.RynthAelrynth", "Aelrynth", 4277),
|
||||
};
|
||||
foreach (var kv in expected)
|
||||
{
|
||||
string file = Path.Combine(plugins, kv.Value.Dir, "Resources", $"quests.{kv.Key}.csv");
|
||||
Check.True(File.Exists(file), kv.Value.Dir + " has its pack " + Path.GetFileName(file));
|
||||
if (!File.Exists(file)) continue;
|
||||
string csv = File.ReadAllText(file);
|
||||
Check.True(ServerPackQuestPack.Usable(csv), kv.Key + ": a quest list (QuestFlag header and rows)");
|
||||
Check.Eq(ServerPackQuestPack.CountRows(csv), kv.Value.Rows, kv.Key + ": the same rows as before the move");
|
||||
string[] lines = csv.Replace("\r", "").Split('\n', StringSplitOptions.RemoveEmptyEntries);
|
||||
string[] header = lines[0].Split(',');
|
||||
int server = Array.FindIndex(header, h => h.Trim().Equals("Server", StringComparison.OrdinalIgnoreCase));
|
||||
Check.True(server >= 0, kv.Key + ": has a Server column");
|
||||
int other = lines.Skip(1).Count(l => l.Split(',')[server].Trim() != kv.Value.Name);
|
||||
Check.Eq(other, 0, $"{kv.Key}: every row's Server is {kv.Value.Name} (the pack's tag, the plugin's server name)");
|
||||
string csproj = File.ReadAllText(Path.Combine(plugins, kv.Value.Dir, kv.Value.Dir + ".csproj"));
|
||||
Check.True(csproj.Contains("<RynthPluginServerId>" + kv.Key + "</RynthPluginServerId>")
|
||||
&& csproj.Contains("<RynthPluginServerName>" + kv.Value.Name + "</RynthPluginServerName>"),
|
||||
kv.Value.Dir + ": the pack's file name is its server id, the rows' Server its server name");
|
||||
}
|
||||
|
||||
// No other server plugin carries a pack, and none carries another server's.
|
||||
foreach (string dir in Directory.GetDirectories(plugins, "RynthCore.Plugin.Rynth*"))
|
||||
{
|
||||
string res = Path.Combine(dir, "Resources");
|
||||
if (!Directory.Exists(res)) continue;
|
||||
foreach (string f in Directory.GetFiles(res, "quests.*.csv"))
|
||||
{
|
||||
string id = Path.GetFileNameWithoutExtension(f).Substring("quests.".Length);
|
||||
Check.True(expected.TryGetValue(id, out var e) && Path.GetFileName(dir) == e.Dir, $"{Path.GetFileName(dir)}/{Path.GetFileName(f)} is in its own server's plugin");
|
||||
}
|
||||
}
|
||||
string oracle = Path.Combine(SuitePluginsDir(), "RynthCore.Plugin.RynthOracle");
|
||||
string[] left = Directory.GetFiles(Path.Combine(oracle, "Resources"), "quests*.csv").Select(Path.GetFileName).ToArray()!;
|
||||
Check.True(left.SequenceEqual(new[] { "quests.csv" }), "RynthOracle keeps only the retail list: " + string.Join(",", left));
|
||||
Check.False(File.ReadAllText(Path.Combine(oracle, "RynthCore.Plugin.RynthOracle.csproj")).Contains("quests.conquest", StringComparison.OrdinalIgnoreCase),
|
||||
"and embeds no server's pack");
|
||||
string props = File.ReadAllText(Path.Combine(plugins, "Shared", "ServerPack", "ServerPlugin.props"));
|
||||
Check.True(props.Contains("quests.$(RynthPluginServerId).csv") && props.Contains("LogicalName=\"" + ServerPackQuestPack.ResourceName + "\""),
|
||||
"ServerPlugin.props embeds Resources\\quests.<server id>.csv as the served pack");
|
||||
}
|
||||
|
||||
private const string Sample =
|
||||
"QuestFlag,Server,Quest,Url,Info,Hint,Repeatable\n"
|
||||
+ "aaaflag,Example,A quest,,,,FALSE\n"
|
||||
+ "\n"
|
||||
+ "bbbflag,Example,\"Another, with a comma\",,,,TRUE\n";
|
||||
|
||||
private static ServerPackInfo Example() => new("Example", "Example", new[] { "play.example.test" }, new[] { "Example" });
|
||||
|
||||
private static void InfoJson()
|
||||
{
|
||||
string json = ServerPackQuestPack.BuildInfoJson(Example(), "RynthExample", "0.1.0", Sample);
|
||||
using JsonDocument doc = JsonDocument.Parse(json);
|
||||
JsonElement root = doc.RootElement;
|
||||
Check.Eq(root.GetProperty("schema").GetInt32(), ServerPackQuestPack.Schema, "schema");
|
||||
Check.Eq(root.GetProperty("server").GetString(), "example", "server: the RynthCore id (lower case)");
|
||||
Check.Eq(root.GetProperty("tag").GetString(), "Example", "tag: the server's name (the master list's Server column)");
|
||||
Check.Eq(root.GetProperty("plugin").GetString(), "RynthExample", "plugin");
|
||||
Check.Eq(root.GetProperty("version").GetString(), "0.1.0", "version");
|
||||
Check.Eq(root.GetProperty("rows").GetInt32(), 2, "rows: data lines, blank ones skipped");
|
||||
Check.Eq(root.GetProperty("bytes").GetInt32(), System.Text.Encoding.UTF8.GetByteCount(Sample), "bytes: the CSV's UTF-8 length");
|
||||
Check.Eq(root.GetProperty("revision").GetInt32(), ServerPackQuestPack.Revision, "revision");
|
||||
Check.Eq(ServerPackQuestPack.CountRows(Sample), 2, "CountRows");
|
||||
Check.True(ServerPackQuestPack.Usable("QuestFlag,Server\nx,Example\n"), "a BOM before the header is fine");
|
||||
Check.True(ServerPackQuestPack.Usable("Flag,Quest\r\nx,y\r\n"), "Flag works as the column name too (CRLF lines)");
|
||||
}
|
||||
|
||||
private static void NoPack()
|
||||
{
|
||||
ServerPackInfo info = Example();
|
||||
Check.Eq(ServerPackQuestPack.BuildInfoJson(info, "RynthExample", "0.1.0", null), "", "null: no pack");
|
||||
Check.Eq(ServerPackQuestPack.BuildInfoJson(info, "RynthExample", "0.1.0", ""), "", "empty: no pack");
|
||||
Check.Eq(ServerPackQuestPack.BuildInfoJson(info, "RynthExample", "0.1.0", "QuestFlag,Server\n"), "", "a header alone: no pack");
|
||||
Check.Eq(ServerPackQuestPack.BuildInfoJson(info, "RynthExample", "0.1.0", "Name,Notes\na,b\n"), "", "no QuestFlag column: no pack");
|
||||
Check.False(ServerPackQuestPack.Usable("<html>404</html>"), "junk is not usable");
|
||||
}
|
||||
|
||||
private static void InfoAscii()
|
||||
{
|
||||
var odd = new ServerPackInfo("odd", "Odd \"Name\" é", new[] { "a" }, Array.Empty<string>());
|
||||
string json = ServerPackQuestPack.BuildInfoJson(odd, "Rynth\\Odd", "1", Sample);
|
||||
foreach (char c in json) Check.True(c >= 0x20 && c <= 0x7e, "plain ASCII: " + (int)c);
|
||||
using JsonDocument doc = JsonDocument.Parse(json);
|
||||
Check.Eq(doc.RootElement.GetProperty("tag").GetString(), "Odd \"Name\" é", "quotes and accents survive");
|
||||
Check.Eq(doc.RootElement.GetProperty("plugin").GetString(), "Rynth\\Odd", "backslash survives");
|
||||
}
|
||||
}
|
||||
67
Tools/RynthServerPack.Tests/RynthServerPack.Tests.csproj
Normal file
67
Tools/RynthServerPack.Tests/RynthServerPack.Tests.csproj
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!--
|
||||
Tests for the server plugins (Plugins\Shared\ServerPack, built into RynthColdeve, RynthAelrynth, ...):
|
||||
- the shared model (ServerPackModel.cs, ServerPackInfo.cs): RynthCore's "servermenu" verdict,
|
||||
the world-name fallback, the override commands and the sections manifest;
|
||||
- every server plugin's csproj, read as XML: unique ids, plugin names and hosts, and no
|
||||
server's host claimed by another server's list (RynthCore would load the wrong plugin);
|
||||
- the launcher's known-server catalog (RynthCore.App\KnownServerCatalog.cs): every entry names
|
||||
a server plugin whose hosts claim the entry's host, with the same port and emulator.
|
||||
The plugins are NativeAOT x86 libraries, so the pure sources are compiled in here directly.
|
||||
The SDK's manifest file (BCL only) supplies RynthCore's host matching.
|
||||
Run: dotnet run -c Release (exit 0 = pass, 1 = fail; an argument filters by test name)
|
||||
-->
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<InvariantGlobalization>true</InvariantGlobalization>
|
||||
<!-- RynthServerProfileApi.cs declares the interface's (function-pointer) table. -->
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<RootNamespace>RynthServerPack.Tests</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Include="..\..\Plugins\Shared\ServerPack\ServerPackInfo.cs" Link="Plugin\ServerPackInfo.cs" />
|
||||
<Compile Include="..\..\Plugins\Shared\ServerPack\ServerPackModel.cs" Link="Plugin\ServerPackModel.cs" />
|
||||
<!-- The hooks for a server's own features: pages, the settings file, the own-reply window. -->
|
||||
<Compile Include="..\..\Plugins\Shared\ServerPack\ServerPackPages.cs" Link="Plugin\ServerPackPages.cs" />
|
||||
<Compile Include="..\..\Plugins\Shared\ServerPack\ServerPackSettings.cs" Link="Plugin\ServerPackSettings.cs" />
|
||||
<Compile Include="..\..\Plugins\Shared\ServerPack\ServerChatRequest.cs" Link="Plugin\ServerChatRequest.cs" />
|
||||
<!-- RynthConquest's own features (pure parts) and the RynthOracle sources it links. -->
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthConquest\Conquest\ConquestData.cs" Link="Conquest\ConquestData.cs" />
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthConquest\Conquest\ConquestFeature.cs" Link="Conquest\ConquestFeature.cs" />
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthConquest\Conquest\CustomQuests.cs" Link="Conquest\CustomQuests.cs" />
|
||||
<Compile Include="$(RynthSuiteRoot)Plugins\RynthCore.Plugin.RynthOracle\Data\QuestFlags.cs" Link="Oracle\QuestFlags.cs" />
|
||||
<Compile Include="$(RynthSuiteRoot)Plugins\RynthCore.Plugin.RynthOracle\Data\TimeText.cs" Link="Oracle\TimeText.cs" />
|
||||
<Compile Include="$(RynthSuiteRoot)Plugins\RynthCore.Plugin.RynthOracle\Data\Csv.cs" Link="Oracle\Csv.cs" />
|
||||
<EmbeddedResource Include="..\..\Plugins\RynthCore.Plugin.RynthConquest\Resources\customquests.csv" LogicalName="RynthConquest.customquests.csv" />
|
||||
<!-- RynthAelrynth's own features (pure parts). -->
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAelrynth\Aelrynth\AelrynthBoards.cs" Link="Aelrynth\AelrynthBoards.cs" />
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAelrynth\Aelrynth\AelrynthFeature.cs" Link="Aelrynth\AelrynthFeature.cs" />
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAelrynth\Aelrynth\VaultFeed.cs" Link="Aelrynth\VaultFeed.cs" />
|
||||
<!-- The difficulty tier RynthAelrynth publishes for RynthAi (and the value names, RynthServerProfileApi.cs). -->
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAelrynth\Aelrynth\AelrynthDifficulty.cs" Link="Aelrynth\AelrynthDifficulty.cs" />
|
||||
<Compile Include="$(RynthSuiteRoot)Plugins\Shared\RynthServerProfileApi.cs" Link="Shared\RynthServerProfileApi.cs" />
|
||||
<Compile Include="$(RynthSuiteRoot)Plugins\Shared\ChatSource.cs" Link="Shared\ChatSource.cs" />
|
||||
<Compile Include="$(RynthSuiteRoot)Plugins\Shared\StorageFeed.cs" Link="Shared\StorageFeed.cs" />
|
||||
<!-- RynthCore's own sections-manifest parser (pure), so the manifest is checked the way the engine reads it. -->
|
||||
<Compile Include="..\..\..\RynthCore\src\RynthCore.Engine\UI\Sections\SectionManifest.cs" Link="Engine\SectionManifest.cs" />
|
||||
<!-- "RynthServer.Profile": the profile JSON, and the shared reader's parser that consumes it. -->
|
||||
<Compile Include="..\..\Plugins\Shared\ServerPack\ServerPackProfile.cs" Link="Plugin\ServerPackProfile.cs" />
|
||||
<!-- "RynthServer.QuestPack": a server plugin's own quest list (the info JSON; the pack itself is data). -->
|
||||
<Compile Include="..\..\Plugins\Shared\ServerPack\ServerPackQuestPack.cs" Link="Plugin\ServerPackQuestPack.cs" />
|
||||
<!-- RynthConquest's pack, under the logical name ServerPlugin.props gives it, so the served pack is checked as embedded. -->
|
||||
<EmbeddedResource Include="..\..\Plugins\RynthCore.Plugin.RynthConquest\Resources\quests.conquest.csv" LogicalName="ServerPack.quests.csv" />
|
||||
<Compile Include="$(RynthSuiteRoot)Plugins\Shared\EngineServerState.cs" Link="Shared\EngineServerState.cs" />
|
||||
<Compile Include="..\..\..\RynthCore\src\RynthCore.PluginSdk\Manifest\RynthPluginManifest.cs" Link="Sdk\RynthPluginManifest.cs" />
|
||||
<!-- The launcher's known-server picker, checked against the plugins it names. -->
|
||||
<Compile Include="..\..\..\RynthCore\src\RynthCore.App\LaunchServerProfile.cs" Link="Launcher\LaunchServerProfile.cs" />
|
||||
<Compile Include="..\..\..\RynthCore\src\RynthCore.App\KnownServerCatalog.cs" Link="Launcher\KnownServerCatalog.cs" />
|
||||
<!-- The RynthAi test tools' check/runner harness (no plugin code in it). -->
|
||||
<Compile Include="$(RynthSuiteRoot)Tools\RynthCore.RynthAiTests\Harness\Check.cs" Link="Harness\Check.cs" />
|
||||
<Compile Include="$(RynthSuiteRoot)Tools\RynthCore.RynthAiTests\Harness\Runner.cs" Link="Harness\Runner.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
210
Tools/RynthServerPack.Tests/ServerPackHooksTests.cs
Normal file
210
Tools/RynthServerPack.Tests/ServerPackHooksTests.cs
Normal file
|
|
@ -0,0 +1,210 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using RynthCore.Engine.UI.Sections;
|
||||
using RynthCore.Plugin.ServerPack;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthServerPack.Tests;
|
||||
|
||||
// The shared hooks a server plugin's own features use (2026-10-20, when RynthOracle's and
|
||||
// RynthInventory's Conquest and Aelrynth features moved into RynthConquest and RynthAelrynth):
|
||||
// pages beside the server card, the plugin's own settings file (with a one-time migration), live
|
||||
// numbers in the "RynthServer.Profile" JSON, and the own-reply window.
|
||||
internal static class ServerPackHooksTests
|
||||
{
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("hooks: page ids, surfaces and the surface a page is drawn under", PageNames);
|
||||
r.Add("hooks: bad, duplicate and surplus pages are left out", PageValidation);
|
||||
r.Add("hooks: pages are server-only primary views of the Server section, accepted by RynthCore's parser", PagesInManifest);
|
||||
r.Add("hooks: settings round-trip and keep values the plugin doesn't know", SettingsRoundTrip);
|
||||
r.Add("hooks: settings migration runs once, and a broken file means defaults", SettingsMigration);
|
||||
r.Add("hooks: profile values are published, validated and read back", ProfileValues);
|
||||
r.Add("hooks: the own-reply window opens, stretches and closes", ReplyWindow);
|
||||
}
|
||||
|
||||
internal static string TempDir()
|
||||
{
|
||||
string dir = Path.Combine(Path.GetTempPath(), "RynthServerPack.Tests", Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(dir);
|
||||
return dir;
|
||||
}
|
||||
|
||||
private static void PageNames()
|
||||
{
|
||||
Check.True(ServerPackPages.IsValidId("bank") && ServerPackPages.IsValidId("top-10"), "plain ids");
|
||||
Check.False(ServerPackPages.IsValidId("") || ServerPackPages.IsValidId("Bank") || ServerPackPages.IsValidId("a.b")
|
||||
|| ServerPackPages.IsValidId(new string('a', 17)), "empty, capitals, dots and long ids are refused");
|
||||
Check.Eq(ServerPackPages.SurfaceFor("conquest", "bank"), "section:server-conquest.bank", "surface");
|
||||
Check.Eq(ServerPackPages.PageIdOf("section:server-conquest.bank", "conquest"), "bank", "page from its surface");
|
||||
Check.Eq(ServerPackPages.PageIdOf("section:server-conquest.bank:popout", "conquest"), "bank", "popped out");
|
||||
Check.Null(ServerPackPages.PageIdOf("section:server-conquest", "conquest"), "the card is not a page");
|
||||
Check.Null(ServerPackPages.PageIdOf("section:server-aelrynth.top", "conquest"), "another server's page");
|
||||
Check.Null(ServerPackPages.PageIdOf("section:server-conquest.Bad!", "conquest"), "a malformed page id");
|
||||
Check.Null(ServerPackPages.PageIdOf(null, "conquest"), "null");
|
||||
string longest = ServerPackPages.SurfaceFor(new string('a', 32), new string('b', ServerPackPages.MaxIdLength));
|
||||
Check.True(longest.Length <= SectionManifestParser.MaxSurfaceLength, "the longest surface fits RynthCore's cap: " + longest.Length);
|
||||
}
|
||||
|
||||
private static void PageValidation()
|
||||
{
|
||||
Action draw = () => { };
|
||||
var notes = new List<string>();
|
||||
var pages = new List<ServerPage>
|
||||
{
|
||||
new("one", "One", "", draw), new("one", "Again", "", draw), new("Two", "Two", "", draw),
|
||||
new("three", " ", "", draw), new("four", "Four", "tip", null!),
|
||||
};
|
||||
for (int i = 0; i < 8; i++) pages.Add(new ServerPage("p" + i, "Page " + i, "", draw));
|
||||
List<ServerPage> kept = ServerPackPages.Validate(pages, notes.Add);
|
||||
Check.Eq(kept.Count, ServerPackPages.MaxPages, "capped");
|
||||
Check.Eq(kept[0].Id, "one", "first kept");
|
||||
Check.Eq(kept.Count(p => p.Id == "one"), 1, "a duplicate id is dropped");
|
||||
Check.False(kept.Any(p => p.Id is "Two" or "three" or "four"), "bad id, no label, nothing to draw");
|
||||
Check.True(notes.Count == pages.Count - kept.Count, "every dropped page is reported: " + string.Join(" | ", notes));
|
||||
Check.Eq(ServerPackPages.Validate(null).Count, 0, "no pages");
|
||||
string label = new string('x', 60);
|
||||
Check.Eq(ServerPackPages.Validate(new[] { new ServerPage("x", label, "", draw) })[0].Label.Length, ServerPackPages.MaxLabelLength, "label capped");
|
||||
}
|
||||
|
||||
private static void PagesInManifest()
|
||||
{
|
||||
ServerPackInfo info = new("conquest", "Conquest", new[] { "acconquest.ddns.net" }, new[] { "Conquest" });
|
||||
var pages = ServerPackPages.Validate(new[]
|
||||
{
|
||||
new ServerPage("main", "Conquest", "Bank, augs and more", () => { }),
|
||||
new ServerPage("boards", "Leaderboards", "", () => { }),
|
||||
});
|
||||
string json = ServerPackModel.BuildSectionsJson(info, "RynthConquest", pages);
|
||||
SectionManifest m = SectionManifestParser.Parse("RynthConquest", json, out string error);
|
||||
Check.Eq(error, "", "RynthCore parses it");
|
||||
Check.Eq(m.Contributions.Length, 3, "the card and two pages");
|
||||
SectionContribution card = m.Contributions.Single(c => !c.Primary);
|
||||
Check.Eq(card.Surface, "section:server-conquest", "the card keeps its surface");
|
||||
SectionContribution[] views = m.Contributions.Where(c => c.Primary).ToArray();
|
||||
Check.True(views.All(c => c.Section == ServerPackModel.SectionId && c.Server == "conquest" && c.IsSurface),
|
||||
"pages: primary views of the Server section, only on Conquest");
|
||||
Check.Eq(views[0].Surface, "section:server-conquest.main", "page surface");
|
||||
Check.Eq(views[0].Label, "Conquest", "page label");
|
||||
Check.Eq(views[0].Tooltip, "Bank, augs and more", "page tooltip");
|
||||
Check.Eq(views[1].Tooltip, "Leaderboards (RynthConquest)", "a default tooltip");
|
||||
Check.True(views[0].Order < views[1].Order, "pages keep their order");
|
||||
Check.True(views[0].Width > 0 && views[0].Height > 0, "pages say their size");
|
||||
|
||||
// Without pages the manifest is byte for byte what it was.
|
||||
Check.Eq(ServerPackModel.BuildSectionsJson(info, "RynthConquest", null), ServerPackModel.BuildSectionsJson(info, "RynthConquest"),
|
||||
"no pages: the old manifest");
|
||||
Check.Eq(SectionManifestParser.Parse("x", ServerPackModel.BuildSectionsJson(info, "RynthConquest"), out _).Contributions.Length, 1,
|
||||
"no pages: only the card");
|
||||
}
|
||||
|
||||
private static void SettingsRoundTrip()
|
||||
{
|
||||
string dir = TempDir();
|
||||
try
|
||||
{
|
||||
string path = Path.Combine(dir, "rynthtest.json");
|
||||
File.WriteAllText(path, "{ \"future\": {\"a\":[1,2]}, \"flag\": false, \"name\": \"x\" }");
|
||||
var s = new ServerPackSettings(path);
|
||||
s.Load();
|
||||
Check.Eq(s.LastError, "", "read");
|
||||
Check.False(s.GetBool("flag", true), "a stored false");
|
||||
Check.True(s.GetBool("missing", true), "a missing value falls back");
|
||||
Check.True(s.GetBool("name", true), "a value of another type falls back");
|
||||
Check.Eq(s.GetString("name", "?"), "x", "text");
|
||||
Check.True(s.SetBool("flag", true), "a change says so");
|
||||
Check.False(s.SetBool("flag", true), "the same value is no change");
|
||||
s.SetString("quote", "a \"b\" \\ c");
|
||||
Check.True(s.Save(), "saved");
|
||||
|
||||
var again = new ServerPackSettings(path);
|
||||
again.Load();
|
||||
Check.True(again.GetBool("flag", false), "the change was kept");
|
||||
Check.Eq(again.GetString("quote", ""), "a \"b\" \\ c", "text escaped and read back");
|
||||
using JsonDocument doc = JsonDocument.Parse(File.ReadAllText(path));
|
||||
Check.Eq(doc.RootElement.GetProperty("future").GetProperty("a").GetArrayLength(), 2, "an unknown value is written back as it was");
|
||||
Check.False(File.Exists(path + ".tmp"), "no temporary file left");
|
||||
Check.True(ServerPackSettings.DefaultPath("RynthConquest").EndsWith(Path.Combine("RynthCore", "rynthconquest.json"), StringComparison.Ordinal),
|
||||
"%APPDATA%\\RynthCore\\<plugin>.json");
|
||||
}
|
||||
finally { try { Directory.Delete(dir, true); } catch { } }
|
||||
}
|
||||
|
||||
private static void SettingsMigration()
|
||||
{
|
||||
string dir = TempDir();
|
||||
try
|
||||
{
|
||||
string old = Path.Combine(dir, "old.json"), mine = Path.Combine(dir, "mine.json");
|
||||
File.WriteAllText(old, "{ \"moved\": true, \"text\": \"t\" }");
|
||||
Check.Eq(ServerPackSettings.ReadBoolFrom(old, "moved"), (bool?)true, "the old home's value");
|
||||
Check.Null(ServerPackSettings.ReadBoolFrom(old, "text"), "not a true/false value");
|
||||
Check.Null(ServerPackSettings.ReadBoolFrom(old, "absent"), "missing value");
|
||||
Check.Null(ServerPackSettings.ReadBoolFrom(Path.Combine(dir, "nope.json"), "moved"), "missing file");
|
||||
|
||||
var s = new ServerPackSettings(mine);
|
||||
s.Load();
|
||||
int runs = 0;
|
||||
Action<ServerPackSettings> migrate = t => { runs++; if (ServerPackSettings.ReadBoolFrom(old, "moved") is bool b) t.SetBool("moved", b); };
|
||||
Check.True(s.MigrateOnce("migratedFromOld", migrate), "runs the first time");
|
||||
Check.True(s.GetBool("moved", false), "imported");
|
||||
File.WriteAllText(old, "{ \"moved\": false }");
|
||||
var later = new ServerPackSettings(mine);
|
||||
later.Load();
|
||||
Check.False(later.MigrateOnce("migratedFromOld", migrate), "never again (the marker was saved)");
|
||||
Check.True(later.GetBool("moved", false), "later changes to the old home don't come over");
|
||||
Check.Eq(runs, 1, "ran once");
|
||||
|
||||
File.WriteAllText(mine, "{ not json");
|
||||
var broken = new ServerPackSettings(mine);
|
||||
broken.Load();
|
||||
Check.True(broken.LastError.Length > 0 && broken.GetBool("moved", true), "a broken file reads as defaults");
|
||||
}
|
||||
finally { try { Directory.Delete(dir, true); } catch { } }
|
||||
}
|
||||
|
||||
private static void ProfileValues()
|
||||
{
|
||||
var v = new ServerProfileValues();
|
||||
int r0 = v.Revision;
|
||||
Check.True(v.Set("voidDotDurationScale", 1.35), "set");
|
||||
Check.True(v.Revision > r0, "a change bumps the revision");
|
||||
int r1 = v.Revision;
|
||||
Check.True(v.Set("voidDotDurationScale", 1.35) && v.Revision == r1, "the same value is no change");
|
||||
Check.False(v.Set("bad key", 1) || v.Set("", 1) || v.Set("x", double.NaN) || v.Set("y", double.PositiveInfinity), "bad keys and numbers");
|
||||
|
||||
ServerPackInfo info = new("conquest", "Conquest", new[] { "h" }, new[] { "Conquest" });
|
||||
string json = ServerPackProfile.BuildJson(info, "RynthConquest", "0.2.0", true, "Conquest", v.Snapshot(out int rev));
|
||||
Check.Eq(rev, v.Revision, "the snapshot's revision");
|
||||
Check.Near(RynthCore.Plugin.Shared.ServerProfileView.Value(json, "voidDotDurationScale", 1), 1.35, 1e-12, "a reader gets the value");
|
||||
Check.Eq(RynthCore.Plugin.Shared.ServerProfileView.Value(json, "other", 7), 7.0, "a missing value falls back");
|
||||
Check.Eq(RynthCore.Plugin.Shared.ServerProfileView.Value("", "voidDotDurationScale", 1), 1.0, "no profile falls back");
|
||||
Check.Eq(RynthCore.Plugin.Shared.ServerProfileView.Value("{\"values\":{\"k\":\"2\"}}", "k", 1), 1.0, "text is not a number");
|
||||
Check.Eq(RynthCore.Plugin.Shared.ServerProfileView.Value("{broken", "k", 3), 3.0, "broken JSON falls back");
|
||||
using (JsonDocument doc = JsonDocument.Parse(ServerPackProfile.BuildJson(info, "RynthConquest", "0.2.0", true, "Conquest")))
|
||||
Check.Eq(doc.RootElement.GetProperty("values").EnumerateObject().Count(), 0, "no values: an empty object");
|
||||
|
||||
Check.True(v.Remove("voidDotDurationScale") && !v.Remove("voidDotDurationScale"), "remove");
|
||||
v.Set("a", 1);
|
||||
int r2 = v.Revision;
|
||||
v.Clear();
|
||||
Check.True(v.Revision > r2 && v.Snapshot(out _).Length == 0, "clear (logout)");
|
||||
}
|
||||
|
||||
private static void ReplyWindow()
|
||||
{
|
||||
var req = new ServerChatRequest();
|
||||
Check.False(req.Awaiting(0), "nothing asked");
|
||||
req.Sent(1000);
|
||||
Check.True(req.Awaiting(1000 + ServerChatRequest.WindowMs - 1), "inside the window");
|
||||
Check.False(req.Awaiting(1000 + ServerChatRequest.WindowMs), "the window closes");
|
||||
req.Sent(1000);
|
||||
req.Extend(5500);
|
||||
Check.True(req.Awaiting(7000), "a reply line stretches it");
|
||||
req.Clear();
|
||||
Check.False(req.Awaiting(1001), "cleared");
|
||||
}
|
||||
}
|
||||
243
Tools/RynthServerPack.Tests/ServerPackModelTests.cs
Normal file
243
Tools/RynthServerPack.Tests/ServerPackModelTests.cs
Normal file
|
|
@ -0,0 +1,243 @@
|
|||
using System;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using RynthCore.Plugin.ServerPack;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthServerPack.Tests;
|
||||
|
||||
// The shared server-plugin model (Plugins\Shared\ServerPack\ServerPackModel.cs): RynthCore's
|
||||
// "servermenu" verdict for the plugin's own server, the world-name fallback before one arrives,
|
||||
// the override commands the card sends, and the sections manifest RynthCore reads.
|
||||
internal static class ServerPackModelTests
|
||||
{
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("server pack: RynthCore's push gives this server's verdict, override and reason", EnginePush);
|
||||
r.Add("server pack: a push without this server, or not a push, changes nothing", ForeignPush);
|
||||
r.Add("server pack: before any push the world name decides", WorldFallback);
|
||||
r.Add("server pack: override commands are checked before sending", ForceCommands);
|
||||
r.Add("server pack: the sections manifest declares the server and a server-only card", SectionsJson);
|
||||
r.Add("server pack: logout clears the verdict", ClearOnLogout);
|
||||
r.Add("server pack: the card's botting line and address", InfoText);
|
||||
r.Add("server pack: the RynthServer.Profile JSON carries the server's settings", ProfileJson);
|
||||
r.Add("server pack: the profile JSON is plain ASCII and escaped", ProfileJsonAscii);
|
||||
}
|
||||
|
||||
private static void ProfileJson()
|
||||
{
|
||||
ServerPackInfo info = new("Coldeve", "Coldeve", new[] { "play.coldeve.ac" }, new[] { "Coldeve" })
|
||||
{
|
||||
Port = 9050, Ruleset = "PvP", Status = "Stable", Botting = BottingPolicy.Restricted, BottingNote = "attended only",
|
||||
AccountLimit = "3 accounts", Facts = new[] { "fact one" }, Commands = new[] { new ServerCommand("/x", "does x") },
|
||||
Discord = "https://discord.gg/x",
|
||||
};
|
||||
string json = ServerPackProfile.BuildJson(info, "RynthColdeve", "0.1.2", true, "Coldeve");
|
||||
using JsonDocument doc = JsonDocument.Parse(json);
|
||||
JsonElement root = doc.RootElement;
|
||||
Check.Eq(root.GetProperty("schema").GetInt32(), ServerPackProfile.Schema, "schema");
|
||||
Check.Eq(root.GetProperty("id").GetString(), "coldeve", "id (lower-cased)");
|
||||
Check.Eq(root.GetProperty("plugin").GetString(), "RynthColdeve", "plugin");
|
||||
Check.Eq(root.GetProperty("version").GetString(), "0.1.2", "version");
|
||||
Check.True(root.GetProperty("active").GetBoolean(), "active");
|
||||
Check.Eq(root.GetProperty("world").GetString(), "Coldeve", "world");
|
||||
Check.Eq(root.GetProperty("hosts")[0].GetString(), "play.coldeve.ac", "hosts");
|
||||
Check.Eq(root.GetProperty("port").GetInt32(), 9050, "port");
|
||||
Check.Eq(root.GetProperty("ruleset").GetString(), "PvP", "ruleset");
|
||||
Check.Eq(root.GetProperty("botting").GetString(), "restricted", "botting");
|
||||
Check.Eq(root.GetProperty("bottingNote").GetString(), "attended only", "botting note");
|
||||
Check.Eq(root.GetProperty("facts")[0].GetString(), "fact one", "facts");
|
||||
Check.Eq(root.GetProperty("commands")[0].GetProperty("what").GetString(), "does x", "commands");
|
||||
Check.Eq(root.GetProperty("discord").GetString(), "https://discord.gg/x", "links");
|
||||
|
||||
// What a reader (RynthOracle, RynthAi's /ra server) makes of it.
|
||||
var view = RynthCore.Plugin.Shared.ServerProfileView.Parse(json);
|
||||
Check.True(view != null, "the shared reader parses it");
|
||||
Check.Eq(view!.Summary(), "PvP, ACE; botting restricted - attended only; accounts: 3 accounts", "the reader's summary");
|
||||
|
||||
// No salvage defined: an empty list, which the Crafting tab reads as "none defined".
|
||||
Check.Eq(root.GetProperty("salvage").GetArrayLength(), 0, "no salvage: empty list");
|
||||
Check.Eq(RynthCore.Plugin.Shared.ServerSalvageView.ParseList(json).Count, 0, "the reader sees none");
|
||||
|
||||
// Salvage defined: each row round-trips through the shared reader.
|
||||
ServerPackInfo withSalvage = new("x", "X", new[] { "x.example" }, new[] { "X" })
|
||||
{
|
||||
Salvage = new[]
|
||||
{
|
||||
new ServerSalvage("melee", 52, "+1 tink past the cap", "once", UsesTinkSlot: false),
|
||||
new ServerSalvage("Armor", 64, "+30 armor level"),
|
||||
new ServerSalvage("", 64, "no bench: skipped"),
|
||||
},
|
||||
};
|
||||
var salvage = RynthCore.Plugin.Shared.ServerSalvageView.ParseList(
|
||||
ServerPackProfile.BuildJson(withSalvage, "RynthX", "1", true, "X"));
|
||||
Check.Eq(salvage.Count, 2, "rows without a bench are skipped");
|
||||
Check.Eq(salvage[0].Bench, "melee", "bench");
|
||||
Check.Eq(salvage[0].Material, 52, "material id");
|
||||
Check.Eq(salvage[0].Kind, "once", "kind");
|
||||
Check.False(salvage[0].UsesTinkSlot, "no tink slot");
|
||||
Check.Eq(salvage[1].Bench, "armor", "bench lower-cased");
|
||||
Check.Eq(salvage[1].Kind, "tink", "default kind");
|
||||
Check.True(salvage[1].UsesTinkSlot, "slot by default");
|
||||
Check.Eq(RynthCore.Plugin.Shared.ServerSalvageView.ParseList("{\"id\":\"x\"}").Count, 0, "a profile without the list (older plugins)");
|
||||
|
||||
// The optional row fields: absent = off / the default, and the writer leaves them out then.
|
||||
Check.True(salvage.All(v => v.AppliedInt == 0 && !v.Prepared && v.Order == 0 && !v.AfterCap
|
||||
&& v.StackGroup.Length == 0 && v.StackCap == 0), "optional fields default when absent");
|
||||
string plain = ServerPackProfile.BuildJson(withSalvage, "RynthX", "1", true, "X");
|
||||
Check.True(!plain.Contains("\"applied\"") && !plain.Contains("\"prepared\"") && !plain.Contains("\"order\"")
|
||||
&& !plain.Contains("\"afterCap\"") && !plain.Contains("\"stackGroup\""), "unset fields are not written");
|
||||
|
||||
ServerPackInfo withRules = new("x", "X", new[] { "x.example" }, new[] { "X" })
|
||||
{
|
||||
Salvage = new[]
|
||||
{
|
||||
new ServerSalvage("melee", 52, "post-cap", "once", UsesTinkSlot: false, Order: 995, AfterCap: true),
|
||||
new ServerSalvage("jewelry", 71, "stack", UsesTinkSlot: false, Order: 50, StackGroup: "jewelry-stack", StackCap: 10),
|
||||
new ServerSalvage("trinkets", 20, "tier", "once", UsesTinkSlot: false, AppliedInt: 384, Prepared: true, Order: 10),
|
||||
},
|
||||
};
|
||||
var rules = RynthCore.Plugin.Shared.ServerSalvageView.ParseList(
|
||||
ServerPackProfile.BuildJson(withRules, "RynthX", "1", true, "X"));
|
||||
Check.Eq(rules.Count, 3, "rows with rules");
|
||||
Check.True(rules[0].AfterCap && rules[0].Order == 995 && !rules[0].Prepared && rules[0].StackGroup.Length == 0, "after cap + order");
|
||||
Check.Eq(rules[1].StackGroup, "jewelry-stack", "stack group");
|
||||
Check.Eq(rules[1].StackCap, 10, "stack cap");
|
||||
Check.True(rules[2].Prepared && rules[2].AppliedInt == 384 && rules[2].Order == 10 && !rules[2].AfterCap, "prepared + applied + order");
|
||||
Check.Eq(RynthCore.Plugin.Shared.ServerSalvageView.ParseList(
|
||||
"{\"salvage\":[{\"bench\":\"jewelry\",\"material\":64,\"stackGroup\":\"g\"},{\"bench\":\"jewelry\",\"material\":71,\"stackGroup\":\"g\",\"stackCap\":0}]}")
|
||||
.Count(v => v.StackGroup.Length > 0), 0, "a stack group without a positive cap is no group");
|
||||
var odd = RynthCore.Plugin.Shared.ServerSalvageView.ParseList(
|
||||
"{\"salvage\":[{\"bench\":\"melee\",\"material\":52,\"applied\":\"x\",\"prepared\":1,\"order\":null,\"afterCap\":\"yes\"}]}");
|
||||
Check.True(odd.Count == 1 && odd[0].AppliedInt == 0 && !odd[0].Prepared && odd[0].Order == 0 && !odd[0].AfterCap,
|
||||
"fields of the wrong type read as absent");
|
||||
|
||||
string idle = ServerPackProfile.BuildJson(info, "RynthColdeve", "0.1.2", false, null);
|
||||
using JsonDocument idleDoc = JsonDocument.Parse(idle);
|
||||
Check.False(idleDoc.RootElement.GetProperty("active").GetBoolean(), "not active");
|
||||
Check.Eq(idleDoc.RootElement.GetProperty("world").GetString(), "", "no world before login");
|
||||
Check.Eq(ServerPackProfile.BottingName(BottingPolicy.Unknown), "unknown", "unknown botting");
|
||||
}
|
||||
|
||||
private static void ProfileJsonAscii()
|
||||
{
|
||||
ServerPackInfo info = new("x", "Caf\u00e9 \"Q\"\n", Array.Empty<string>(), Array.Empty<string>()) { Summary = "a\\b\tc \u2014 d" };
|
||||
string json = ServerPackProfile.BuildJson(info, "RynthX", "1", false, "");
|
||||
bool ascii = true;
|
||||
foreach (char c in json) if (c > 0x7e || c < 0x20) ascii = false;
|
||||
Check.True(ascii, "only printable ASCII: " + json);
|
||||
using JsonDocument doc = JsonDocument.Parse(json);
|
||||
Check.Eq(doc.RootElement.GetProperty("name").GetString(), "Caf\u00e9 \"Q\"", "name round-trips (trimmed)");
|
||||
Check.Eq(doc.RootElement.GetProperty("summary").GetString(), "a\\b\tc \u2014 d", "summary round-trips");
|
||||
}
|
||||
|
||||
private static ServerPackInfo Coldeve() =>
|
||||
new("Coldeve", "Coldeve", new[] { "play.coldeve.ac" }, new[] { "Coldeve" }) { Discord = "https://discord.gg/x" };
|
||||
|
||||
private const string Push =
|
||||
"V\tcoldeve\tColdeve\t1\ton\t0\tforced on for this character\n" +
|
||||
"V\tilt\tInfinite Leaftide\t0\tauto\t0\tnot Infinite Leaftide\n" +
|
||||
"X\tchar\tChar\n" +
|
||||
"S\tcoldeve\tColdeve\t1\t/rc server coldeve on\n" +
|
||||
"I\tColdeve server (RynthColdeve)\t/rc miniremote section char\tWhat is known.\tsection:char\n";
|
||||
|
||||
private static void EnginePush()
|
||||
{
|
||||
var model = new ServerPackModel(Coldeve());
|
||||
Check.True(model.ApplyEngine(Push, 1234), "taken");
|
||||
ServerVerdictView? v = model.Engine;
|
||||
Check.True(v != null, "this server's verdict");
|
||||
Check.True(v!.Active, "active");
|
||||
Check.Eq(v.Force, "on", "override");
|
||||
Check.False(v.Detected, "forced, not detected");
|
||||
Check.Eq(v.Reason, "forced on for this character", "reason");
|
||||
Check.Eq(model.EngineAtMs, 1234L, "when");
|
||||
Check.True(model.IsActive("SomewhereElse"), "RynthCore's verdict beats the world name");
|
||||
}
|
||||
|
||||
private static void ForeignPush()
|
||||
{
|
||||
var model = new ServerPackModel(Coldeve());
|
||||
Check.False(model.ApplyEngine("X\tchar\tChar\n", 1), "no server lines: not a push");
|
||||
Check.False(model.ApplyEngine(null, 1), "null");
|
||||
Check.False(model.ApplyEngine(new string('V', ServerPackModel.MaxPayload + 1), 1), "too long");
|
||||
Check.True(model.Engine == null, "nothing published");
|
||||
|
||||
// A push that lists other servers but not this one yet (RynthCore hasn't read the manifest).
|
||||
Check.True(model.ApplyEngine("V\tilt\tInfinite Leaftide\t1\tauto\t1\thost matches\n", 2), "a push");
|
||||
Check.True(model.Engine == null, "no verdict for this server");
|
||||
ServerPackModel.ParseEngine("V\tCOLDEVE\tColdeve\t0\tweird\t1\n", "coldeve", out bool listed);
|
||||
Check.True(listed, "listed");
|
||||
Check.Eq(ServerPackModel.ParseEngine("V\tCOLDEVE\tColdeve\t0\tweird\t1\n", "coldeve", out _)!.Force, "auto",
|
||||
"id case ignored; an unknown override reads as auto; no reason field is fine");
|
||||
}
|
||||
|
||||
private static void WorldFallback()
|
||||
{
|
||||
var model = new ServerPackModel(Coldeve());
|
||||
Check.True(model.IsActive("Coldeve"), "exact world name");
|
||||
Check.True(model.IsActive(" coldeve "), "case and spaces");
|
||||
Check.False(model.IsActive("ColdeveTwo"), "no partial match without '*'");
|
||||
Check.False(model.IsActive(null), "unknown world");
|
||||
Check.True(ServerPackModel.WorldMatches("Aeshnidae Live", new[] { "Aelrynth*", "Aeshnidae*" }), "wildcard");
|
||||
Check.False(ServerPackModel.WorldMatches("LeafDawn", new[] { "Leafdawning" }), "LeafDawn is not Leafdawning");
|
||||
Check.True(ServerPackModel.WorldMatches("Infinite Leaftide", new[] { "*Leaftide*" }), "both ends");
|
||||
}
|
||||
|
||||
private static void ForceCommands()
|
||||
{
|
||||
Check.Eq(ServerPackModel.ForceCommand("coldeve", "On"), "/rc server coldeve on", "on");
|
||||
Check.Eq(ServerPackModel.ForceCommand("coldeve", "auto"), "/rc server coldeve auto", "auto");
|
||||
Check.Eq(ServerPackModel.ForceCommand("coldeve", "maybe"), "", "unknown mode");
|
||||
Check.Eq(ServerPackModel.ForceCommand("cold eve", "on"), "", "an id with a space");
|
||||
Check.Eq(ServerPackModel.ForceCommand("coldeve; /quit", "on"), "", "no command injection through the id");
|
||||
Check.False(ServerPackModel.IsSafeId(new string('a', 33)), "too long");
|
||||
}
|
||||
|
||||
private static void SectionsJson()
|
||||
{
|
||||
string json = ServerPackModel.BuildSectionsJson(Coldeve(), "RynthColdeve");
|
||||
using JsonDocument doc = JsonDocument.Parse(json);
|
||||
JsonElement root = doc.RootElement;
|
||||
Check.Eq(root.GetProperty("version").GetInt32(), 1, "schema 1");
|
||||
JsonElement server = root.GetProperty("servers")[0];
|
||||
Check.Eq(server.GetProperty("id").GetString(), "coldeve", "server id lower-cased");
|
||||
Check.Eq(server.GetProperty("hosts")[0].GetString(), "play.coldeve.ac", "hosts");
|
||||
Check.Eq(server.GetProperty("worldNames")[0].GetString(), "Coldeve", "world names");
|
||||
JsonElement card = root.GetProperty("contributions")[0];
|
||||
Check.Eq(card.GetProperty("section").GetString(), "server", "in the Server section (not Session Stats)");
|
||||
JsonElement section = root.GetProperty("sections")[0];
|
||||
Check.Eq(section.GetProperty("id").GetString(), "server", "the Server section is declared");
|
||||
Check.Eq(section.GetProperty("label").GetString(), "Server", "its label");
|
||||
Check.Eq(section.GetProperty("order").GetInt32(), 50, "after Session Stats, before Map");
|
||||
Check.Eq(card.GetProperty("server").GetString(), "coldeve", "only while Coldeve is active");
|
||||
Check.Eq(card.GetProperty("surface").GetString(), "section:server-coldeve", "the card's surface");
|
||||
|
||||
var quoted = new ServerPackInfo("odd", "Odd \"Name\"\n", new[] { "a\\b" }, Array.Empty<string>());
|
||||
using JsonDocument odd = JsonDocument.Parse(ServerPackModel.BuildSectionsJson(quoted, "RynthOdd"));
|
||||
Check.Eq(odd.RootElement.GetProperty("servers")[0].GetProperty("hosts")[0].GetString(), "a\\b", "escaped");
|
||||
}
|
||||
|
||||
private static void ClearOnLogout()
|
||||
{
|
||||
var model = new ServerPackModel(Coldeve());
|
||||
model.ApplyEngine(Push, 5);
|
||||
model.Clear();
|
||||
Check.True(model.Engine == null, "verdict cleared");
|
||||
Check.Eq(model.EngineAtMs, 0L, "time cleared");
|
||||
Check.False(model.IsActive("Elsewhere"), "back to the world name");
|
||||
}
|
||||
|
||||
private static void InfoText()
|
||||
{
|
||||
ServerPackInfo c = Coldeve();
|
||||
Check.Eq(c.Address, "play.coldeve.ac:9000", "address");
|
||||
Check.True(c.BottingText.StartsWith("Not published"), "unknown policy says so");
|
||||
Check.True(c.BottingText.Contains("Discord"), "and points at the Discord");
|
||||
var lev = new ServerPackInfo("example", "Example", new[] { "play.example.test" }, new[] { "Example" })
|
||||
{ Botting = BottingPolicy.Forbidden, BottingNote = "no automation" };
|
||||
Check.Eq(lev.BottingText, "Forbidden - no automation", "forbidden");
|
||||
Check.Eq(new ServerPackInfo("x", "", Array.Empty<string>(), Array.Empty<string>()).Address, "", "no host, no address");
|
||||
Check.True(ServerPackModel.LauncherSteps(c)[0].Contains("play.coldeve.ac:9000"), "setup names the address");
|
||||
}
|
||||
}
|
||||
112
Tools/RynthServerPack.Tests/ServerProjectsTests.cs
Normal file
112
Tools/RynthServerPack.Tests/ServerProjectsTests.cs
Normal file
|
|
@ -0,0 +1,112 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Xml.Linq;
|
||||
using RynthCore.PluginSdk.Manifest;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthServerPack.Tests;
|
||||
|
||||
// Every server plugin's csproj (Plugins\RynthCore.Plugin.Rynth*\ with RynthPluginServerId), read as
|
||||
// XML: the detection data RynthCore's loader and sections use must be unique and must not overlap,
|
||||
// or a client would load (or show) the wrong server's plugin.
|
||||
internal static class ServerProjectsTests
|
||||
{
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("server projects: every listed server has a plugin", AllServersPresent);
|
||||
r.Add("server projects: ids, plugin names and hosts are unique", Unique);
|
||||
r.Add("server projects: no server's host is claimed by another server's list", NoHostOverlap);
|
||||
r.Add("server projects: each new server plugin has ServerData.cs and imports the shared props", Layout);
|
||||
}
|
||||
|
||||
// The shared plugins' own check (they name no server, send no server's commands) is RynthSuite's
|
||||
// (Tools/RynthSuite.BoundaryTests) since the server plugins moved to RynthServers (2026-10-21).
|
||||
|
||||
private sealed record Project(string Dir, string PluginName, string Id, string Name, string[] Hosts, string[] Worlds, bool Shared);
|
||||
|
||||
/// <summary>The servers in the request (the server list's busiest, plus Aelrynth) and their plugins.</summary>
|
||||
private static readonly string[] Expected =
|
||||
{
|
||||
"coldeve", "ilt", "frostace", "reefcull", "conquest", "dreamweave", "portalstorm", "sundering",
|
||||
"achard", "leafdawn", "derptide", "frostcull", "thistlecrown", "eversong", "leafdawning", "aelrynth",
|
||||
// Added 2026-10-21 with its quest pack (it was RynthOracle's).
|
||||
"levistras",
|
||||
};
|
||||
|
||||
private static string PluginsDir()
|
||||
{
|
||||
string? dir = AppContext.BaseDirectory;
|
||||
while (dir != null && !Directory.Exists(Path.Combine(dir, "Plugins", "Shared", "ServerPack")))
|
||||
dir = Path.GetDirectoryName(dir);
|
||||
if (dir == null) throw new DirectoryNotFoundException("RynthSuite\\Plugins not found above " + AppContext.BaseDirectory);
|
||||
return Path.Combine(dir, "Plugins");
|
||||
}
|
||||
|
||||
private static List<Project> Load()
|
||||
{
|
||||
var list = new List<Project>();
|
||||
foreach (string dir in Directory.GetDirectories(PluginsDir(), "RynthCore.Plugin.Rynth*"))
|
||||
{
|
||||
string csproj = Path.Combine(dir, Path.GetFileName(dir) + ".csproj");
|
||||
if (!File.Exists(csproj)) continue;
|
||||
XDocument doc = XDocument.Load(csproj);
|
||||
string Prop(string name) => doc.Descendants(name).FirstOrDefault()?.Value.Trim() ?? "";
|
||||
string id = Prop("RynthPluginServerId");
|
||||
if (id.Length == 0) continue;
|
||||
string[] Split(string v) => v.Split('|', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
|
||||
bool shared = doc.Descendants("Import").Any(i => (i.Attribute("Project")?.Value ?? "").EndsWith("ServerPlugin.props"));
|
||||
string asm = Prop("AssemblyName");
|
||||
list.Add(new Project(dir, asm.Replace("RynthCore.Plugin.", ""), id, Prop("RynthPluginServerName"),
|
||||
Split(Prop("RynthPluginServerHosts")), Split(Prop("RynthPluginServerWorldNames")), shared));
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
private static void AllServersPresent()
|
||||
{
|
||||
List<Project> projects = Load();
|
||||
foreach (string id in Expected)
|
||||
Check.True(projects.Any(p => p.Id == id), "a server plugin for " + id);
|
||||
Check.Eq(projects.Count, Expected.Length, "no unexpected server plugins");
|
||||
}
|
||||
|
||||
private static void Unique()
|
||||
{
|
||||
List<Project> projects = Load();
|
||||
Check.Eq(projects.Select(p => p.Id).Distinct().Count(), projects.Count, "ids unique");
|
||||
Check.Eq(projects.Select(p => p.PluginName.ToLowerInvariant()).Distinct().Count(), projects.Count, "plugin names unique");
|
||||
var hosts = projects.SelectMany(p => p.Hosts).Select(h => h.ToLowerInvariant()).ToList();
|
||||
Check.Eq(hosts.Distinct().Count(), hosts.Count, "hosts unique");
|
||||
foreach (Project p in projects)
|
||||
{
|
||||
Check.True(p.Hosts.Length > 0, p.PluginName + " lists a host (the loader picks plugins by host)");
|
||||
Check.True(p.Worlds.Length > 0, p.PluginName + " lists a world name");
|
||||
Check.True(p.Name.Length > 0, p.PluginName + " has a display name");
|
||||
}
|
||||
}
|
||||
|
||||
private static void NoHostOverlap()
|
||||
{
|
||||
List<Project> projects = Load();
|
||||
foreach (Project owner in projects)
|
||||
foreach (string host in owner.Hosts.Where(h => !h.Contains('*')))
|
||||
foreach (Project other in projects.Where(o => o != owner))
|
||||
{
|
||||
var server = new RynthPluginServer { Id = other.Id, Hosts = other.Hosts.ToList() };
|
||||
Check.False(server.MatchesHost(host, out string hit),
|
||||
$"{owner.PluginName}'s host {host} is not claimed by {other.PluginName} ({hit})");
|
||||
}
|
||||
}
|
||||
|
||||
private static void Layout()
|
||||
{
|
||||
foreach (Project p in Load().Where(p => p.Id != "ilt"))
|
||||
{
|
||||
Check.True(p.Shared, p.PluginName + " imports Shared\\ServerPack\\ServerPlugin.props");
|
||||
Check.True(File.Exists(Path.Combine(p.Dir, "ServerData.cs")), p.PluginName + " has ServerData.cs");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
229
Tools/RynthServerPack.Tests/VaultTests.cs
Normal file
229
Tools/RynthServerPack.Tests/VaultTests.cs
Normal file
|
|
@ -0,0 +1,229 @@
|
|||
using System.Collections.Generic;
|
||||
using RynthCore.Plugin.RynthAelrynth;
|
||||
using RynthCore.Plugin.Shared;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthServerPack.Tests;
|
||||
|
||||
// The Aelrynth account vault: /mule-data answers, one "~ael1" line a page (Aeshnidae.Mule MuleData.cs).
|
||||
// Moved with the feed from RynthInventory.Tests on 2026-10-20: RynthAelrynth reads the vault now and
|
||||
// hands it to RynthInventory through the storage feed (Plugins/Shared/StorageFeed.cs).
|
||||
internal static class VaultTests
|
||||
{
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("vault: pages are asked one after the other and filed as one record", Pages);
|
||||
r.Add("vault: other plugins' lines and players' imitations are left alone", Imitations);
|
||||
r.Add("vault: a server without the command is asked once", Unsupported);
|
||||
r.Add("vault: loading, changed and silent vaults are never filed half or empty", Retries);
|
||||
r.Add("vault: RynthAelrynth asks after login, every ten minutes and on /rserver vault", Schedule);
|
||||
r.Add("vault: the record reaches RynthInventory's format intact (plain ASCII)", HandOff);
|
||||
}
|
||||
|
||||
private const string A = "{\"o\":2147483649,\"w\":100,\"n\":\"Acid Assagai\",\"i\":100667000,\"u\":100667001,\"v\":100667002,\"s\":3,\"m\":100,\"y\":1,\"e\":1}";
|
||||
private const string B = "{\"o\":2147483650,\"w\":101,\"n\":\"Pyreal\",\"i\":100667003,\"y\":8192}";
|
||||
|
||||
private static string VaultPage(int page, int pages, int count, string items, bool ready = true, string why = "") =>
|
||||
ready
|
||||
? "~ael1 {\"t\":\"mule\",\"ready\":true,\"page\":" + page + ",\"pages\":" + pages + ",\"count\":" + count + ",\"max\":1000,\"items\":[" + items + "]}"
|
||||
: "~ael1 {\"t\":\"mule\",\"ready\":false,\"why\":\"" + why + "\"}";
|
||||
|
||||
private static (VaultFeed Feed, List<string> Sent) NewVault()
|
||||
{
|
||||
var sent = new List<string>();
|
||||
return (new VaultFeed(t => { sent.Add(t); return true; }), sent);
|
||||
}
|
||||
|
||||
private static void Pages()
|
||||
{
|
||||
(VaultFeed v, List<string> sent) = NewVault();
|
||||
Check.True(v.Ask(1000), "ask starts");
|
||||
Check.Eq(sent.Count == 1 ? sent[0] : "?", "/mule-data", "page 1 asked first");
|
||||
Check.True(v.ShouldEat(VaultPage(1, 2, 2, A)), "page 1 is eaten");
|
||||
v.Tick(1100, "Tom");
|
||||
Check.Eq(sent.Count == 2 ? sent[1] : "?", "/mule-data 2", "page 2 asked when page 1 came");
|
||||
Check.Null(v.Record, "nothing filed before the last page");
|
||||
Check.True(v.ShouldEat(VaultPage(2, 2, 2, B)), "page 2 is eaten");
|
||||
v.Tick(1200, "Tom");
|
||||
StorageFeedRecord? r = v.Record;
|
||||
Check.True(r != null && v.TakeChanged() && !v.TakeChanged(), "filed once");
|
||||
Check.Eq(r?.Items.Count ?? -1, 2, "both pages' items");
|
||||
Check.Eq(r?.Id ?? 0, VaultFeed.VaultId("tom"), "id follows the account, case-blind");
|
||||
Check.True(StorageFeed.IsStandInId(r?.Id ?? 0), "id is a stand-in, far from real objects");
|
||||
Check.Eq(r?.Label ?? "", "Account vault", "label");
|
||||
Check.Eq(r?.Name ?? "", "Aelrynth vault", "name");
|
||||
StorageFeedItem a = r!.Items[0];
|
||||
Check.Eq(a.Name, "Acid Assagai", "name"); Check.Eq(a.Icon, 100667000u, "icon"); Check.Eq(a.Underlay, 100667001u, "underlay");
|
||||
Check.Eq(a.Overlay, 100667002u, "overlay"); Check.Eq(a.Stack, 3, "stack"); Check.Eq(a.MaxStack, 100, "max stack");
|
||||
Check.Eq(a.ItemType, 1u, "item type");
|
||||
Check.Eq(r.Items[1].Stack, 1, "no stack field is a stack of 1");
|
||||
Check.Eq(v.Status, VaultFeed.State.Idle, "idle again");
|
||||
Check.Eq(VaultFeed.VaultId("Tom"), 0xFF000000u | (FnvOf("tom") & 0x00FFFFFFu), "the id RynthInventory used before the move (no second vault)");
|
||||
}
|
||||
|
||||
private static uint FnvOf(string s)
|
||||
{
|
||||
uint h = 2166136261u;
|
||||
foreach (char c in s) { h ^= c; h *= 16777619u; }
|
||||
return h;
|
||||
}
|
||||
|
||||
private static void Imitations()
|
||||
{
|
||||
{
|
||||
(VaultFeed v, _) = NewVault();
|
||||
v.Ask(0);
|
||||
Check.False(v.ShouldEat("~ael1 {\"t\":\"inspect\",\"ok\":true}"), "the Companion's line stays visible");
|
||||
Check.False(v.ShouldEat("Welcome to Aelrynth"), "ordinary chat stays visible");
|
||||
Check.False(v.ShouldEat(null), "null is fine");
|
||||
}
|
||||
{
|
||||
(VaultFeed v, _) = NewVault();
|
||||
v.Ask(0);
|
||||
Check.False(v.ShouldEat("Bob says, \"" + VaultPage(1, 1, 1, A) + "\"", 2), "spoken data line is not ours");
|
||||
Check.False(v.ShouldEat("Bob " + VaultPage(1, 1, 1, A), 12), "an emoted data line is not ours");
|
||||
Check.False(v.ShouldEat("Bob " + VaultPage(1, 1, 1, A)), "a data line not at the start is not ours, type unknown");
|
||||
Check.False(v.ShouldEat(VaultPage(1, 1, 1, A), 3), "a data line in a tell is not ours");
|
||||
Check.False(v.ShouldEat("Bob tells you, \"Unknown command: mule-data\"", 3), "a told unknown-command line is not ours");
|
||||
Check.False(v.ShouldEat("Unknown command: mule-data", 2), "unknown-command in speech is not ours");
|
||||
Check.False(v.ShouldEat("Unknown command: mule-data-ish"), "another command's refusal is not ours");
|
||||
Check.True(v.ShouldEat("Unknown command: mule-data", 15), "ACE's real reply (Help) is ours");
|
||||
}
|
||||
{
|
||||
(VaultFeed v, _) = NewVault();
|
||||
v.Ask(0);
|
||||
Check.True(v.ShouldEat(" " + VaultPage(1, 1, 1, A), 0), "the server's line (Broadcast), leading space allowed");
|
||||
}
|
||||
{
|
||||
(VaultFeed v, _) = NewVault();
|
||||
Check.True(v.ShouldEat(VaultPage(1, 1, 1, A)), "a line typed by hand while we are not asking is eaten");
|
||||
v.Tick(0, "tom");
|
||||
Check.Null(v.Record, "but ignored when we did not ask");
|
||||
}
|
||||
}
|
||||
|
||||
private static void Unsupported()
|
||||
{
|
||||
{
|
||||
(VaultFeed v, List<string> sent) = NewVault();
|
||||
v.Ask(0);
|
||||
Check.True(v.ShouldEat("Unknown command: /mule-data"), "the unknown-command reply is eaten while we wait");
|
||||
v.Tick(100, "tom");
|
||||
Check.Eq(v.Status, VaultFeed.State.Unsupported, "unsupported");
|
||||
Check.False(v.Ask(200), "not asked again");
|
||||
Check.Eq(sent.Count, 1, "one probe, no more");
|
||||
Check.True(v.Ask(300, force: true), "/rserver vault asks anyway");
|
||||
}
|
||||
{
|
||||
(VaultFeed v, _) = NewVault();
|
||||
Check.False(v.ShouldEat("Unknown command: /mule-data"), "an unknown-command line we did not provoke is left alone");
|
||||
}
|
||||
}
|
||||
|
||||
private static void Retries()
|
||||
{
|
||||
// A vault the server is still loading is asked again, and never recorded as empty.
|
||||
{
|
||||
(VaultFeed v, List<string> sent) = NewVault();
|
||||
v.Ask(0);
|
||||
v.ShouldEat(VaultPage(1, 1, 0, "", ready: false, why: "loading"));
|
||||
v.Tick(10, "tom");
|
||||
Check.Eq(v.Status, VaultFeed.State.Waiting, "waiting");
|
||||
v.Tick(2000, "tom");
|
||||
Check.Eq(sent.Count, 1, "not before the retry delay");
|
||||
v.Tick(3500, "tom");
|
||||
Check.Eq(sent.Count, 2, "asked again after it");
|
||||
Check.Null(v.Record, "never recorded");
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
v.ShouldEat(VaultPage(1, 1, 0, "", ready: false, why: "loading"));
|
||||
v.Tick(4000 + i * 4000, "tom");
|
||||
}
|
||||
Check.True(v.Status != VaultFeed.State.Asking || sent.Count < 12, "it gives up after a few tries");
|
||||
Check.Null(v.Record, "still never recorded");
|
||||
}
|
||||
// A vault that changed between pages is read again, not filed half and half.
|
||||
{
|
||||
(VaultFeed v, _) = NewVault();
|
||||
v.Ask(0);
|
||||
v.ShouldEat(VaultPage(1, 2, 3, A));
|
||||
v.Tick(10, "tom");
|
||||
v.ShouldEat(VaultPage(2, 2, 3, B)); // 2 read, the server says 3
|
||||
v.Tick(20, "tom");
|
||||
Check.Null(v.Record, "a mismatched read is not filed");
|
||||
Check.Eq(v.Status, VaultFeed.State.Waiting, "and is retried");
|
||||
}
|
||||
// Silence is an idle feed, not a stuck one.
|
||||
{
|
||||
(VaultFeed v, _) = NewVault();
|
||||
v.Ask(0);
|
||||
v.Tick(20_000, "tom");
|
||||
Check.Eq(v.Status, VaultFeed.State.Idle, "no answer in time");
|
||||
Check.True(v.Ask(21_000), "can ask again");
|
||||
}
|
||||
// Garbage inside a mule line does not throw.
|
||||
{
|
||||
(VaultFeed v, _) = NewVault();
|
||||
v.Ask(0);
|
||||
v.ShouldEat("~ael1 {\"t\":\"mule\",\"ready\":tru");
|
||||
v.Tick(5, "tom");
|
||||
Check.True(v.Record == null && v.Status == VaultFeed.State.Idle, "bad JSON drops the read");
|
||||
}
|
||||
}
|
||||
|
||||
private static void Schedule()
|
||||
{
|
||||
var sent = new List<string>();
|
||||
var f = new AelrynthFeature { SendCommand = t => { sent.Add(t); return true; } };
|
||||
f.Reset();
|
||||
long login = 50_000;
|
||||
Check.Null(f.VaultTick(login, "tom"), "nothing at login");
|
||||
Check.Eq(sent.Count, 0, "not asked at once");
|
||||
f.VaultTick(login + VaultFeed.FirstAskMs - 1, "tom");
|
||||
Check.Eq(sent.Count, 0, "not before the first delay");
|
||||
f.VaultTick(login + VaultFeed.FirstAskMs, "tom");
|
||||
Check.Eq(sent.Count == 1 ? sent[0] : "?", "/mule-data", "asked after the first delay");
|
||||
Check.True(f.OnChatLine(VaultPage(1, 1, 1, A), 0, login + VaultFeed.FirstAskMs + 10), "its reply is always hidden");
|
||||
StorageFeedRecord? read = f.VaultTick(login + VaultFeed.FirstAskMs + 20, "tom");
|
||||
Check.True(read != null && read.Items.Count == 1, "the finished read is handed back once");
|
||||
Check.Null(f.VaultTick(login + VaultFeed.FirstAskMs + 30, "tom"), "and only once");
|
||||
f.VaultTick(login + VaultFeed.FirstAskMs + VaultFeed.RefreshMs, "tom");
|
||||
Check.Eq(sent.Count, 2, "read again ten minutes later");
|
||||
f.OnChatLine(VaultPage(1, 1, 1, A), 0, login + VaultFeed.FirstAskMs + VaultFeed.RefreshMs + 1);
|
||||
f.VaultTick(login + VaultFeed.FirstAskMs + VaultFeed.RefreshMs + 2, "tom");
|
||||
Check.True(f.VaultAskNow(login + 700_000) && sent.Count == 3, "/rserver vault reads it now");
|
||||
|
||||
// A server without the command: one probe per login, then quiet.
|
||||
var g = new AelrynthFeature { SendCommand = t => { sent.Add(t); return true; } };
|
||||
g.Reset();
|
||||
int before = sent.Count;
|
||||
g.VaultTick(0, "tom");
|
||||
g.VaultTick(VaultFeed.FirstAskMs, "tom");
|
||||
g.OnChatLine("Unknown command: mule-data", 0, VaultFeed.FirstAskMs + 1);
|
||||
g.VaultTick(VaultFeed.FirstAskMs + 2, "tom");
|
||||
g.VaultTick(VaultFeed.FirstAskMs + 3 * VaultFeed.RefreshMs, "tom");
|
||||
Check.Eq(sent.Count - before, 1, "no vault on the server: asked once, then never on a timer");
|
||||
g.Reset();
|
||||
Check.Eq(g.Vault.Status, VaultFeed.State.Idle, "the next login asks again");
|
||||
}
|
||||
|
||||
private static void HandOff()
|
||||
{
|
||||
var items = new List<StorageFeedItem>
|
||||
{
|
||||
new(2147483649u, 100, "Acid \"Assagai\" \\ é", 100667000, 100667001, 100667002, 3, 100, 1),
|
||||
new(2147483650u, 101, "Pyreal", 100667003, 0, 0, 1, 0, 8192),
|
||||
};
|
||||
var rec = new StorageFeedRecord(VaultFeed.VaultId("tom"), VaultFeed.VaultName, VaultFeed.Label, items);
|
||||
string json = StorageFeed.ToJson(rec);
|
||||
bool ascii = true;
|
||||
foreach (char c in json) if (c > 0x7e || c < 0x20) ascii = false;
|
||||
Check.True(ascii, "plain ASCII (the broker carries ANSI)");
|
||||
StorageFeedRecord? back = StorageFeed.Parse(json, out string error);
|
||||
Check.Eq(error, "", "parsed");
|
||||
Check.True(back != null && back.Id == rec.Id && back.Name == rec.Name && back.Label == rec.Label && back.Items.Count == 2, "the record");
|
||||
Check.Eq(back!.Items[0], items[0], "an item, name escapes included");
|
||||
Check.Eq(back.Items[1], items[1], "another");
|
||||
Check.Eq(StorageFeed.TargetPlugin + "/" + StorageFeed.Action, "RynthInventory/storage", "sent to RynthInventory's \"storage\" command");
|
||||
}
|
||||
}
|
||||
297
Tools/RynthThreads.Tests/InferenceTests.cs
Normal file
297
Tools/RynthThreads.Tests/InferenceTests.cs
Normal file
|
|
@ -0,0 +1,297 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using RynthCore.Plugin.RynthThreads.Threads;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthThreads.Tests;
|
||||
|
||||
// The odds (Threads/PressInference.cs): rates, intervals and comparisons, on the first real presses
|
||||
// and on made-up ones.
|
||||
internal static class InferenceTests
|
||||
{
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("infer: the 4 real Lead Scarab presses (old JSON lines): rates, intervals, Affinity group", RealPresses);
|
||||
r.Add("infer: with/without a component; 'more likely' only when clear; 'always' only at 10+", WithWithout);
|
||||
r.Add("infer: Wilson intervals and the Fisher test", Statistics);
|
||||
r.Add("infer: exact combinations of components", Combinations);
|
||||
r.Add("infer: No components and All presses rows; incomplete presses left out", NoComponentsAndAll);
|
||||
r.Add("infer: Affinity grouping and the split by material", AffinityGroup);
|
||||
r.Add("infer: per-modifier view: overall, no components, each component (0% too)", ModifierView);
|
||||
r.Add("infer: values by level, tags, results and modifiers per press", ReportDetails);
|
||||
r.Add("infer: the sample press runs through the whole report", SampleReport);
|
||||
}
|
||||
|
||||
/// <summary>The first 4 presses from presses.jsonl (2026-10-12, all Lead Scarab), exactly as written.</summary>
|
||||
internal static readonly string[] RealLines =
|
||||
{
|
||||
"""{"v":1,"id":"ccbf1dd788704e08","time":"2026-10-12T23:44:32.8501639Z","server":"DreamWeave","character":"Drakkon","fragment":"Raw Fragment","fragmentLevel":185,"tool":"Fragment Press","outcome":"Pressed. It holds.","componentsSeen":true,"components":["Lead Scarab"],"random":"Remaining slots drawn at random.","modifiers":[{"name":"Radiant","description":"kills pay x1.84 luminance","numbers":[{"value":1.84,"kind":"mult","text":"x1.84"}]},{"name":"Amethyst Affinity","description":"10% of kills leave amethyst to salvage","numbers":[{"value":10,"kind":"pct","text":"10%"}]},{"name":"Precise","description":"monsters have \u002B27 critical strike rating, landing more critical hits","numbers":[{"value":27,"kind":"plus","text":"\u002B27"}]},{"name":"Guarded","description":"the boss has x1.91 health","numbers":[{"value":1.91,"kind":"mult","text":"x1.91"}]},{"name":"Savage","description":"monsters attack with \u002B35 damage rating, hitting harder","numbers":[{"value":35,"kind":"plus","text":"\u002B35"}]}],"resultLevel":175,"entries":3,"complete":true,"end":"done","raw":["Using the Raw Fragment (Level 185) with the Fragment Press","Pressed. It holds.","Components selected: Lead Scarab","Remaining slots drawn at random.","The gem carries:"," Radiant - kills pay x1.84 luminance"," Amethyst Affinity - 10% of kills leave amethyst to salvage"," Precise - monsters have \u002B27 critical strike rating, landing more critical hits"," Guarded - the boss has x1.91 health"," Savage - monsters attack with \u002B35 damage rating, hitting harder","Level 175, 3 entries."],"extra":[]}""",
|
||||
"""{"v":1,"id":"6613196a36424f8c","time":"2026-10-12T23:50:31.1229501Z","server":"DreamWeave","character":"Drakkon","fragment":"Raw Fragment","fragmentLevel":185,"tool":"Fragment Press","outcome":"Pressed. It holds.","componentsSeen":true,"components":["Lead Scarab"],"random":"Remaining slots drawn at random.","modifiers":[{"name":"Radiant","description":"kills pay x1.75 luminance","numbers":[{"value":1.75,"kind":"mult","text":"x1.75"}]},{"name":"Iron Affinity","description":"8% of kills leave iron to salvage","numbers":[{"value":8,"kind":"pct","text":"8%"}]},{"name":"Teeming","description":"67% more monsters","numbers":[{"value":67,"kind":"pct","text":"67%"}]},{"name":"Guarded","description":"the boss has x1.83 health","numbers":[{"value":1.83,"kind":"mult","text":"x1.83"}]},{"name":"Swift","description":"monsters move at x1.21 speed","numbers":[{"value":1.21,"kind":"mult","text":"x1.21"}]},{"name":"Shieldbreaker","description":"monsters ignore 54% of your shield","numbers":[{"value":54,"kind":"pct","text":"54%"}]}],"resultLevel":175,"entries":3,"complete":true,"end":"done","raw":["Using the Raw Fragment (Level 185) with the Fragment Press","Pressed. It holds.","Components selected: Lead Scarab","Remaining slots drawn at random.","The gem carries:"," Radiant - kills pay x1.75 luminance"," Iron Affinity - 8% of kills leave iron to salvage"," Teeming - 67% more monsters"," Guarded - the boss has x1.83 health"," Swift - monsters move at x1.21 speed"," Shieldbreaker - monsters ignore 54% of your shield","Level 175, 3 entries."],"extra":[]}""",
|
||||
"""{"v":1,"id":"1e960ea87fa64343","time":"2026-10-13T00:22:04.7703741Z","server":"DreamWeave","character":"Drakkon","fragment":"Raw Fragment","fragmentLevel":185,"tool":"Fragment Press","outcome":"Pressed. It holds.","componentsSeen":true,"components":["Lead Scarab"],"random":"Remaining slots drawn at random.","modifiers":[{"name":"Bounteous","description":"kills drop x1.51 loot","numbers":[{"value":1.51,"kind":"mult","text":"x1.51"}]},{"name":"Serpentine Affinity","description":"22% of kills leave serpentine to salvage","numbers":[{"value":22,"kind":"pct","text":"22%"}]},{"name":"Champions","description":"30% of the run\u0027s monsters are elites","numbers":[{"value":30,"kind":"pct","text":"30%"}]},{"name":"Guarded","description":"the boss has x2.18 health","numbers":[{"value":2.18,"kind":"mult","text":"x2.18"}]},{"name":"Enraged","description":"the boss attacks with \u002B54 damage rating, hitting harder","numbers":[{"value":54,"kind":"plus","text":"\u002B54"}]},{"name":"Precise","description":"monsters have \u002B19 critical strike rating, landing more critical hits","numbers":[{"value":19,"kind":"plus","text":"\u002B19"}]}],"resultLevel":175,"entries":3,"complete":true,"end":"done","raw":["Using the Raw Fragment (Level 185) with the Fragment Press","Pressed. It holds.","Components selected: Lead Scarab","Remaining slots drawn at random.","The gem carries:"," Bounteous - kills drop x1.51 loot"," Serpentine Affinity - 22% of kills leave serpentine to salvage"," Champions - 30% of the run\u0027s monsters are elites"," Guarded - the boss has x2.18 health"," Enraged - the boss attacks with \u002B54 damage rating, hitting harder"," Precise - monsters have \u002B19 critical strike rating, landing more critical hits","Level 175, 3 entries."],"extra":[]}""",
|
||||
"""{"v":1,"id":"f0bf2c2811904c52","time":"2026-10-13T00:34:08.9352276Z","server":"DreamWeave","character":"Drakkon","fragment":"Raw Fragment","fragmentLevel":185,"tool":"Fragment Press","outcome":"Pressed. It holds.","componentsSeen":true,"components":["Lead Scarab"],"random":"Remaining slots drawn at random.","modifiers":[{"name":"Enlightened","description":"kills pay x1.43 experience","numbers":[{"value":1.43,"kind":"mult","text":"x1.43"}]},{"name":"Obsidian Affinity","description":"7% of kills leave obsidian to salvage","numbers":[{"value":7,"kind":"pct","text":"7%"}]},{"name":"Shieldbreaker","description":"monsters ignore 51% of your shield","numbers":[{"value":51,"kind":"pct","text":"51%"}]},{"name":"Savage","description":"monsters attack with \u002B33 damage rating, hitting harder","numbers":[{"value":33,"kind":"plus","text":"\u002B33"}]},{"name":"Stalwart","description":"monsters have \u002B20 damage resist rating, taking less damage from you","numbers":[{"value":20,"kind":"plus","text":"\u002B20"}]}],"resultLevel":175,"entries":3,"complete":true,"end":"done","raw":["Using the Raw Fragment (Level 185) with the Fragment Press","Pressed. It holds.","Components selected: Lead Scarab","Remaining slots drawn at random.","The gem carries:"," Enlightened - kills pay x1.43 experience"," Obsidian Affinity - 7% of kills leave obsidian to salvage"," Shieldbreaker - monsters ignore 51% of your shield"," Savage - monsters attack with \u002B33 damage rating, hitting harder"," Stalwart - monsters have \u002B20 damage resist rating, taking less damage from you","Level 175, 3 entries."],"extra":["[BANK] Debited 1 Trade Notes (250,000) (250,000 pyreals) from your bank."]}""",
|
||||
};
|
||||
|
||||
internal static List<Press> Real() => RealLines.Select(l => PressStore.FromJson(l)!).ToList();
|
||||
|
||||
private static int _n;
|
||||
|
||||
/// <summary>A complete press with these components and modifiers ("Name" or "Name=x1.5 text").</summary>
|
||||
internal static Press P(string components, string modifiers, int level = 100, bool complete = true, int? result = null, int? entries = null)
|
||||
{
|
||||
var p = new Press
|
||||
{
|
||||
Id = "t" + (++_n),
|
||||
TimeUtc = new DateTime(2026, 10, 12, 19, 0, 0, DateTimeKind.Utc).AddSeconds(_n),
|
||||
Character = "Tester",
|
||||
Server = "DreamWeave",
|
||||
Fragment = "Raw Fragment",
|
||||
FragmentLevel = level,
|
||||
Outcome = "Pressed. It holds.",
|
||||
ComponentsSeen = true,
|
||||
Components = PressParser.SplitComponents(components),
|
||||
Complete = complete,
|
||||
End = complete ? "done" : "timeout",
|
||||
ResultLevel = result,
|
||||
Entries = entries,
|
||||
};
|
||||
foreach (string m in modifiers.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
|
||||
{
|
||||
string[] parts = m.Split('=', 2);
|
||||
string desc = parts.Length > 1 ? parts[1] : "something";
|
||||
p.Modifiers.Add(new GemModifier { Name = parts[0], Description = desc, Numbers = PressParser.Numbers(desc) });
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
private static List<Press> Many(int count, string components, string modifiers) =>
|
||||
Enumerable.Range(0, count).Select(_ => P(components, modifiers)).ToList();
|
||||
|
||||
private static Odds? Odd(GroupReport? g, string mod) => g?.Find(mod);
|
||||
|
||||
private static void RealPresses()
|
||||
{
|
||||
List<Press> presses = Real();
|
||||
Check.True(presses.All(p => p != null && p.Usable), "all 4 old lines load as complete presses");
|
||||
Check.Eq(string.Join(",", presses.Select(p => p.ComponentsText).Distinct()), "Lead Scarab", "all Lead Scarab");
|
||||
ThreadsReport r = PressInference.Build(presses);
|
||||
GroupReport? ls = r.Component("Lead Scarab");
|
||||
Check.NotNull(ls, "Lead Scarab row");
|
||||
if (ls == null) return;
|
||||
Check.Eq(ls.Presses, 4, "4 presses");
|
||||
|
||||
Odds g = Odd(ls, "Guarded")!;
|
||||
Check.Eq((g.Hits, g.N), (3, 4), "Guarded 3/4");
|
||||
Check.Eq(PressInference.OddsText(g), "75% (3/4, 30-95%)", "Guarded text");
|
||||
Check.Eq(g.Values, "x1.83 to x2.18", "Guarded values");
|
||||
Odds rad = Odd(ls, "Radiant")!;
|
||||
Check.Eq(PressInference.OddsText(rad), "50% (2/4, 15-85%)", "Radiant 2/4");
|
||||
Check.Eq(PressInference.OddsText(Odd(ls, "Champions")!), "25% (1/4, 5-70%)", "Champions 1/4");
|
||||
|
||||
Odds aff = Odd(ls, PressInference.AffinityGroup)!;
|
||||
Check.Eq((aff.Hits, aff.N), (4, 4), "Affinity group 4/4");
|
||||
Check.Eq(PressInference.OddsText(aff), "100% (4/4, 51-100%)", "Affinity text");
|
||||
Check.Eq(PressInference.SplitText(aff), "Amethyst 1, Iron 1, Obsidian 1, Serpentine 1", "split 1 each");
|
||||
Check.Eq(aff.Values, "7% to 22%", "affinity values across materials");
|
||||
Check.Null(Odd(ls, "Amethyst Affinity"), "materials are not rows of their own");
|
||||
Check.Eq(ls.Odds[0].Modifier, PressInference.AffinityGroup, "sorted by rate: Affinity first");
|
||||
Check.Eq(ls.Odds[1].Modifier, "Guarded", "then Guarded");
|
||||
|
||||
Check.Eq(PressInference.OtherText(g, ls.OtherLabel), "without: no data", "nothing without Lead Scarab");
|
||||
Check.False(ls.Odds.Any(o => o.MoreLikely), "no 'more likely' with nothing to compare");
|
||||
Check.Eq(r.All?.Presses, 4, "All presses row");
|
||||
Check.Eq(r.Combinations.Count, 0, "no combinations");
|
||||
Check.Null(r.NoComponents, "no No components row");
|
||||
Check.Eq(PressInference.ModifiersText(ls), "5.5 modifiers per press (5-6)", "modifiers per press");
|
||||
Check.Eq(PressInference.ResultsText(ls), "L185 -> 175, 3 entries: 4", "results");
|
||||
Check.Eq(r.Modifier("Affinity")?.Overall.Hits, 4, "modifier view: Affinity 4/4");
|
||||
Check.Null(r.Modifier("Iron Affinity"), "no Iron Affinity modifier entry");
|
||||
Check.Eq(r.Modifiers.Count, 13, "13 modifiers (affinities as one)");
|
||||
}
|
||||
|
||||
private static void WithWithout()
|
||||
{
|
||||
var presses = Many(5, "Red Taper", "Bounteous, Hardy");
|
||||
presses.Add(P("Red Taper", "Teeming, Hardy"));
|
||||
presses.AddRange(Many(3, "", "Hardy, Teeming"));
|
||||
presses.AddRange(Many(3, "", "Savage, Teeming"));
|
||||
ThreadsReport r = PressInference.Build(presses);
|
||||
GroupReport red = r.Component("Red Taper")!;
|
||||
Odds b = Odd(red, "Bounteous")!;
|
||||
Check.Eq((b.Hits, b.N, b.OtherHits, b.OtherN), (5, 6, 0, 6), "Bounteous 5/6 with, 0/6 without");
|
||||
Check.True(b.MoreLikely, "Bounteous more likely with Red Taper");
|
||||
Check.Eq(PressInference.LikelyText(b, red), "more likely with Red Taper", "wording");
|
||||
Check.Eq(PressInference.OtherText(b, red.OtherLabel), "without: 0% (0/6)", "without text");
|
||||
Odds h = Odd(red, "Hardy")!;
|
||||
Check.Eq((h.Hits, h.OtherHits), (6, 3), "Hardy 6/6 with, 3/6 without");
|
||||
Check.False(h.MoreLikely, "Hardy 6/6 vs 3/6: not clear (p ~ 0.09)");
|
||||
Check.Eq(red.Odds[0].Modifier, "Hardy", "sorted by rate: Hardy (100%) first");
|
||||
|
||||
// Few presses: nothing claimed.
|
||||
r = PressInference.Build(Many(2, "Blue Taper", "Bounteous").Concat(Many(2, "", "Hardy")).ToList());
|
||||
Check.False(Odd(r.Component("Blue Taper"), "Bounteous")!.MoreLikely, "2/2 vs 0/2: not claimed");
|
||||
|
||||
// 'always' only at 100% over 10 or more.
|
||||
r = PressInference.Build(Many(9, "Green Taper", "Teeming").Concat(Many(9, "", "Hardy")).ToList());
|
||||
GroupReport green = r.Component("Green Taper")!;
|
||||
Check.Eq(PressInference.LikelyText(Odd(green, "Teeming")!, green), "more likely with Green Taper", "9/9: more likely, not always");
|
||||
r = PressInference.Build(Many(10, "Green Taper", "Teeming").Concat(Many(10, "", "Hardy")).ToList());
|
||||
green = r.Component("Green Taper")!;
|
||||
Check.Eq(PressInference.LikelyText(Odd(green, "Teeming")!, green), "always with Green Taper so far", "10/10: always so far");
|
||||
|
||||
// The No components row is compared with presses that had components.
|
||||
r = PressInference.Build(Many(6, "Red Taper", "Hardy").Concat(Many(6, "", "Teeming")).ToList());
|
||||
Odds t = Odd(r.NoComponents, "Teeming")!;
|
||||
Check.True(t.MoreLikely, "Teeming 6/6 plain vs 0/6 with components");
|
||||
Check.Eq(PressInference.LikelyText(t, r.NoComponents!), "more likely with no components", "no-components wording");
|
||||
}
|
||||
|
||||
private static void Statistics()
|
||||
{
|
||||
var (lo, hi) = PressInference.Wilson(3, 4);
|
||||
Check.True(Math.Abs(lo - 0.3006) < 0.001 && Math.Abs(hi - 0.9544) < 0.001, $"3/4: 30.1-95.4% ({lo:0.0000}-{hi:0.0000})");
|
||||
(lo, hi) = PressInference.Wilson(0, 5);
|
||||
Check.True(lo == 0 && Math.Abs(hi - 0.4345) < 0.001, $"0/5: 0-43% ({hi:0.0000})");
|
||||
(lo, hi) = PressInference.Wilson(0, 0);
|
||||
Check.True(lo == 0 && hi == 1, "0/0: anything");
|
||||
Check.True(Math.Abs(PressInference.FisherGreater(3, 3, 0, 3) - 0.05) < 1e-9, "3/3 vs 0/3: p = 1/20");
|
||||
Check.True(Math.Abs(PressInference.FisherGreater(5, 6, 0, 6) - 7.0 / 924) < 1e-9, "5/6 vs 0/6: p = 7/924");
|
||||
Check.True(Math.Abs(PressInference.FisherGreater(0, 4, 4, 4) - 1) < 1e-9, "0 hits: p = 1");
|
||||
Check.Eq(PressInference.OddsText(new Odds { Hits = 30, N = 60 }), "50% (30/60)", "no interval from 50 presses");
|
||||
Check.Eq(PressInference.OddsText(new Odds { Hits = 0, N = 0 }), "no data", "empty");
|
||||
}
|
||||
|
||||
private static void Combinations()
|
||||
{
|
||||
var presses = Many(3, "Red Taper, Blue Taper", "Bounteous, Savage");
|
||||
presses.AddRange(Many(2, "Red Taper", "Bounteous, Hardy"));
|
||||
presses.Add(P("Blue Taper", "Savage, Hardy"));
|
||||
presses.AddRange(Many(2, "", "Hardy, Teeming"));
|
||||
ThreadsReport r = PressInference.Build(presses);
|
||||
Check.Eq(r.Combinations.Count, 1, "one combination");
|
||||
GroupReport? combo = r.Combination("Blue Taper + Red Taper");
|
||||
Check.NotNull(combo, "named by its sorted components");
|
||||
if (combo == null) return;
|
||||
Check.Eq(combo.Presses, 3, "3 presses with exactly both");
|
||||
Check.Eq(combo.Members.Count, 2, "two members");
|
||||
Check.Eq(r.Component("Red Taper")!.Presses, 5, "component row counts every press with it");
|
||||
Check.Eq(r.Component("Blue Taper")!.Presses, 4, "Blue Taper 4");
|
||||
Odds s = Odd(combo, "Savage")!;
|
||||
Check.Eq((s.Hits, s.N, s.OtherHits, s.OtherN), (3, 3, 1, 5), "Savage 3/3 in the combination, 1/5 in other presses");
|
||||
Check.Eq(PressInference.OtherText(s, combo.OtherLabel), "other presses: 20% (1/5)", "comparison label");
|
||||
Check.Eq(PressInference.Build(Many(2, "Blue Taper, Red Taper", "Hardy").Concat(Many(1, "Red Taper, Blue Taper", "Hardy")).ToList())
|
||||
.Combination("Blue Taper + Red Taper")?.Presses, 3, "order of components doesn't matter");
|
||||
}
|
||||
|
||||
private static void NoComponentsAndAll()
|
||||
{
|
||||
var presses = Many(4, "Red Taper", "Bounteous, Hardy");
|
||||
presses.AddRange(Many(2, "", "Hardy, Teeming"));
|
||||
presses.Add(P("", "Teeming"));
|
||||
presses.Add(P("Red Taper", "Savage", complete: false));
|
||||
presses.Add(P("", "")); // finished but no gem block: not usable
|
||||
ThreadsReport r = PressInference.Build(presses);
|
||||
Check.Eq((r.Total, r.Usable, r.Incomplete), (9, 7, 1), "totals");
|
||||
Check.Eq(r.Component("Red Taper")!.Presses, 4, "incomplete press left out");
|
||||
|
||||
GroupReport? nc = r.NoComponents;
|
||||
Check.NotNull(nc, "No components row");
|
||||
if (nc == null) return;
|
||||
Check.Eq((nc.Presses, nc.Kind), (3, GroupKind.NoComponents), "3 plain presses");
|
||||
Odds t = Odd(nc, "Teeming")!;
|
||||
Check.Eq((t.Hits, t.N, t.OtherHits, t.OtherN), (3, 3, 0, 4), "Teeming 3/3 plain, 0/4 with components");
|
||||
Check.Eq(PressInference.OtherText(t, nc.OtherLabel), "with components: 0% (0/4)", "comparison label");
|
||||
Check.Eq(nc.Odds[0].Modifier, "Teeming", "most common plain draw first");
|
||||
|
||||
GroupReport all = r.All!;
|
||||
Check.Eq((all.Presses, all.Kind), (7, GroupKind.All), "All presses: every usable press");
|
||||
Odds h = Odd(all, "Hardy")!;
|
||||
Check.Eq((h.Hits, h.N), (6, 7), "Hardy 6/7 overall");
|
||||
Check.False(h.Compared, "the baseline isn't compared");
|
||||
Check.Eq(PressInference.OtherText(h, all.OtherLabel), "", "no comparison text");
|
||||
Check.False(all.Odds.Any(o => o.MoreLikely), "never flagged");
|
||||
}
|
||||
|
||||
private static void AffinityGroup()
|
||||
{
|
||||
Check.Eq(PressInference.Material("Green Garnet Affinity"), "Green Garnet", "two-word material");
|
||||
Check.Eq(PressInference.Key("Tourmaline Affinity"), PressInference.AffinityGroup, "grouped");
|
||||
Check.Null(PressInference.Material("Affinity"), "bare 'Affinity' is not a material");
|
||||
Check.Eq(PressInference.Key("Guarded"), "Guarded", "others keep their name");
|
||||
Check.Eq(PressInference.Display(PressInference.AffinityGroup), "Affinity (any)", "display name");
|
||||
|
||||
var presses = new List<Press>
|
||||
{
|
||||
P("Red Taper", "Iron Affinity=8% of kills leave iron to salvage, Hardy"),
|
||||
P("Red Taper", "Iron Affinity=10% of kills leave iron to salvage, Teeming"),
|
||||
P("Red Taper", "Amethyst Affinity=12% of kills leave amethyst to salvage, Gold Affinity=5% of kills leave gold to salvage"),
|
||||
P("", "Hardy"),
|
||||
};
|
||||
ThreadsReport r = PressInference.Build(presses);
|
||||
Odds a = Odd(r.Component("Red Taper"), PressInference.AffinityGroup)!;
|
||||
Check.Eq((a.Hits, a.N, a.OtherHits, a.OtherN), (3, 3, 0, 1), "a press with two affinities counts once");
|
||||
Check.Eq(PressInference.SplitText(a), "Iron 2, Amethyst 1, Gold 1", "split counts both, most first");
|
||||
ModifierReport m = r.Modifier("Affinity")!;
|
||||
Check.True(m.IsGroup, "modifier view: the group");
|
||||
Check.Eq(m.Tag, "reward", "salvage: reward");
|
||||
Check.Eq(m.Values, "8% to 12%", "values over every material (first affinity per press)");
|
||||
}
|
||||
|
||||
private static void ModifierView()
|
||||
{
|
||||
var presses = Many(3, "Red Taper", "Bounteous, Hardy");
|
||||
presses.AddRange(Many(2, "Blue Taper", "Hardy"));
|
||||
presses.Add(P("Blue Taper, Red Taper", "Bounteous"));
|
||||
presses.AddRange(Many(2, "", "Teeming, Bounteous"));
|
||||
ThreadsReport r = PressInference.Build(presses);
|
||||
ModifierReport b = r.Modifier("Bounteous")!;
|
||||
Check.Eq((b.Overall.Hits, b.Overall.N), (6, 8), "overall 6/8");
|
||||
Check.Eq((b.NoComponents?.Hits, b.NoComponents?.N, b.NoComponents?.OtherHits, b.NoComponents?.OtherN), ((int?)2, (int?)2, (int?)4, (int?)6), "no components 2/2 vs 4/6");
|
||||
Check.Eq(string.Join(", ", b.ByGroup.Select(x => $"{x.Group.Name} {x.Odds.Hits}/{x.Odds.N}")),
|
||||
"Red Taper 4/4, Blue Taper + Red Taper 1/1, Blue Taper 1/3", "each component and combination, likeliest first");
|
||||
Odds teemingBlue = r.Modifier("Teeming")!.ByGroup.First(x => x.Group.Name == "Blue Taper").Odds;
|
||||
Check.Eq((teemingBlue.Hits, teemingBlue.N, teemingBlue.OtherHits, teemingBlue.OtherN), (0, 3, 2, 5), "0% rows are kept, with their comparison");
|
||||
}
|
||||
|
||||
private static void ReportDetails()
|
||||
{
|
||||
var presses = new List<Press>
|
||||
{
|
||||
P("Red Taper", "Bounteous=kills drop x1.38 loot, Hardy=monsters have x1.5 health", level: 185, result: 175, entries: 3),
|
||||
P("Red Taper", "Bounteous=kills drop x1.52 loot", level: 185, result: 175, entries: 3),
|
||||
P("Red Taper", "Bounteous=kills drop x1.20 loot", level: 120, result: 110, entries: 2),
|
||||
P("Red Taper", "Hardy=monsters have x2 health", complete: false),
|
||||
P("", "Hardy=monsters have x1.81 health, Teeming=75% more monsters", level: 120),
|
||||
P("", "Teeming=60% more monsters", level: 120),
|
||||
};
|
||||
ThreadsReport r = PressInference.Build(presses);
|
||||
GroupReport red = r.Component("Red Taper")!;
|
||||
Check.Eq(PressInference.ResultsText(red), "L185 -> 175, 3 entries: 2; L120 -> 110, 2 entries: 1", "results, most common first");
|
||||
Check.Eq(PressInference.ModifiersText(red), "1.33 modifiers per press (1-2)", "modifiers per press");
|
||||
Check.Eq(Odd(red, "Bounteous")!.Values, "x1.2 to x1.52", "values with the component");
|
||||
|
||||
ModifierReport b = r.Modifier("Bounteous")!;
|
||||
Check.Eq(b.Values, "x1.2 to x1.52", "value range");
|
||||
Check.Eq(b.ByLevel.Count, 2, "two fragment levels");
|
||||
Check.Eq(b.ByLevel[0].Level, 120, "lowest level first");
|
||||
Check.Eq(b.ByLevel[1].Values, "x1.38 to x1.52", "level 185 range");
|
||||
Check.Eq(b.Tag, "reward", "loot is a reward");
|
||||
Check.Eq(r.Modifier("Hardy")!.Tag, "harder", "monster health is harder");
|
||||
Check.Eq(PressInference.Tag("something odd"), "", "no tag when the text doesn't say");
|
||||
|
||||
ThreadsReport empty = PressInference.Build(new List<Press>());
|
||||
Check.True(empty.Usable == 0 && empty.All == null && empty.Modifiers.Count == 0, "empty input");
|
||||
}
|
||||
|
||||
private static void SampleReport()
|
||||
{
|
||||
Press p = new PressParser().Feed(string.Join("\n", ParserTests.Sample), 1)![0];
|
||||
ThreadsReport r = PressInference.Build(new[] { p });
|
||||
Check.Eq(r.Component("Red Taper")?.Presses, 1, "Red Taper counted");
|
||||
Check.Eq(r.Modifiers.Count, 6, "six modifiers in the report");
|
||||
Check.Eq(r.Modifier("Affinity")?.Tag, "reward", "salvage is a reward");
|
||||
Check.Eq(PressInference.SplitText(r.Modifier("Affinity")!.Overall), "Tourmaline 1", "Tourmaline");
|
||||
Check.Eq(r.Modifier("Enraged")?.Tag, "harder", "boss damage is harder");
|
||||
Check.Eq(PressInference.OddsText(r.Component("Red Taper")!.Find("Hardy")!), "100% (1/1, 21-100%)", "one press: wide range");
|
||||
}
|
||||
}
|
||||
258
Tools/RynthThreads.Tests/ParserTests.cs
Normal file
258
Tools/RynthThreads.Tests/ParserTests.cs
Normal file
|
|
@ -0,0 +1,258 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using RynthCore.Plugin.RynthThreads.Threads;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthThreads.Tests;
|
||||
|
||||
// The chat parser (Threads/PressParser.cs). The sample is real DreamWeave chat from 2026-10-12
|
||||
// (timestamps removed: the plugin sees the text without them), with another player's line in it.
|
||||
internal static class ParserTests
|
||||
{
|
||||
public static readonly string[] Sample =
|
||||
{
|
||||
"Using the Raw Fragment (Level 185) with the Fragment Press",
|
||||
"Yorick is recalling to the marketplace.",
|
||||
"Pressed. It holds.",
|
||||
"Components selected: Red Taper",
|
||||
"Remaining slots drawn at random.",
|
||||
"The gem carries:",
|
||||
" Bounteous - kills drop x1.38 loot",
|
||||
" Tourmaline Affinity - 12% of kills leave tourmaline to salvage",
|
||||
" Hardy - monsters have x1.81 health",
|
||||
" Enraged - the boss attacks with +29 damage rating, hitting harder",
|
||||
" Teeming - 75% more monsters",
|
||||
" Savage - monsters attack with +20 damage rating, hitting harder",
|
||||
"Level 190, 4 entries.",
|
||||
};
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("parse: the real sample, line by line, with another player's line in it", SampleLineByLine);
|
||||
r.Add("parse: the sample as one message with newlines", SampleOneMessage);
|
||||
r.Add("parse: several components (commas, 'and'), sorted", SeveralComponents);
|
||||
r.Add("parse: no components (no line, 'none', 'No components ...')", NoComponents);
|
||||
r.Add("parse: incomplete presses (timeout, next press, other Using line, logout)", Incomplete);
|
||||
r.Add("parse: unknown and odd lines never throw and never become modifiers", UnknownLines);
|
||||
r.Add("parse: numbers and their forms", NumberForms);
|
||||
}
|
||||
|
||||
private static List<Press> FeedAll(PressParser parser, IEnumerable<string> lines, long now = 1000)
|
||||
{
|
||||
var done = new List<Press>();
|
||||
foreach (string line in lines)
|
||||
if (parser.Feed(line, now) is { } d) done.AddRange(d);
|
||||
return done;
|
||||
}
|
||||
|
||||
private static void SampleLineByLine()
|
||||
{
|
||||
var parser = new PressParser();
|
||||
List<Press> done = FeedAll(parser, Sample);
|
||||
Check.Eq(done.Count, 1, "one press");
|
||||
if (done.Count != 1) return;
|
||||
CheckSample(done[0]);
|
||||
Check.False(parser.Busy, "parser idle after the Level line");
|
||||
}
|
||||
|
||||
private static void SampleOneMessage()
|
||||
{
|
||||
var parser = new PressParser();
|
||||
List<Press>? done = parser.Feed(string.Join("\n", Sample) + "\n", 1000);
|
||||
Check.Eq(done?.Count ?? 0, 1, "one press from one message");
|
||||
if (done is { Count: 1 }) CheckSample(done[0]);
|
||||
// CRLF too.
|
||||
done = new PressParser().Feed(string.Join("\r\n", Sample), 1000);
|
||||
Check.Eq(done?[0].Modifiers.Count ?? -1, 6, "CRLF lines: 6 modifiers");
|
||||
}
|
||||
|
||||
internal static void CheckSample(Press p)
|
||||
{
|
||||
Check.Eq(p.Fragment, "Raw Fragment", "fragment name");
|
||||
Check.Eq(p.FragmentLevel, 185, "fragment level");
|
||||
Check.Eq(p.Tool, "Fragment Press", "tool");
|
||||
Check.Eq(p.Outcome, "Pressed. It holds.", "outcome");
|
||||
Check.True(p.Held, "held");
|
||||
Check.True(p.ComponentsSeen, "components line seen");
|
||||
Check.Eq(string.Join("|", p.Components), "Red Taper", "components");
|
||||
Check.Eq(p.RandomNote, "Remaining slots drawn at random.", "random note");
|
||||
Check.Eq(p.ResultLevel, 190, "result level");
|
||||
Check.Eq(p.Entries, 4, "entries (raw, not the modifier count)");
|
||||
Check.True(p.Complete, "complete");
|
||||
Check.Eq(p.End, "done", "end reason");
|
||||
Check.Eq(p.Modifiers.Count, 6, "six modifiers");
|
||||
Check.Eq(p.Raw.Count, 12, "12 own raw lines");
|
||||
Check.Eq(string.Join("|", p.Extra), "Yorick is recalling to the marketplace.", "the foreign line is kept apart");
|
||||
Check.False(p.Raw.Any(l => l.Contains("Yorick")), "no foreign line in Raw");
|
||||
Check.Eq(p.Raw[5], " Bounteous - kills drop x1.38 loot", "raw lines kept as is (indent too)");
|
||||
if (p.Modifiers.Count != 6) return;
|
||||
|
||||
(string Name, string Kinds, string Values, string Desc)[] want =
|
||||
{
|
||||
("Bounteous", "mult", "1.38", "kills drop x1.38 loot"),
|
||||
("Tourmaline Affinity", "pct", "12", "12% of kills leave tourmaline to salvage"),
|
||||
("Hardy", "mult", "1.81", "monsters have x1.81 health"),
|
||||
("Enraged", "plus", "29", "the boss attacks with +29 damage rating, hitting harder"),
|
||||
("Teeming", "pct", "75", "75% more monsters"),
|
||||
("Savage", "plus", "20", "monsters attack with +20 damage rating, hitting harder"),
|
||||
};
|
||||
for (int i = 0; i < want.Length; i++)
|
||||
{
|
||||
GemModifier m = p.Modifiers[i];
|
||||
Check.Eq(m.Name, want[i].Name, $"modifier {i} name");
|
||||
Check.Eq(m.Description, want[i].Desc, $"{want[i].Name} description");
|
||||
Check.Eq(string.Join(",", m.Numbers.Select(n => n.Kind)), want[i].Kinds, $"{want[i].Name} number kinds");
|
||||
Check.Eq(string.Join(",", m.Numbers.Select(n => n.Value.ToString(System.Globalization.CultureInfo.InvariantCulture))), want[i].Values, $"{want[i].Name} values");
|
||||
}
|
||||
Check.Eq(p.Modifiers[0].Numbers[0].Text, "x1.38", "text as written");
|
||||
Check.Eq(p.Modifiers[3].Numbers[0].Text, "+29", "rating text");
|
||||
}
|
||||
|
||||
private static string[] Press(string components, params string[] mods)
|
||||
{
|
||||
var lines = new List<string> { "Using the Raw Fragment (Level 100) with the Fragment Press", "Pressed. It holds." };
|
||||
if (components != null) lines.Add(components);
|
||||
lines.Add("Remaining slots drawn at random.");
|
||||
lines.Add("The gem carries:");
|
||||
lines.AddRange(mods.Select(m => " " + m));
|
||||
lines.Add("Level 104, 2 entries.");
|
||||
return lines.ToArray();
|
||||
}
|
||||
|
||||
private static void SeveralComponents()
|
||||
{
|
||||
Press p = FeedAll(new PressParser(), Press("Components selected: Red Taper, Blue Taper, Pyreal", "Hardy - monsters have x1.5 health")).Single();
|
||||
Check.Eq(string.Join("|", p.Components), "Blue Taper|Pyreal|Red Taper", "three, sorted");
|
||||
p = FeedAll(new PressParser(), Press("Components selected: Red Taper and Yellow Taper.", "Hardy - x")).Single();
|
||||
Check.Eq(string.Join("|", p.Components), "Red Taper|Yellow Taper", "'and' splits, trailing dot dropped");
|
||||
p = FeedAll(new PressParser(), Press("Components selected: Red Taper, red taper", "Hardy - x")).Single();
|
||||
Check.Eq(p.Components.Count, 1, "the same component twice counts once");
|
||||
}
|
||||
|
||||
private static void NoComponents()
|
||||
{
|
||||
Press p = FeedAll(new PressParser(), Press(null!, "Teeming - 75% more monsters")).Single();
|
||||
Check.False(p.ComponentsSeen, "no line: not seen");
|
||||
Check.Eq(p.Components.Count, 0, "no line: none");
|
||||
Check.True(p.Complete && p.Usable, "still complete and usable");
|
||||
|
||||
p = FeedAll(new PressParser(), Press("Components selected: none", "Teeming - 75% more monsters")).Single();
|
||||
Check.True(p.ComponentsSeen && p.Components.Count == 0, "'none'");
|
||||
p = FeedAll(new PressParser(), Press("No components selected.", "Teeming - 75% more monsters")).Single();
|
||||
Check.True(p.ComponentsSeen && p.Components.Count == 0, "'No components selected.'");
|
||||
Check.Eq(p.ComponentsText, "no components", "shown as 'no components'");
|
||||
}
|
||||
|
||||
private static void Incomplete()
|
||||
{
|
||||
// Timeout: the Level line never comes.
|
||||
var parser = new PressParser();
|
||||
string[] lines = Sample.Take(Sample.Length - 1).ToArray();
|
||||
Check.Eq(FeedAll(parser, lines, 1000).Count, 0, "nothing finished yet");
|
||||
Check.Null(parser.Tick(1000 + PressParser.TimeoutMs - 1), "not before the timeout");
|
||||
// Other chat doesn't keep it open.
|
||||
parser.Feed("Someone says, \"hello\"", 1000 + PressParser.TimeoutMs - 1);
|
||||
Press? t = parser.Tick(1000 + PressParser.TimeoutMs);
|
||||
Check.NotNull(t, "timed out");
|
||||
if (t != null)
|
||||
{
|
||||
Check.False(t.Complete, "incomplete");
|
||||
Check.Eq(t.End, "timeout", "reason");
|
||||
Check.Eq(t.Modifiers.Count, 6, "what was gathered is kept");
|
||||
Check.Null(t.ResultLevel, "no result level");
|
||||
Check.False(t.Usable, "not used by the inference");
|
||||
}
|
||||
|
||||
// The next press starts before this one's Level line.
|
||||
parser = new PressParser();
|
||||
var done = FeedAll(parser, Sample.Take(4).Concat(Sample));
|
||||
Check.Eq(done.Count, 2, "two presses");
|
||||
if (done.Count == 2)
|
||||
{
|
||||
Check.True(!done[0].Complete && done[0].End == "next use", "first: incomplete, next use");
|
||||
Check.Eq(done[0].Outcome, "Pressed. It holds.", "first kept its outcome");
|
||||
Check.True(done[1].Complete && done[1].Modifiers.Count == 6, "second complete");
|
||||
}
|
||||
|
||||
// Some other "Using ..." line ends it and starts nothing.
|
||||
parser = new PressParser();
|
||||
done = FeedAll(parser, Sample.Take(3).Append("Using the Mana Stone on the Robe of Ages"));
|
||||
Check.Eq(done.Count, 1, "ended by another Using line");
|
||||
Check.False(parser.Busy, "no new press from an unrelated Using line");
|
||||
Check.Eq(done.Count == 1 ? done[0].End : "", "next use", "reason");
|
||||
|
||||
// Logout.
|
||||
parser = new PressParser();
|
||||
FeedAll(parser, Sample.Take(2));
|
||||
Press? f = parser.Flush("logout");
|
||||
Check.True(f != null && f.End == "logout" && !f.Complete, "flush at logout");
|
||||
Check.Null(parser.Flush("logout"), "nothing left to flush");
|
||||
}
|
||||
|
||||
private static void UnknownLines()
|
||||
{
|
||||
var parser = new PressParser();
|
||||
string[] junk =
|
||||
{
|
||||
"", " ", "\n\n", "Level 190, 4 entries.", "Pressed. It holds.", " Hardy - monsters have x1.81 health",
|
||||
new string('x', 5000), "Components selected:", "The gem carries:", "☃ éè ???", "Using", "Using the",
|
||||
"with the Fragment Press", "1234567890123456789012345678901234567890", " - just a dash", "x%+",
|
||||
};
|
||||
int finished = 0;
|
||||
foreach (string j in junk)
|
||||
finished += parser.Feed(j, 1000)?.Count ?? 0;
|
||||
Check.Eq(finished, 0, "nothing comes out of junk while idle");
|
||||
Check.False(parser.Busy, "still idle");
|
||||
Check.Null(parser.Feed(null, 1000), "null text");
|
||||
|
||||
// Inside a press: junk goes to Extra, chat-like dash lines don't become modifiers, a failed outcome is kept.
|
||||
var lines = new List<string>
|
||||
{
|
||||
"Using the Woven Shard (Level 12) with the Fragment Press",
|
||||
"Pressed. It cracks.",
|
||||
"The gem carries:",
|
||||
"Bob says, \"Hardy - is that good?\"",
|
||||
"[Trade] Alice - selling tapers",
|
||||
"☃☃☃",
|
||||
" Strange Sigil - something we've never seen, 3 times",
|
||||
" not a modifier line",
|
||||
new string('y', 2000),
|
||||
"Level 12, 1 entry.",
|
||||
};
|
||||
List<Press> done = FeedAll(parser, lines);
|
||||
Check.Eq(done.Count, 1, "one press");
|
||||
if (done.Count != 1) return;
|
||||
Press p = done[0];
|
||||
Check.Eq(p.Fragment, "Woven Shard", "other fragment name");
|
||||
Check.Eq(p.FragmentLevel, 12, "its level");
|
||||
Check.Eq(p.Outcome, "Pressed. It cracks.", "a failed outcome is kept as said");
|
||||
Check.False(p.Held, "not held");
|
||||
Check.Eq(p.Modifiers.Count, 1, "only the real modifier line");
|
||||
Check.Eq(p.Modifiers.Count == 1 ? p.Modifiers[0].Name : "", "Strange Sigil", "unknown modifier name kept");
|
||||
Check.Eq(p.Entries, 1, "'1 entry' singular");
|
||||
Check.True(p.Extra.Count >= 4, "unfitting lines kept in Extra");
|
||||
Check.True(p.Extra.All(l => l.Length <= 400), "long lines cut");
|
||||
|
||||
// A fragment without a level, and a press that isn't the Fragment Press.
|
||||
done = FeedAll(new PressParser(), new[] { "Using the Odd Shard with the Fragment Press", "Level 3, 0 entries." });
|
||||
Check.True(done.Count == 1 && done[0].FragmentLevel == null && done[0].Fragment == "Odd Shard", "no level in the name");
|
||||
Check.True(done.Count == 1 && done[0].Complete && !done[0].Usable, "complete, but no modifiers: not usable");
|
||||
done = FeedAll(new PressParser(), new[] { "Using the Pyreal Ingot with the Forge", "Level 3, 0 entries." });
|
||||
Check.Eq(done.Count, 0, "not a Press: ignored");
|
||||
}
|
||||
|
||||
private static void NumberForms()
|
||||
{
|
||||
string Forms(string s) => string.Join(" ", PressParser.Numbers(s).Select(n => n.Kind + ":" + n.Value.ToString(System.Globalization.CultureInfo.InvariantCulture)));
|
||||
Check.Eq(Forms("kills drop x1.38 loot"), "mult:1.38", "multiplier");
|
||||
Check.Eq(Forms("12% of kills"), "pct:12", "percent");
|
||||
Check.Eq(Forms("+29 damage rating"), "plus:29", "rating");
|
||||
Check.Eq(Forms("attacks with +29."), "plus:29", "rating before a full stop");
|
||||
Check.Eq(Forms("-5 damage rating"), "plus:-5", "negative rating");
|
||||
Check.Eq(Forms("+12% more"), "pct:12", "signed percent is a percent");
|
||||
Check.Eq(Forms("spawns 3 bosses in 10.5 seconds"), "num:3 num:10.5", "plain numbers");
|
||||
Check.Eq(Forms("max5 and box2"), "", "digits glued to words aren't numbers");
|
||||
Check.Eq(Forms("no numbers here"), "", "none");
|
||||
}
|
||||
}
|
||||
51
Tools/RynthThreads.Tests/Program.cs
Normal file
51
Tools/RynthThreads.Tests/Program.cs
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
// The engine parser's only outside dependency: the registry's limits (the engine's values).
|
||||
namespace RynthCore.Engine.UI.ScriptWindows
|
||||
{
|
||||
internal static class ScriptWindowRegistry
|
||||
{
|
||||
public const int MaxOpsPerWindow = 1500;
|
||||
public const int MaxBytesPerWindow = 64 * 1024;
|
||||
public const int MaxWindowsPerOwner = 32;
|
||||
public const int MaxBytesPerSubmit = 256 * 1024;
|
||||
}
|
||||
}
|
||||
|
||||
namespace RynthThreads.Tests
|
||||
{
|
||||
// Offline tests for RynthThreads. Each test prints PASS / FAIL.
|
||||
//
|
||||
// Run: dotnet run -c Release (all tests)
|
||||
// dotnet run -c Release -- infer (tests whose name contains "infer")
|
||||
internal static class Program
|
||||
{
|
||||
/// <summary>Scratch folder next to the exe for files tests write. Emptied at start.</summary>
|
||||
public static string TempRoot { get; } = Path.Combine(AppContext.BaseDirectory, "scratch");
|
||||
|
||||
private static int Main(string[] args)
|
||||
{
|
||||
if (Directory.Exists(TempRoot)) Directory.Delete(TempRoot, recursive: true);
|
||||
Directory.CreateDirectory(TempRoot);
|
||||
|
||||
var runner = new Runner();
|
||||
ParserTests.Register(runner);
|
||||
InferenceTests.Register(runner);
|
||||
StoreTests.Register(runner);
|
||||
WindowTests.Register(runner);
|
||||
int rc = runner.Run("RynthThreads tests", args.Length > 0 ? args[0] : null);
|
||||
try { Directory.Delete(TempRoot, recursive: true); } catch { }
|
||||
return rc;
|
||||
}
|
||||
|
||||
/// <summary>A fresh empty folder under the scratch root.</summary>
|
||||
public static string NewFolder(string name)
|
||||
{
|
||||
string path = Path.Combine(TempRoot, name + "-" + Guid.NewGuid().ToString("N").Substring(0, 6));
|
||||
Directory.CreateDirectory(path);
|
||||
return path;
|
||||
}
|
||||
}
|
||||
}
|
||||
39
Tools/RynthThreads.Tests/RynthThreads.Tests.csproj
Normal file
39
Tools/RynthThreads.Tests/RynthThreads.Tests.csproj
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!--
|
||||
Offline tests for the RynthThreads plugin (DreamWeave Fragment Press results): the chat parser
|
||||
(the real sample with an interleaved line, several / no components, incomplete presses, odd
|
||||
text), the inference rules on made-up presses (a forced modifier at n = 3 but not n = 1, n = 2,
|
||||
the 90% rule, base rates, several components in one press), the shared presses.jsonl (JSON
|
||||
round trip, following the file's growth, two writers appending at once) and that the window's
|
||||
display list is accepted by the engine's own parser (RynthCore
|
||||
src/RynthCore.Engine/UI/ScriptWindows/DisplayListParser.cs, from the sibling checkout).
|
||||
The plugin is a NativeAOT x86 library, so its sources are compiled in here. Files go to a
|
||||
scratch folder next to the exe, never %LOCALAPPDATA%.
|
||||
Run: dotnet run -c Release (exit 0 = pass, 1 = fail; an argument filters by test name)
|
||||
-->
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0-windows</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<InvariantGlobalization>true</InvariantGlobalization>
|
||||
<RootNamespace>RynthThreads.Tests</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginCore\RynthCore.PluginCore.csproj" />
|
||||
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginSdk\RynthCore.PluginSdk.csproj" />
|
||||
<!-- The engine parser's whitelists use ImGui.NET's enums. -->
|
||||
<PackageReference Include="ImGui.NET" Version="1.91.6.1" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthThreads\**\*.cs" Exclude="..\..\Plugins\RynthCore.Plugin.RynthThreads\obj\**;..\..\Plugins\RynthCore.Plugin.RynthThreads\bin\**" Link="RynthThreads\%(RecursiveDir)%(Filename)%(Extension)" />
|
||||
<Compile Include="..\..\..\RynthCore\src\RynthCore.Engine\UI\ScriptWindows\DisplayListParser.cs" Link="Engine\DisplayListParser.cs" />
|
||||
<!-- The RynthAi test tools' check/runner harness (no plugin code in it). -->
|
||||
<Compile Include="$(RynthSuiteRoot)Tools\RynthCore.RynthAiTests\Harness\Check.cs" Link="Harness\Check.cs" />
|
||||
<Compile Include="$(RynthSuiteRoot)Tools\RynthCore.RynthAiTests\Harness\Runner.cs" Link="Harness\Runner.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
181
Tools/RynthThreads.Tests/StoreTests.cs
Normal file
181
Tools/RynthThreads.Tests/StoreTests.cs
Normal file
|
|
@ -0,0 +1,181 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using RynthCore.Plugin.RynthThreads.Threads;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthThreads.Tests;
|
||||
|
||||
// The shared presses.jsonl (Threads/PressStore.cs).
|
||||
internal static class StoreTests
|
||||
{
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("store: a press survives the JSON round trip", RoundTrip);
|
||||
r.Add("store: another client's presses are read as the file grows; no doubles", FollowsGrowth);
|
||||
r.Add("store: odd lines are skipped, a half-written line waits", OddLines);
|
||||
r.Add("store: two writers appending at once lose nothing", ConcurrentAppends);
|
||||
r.Add("store: CSV export", CsvExport);
|
||||
}
|
||||
|
||||
private static Press Sample() => new PressParser().Feed(string.Join("\n", ParserTests.Sample), 1)![0];
|
||||
|
||||
private static void RoundTrip()
|
||||
{
|
||||
Press p = Sample();
|
||||
p.Server = "DreamWeave";
|
||||
p.Character = "Tester \"Quote\"";
|
||||
string json = PressStore.ToJson(p);
|
||||
Check.False(json.Contains('\n'), "one line");
|
||||
Press? back = PressStore.FromJson(json);
|
||||
Check.NotNull(back, "reads back");
|
||||
if (back == null) return;
|
||||
ParserTests.CheckSample(back);
|
||||
Check.Eq(back.Id, p.Id, "id");
|
||||
Check.Eq(back.Character, "Tester \"Quote\"", "character (escaped quotes)");
|
||||
Check.Eq(back.Server, "DreamWeave", "server");
|
||||
Check.Eq(back.TimeUtc, p.TimeUtc, "time");
|
||||
Check.Eq(back.Modifiers[3].Numbers[0].Text, "+29", "number text");
|
||||
|
||||
// Missing fields and unknown ones (a later version) are fine.
|
||||
Press? minimal = PressStore.FromJson("{\"id\":\"x1\",\"future\":[1,2],\"modifiers\":[{\"name\":\"Hardy\"},{\"description\":\"no name\"}]}");
|
||||
Check.True(minimal != null && minimal.Id == "x1" && minimal.Modifiers.Count == 1 && minimal.FragmentLevel == null,
|
||||
"minimal line reads, nameless modifier dropped");
|
||||
Check.Null(PressStore.FromJson("not json"), "garbage");
|
||||
Check.Null(PressStore.FromJson("[1,2]"), "not an object");
|
||||
}
|
||||
|
||||
private static void FollowsGrowth()
|
||||
{
|
||||
string folder = Program.NewFolder("growth");
|
||||
var a = new PressStore(folder);
|
||||
var b = new PressStore(folder);
|
||||
Check.Eq(b.Poll(), 0, "no file yet");
|
||||
|
||||
Check.Null(a.Record(Sample()), "client A writes");
|
||||
Check.Eq(a.Poll(), 0, "A reading its own press back adds nothing");
|
||||
Check.Eq(a.Presses.Count, 1, "A has it once");
|
||||
Check.Eq(b.Poll(), 1, "client B sees it");
|
||||
Check.Eq(b.Poll(), 0, "and only once");
|
||||
|
||||
Press second = Sample();
|
||||
second.Components = new List<string> { "Blue Taper" };
|
||||
a.Record(second);
|
||||
b.Record(Sample());
|
||||
Check.Eq(b.Poll(), 1, "B gets A's second press (its own is already there)");
|
||||
Check.Eq(a.Poll(), 1, "A gets B's press");
|
||||
Check.Eq(a.Presses.Count, 3, "A: 3");
|
||||
Check.Eq(b.Presses.Count, 3, "B: 3");
|
||||
|
||||
// A fresh client reads them all.
|
||||
var c = new PressStore(folder);
|
||||
Check.Eq(c.Poll(), 3, "a new client loads everything");
|
||||
int v = c.Version;
|
||||
c.Poll();
|
||||
Check.Eq(c.Version, v, "nothing new: unchanged");
|
||||
}
|
||||
|
||||
private static void OddLines()
|
||||
{
|
||||
string folder = Program.NewFolder("odd");
|
||||
var s = new PressStore(folder);
|
||||
Directory.CreateDirectory(folder);
|
||||
string good = PressStore.ToJson(Sample());
|
||||
File.WriteAllText(s.FilePath, good + "\n\nnot json at all\n{\"broken\":\n" + good.Substring(0, 20));
|
||||
Check.Eq(s.Poll(), 1, "the good line");
|
||||
Check.Eq(s.BadLines, 2, "two bad lines counted");
|
||||
// The half line gets finished (with a different id: a new press).
|
||||
Press other = Sample();
|
||||
string rest = PressStore.ToJson(other);
|
||||
File.WriteAllText(s.FilePath, good + "\n\nnot json at all\n{\"broken\":\n" + rest + "\n");
|
||||
Check.Eq(s.Poll(), 1, "the finished line is read");
|
||||
Check.Eq(s.Presses.Count, 2, "two presses");
|
||||
}
|
||||
|
||||
private static void ConcurrentAppends()
|
||||
{
|
||||
string folder = Program.NewFolder("concurrent");
|
||||
const int perWriter = 250;
|
||||
var writers = new[] { new PressStore(folder), new PressStore(folder) };
|
||||
var errors = new int[2];
|
||||
using var stop = new CancellationTokenSource();
|
||||
|
||||
// A third party holding the file now and then, as another client mid-write would.
|
||||
var holder = new Thread(() =>
|
||||
{
|
||||
while (!stop.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var fs = new FileStream(Path.Combine(folder, PressStore.FileName), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
|
||||
Thread.Sleep(3);
|
||||
}
|
||||
catch (IOException) { }
|
||||
Thread.Sleep(2);
|
||||
}
|
||||
});
|
||||
holder.Start();
|
||||
|
||||
var threads = Enumerable.Range(0, 2).Select(w => new Thread(() =>
|
||||
{
|
||||
for (int i = 0; i < perWriter; i++)
|
||||
{
|
||||
Press p = Sample();
|
||||
p.Character = "Writer" + w;
|
||||
p.Components = new List<string> { "C" + i };
|
||||
if (writers[w].Record(p) != null) errors[w]++;
|
||||
}
|
||||
})).ToList();
|
||||
threads.ForEach(t => t.Start());
|
||||
threads.ForEach(t => t.Join());
|
||||
stop.Cancel();
|
||||
holder.Join();
|
||||
|
||||
// Whatever found the file busy every time is written now.
|
||||
foreach (PressStore w in writers)
|
||||
for (int i = 0; i < 50 && w.FlushPending() > 0; i++) Thread.Sleep(10);
|
||||
Check.Eq(writers[0].PendingCount + writers[1].PendingCount, 0, "nothing left pending");
|
||||
|
||||
string[] lines = File.ReadAllLines(Path.Combine(folder, PressStore.FileName), Encoding.UTF8)
|
||||
.Where(l => l.Length > 0).ToArray();
|
||||
Check.Eq(lines.Length, 2 * perWriter, "every press is one line");
|
||||
List<Press?> read = lines.Select(PressStore.FromJson).ToList();
|
||||
Check.True(read.All(p => p != null && p.Modifiers.Count == 6), "every line is a whole press");
|
||||
Check.Eq(read.Select(p => p!.Id).Distinct().Count(), 2 * perWriter, "all ids distinct");
|
||||
Check.Eq(read.Count(p => p!.Character == "Writer0"), perWriter, "writer 0's presses all there");
|
||||
Check.Eq(read.Count(p => p!.Character == "Writer1"), perWriter, "writer 1's presses all there");
|
||||
|
||||
var reader = new PressStore(folder);
|
||||
Check.Eq(reader.Poll(), 2 * perWriter, "a reader loads them all");
|
||||
Check.Eq(reader.BadLines, 0, "no bad lines");
|
||||
Console.WriteLine($" (appends that found the file busy every try and waited: {errors[0] + errors[1]})");
|
||||
}
|
||||
|
||||
private static void CsvExport()
|
||||
{
|
||||
string folder = Program.NewFolder("csv");
|
||||
var s = new PressStore(folder);
|
||||
Press p = Sample();
|
||||
p.Character = "Tester, Jr.";
|
||||
s.Record(p);
|
||||
Press q = Sample();
|
||||
q.Components = new List<string> { "=cmd", "Red Taper" };
|
||||
q.Complete = false;
|
||||
q.End = "timeout";
|
||||
s.Record(q);
|
||||
string path = s.ExportCsv(new DateTime(2026, 10, 12, 19, 30, 0));
|
||||
Check.True(File.Exists(path) && Path.GetDirectoryName(path) == folder, "written next to presses.jsonl");
|
||||
Check.Eq(Path.GetFileName(path), "presses-20261012-193000.csv", "file name");
|
||||
string[] rows = File.ReadAllLines(path);
|
||||
Check.Eq(rows.Length, 3, "header + 2 rows");
|
||||
Check.True(rows[0].StartsWith("time_utc,server,character,fragment,fragment_level"), "header");
|
||||
Check.True(rows[1].Contains("\"Tester, Jr.\""), "comma value quoted");
|
||||
Check.True(rows[1].Contains(",Raw Fragment,185,Pressed. It holds.,Red Taper,190,4,yes,6,"), "columns");
|
||||
Check.True(rows[1].Contains("Bounteous: kills drop x1.38 loot | Tourmaline Affinity"), "modifiers joined");
|
||||
Check.True(rows[2].Contains("'=cmd; Red Taper"), "a formula-looking cell is defused");
|
||||
Check.True(rows[2].Contains("no (timeout)"), "incomplete marked");
|
||||
}
|
||||
}
|
||||
186
Tools/RynthThreads.Tests/WindowTests.cs
Normal file
186
Tools/RynthThreads.Tests/WindowTests.cs
Normal file
|
|
@ -0,0 +1,186 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.CompilerServices;
|
||||
using RynthCore.Engine.UI.ScriptWindows;
|
||||
using RynthCore.Plugin.RynthThreads;
|
||||
using RynthCore.Plugin.RynthThreads.Threads;
|
||||
using RynthCore.Plugin.RynthThreads.Ui;
|
||||
using RynthCore.Plugin.RynthThreads.Views;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthThreads.Tests;
|
||||
|
||||
// The window's display list against the engine's own parser, the server check and /rthreads stats.
|
||||
internal static class WindowTests
|
||||
{
|
||||
[UnsafeAccessor(UnsafeAccessorKind.Method, Name = "Write")]
|
||||
private static extern int Write(UiHost h);
|
||||
|
||||
[UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_submit")]
|
||||
private static extern ref byte[] SubmitBuffer(UiHost h);
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("window: every tab, headers open, parses in the engine (bar button set)", EveryTab);
|
||||
r.Add("window: DreamWeave check and /rthreads stats lines", ServerAndStats);
|
||||
r.Add("window: Components and Modifiers tab text for the 4 real presses", RealText);
|
||||
}
|
||||
|
||||
private static List<Press> Data()
|
||||
{
|
||||
var presses = new List<Press>();
|
||||
for (int i = 0; i < 3; i++) presses.Add(InferenceTests.P("Red Taper", "Bounteous=kills drop x1.38 loot, Hardy=monsters have x1.5 health", level: 185));
|
||||
for (int i = 0; i < 4; i++) presses.Add(InferenceTests.P("", "Hardy=monsters have x1.81 health, Teeming=75% more monsters", level: 185));
|
||||
presses.Add(InferenceTests.P("Blue Taper, Red Taper", "Bounteous=kills drop x1.4 loot", level: 120));
|
||||
Press raw = new PressParser().Feed(string.Join("\n", ParserTests.Sample), 1)![0];
|
||||
presses.Add(raw);
|
||||
presses.Add(InferenceTests.P("Red Taper", "Hardy", complete: false));
|
||||
return presses;
|
||||
}
|
||||
|
||||
private static unsafe void EveryTab()
|
||||
{
|
||||
List<Press> presses = Data();
|
||||
ThreadsReport report = PressInference.Build(presses);
|
||||
var panel = new ThreadsPanel { Report = () => report, Presses = () => presses };
|
||||
var host = new UiHost();
|
||||
UiWindow w = host.Add(new UiWindow("RynthThreads/Main", "RynthThreads") { DefaultWidth = 440f, DefaultHeight = 480f, MinWidth = 320f, MinHeight = 220f });
|
||||
|
||||
void Pass()
|
||||
{
|
||||
w.Begin();
|
||||
panel.Draw(w);
|
||||
w.End();
|
||||
}
|
||||
void OpenAll(IEnumerable<string> ids)
|
||||
{
|
||||
foreach (string id in ids) w.Dispatch(w.KeyOf(id), new UiEvent(UiFormat.EvOpen, b: true));
|
||||
}
|
||||
void Click(string id) => w.Dispatch(w.KeyOf(id), new UiEvent(UiFormat.EvClicked));
|
||||
|
||||
string[] tabs = { "tab.c", "tab.m", "tab.p" };
|
||||
foreach (string tab in tabs)
|
||||
{
|
||||
Pass();
|
||||
Click(tab);
|
||||
Pass();
|
||||
OpenAll(report.Components.Select(c => "c:" + c.Name).Append("c:(none)").Append("c:(all)")
|
||||
.Concat(report.Combinations.Select(c => "k:" + c.Name))
|
||||
.Concat(report.Modifiers.Select(m => "m:" + m.Name))
|
||||
.Concat(presses.Select(p => "p:" + p.Id)));
|
||||
Pass();
|
||||
|
||||
int n = Write(host);
|
||||
byte[] buf = SubmitBuffer(host);
|
||||
int rc;
|
||||
List<ParsedWindow> windows;
|
||||
string error;
|
||||
fixed (byte* p = buf) rc = DisplayListParser.Parse(p, n, 4000f, out _, out windows, out error);
|
||||
Check.Eq(rc, 0, $"{tab}: the engine accepts the list ({error})");
|
||||
if (rc != 0 || windows.Count != 1) continue;
|
||||
Check.Eq(windows[0].Title, "RynthThreads", "title (the bar button's tooltip)");
|
||||
Check.True((windows[0].Flags & WindowFlags.ShowInBar) != 0 && (windows[0].Flags & WindowFlags.BarButton) != 0, "bar button");
|
||||
Check.True(windows[0].List!.OpCount > 20, $"{tab}: something drawn ({windows[0].List!.OpCount} ops)");
|
||||
}
|
||||
string body = System.Text.Encoding.UTF8.GetString(w.Body);
|
||||
Check.True(body.Contains("Level 190, 4 entries."), "presses tab shows raw lines");
|
||||
Check.True(body.Contains("Yorick is recalling"), "and the other lines kept beside them");
|
||||
|
||||
// Empty data still draws.
|
||||
var empty = new ThreadsPanel();
|
||||
w.Begin();
|
||||
empty.Draw(w);
|
||||
w.End();
|
||||
Check.True(System.Text.Encoding.UTF8.GetString(w.Body).Contains("No presses yet"), "empty window explains itself");
|
||||
}
|
||||
|
||||
private static void ServerAndStats()
|
||||
{
|
||||
Check.True(RynthThreadsPlugin.IsDreamWeave("DreamWeave"), "DreamWeave");
|
||||
Check.True(RynthThreadsPlugin.IsDreamWeave("dreamweave PvE"), "any case, extra words");
|
||||
Check.False(RynthThreadsPlugin.IsDreamWeave("Aelrynth"), "Aelrynth");
|
||||
Check.False(RynthThreadsPlugin.IsDreamWeave(""), "empty");
|
||||
Check.False(RynthThreadsPlugin.IsDreamWeave(null), "null");
|
||||
|
||||
List<string> lines = RynthThreadsPlugin.StatsLines(PressInference.Build(Data()), @"C:\x\presses.jsonl");
|
||||
Check.True(lines[0].StartsWith("10 presses (9 complete, 1 incomplete)"), "totals line: " + lines[0]);
|
||||
Check.True(lines.Any(l => l.StartsWith("Red Taper (5): Bounteous 100%+, Hardy 80%")), "Red Taper line");
|
||||
Check.True(lines.Any(l => l == "Blue Taper (1): Bounteous 100%"), "Blue Taper line");
|
||||
Check.True(lines.Any(l => l.StartsWith("No components (4): Hardy 100%")), "No components line");
|
||||
Check.False(lines.Any(l => l.Contains("Affinity")), "the Affinity group is left out");
|
||||
Check.True(lines.Contains("+ = more likely with it than without."), "legend");
|
||||
Check.Eq(lines[^1], @"File: C:\x\presses.jsonl", "file named last");
|
||||
Check.True(lines.Count <= 9, "short");
|
||||
}
|
||||
|
||||
/// <summary>The window's text ops in order (headers as "== label", indented by Indent ops).</summary>
|
||||
internal static List<string> TextOf(ReadOnlySpan<byte> b)
|
||||
{
|
||||
var lines = new List<string>();
|
||||
int i = 0, indent = 0;
|
||||
string Str(ReadOnlySpan<byte> s, int at) =>
|
||||
System.Text.Encoding.UTF8.GetString(s.Slice(at + 2, s[at] | (s[at + 1] << 8)));
|
||||
while (i + 4 <= b.Length)
|
||||
{
|
||||
byte code = b[i], flags = b[i + 1];
|
||||
int len = b[i + 2] | (b[i + 3] << 8), at = i + 4;
|
||||
if (code == UiFormat.OpEnd && len == 0) break;
|
||||
string pad = new string(' ', indent * 2);
|
||||
switch (code)
|
||||
{
|
||||
case UiFormat.OpText: case UiFormat.OpTextWrapped: case UiFormat.OpTextDisabled: case UiFormat.OpSeparatorText:
|
||||
lines.Add(pad + Str(b, at)); break;
|
||||
case UiFormat.OpBulletText: lines.Add(pad + "- " + Str(b, at)); break;
|
||||
case UiFormat.OpTextColored: lines.Add(pad + Str(b, at + 4)); break;
|
||||
case UiFormat.OpCollapsingHeader:
|
||||
string h = Str(b, at + 4);
|
||||
int cut = h.IndexOf("###", StringComparison.Ordinal);
|
||||
lines.Add(pad + "== " + (cut >= 0 ? h.Substring(0, cut) : h)); break;
|
||||
case UiFormat.OpIndent: indent++; break;
|
||||
case UiFormat.OpUnindent: indent = Math.Max(0, indent - 1); break;
|
||||
}
|
||||
i = at + len + ((flags & UiFormat.OpHasBlock) != 0 ? 4 : 0);
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
private static void RealText()
|
||||
{
|
||||
List<Press> presses = InferenceTests.Real();
|
||||
ThreadsReport report = PressInference.Build(presses);
|
||||
var panel = new ThreadsPanel { Report = () => report, Presses = () => presses };
|
||||
var w = new UiWindow("RynthThreads/Main", "RynthThreads");
|
||||
void Pass() { w.Begin(); panel.Draw(w); w.End(); }
|
||||
void Open(string id) => w.Dispatch(w.KeyOf(id), new UiEvent(UiFormat.EvOpen, b: true));
|
||||
|
||||
Pass();
|
||||
Open("c:(all)");
|
||||
Open("c:Lead Scarab");
|
||||
Pass();
|
||||
List<string> comp = TextOf(w.Body);
|
||||
Check.True(comp.Contains("== Lead Scarab (4 presses)"), "Lead Scarab header");
|
||||
Check.True(comp.Any(l => l.Trim() == "- Guarded 75% (3/4, 30-95%); without: no data; x1.83 to x2.18"), "Guarded line");
|
||||
Check.True(comp.Any(l => l.Trim() == "- Affinity (any) 100% (4/4, 51-100%); without: no data; 7% to 22%"), "Affinity line");
|
||||
Check.True(comp.Any(l => l.Trim() == "Amethyst 1, Iron 1, Obsidian 1, Serpentine 1"), "split line");
|
||||
Check.True(comp.Any(l => l.Trim() == "- Guarded 75% (3/4, 30-95%); x1.83 to x2.18"), "All presses: no comparison");
|
||||
|
||||
w.Dispatch(w.KeyOf("tab.m"), new UiEvent(UiFormat.EvClicked));
|
||||
Pass();
|
||||
Open("m:Affinity");
|
||||
Open("m:Guarded");
|
||||
Pass();
|
||||
List<string> mods = TextOf(w.Body);
|
||||
Check.True(mods.Contains("== Guarded 75% (3/4, 30-95%) [harder]") || mods.Contains("== Guarded 75% (3/4, 30-95%)"), "Guarded header");
|
||||
Check.True(mods.Any(l => l.Trim() == "- Lead Scarab 75% (3/4, 30-95%); without: no data; x1.83 to x2.18"), "Guarded with Lead Scarab");
|
||||
Check.True(mods.Any(l => l.Trim() == "- Amethyst: 25% (1/4, 5-70%)"), "Affinity by material");
|
||||
|
||||
if (Environment.GetEnvironmentVariable("RYNTHTHREADS_DUMP") == "1")
|
||||
{
|
||||
Console.WriteLine("---- Components tab ----");
|
||||
foreach (string l in comp) Console.WriteLine(l);
|
||||
Console.WriteLine("---- Modifiers tab ----");
|
||||
foreach (string l in mods) Console.WriteLine(l);
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue