Snapshot for release 2026.10.9.3 (internal 8c6b770)

This commit is contained in:
Tom Bohar 2026-10-09 21:42:40 -04:00
commit e6fffb0f42
25 changed files with 953 additions and 47 deletions

View file

@ -411,7 +411,7 @@ internal static partial class Program
Eq(back.Rules[0].Name, "Keep gems", $"{label}: rule 1 kept");
Check(!back.Rules[2].Enabled && back.Rules[2].Action == LootAction.Sell && back.Rules[2].Conditions[0].ToString() == orig.Rules[1].Conditions[0].ToString(),
$"{label}: disabled rule kept as it was");
Eq(back.Rules[3].KeepCount, 1, $"{label}: (KeepCount 0 reads back as 1 in the native loader, before and after alike)");
Eq(back.Rules[3].KeepCount, 0, $"{label}: KeepCount 0 is written and reads back as 0, before and after alike");
Eq(LootProfile.Load(path + ".bak").Rules[2].KeepCount, back.Rules[3].KeepCount, $"{label}: same as the original reads");
Eq(string.Join(" ; ", back.Rules[3].Conditions), string.Join(" ; ", orig.Rules[2].Conditions), $"{label}: rule 3's conditions kept");
Eq(back.SalvageCombine?.DefaultBands, "1-6, 7-10", $"{label}: salvage combine kept");

View file

@ -86,6 +86,7 @@ internal static class Program
HazardEscapeTests.Register(runner);
ManaStoneChoiceTests.Register(runner);
CustomDebuffTests.Register(runner);
ProfileLoadTests.Register(runner);
return runner.Run("RynthAi host tests", args.Length > 0 ? args[0] : null);
}
}

View file

@ -62,9 +62,7 @@ internal static class BuffTests
r.Add("buff choice: a mastery whose name has several spell ids", MultiIdMastery); // was a known failure; fixed by 0aedcee
r.Add("buff timers: tier-8 weapon auras last 90 minutes", TierEightAuras); // was a known failure; fixed by 9a317a8
r.Add("buff chat: another player's speech can't record a buff timer", SpeechIsNotACast); // was a known failure; fixed by 0e384d2
r.KnownFailure("buff school: Armor Tinkering Expertise is a Creature Enchantment spell",
"SkillForBuff matches \"Armor\" first and files it under Life Magic: its tier comes from Life Magic, and a character without Life Magic never casts it (not fixed on any branch)",
ArmorTinkeringSchool);
r.Add("buff school: Armor Tinkering Expertise is a Creature Enchantment spell", ArmorTinkeringSchool); // was a known failure
}
// ── Rig ───────────────────────────────────────────────────────────────────
@ -401,7 +399,12 @@ internal static class BuffTests
private static void ArmorTinkeringSchool()
{
Check.Eq(BuffManager.SkillForBuff("Armor Tinkering Expertise"), AcSkillType.CreatureEnchantment, "Armor Tinkering Expertise");
foreach (string n in new[] { "Armor Tinkering Expertise", "Item Tinkering Expertise", "Weapon Tinkering Expertise",
"Magic Item Tinkering Expertise", "Prodigal Armor Expertise", "Incantation of Armor Tinkering Expertise" })
Check.Eq(BuffManager.SkillForBuff(n), AcSkillType.CreatureEnchantment, n);
// The "Armor" keyword still files real Life Magic armor buffs under Life.
foreach (string n in new[] { "Armor", "Incantation of Armor", "Prodigal Armor", "Blade Protection", "Regeneration" })
Check.Eq(BuffManager.SkillForBuff(n), AcSkillType.LifeMagic, n);
}
private static void ItemEnchantments()

View file

@ -53,9 +53,8 @@ internal static class ExpressionTests
r.Add("expr: chat and echo", ChatFunctions);
r.Add("expr: $name reads an unset variable like getvar[name]", DollarMatchesGetvar); // was a known failure; fixed by 79a39b7
r.Add("expr: arithmetic that gives negative zero is false", NegativeZeroIsFalse); // was a known failure; fixed by 92a6318
r.KnownFailure("expr: list items may contain commas or be lists",
"lists are stored as \"[a,b]\" and split on every comma, so an item with a comma (or a nested list) becomes several items",
ListItemsWithCommas);
r.Add("expr: list items may contain commas or be lists", ListItemsWithCommas); // was a known failure
r.Add("expr: list text saved before escaping reads the same", OldListTextReadsTheSame);
r.Add("expr: # takes a regex pattern without backticks, as documented", RegexOperatorUnquoted); // was a known failure; fixed by c34b39c
r.Add("expr: vitae[] reports no penalty when it cannot read vitae", VitaeWithoutHost); // was a known failure; fixed by 33f23f7
}
@ -914,6 +913,48 @@ internal static class ExpressionTests
var e = Engine();
Check.Eq(e.Evaluate("listcount[listcreate[`a,b`, c]]"), "2", "an item holding a comma");
Check.Eq(e.Evaluate("listcount[listadd[listcreate[a], listcreate[b,c]]]"), "2", "a list added to a list");
// The items come back whole, and a nested list reads as a list again.
Check.Eq(e.Evaluate("listgetitem[listcreate[`a,b`, c], 0]"), "a,b", "the comma item reads back unescaped");
Check.Eq(e.Evaluate("listgetitem[listadd[listcreate[a], listcreate[b,c]], 1]"), "[b,c]", "the nested list reads back as a list");
Check.Eq(e.Evaluate("listcount[listgetitem[listadd[listcreate[a], listcreate[b,c]], 1]]"), "2", "and has its own two items");
Check.Eq(e.Evaluate("listcontains[listcreate[`a,b`, c], `a,b`]"), "1", "listcontains finds the comma item");
Check.Eq(e.Evaluate("listindexof[listcreate[x, `a,b`], `a,b`]"), "1", "listindexof finds it at 1");
// Brackets and backslashes in plain text survive too; plain lists keep their old text.
Check.Eq(e.Evaluate("listgetitem[listcreate[`x[1`, `c:\\d`], 0]"), "x[1", "an unbalanced bracket");
Check.Eq(e.Evaluate("listgetitem[listcreate[`x[1`, `c:\\d`], 1]"), "c:\\d", "a backslash");
Check.Eq(e.Evaluate("listcreate[a, b, c]"), "[a,b,c]", "a plain list is written as before");
// A nested list holding a comma item: the escape survives the nesting.
e.Evaluate("setvar[inner, listcreate[`p,q`, r]]");
e.Evaluate("setvar[outer, listadd[listcreate[z], getvar[inner]]]");
Check.Eq(e.Evaluate("listgetitem[listgetitem[getvar[outer], 1], 0]"), "p,q", "two levels down");
}
private static void OldListTextReadsTheSame()
{
// List text a meta built by hand, or saved in a pvar before escaping existed, reads the same.
var e = Engine();
e.Evaluate("setvar[old, `[a,b,c]`]");
Is(e, "listcount[getvar[old]]", "3");
Is(e, "listgetitem[getvar[old], 1]", "b");
Is(e, "listcount[`[a,,b,]`]", "4"); // empty items kept, as with Split
Is(e, "listgetitem[`[a,,b,]`, 1]", "");
Is(e, "listreduce[`[1,2,3]`, `$2 + $1`]", "6");
Is(e, "listsort[`[b,a,c]`]", "[a,b,c]");
Is(e, "listmap[`[1,2]`, `$1 * 2`]", "[2,4]");
Is(e, "listadd[`[a,b]`, c]", "[a,b,c]");
Is(e, "listremove[`[a,b,c]`, b]", "[a,c]");
Is(e, "listreverse[`[1,2,3]`]", "[3,2,1]");
Is(e, "listfromrange[1, 3]", "[1,2,3]");
// A backslash that is not an escape is plain text (a path saved before escaping existed)...
Is(e, "listcount[`[c:\\d,x]`]", "2");
Is(e, "listgetitem[`[c:\\d,x]`, 0]", "c:\\d");
// ...and writing the list again escapes it, which reads back the same.
Is(e, "listadd[`[c:\\d]`, y]", "[c:\\\\d,y]");
Is(e, "listgetitem[listadd[`[c:\\d]`, y], 0]", "c:\\d");
}
private static void RegexOperatorUnquoted()

View file

@ -25,6 +25,7 @@ internal static class ItemInfoTests
public static void Register(Runner r)
{
r.Add("iteminfo: a weapon's damage, mods, imbue, slayer, spells and wield line", WeaponLine);
r.Add("iteminfo: Crushing Blow as the dealt crit multiplier, Biting Strike as a crit chance", CritStats);
r.Add("iteminfo: armor's set, AL, ratings, tinks and wield level", ArmorLine);
r.Add("iteminfo: jewelry with mana, diff and craft; a bare item stays short", JewelryAndBareItem);
r.Add("iteminfo: a selected item already appraised prints at once, no ID", SelectedAppraised);
@ -103,6 +104,30 @@ internal static class ItemInfoTests
Check.False(s.Contains("not identified"), "identified: no note");
}
private static void CritStats()
{
var w = new Fake { Name = "Ornate Katar" };
w.Ints[ItemInfoText.IntItemType] = 0x1;
w.Ints[ItemInfoText.IntDamage] = 77;
w.Ints[ItemInfoText.IntWeaponTime] = 30;
w.Floats[ItemInfoText.FloatCriticalMultiplier] = 2.66;
w.Floats[ItemInfoText.FloatCriticalFrequency] = 0.15;
w.Floats[ItemInfoText.FloatWeaponOffense] = 1.18;
string s = ItemInfoText.Describe(w, Spell);
InOrder(s, new[] { "Dmg 77", "Speed 30", "Crushing Blow 3.66x", "Biting Strike 15%", "(+18% atk)" }, "crit stats");
w.Floats[ItemInfoText.FloatCriticalMultiplier] = 1.0; // an ordinary crit
w.Floats[ItemInfoText.FloatCriticalFrequency] = 0.125;
s = ItemInfoText.Describe(w, Spell);
Check.False(s.Contains("Crushing Blow"), "a 1.0 multiplier is an ordinary crit: not shown");
Check.True(s.Contains("Biting Strike 12.5%"), "a fractional crit chance keeps one decimal");
var a = new Fake { Name = "Chainmail Tassets" };
a.Ints[ItemInfoText.IntItemType] = 0x2;
a.Floats[ItemInfoText.FloatCriticalMultiplier] = 3.0;
Check.False(ItemInfoText.Describe(a, Spell).Contains("Crushing Blow"), "only weapons show crit stats");
}
private static void ArmorLine()
{
var a = new Fake { Name = "Chainmail Tassets" };
@ -203,7 +228,8 @@ internal static class ItemInfoTests
public void Tick() => typeof(RynthAiPlugin).GetMethod("TickItemInfo", Any)!.Invoke(P, null);
public string[] InfoLines => FakeHost.Chat.Where(c => c.StartsWith("[RynthAi] ", StringComparison.Ordinal)).ToArray();
public string[] InfoLines => FakeHost.Chat.Where(c => c.StartsWith("[RynthAi] ", StringComparison.Ordinal)
|| c.StartsWith(RynthAiPlugin.ItemPrefix, StringComparison.Ordinal)).ToArray();
}
private static void Done() => RynthAiPlugin.ItemInfoClock = () => Environment.TickCount64;
@ -319,13 +345,13 @@ internal static class ItemInfoTests
FakeHost.Appraised.Add(Ring);
w.Command("/ra iteminfo mana scarab");
w.Tick();
Check.True(w.InfoLines.Last().StartsWith("[RynthAi] Mana Scarab", StringComparison.Ordinal), $"exact name, any case: {w.InfoLines.Last()}");
Check.True(w.InfoLines.Last().StartsWith("[RynthAi Item] Mana Scarab", StringComparison.Ordinal), $"exact name, any case: {w.InfoLines.Last()}");
w.Command("/ra iteminfo Scarab");
w.Tick();
Check.True(w.InfoLines.Last().Contains("Scarab") && !w.InfoLines.Last().Contains("not in your"), "a partial name finds a scarab");
w.Command("/ra iteminfo ring");
w.Tick();
Check.True(w.InfoLines.Last().StartsWith("[RynthAi] Gold Ring", StringComparison.Ordinal), "partial: Gold Ring");
Check.True(w.InfoLines.Last().StartsWith("[RynthAi Item] Gold Ring", StringComparison.Ordinal), "partial: Gold Ring");
Check.Eq(FakeHost.SelectedItem, 0u, "a named lookup doesn't need a selection");
}
finally { Done(); }

View file

@ -54,9 +54,8 @@ internal static class MetaTests
r.Add("meta: state snapshot", Snapshot);
r.Add("meta: VendorClosed fires after a vendor closes", VendorClosedFires); // was a known failure; fixed by ef68455
r.Add("meta: InventoryItemCount counts stack sizes", InventoryCountsStacks); // was a known failure; fixed by 716f16d
r.KnownFailure("meta: SecondsInStateP keeps counting across a call and return",
"SecondsInStateP_GE survives a macro stop/start since 1ee6145, but still restarts whenever the state is re-entered (SetState, Call, Return), as VTank documents it; RynthScript says it survives re-entry. Open compatibility call (2026-09-30 audit, question 16)",
SecondsInStatePPersists);
r.Add("meta: SecondsInStateP keeps counting across a call and return", SecondsInStatePPersists); // was a known failure (2026-09-30 audit, question 16: RynthScript's re-entry rule)
r.Add("meta: SecondsInStateP pauses in a call, survives SetState to itself, restarts on a new state or meta", SecondsInStatePRules);
r.Add("meta: MainHealthPHE / MainManaPHE mean 'percent >='", PercentConditionsAreGE); // was a known failure; fixed by a7c4618
r.Add("meta: a negative vital threshold never holds", NegativeVitalThreshold); // was a known failure; fixed by 6f72b67
r.Add("meta edit: saving a rule keeps the running meta's state, clocks and latch", EditKeepsRunningMeta);
@ -1105,6 +1104,78 @@ internal static class MetaTests
Check.Eq(rig.Var("p"), "1", "SecondsInStateP_GE 25 after 25 s spent in Default around a 1 s call");
}
private static void SecondsInStatePRules()
{
// Paused while Default has Called Sub: 25 s of wall time is only 15 s in Default.
var call = new Rig(rules: new[]
{
Mark("Default", C.SecondsInStateP_GE, "20", "p"),
Rule("Default", C.SecondsInState_GE, "10", A.CallMetaState, "Sub"),
Rule("Sub", C.SecondsInState_GE, "10", A.ReturnFromCall, ""),
});
call.Tick(); // T0: Default
call.Tick(10); // T0+10: call Sub
call.Tick();
call.Tick(10); // T0+20: return
call.Tick();
call.Tick(5); // T0+25: 15 s in Default
Check.False(call.Has("p"), "15 s in Default (10 s in Sub not counted)");
call.Tick(5); // T0+30: 20 s in Default
Check.Eq(call.Var("p"), "1", "20 s in Default");
// In the called state the P clock is that state's own, from its entry.
var inSub = new Rig(rules: new[]
{
Rule("Default", C.SecondsInState_GE, "30", A.CallMetaState, "Sub"),
Mark("Sub", C.SecondsInStateP_GE, "5", "sub"),
});
inSub.Tick();
inSub.Tick(30); // call Sub after 30 s in Default
inSub.Tick();
inSub.Tick(4);
Check.False(inSub.Has("sub"), "4 s into Sub");
inSub.Tick(1);
Check.Eq(inSub.Var("sub"), "1", "5 s into Sub");
// SetState to the state it is already in: the plain clock restarts, the P clock does not.
var self = new Rig(rules: new[]
{
Mark("Default", C.SecondsInStateP_GE, "15", "p"),
Rule("Default", C.SecondsInState_GE, "10", A.SetMetaState, "Default"),
});
self.Tick();
self.Tick(10); // SetState Default
self.Tick();
self.Tick(5); // 15 s since Default was entered
Check.Eq(self.Var("p"), "1", "SetState to the same state keeps the P clock");
// A move to another state restarts it.
var move = new Rig(rules: new[]
{
Rule("Default", C.SecondsInState_GE, "10", A.SetMetaState, "Hunt"),
Mark("Hunt", C.SecondsInStateP_GE, "3", "h"),
});
move.Tick();
move.Tick(10);
move.Tick();
move.Tick(2.9);
Check.False(move.Has("h"), "2.9 s into Hunt (restarted on the move)");
move.Tick(0.1);
Check.Eq(move.Var("h"), "1", "3 s into Hunt");
// Loading a meta restarts it, even when the start state has the same name.
var load = new Rig(rules: Mark("Default", C.SecondsInStateP_GE, "15", "p"));
load.Tick();
load.Tick(10);
load.S.ForceStateReset = true;
load.S.MetaCallStackReset = true; // what a meta load sets
load.Tick();
load.Tick(10); // 20 s in Default, 10 s since the load
Check.False(load.Has("p"), "10 s since the meta load");
load.Tick(5);
Check.Eq(load.Var("p"), "1", "15 s since the meta load");
}
private static void PercentConditionsAreGE()
{
var rig = new Rig();

View file

@ -42,9 +42,8 @@ internal static class NativeLootTests
r.Add("loot native: profile JSON round trip keeps rules and order", JsonRoundTrip);
r.Add("loot native: malformed or missing JSON profile", MalformedJson);
r.Add("loot native: an invalid regex in a String rule does not match", InvalidRegexDoesNotThrow); // was a known failure; fixed by a2902c3
r.KnownFailure("loot native: Keep # with a count of 0 survives a save and load",
"LootJsonContext skips default values when writing, so KeepCount 0 is left out and loads back as the initializer's 1",
KeepCountZeroRoundTrip);
r.Add("loot native: Keep # with a count of 0 survives a save and load", KeepCountZeroRoundTrip); // was a known failure
r.Add("loot native: salvage combine turned off survives a save and load", SalvageCombineOffRoundTrip);
}
private static LootRule Rule(string name, LootAction action, params LootCondition[] conds)
@ -366,4 +365,16 @@ internal static class NativeLootTests
Profile(rule).Save(path);
Check.Eq(LootProfile.Load(path).Rules[0].KeepCount, 0, "KeepCount after reload");
}
/// <summary>LootJsonContext skips default values: SalvageCombine.Enabled = false was left out and loaded back as true.</summary>
private static void SalvageCombineOffRoundTrip()
{
var p = Profile(Rule("any", LootAction.Salvage));
p.SalvageCombine = new SalvageCombineSettings { Enabled = false };
string path = TempFile("combine-off.json");
p.Save(path);
var loaded = LootProfile.Load(path);
Check.NotNull(loaded.SalvageCombine, "SalvageCombine after reload");
Check.False(loaded.SalvageCombine?.Enabled ?? true, "SalvageCombine.Enabled stays off");
}
}

View file

@ -0,0 +1,133 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text.Json;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// Loading a profile (login, profile switch) runs LegacyDashboardRenderer.CopySettings, which
// copies the loaded file into the live settings one field at a time. A field with no copy line
// keeps its in-memory default, and the next autosave writes that default over the profile.
// PetAutoRefill, MonsterNameBlacklist and the radar placement were dropped that way.
// - every serialized LegacyUiSettings member set to a non-default value comes through
// CopySettings (catches any field added later without a copy line);
// - a profile written to disk and loaded back serializes unchanged.
internal static class ProfileLoadTests
{
private const BindingFlags Any = BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
public static void Register(Runner r)
{
r.Add("profile: every saved setting survives loading (CopySettings lists each serialized field)", EverySavedFieldIsCopied);
r.Add("profile: settings survive a save and a reload through the profile file", SettingsSurviveReload);
}
/// <summary>LegacyDashboardRenderer.CopySettings(src, dst): what LoadSettings / SwitchProfile run.</summary>
private static void CopySettings(LegacyUiSettings src, LegacyUiSettings dst) =>
typeof(LegacyDashboardRenderer).GetMethod("CopySettings", Any)!.Invoke(null, new object[] { src, dst });
/// <summary>A different value of the member's type that CopySettings' normalizing keeps distinct from the default.</summary>
private static bool TryMutate(string name, Type type, object? value, out object? mutated)
{
mutated = null;
if (name == nameof(LegacyUiSettings.OffhandDefault)) { mutated = "Shield"; return true; } // must parse as an OffhandMode
if (name == nameof(LegacyUiSettings.NavLabelMode)) { mutated = 1; return true; } // NavLabelModes.Clamp: 0..2
Type t = Nullable.GetUnderlyingType(type) ?? type;
if (t == typeof(bool)) { mutated = !((bool?)value ?? false); return true; }
if (t == typeof(int)) { mutated = ((int?)value ?? 0) + 3; return true; } // +3: MovementMode 1/2 map back to 0
if (t == typeof(long)) { mutated = ((long?)value ?? 0) + 3; return true; }
if (t == typeof(uint)) { mutated = ((uint?)value ?? 0) + 3; return true; }
if (t == typeof(float)) { mutated = ((float?)value ?? 0f) + 3f; return true; }
if (t == typeof(double)) { mutated = ((double?)value ?? 0.0) + 3.0; return true; }
if (t == typeof(string)) { mutated = (string?)value + "x"; return true; }
if (t.IsEnum)
{
foreach (object v in Enum.GetValues(t))
if (!v.Equals(value)) { mutated = v; return true; }
}
return false;
}
private static void EverySavedFieldIsCopied()
{
var info = RynthAiJsonContext.Default.LegacyUiSettings;
var defaults = new LegacyUiSettings();
var src = new LegacyUiSettings();
var dst = new LegacyUiSettings();
// Reference members (lists, option objects): dst must end up with a new instance.
var dstOriginal = new Dictionary<string, object?>();
var skipped = new List<string>();
foreach (var p in info.Properties)
{
if (p.Get == null || p.Set == null) continue;
Type t = p.PropertyType;
if (t.IsValueType || t == typeof(string))
{
if (TryMutate(p.Name, t, p.Get(src), out object? m)) p.Set(src, m);
else skipped.Add(p.Name);
}
else
{
dstOriginal[p.Name] = p.Get(dst);
}
}
CopySettings(src, dst);
int members = 0;
var missing = new List<string>();
foreach (var p in info.Properties)
{
if (p.Get == null || p.Set == null) continue;
members++;
if (dstOriginal.TryGetValue(p.Name, out object? before))
{
if (before != null && ReferenceEquals(p.Get(dst), before)) missing.Add(p.Name);
}
else if (!skipped.Contains(p.Name)
&& Equals(p.Get(dst), p.Get(defaults)) && !Equals(p.Get(src), p.Get(defaults)))
{
missing.Add(p.Name);
}
}
Check.True(members > 100, $"the JSON metadata lists the settings ({members} members)");
Check.Eq(skipped.Count, 0, "every value member has a test value (no test value for: " + string.Join(", ", skipped) + ")");
Check.Eq(missing.Count, 0, "members CopySettings leaves at their default: " + string.Join(", ", missing));
}
private static void SettingsSurviveReload()
{
var saved = new LegacyUiSettings();
saved.ItemInfoOnSelect = !saved.ItemInfoOnSelect;
saved.PetAutoRefill = !saved.PetAutoRefill;
saved.MonsterNameBlacklist.Add("Drudge Skulker");
saved.RadarPosX = 120f;
saved.RadarSizeY = 300f;
string path = Path.Combine(Program.TempRoot, "profile-load", "Default.json");
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
File.WriteAllText(path, JsonSerializer.Serialize(saved, RynthAiJsonContext.Default.LegacyUiSettings));
// LoadSettings: read the file, copy it into the live settings object (a fresh session).
var loaded = JsonSerializer.Deserialize(File.ReadAllText(path), RynthAiJsonContext.Default.LegacyUiSettings)!;
var live = new LegacyUiSettings();
CopySettings(loaded, live);
Check.Eq(live.ItemInfoOnSelect, saved.ItemInfoOnSelect, "describe items when selected");
Check.Eq(live.PetAutoRefill, saved.PetAutoRefill, "pet auto refill");
Check.True(live.MonsterNameBlacklist.Contains("Drudge Skulker"), "monster blacklist");
Check.Eq(live.RadarPosX, 120f, "radar position");
Check.Eq(live.RadarSizeY, 300f, "radar size");
// Unchanged JSON means the autosave right after login has nothing to write over the file.
Check.Eq(JsonSerializer.Serialize(live, RynthAiJsonContext.Default.LegacyUiSettings),
JsonSerializer.Serialize(saved, RynthAiJsonContext.Default.LegacyUiSettings),
"the reloaded profile saves back unchanged (autosave writes nothing different)");
}
}

View file

@ -28,7 +28,7 @@ namespace RynthCore.Engine.UI.ScriptWindows
namespace RynthInventory.Tests
{
internal static class Program
internal static partial class Program
{
private static int _pass, _fail;
private static string _temp = "";
@ -64,6 +64,7 @@ namespace RynthInventory.Tests
Run("scheduler: unchanged content is not rewritten", SchedulerUnchanged);
Run("window display lists parse in the engine", Pages);
Run("window events", Events);
Run("vault feed (/mule-data)", VaultTests);
}
finally
{

View file

@ -0,0 +1,138 @@
using System;
using System.Collections.Generic;
using System.Linq;
using RynthCore.Plugin.RynthInventory.Data;
using RynthCore.Plugin.RynthInventory.Scanning;
namespace RynthInventory.Tests
{
// The Aelrynth account vault: /mule-data answers, one "~ael1" line a page (Aeshnidae.Mule MuleData.cs).
internal static partial class Program
{
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 VaultTests()
{
const string A = "{\"o\":2147483649,\"w\":100,\"n\":\"Acid Assagai\",\"i\":100667000,\"u\":100667001,\"v\":100667002,\"s\":3,\"m\":100,\"y\":1,\"e\":1}";
const string B = "{\"o\":2147483650,\"w\":101,\"n\":\"Pyreal\",\"i\":100667003,\"y\":8192}";
// Two pages, asked one after the other, filed as one record.
{
(VaultFeed v, List<string> sent) = NewVault();
Check(v.Ask(1000), "ask starts");
Eq(sent.Count == 1 ? sent[0] : "?", "/mule-data", "page 1 asked first");
Check(v.ShouldEat(VaultPage(1, 2, 2, A)), "page 1 is eaten");
v.Tick(1100, "Tom");
Eq(sent.Count == 2 ? sent[1] : "?", "/mule-data 2", "page 2 asked when page 1 came");
Check(v.Record == null, "nothing filed before the last page");
Check(v.ShouldEat(VaultPage(2, 2, 2, B)), "page 2 is eaten");
v.Tick(1200, "Tom");
StorageRecord? r = v.Record;
Check(r != null && v.TakeChanged() && !v.TakeChanged(), "filed once");
Eq(r?.Items.Count ?? -1, 2, "both pages' items");
Eq(r?.Id ?? 0, VaultFeed.VaultId("tom"), "id follows the account, case-blind");
Check((r?.Id ?? 0) >> 24 == 0xFF, "id is a stand-in, far from real objects");
Eq(r?.Label ?? "", "Account vault", "label");
ItemRecord a = r!.Items[0];
Eq(a.Name, "Acid Assagai", "name"); Eq(a.Icon, 100667000u, "icon"); Eq(a.Underlay, 100667001u, "underlay");
Eq(a.Overlay, 100667002u, "overlay"); Eq(a.Stack, 3, "stack"); Eq(a.MaxStack, 100, "max stack");
Eq(a.Place, ItemPlace.Storage, "place");
Eq(r.Items[1].Stack, 1, "no stack field is a stack of 1");
Eq(v.Status, VaultFeed.State.Idle, "idle again");
}
// Other plugins' lines are left alone.
{
(VaultFeed v, _) = NewVault();
v.Ask(0);
Check(!v.ShouldEat("~ael1 {\"t\":\"inspect\",\"ok\":true}"), "the Companion's line stays visible");
Check(!v.ShouldEat("Welcome to Aelrynth"), "ordinary chat stays visible");
Check(!v.ShouldEat(null), "null is fine");
}
// A server without the command.
{
(VaultFeed v, List<string> sent) = NewVault();
v.Ask(0);
Check(v.ShouldEat("Unknown command: /mule-data"), "the unknown-command reply is eaten while we wait");
v.Tick(100, "tom");
Eq(v.Status, VaultFeed.State.Unsupported, "unsupported");
Check(!v.Ask(200), "not asked again");
Eq(sent.Count, 1, "one probe, no more");
Check(v.Ask(300, force: true), "/ginv vault asks anyway");
}
{
(VaultFeed v, _) = NewVault();
Check(!v.ShouldEat("Unknown command: /mule-data"), "an unknown-command line we did not provoke is left alone");
}
// 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");
Eq(v.Status, VaultFeed.State.Waiting, "waiting");
v.Tick(2000, "tom");
Eq(sent.Count, 1, "not before the retry delay");
v.Tick(3500, "tom");
Eq(sent.Count, 2, "asked again after it");
Check(v.Record == null, "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(v.Status != VaultFeed.State.Asking || sent.Count < 12, "it gives up after a few tries");
Check(v.Record == null, "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(v.Record == null, "a mismatched read is not filed");
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");
Eq(v.Status, VaultFeed.State.Idle, "no answer in time");
Check(v.Ask(21_000), "can ask again");
}
// A line typed by hand while we are not asking is eaten (it is ours) but changes nothing.
{
(VaultFeed v, _) = NewVault();
Check(v.ShouldEat(VaultPage(1, 1, 1, A)), "eaten");
v.Tick(0, "tom");
Check(v.Record == null, "ignored when we did not ask");
}
// 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(v.Record == null && v.Status == VaultFeed.State.Idle, "bad JSON drops the read");
}
}
}
}