rimworld-blax-slaves/Tests/BlaxSlavesTests/Source/SettingsTests.cs

607 lines
31 KiB
C#
Raw Permalink Normal View History

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using BlaxSlaves;
using HarmonyLib;
using RimWorld;
using Verse;
namespace BlaxSlavesTests
{
/// <summary>
/// Smoke tests for the tabbed settings (BlaxSlavesSettings, BlaxSlavesMod), the Compat table and the
/// sibling hooks. Settings files go through vanilla's own LoadedModManager.WriteModSettings and
/// ReadModSettings under a test-only mod id, so they land in the test run's Config folder (run-tests.ps1
/// passes -savedatafolder) and are deleted again. The window itself needs OnGUI, so it isn't drawn.
/// </summary>
public static class SettingsTests
{
private const string TestModId = "BlaxSlavesSettingsTest";
private const string Handle = nameof(BlaxSlavesMod);
// Each field belongs to exactly one tab: the tab that draws it, whose Reset method restores it.
private static readonly string[] GeneralFields =
{
"returnRunaways", "returnChance", "returnDelayMinDays", "returnDelayMaxDays",
"suppressSlaveHarmMood", "keepRelationGrief", "showTimeInSlaveTab",
};
// traderBrandChance is a 1.1 setting (Scribe key unchanged) that the Trade tab draws, so ResetTrade owns it.
private static readonly string[] TradeFields =
{
"traderBrandChance", "buyModeEnabled", "defaultPurchaseMode", "allTradersBuySlaves", "visitorsBuySlaves",
"antiSlaveryTraders", "slaveStockIgnoresColonySize", "slaveSellFactor", "slaveBuyFactor",
};
// Workshop folder (published file id) -> packageId in that item's About.xml, checked 2026-11-28.
private static readonly Dictionary<string, string> ReplacedWorkshopIds = new Dictionary<string, string>
{
{ "3838162426", Compat.TradeAsSlaveOrColonist },
{ "2799461327", Compat.EverybodyBuysSlaves },
{ "3361231919", Compat.SyrMoreSlaves },
};
private static readonly string[] SettingsUiKeys =
{
"BlaxSlaves_TabTrade", "BlaxSlaves_TabGeneral", "BlaxSlaves_TabCompat", "BlaxSlaves_ResetTab",
"BlaxSlaves_SettingNeedsIdeology", "BlaxSlaves_SettingBuyMode", "BlaxSlaves_SettingBuyModeTip",
"BlaxSlaves_SettingBuyModeStandsDown", "BlaxSlaves_SettingPurchaseMode", "BlaxSlaves_SettingPurchaseVanilla",
"BlaxSlaves_SettingPurchaseSlave", "BlaxSlaves_SettingPurchaseColonist", "BlaxSlaves_SettingAllTradersBuy",
"BlaxSlaves_SettingAllTradersBuyTip", "BlaxSlaves_SettingVisitorsBuy", "BlaxSlaves_SettingVisitorsBuyTip",
"BlaxSlaves_SettingAntiSlavery", "BlaxSlaves_SettingAntiSlaveryBuy", "BlaxSlaves_SettingAntiSlaveryRefuse",
"BlaxSlaves_SettingStockAnySize", "BlaxSlaves_SettingStockAnySizeTip", "BlaxSlaves_SettingTraderBrand",
"BlaxSlaves_SettingSellFactor", "BlaxSlaves_SettingSellFactorTip", "BlaxSlaves_SettingBuyFactor",
"BlaxSlaves_SettingBuyFactorTip", "BlaxSlaves_SettingReturn", "BlaxSlaves_SettingReturnTip",
"BlaxSlaves_SettingReturnChance", "BlaxSlaves_SettingReturnDelayMin", "BlaxSlaves_SettingReturnDelayMax",
"BlaxSlaves_SettingMood", "BlaxSlaves_SettingMoodTip", "BlaxSlaves_SettingGrief", "BlaxSlaves_SettingGriefTip",
"BlaxSlaves_SettingTimeAsSlave", "BlaxSlaves_SettingTimeAsSlaveTip", "BlaxSlaves_CompatSiblings",
"BlaxSlaves_CompatNoSiblings", "BlaxSlaves_CompatReplaced", "BlaxSlaves_CompatNoneActive",
};
// ---- mod and window ---------------------------------------------------------------
[BlaxTest("settings: mod has a settings category and Settings is the mod's own instance")]
public static void ModRegistered()
{
BlaxSlavesMod mod = LoadedModManager.GetMod<BlaxSlavesMod>();
T.NotNull(mod, "LoadedModManager.GetMod<BlaxSlavesMod>()");
T.Check(!mod.SettingsCategory().NullOrEmpty(), "SettingsCategory() is empty, so the mod gets no settings window");
T.NotNull(BlaxSlavesMod.Settings, "BlaxSlavesMod.Settings");
T.Check(ReferenceEquals(mod.GetSettings<BlaxSlavesSettings>(), BlaxSlavesMod.Settings),
"BlaxSlavesMod.Settings is not the instance the mod writes on close (GetSettings<BlaxSlavesSettings>())");
var missing = SettingsUiKeys.Where(k => !k.CanTranslate()).ToList();
T.Check(missing.Count == 0, "settings window strings missing from Keyed: " + string.Join(", ", missing));
}
[BlaxTest("settings: closing the window (WriteSettings) raises SettingsChanged once, without errors")]
public static void WriteSettingsRaisesChanged()
{
BlaxSlavesMod mod = LoadedModManager.GetMod<BlaxSlavesMod>();
T.NotNull(mod, "LoadedModManager.GetMod<BlaxSlavesMod>()");
BlaxSlavesSettings before = Copy(BlaxSlavesMod.Settings);
int raised = 0;
Action handler = () => raised++;
BlaxSlavesMod.SettingsChanged += handler;
try
{
// Writes the current (startup) values back to the test run's own Config folder and lets every
// feature re-apply itself, as closing the window does.
mod.WriteSettings();
}
finally
{
BlaxSlavesMod.SettingsChanged -= handler;
StopScribe();
}
T.Equal(1, raised, "SettingsChanged raised by WriteSettings");
List<string> changed = Diff(before, BlaxSlavesMod.Settings, AllNames());
T.Check(changed.Count == 0, "WriteSettings changed in-range settings: " + string.Join("; ", changed));
}
// ---- Scribe -----------------------------------------------------------------------
[BlaxTest("settings: every field round-trips through the settings file")]
public static void RoundTrip()
{
BlaxSlavesSettings src = Varied();
BlaxSlavesSettings defaults = new BlaxSlavesSettings();
var notVaried = Fields.Where(f => Same(f.GetValue(src), f.GetValue(defaults))).Select(f => f.Name).ToList();
T.Check(notVaried.Count == 0,
"test can't give these fields a valid non-default value, so the round trip proves nothing for them (extend Varied()): " + string.Join(", ", notVaried));
string path = SettingsPath();
try
{
LoadedModManager.WriteModSettings(TestModId, Handle, src);
StopScribe();
T.Check(File.Exists(path), "WriteModSettings wrote no file at " + path + " (vanilla's settings file name changed?)");
BlaxSlavesSettings back = LoadedModManager.ReadModSettings<BlaxSlavesSettings>(TestModId, Handle);
StopScribe();
T.NotNull(back, "ReadModSettings result");
List<string> diff = Diff(src, back, AllNames());
T.Check(diff.Count == 0, "settings changed over write and read (missing Scribe_Values key or wrong default?): " + string.Join("; ", diff));
}
finally
{
StopScribe();
Delete(path);
}
}
[BlaxTest("settings: a 1.1 settings file loads its values, 1.2 keys get their defaults")]
public static void OldFileLoads()
{
// The 7 keys the published 1.1 DLL scribes, written the way WriteModSettings writes them.
const string xml =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
"<SettingsBlock>\n" +
"\t<ModSettings Class=\"BlaxSlaves.BlaxSlavesSettings\">\n" +
"\t\t<returnRunaways>False</returnRunaways>\n" +
"\t\t<returnChance>0.5</returnChance>\n" +
"\t\t<returnDelayMinDays>5</returnDelayMinDays>\n" +
"\t\t<returnDelayMaxDays>20</returnDelayMaxDays>\n" +
"\t\t<suppressSlaveHarmMood>False</suppressSlaveHarmMood>\n" +
"\t\t<keepRelationGrief>False</keepRelationGrief>\n" +
"\t\t<traderBrandChance>0.1</traderBrandChance>\n" +
"\t</ModSettings>\n" +
"</SettingsBlock>\n";
var expected = new BlaxSlavesSettings
{
returnRunaways = false,
returnChance = 0.5f,
returnDelayMinDays = 5,
returnDelayMaxDays = 20,
suppressSlaveHarmMood = false,
keepRelationGrief = false,
traderBrandChance = 0.1f,
};
BlaxSlavesSettings loaded = LoadFile(xml);
List<string> diff = Diff(expected, loaded, AllNames());
T.Check(diff.Count == 0, "1.1 settings file loaded wrong (renamed Scribe key?): " + string.Join("; ", diff));
}
[BlaxTest("settings: loading a hand-edited file clamps out-of-range values")]
public static void LoadClamps()
{
const string xml =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
"<SettingsBlock>\n" +
"\t<ModSettings Class=\"BlaxSlaves.BlaxSlavesSettings\">\n" +
"\t\t<returnChance>3</returnChance>\n" +
"\t\t<returnDelayMinDays>0</returnDelayMinDays>\n" +
"\t\t<returnDelayMaxDays>500</returnDelayMaxDays>\n" +
"\t\t<traderBrandChance>-1</traderBrandChance>\n" +
"\t\t<defaultPurchaseMode>9</defaultPurchaseMode>\n" +
"\t\t<antiSlaveryTraders>-4</antiSlaveryTraders>\n" +
"\t\t<slaveSellFactor>5</slaveSellFactor>\n" +
"\t\t<slaveBuyFactor>0.01</slaveBuyFactor>\n" +
"\t</ModSettings>\n" +
"</SettingsBlock>\n";
var expected = new BlaxSlavesSettings
{
returnChance = 1f,
returnDelayMinDays = 1,
returnDelayMaxDays = 60,
traderBrandChance = 0f,
defaultPurchaseMode = BlaxSlavesSettings.PurchaseAlwaysColonist,
antiSlaveryTraders = BlaxSlavesSettings.AntiSlaveryBuyAnyway,
slaveSellFactor = 1f,
slaveBuyFactor = 0.3f,
};
BlaxSlavesSettings loaded = LoadFile(xml);
List<string> diff = Diff(expected, loaded, AllNames());
T.Check(diff.Count == 0, "out-of-range values not clamped on load (Clamp no longer runs in PostLoadInit?): " + string.Join("; ", diff));
}
// ---- Clamp and reset --------------------------------------------------------------
[BlaxTest("settings: Clamp bounds out-of-range values and keeps valid ones")]
public static void ClampBounds()
{
var low = new BlaxSlavesSettings
{
returnChance = -0.5f,
returnDelayMinDays = -3,
returnDelayMaxDays = -3,
traderBrandChance = -0.1f,
defaultPurchaseMode = -1,
antiSlaveryTraders = -1,
slaveSellFactor = 0f,
slaveBuyFactor = 0.29f,
};
low.Clamp();
var lowExpected = new BlaxSlavesSettings
{
returnChance = 0f,
returnDelayMinDays = 1,
returnDelayMaxDays = 1,
traderBrandChance = 0f,
defaultPurchaseMode = BlaxSlavesSettings.PurchaseVanilla,
antiSlaveryTraders = BlaxSlavesSettings.AntiSlaveryBuyAnyway,
slaveSellFactor = 0.3f,
slaveBuyFactor = 0.3f,
};
List<string> diff = Diff(lowExpected, low, AllNames());
T.Check(diff.Count == 0, "too-low values: " + string.Join("; ", diff));
var high = new BlaxSlavesSettings
{
returnChance = 1.5f,
returnDelayMinDays = 31,
returnDelayMaxDays = 61,
traderBrandChance = 2f,
defaultPurchaseMode = 3,
antiSlaveryTraders = 2,
slaveSellFactor = 1.01f,
slaveBuyFactor = 7f,
};
high.Clamp();
var highExpected = new BlaxSlavesSettings
{
returnChance = 1f,
returnDelayMinDays = 30,
returnDelayMaxDays = 60,
traderBrandChance = 1f,
defaultPurchaseMode = BlaxSlavesSettings.PurchaseAlwaysColonist,
antiSlaveryTraders = BlaxSlavesSettings.AntiSlaveryRefuse,
slaveSellFactor = 1f,
slaveBuyFactor = 1f,
};
diff = Diff(highExpected, high, AllNames());
T.Check(diff.Count == 0, "too-high values: " + string.Join("; ", diff));
var crossed = new BlaxSlavesSettings { returnDelayMinDays = 12, returnDelayMaxDays = 5 };
crossed.Clamp();
T.Equal(12, crossed.returnDelayMinDays, "earliest return after Clamp with latest < earliest");
T.Equal(12, crossed.returnDelayMaxDays, "latest return after Clamp with latest < earliest (raised to the earliest)");
BlaxSlavesSettings valid = Varied();
BlaxSlavesSettings copy = Copy(valid);
valid.Clamp();
diff = Diff(copy, valid, AllNames());
T.Check(diff.Count == 0, "Clamp changed valid values: " + string.Join("; ", diff));
var defaults = new BlaxSlavesSettings();
defaults.Clamp();
diff = Diff(new BlaxSlavesSettings(), defaults, AllNames());
T.Check(diff.Count == 0, "Clamp changed the defaults: " + string.Join("; ", diff));
}
[BlaxTest("settings: ResetTrade and ResetGeneral each restore only their own tab")]
public static void ResetPerTab()
{
var listed = new HashSet<string>(GeneralFields.Concat(TradeFields));
var unlisted = AllNames().Where(n => !listed.Contains(n)).ToList();
var unknown = listed.Where(n => typeof(BlaxSlavesSettings).GetField(n) == null).ToList();
var onBothTabs = GeneralFields.Intersect(TradeFields).ToList();
T.Check(unknown.Count == 0, "test lists fields BlaxSlavesSettings doesn't have (renamed?): " + string.Join(", ", unknown));
T.Check(unlisted.Count == 0, "new settings fields not assigned to a tab in this test (and maybe in no Reset method): " + string.Join(", ", unlisted));
T.Check(onBothTabs.Count == 0, "test assigns fields to both tabs, but each has one owner: " + string.Join(", ", onBothTabs));
BlaxSlavesSettings defaults = new BlaxSlavesSettings();
BlaxSlavesSettings varied = Varied();
BlaxSlavesSettings trade = Copy(varied);
trade.ResetTrade();
List<string> notReset = Diff(defaults, trade, TradeFields);
List<string> wronglyReset = Diff(varied, trade, GeneralFields);
T.Check(notReset.Count == 0, "ResetTrade left Trade fields changed: " + string.Join("; ", notReset));
T.Check(wronglyReset.Count == 0, "ResetTrade touched General fields: " + string.Join("; ", wronglyReset));
BlaxSlavesSettings general = Copy(varied);
general.ResetGeneral();
notReset = Diff(defaults, general, GeneralFields);
wronglyReset = Diff(varied, general, TradeFields);
T.Check(notReset.Count == 0, "ResetGeneral left General fields changed: " + string.Join("; ", notReset));
T.Check(wronglyReset.Count == 0, "ResetGeneral touched Trade fields: " + string.Join("; ", wronglyReset));
BlaxSlavesSettings both = Copy(varied);
both.ResetTrade();
both.ResetGeneral();
List<string> left = Diff(defaults, both, AllNames());
T.Check(left.Count == 0, "both reset buttons together leave fields changed: " + string.Join("; ", left));
}
[BlaxTest("settings: every setting a tab draws is one its own reset button restores")]
public static void ResetOwnsDrawnFields()
{
// The tabs need OnGUI, so the fields each one draws are read from its IL. Together with ResetPerTab
// this pins "Reset this tab" to exactly the controls the player sees on that tab.
var problems = new List<string>();
foreach (var (draw, reset, owned) in new[] { ("DoTrade", "ResetTrade", TradeFields), ("DoGeneral", "ResetGeneral", GeneralFields) })
{
MethodInfo method = AccessTools.DeclaredMethod(typeof(BlaxSlavesMod), draw);
T.NotNull(method, "BlaxSlavesMod." + draw + " (renamed?)");
List<string> drawn = SettingsFieldsUsedBy(method);
T.Info(draw + " uses " + string.Join(", ", drawn));
problems.AddRange(drawn.Where(n => !owned.Contains(n)).Select(n => $"{draw} draws {n}, but {reset} doesn't restore it"));
}
T.Check(problems.Count == 0, string.Join("; ", problems));
}
[BlaxTest("settings: the window's listing stays one column, so the scroll height counts every row after a tab switch")]
public static void SettingsListingOneColumn()
{
// Without maxOneColumn, a row past last frame's viewHeight wraps into a second column outside the
// scroll group and CurHeight counts only that column, so a tall tab drawn right after a short one
// loses its last rows (the Reset button) for good.
MethodInfo window = AccessTools.DeclaredMethod(typeof(BlaxSlavesMod), nameof(BlaxSlavesMod.DoSettingsWindowContents));
T.NotNull(window, "BlaxSlavesMod.DoSettingsWindowContents");
List<KeyValuePair<OpCode, object>> body = PatchProcessor.ReadMethodBody(window).ToList();
T.Check(body.Count > 0, "could not read the IL of DoSettingsWindowContents");
bool setsOneColumn = Enumerable.Range(1, body.Count - 1)
.Any(i => body[i].Key == OpCodes.Stfld && IsMaxOneColumn(body[i].Value) && body[i - 1].Key == OpCodes.Ldc_I4_1);
T.Check(setsOneColumn, "DoSettingsWindowContents doesn't set maxOneColumn = true on its listing");
foreach (Type type in new[] { typeof(Listing), typeof(Listing_Standard) })
{
MethodInfo begin = AccessTools.DeclaredMethod(type, nameof(Listing.Begin), new[] { typeof(UnityEngine.Rect) });
if (begin == null)
continue;
bool resets = PatchProcessor.ReadMethodBody(begin).Any(op => op.Key == OpCodes.Stfld && IsMaxOneColumn(op.Value));
T.Check(!resets, type.Name + ".Begin now resets maxOneColumn, so setting it before Begin has no effect");
}
// The layout the fix relies on: rows past the rect's height stay in the first column and CurHeight
// grows with them. The wrapping listing shows the test really crosses the rect's height.
const float rectHeight = 100f, rowHeight = 30f;
const int rows = 10;
var oneColumn = new LayoutOnlyListing { maxOneColumn = true };
var wrapping = new LayoutOnlyListing();
var oneColumnX = new List<float>();
var wrappingX = new List<float>();
oneColumn.Begin(new UnityEngine.Rect(0f, 0f, 400f, rectHeight));
wrapping.Begin(new UnityEngine.Rect(0f, 0f, 400f, rectHeight));
for (int i = 0; i < rows; i++)
{
oneColumnX.Add(oneColumn.GetRect(rowHeight).x);
wrappingX.Add(wrapping.GetRect(rowHeight).x);
}
T.Check(wrappingX.Any(x => x > 0f), "a listing without maxOneColumn didn't wrap past its rect's height, so this check proves nothing (did Listing change?)");
T.Check(oneColumnX.All(x => x == 0f), "a maxOneColumn listing still wrapped rows into a second column: x = " + string.Join(", ", oneColumnX));
T.Equal(rows * rowHeight, oneColumn.CurHeight, "CurHeight of a maxOneColumn listing after " + rows + " rows of " + rowHeight);
}
// ---- Compat -----------------------------------------------------------------------
[BlaxTest("compat: replaced-mod table has unique packageIds that resolve without exceptions")]
public static void ReplacedTable()
{
T.Check(Compat.Replaced != null && Compat.Replaced.Count > 0, "Compat.Replaced is empty");
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var problems = new List<string>();
foreach (Compat.ReplacedMod m in Compat.Replaced)
{
if (m.packageId.NullOrEmpty() || m.packageId.Trim() != m.packageId || m.packageId.Contains(" "))
problems.Add("bad packageId '" + m.packageId + "'");
else if (!seen.Add(m.packageId))
problems.Add("duplicate packageId " + m.packageId);
if (m.name.NullOrEmpty())
problems.Add(m.packageId + ": no name");
if (m.note.NullOrEmpty() || !m.note.CanTranslate())
problems.Add(m.packageId + ": note key '" + m.note + "' missing from Keyed");
try
{
bool active = Compat.IsActive(m.packageId);
string note = m.note.NullOrEmpty() ? "" : (string)m.note.Translate();
if (active)
T.Info("active: " + m.name + " (" + m.packageId + "): " + note);
}
catch (Exception e)
{
problems.Add(m.packageId + ": resolving threw " + e.GetType().Name + ": " + e.Message);
}
}
T.Check(problems.Count == 0, string.Join("; ", problems));
foreach (string id in new[] { Compat.TradeAsSlaveOrColonist, Compat.EverybodyBuysSlaves, Compat.SyrMoreSlaves })
T.Check(seen.Contains(id), "Compat.Replaced misses " + id);
// Where a replaced mod is installed from the Workshop, its About.xml must carry the id we look for.
int checkedMods = 0;
foreach (ModMetaData mod in ModLister.AllInstalledMods)
{
if (mod?.RootDir == null || !mod.OnSteamWorkshop || !ReplacedWorkshopIds.TryGetValue(mod.FolderName, out string id))
continue;
checkedMods++;
T.Check(string.Equals(mod.PackageIdPlayerFacing, id, StringComparison.OrdinalIgnoreCase),
$"Workshop item {mod.FolderName} ({mod.Name}) has packageId {mod.PackageIdPlayerFacing}, Compat looks for {id}");
}
T.Info(checkedMods + " replaced mod(s) installed from the Workshop, packageIds checked against their About.xml");
}
[BlaxTest("compat: IsActive finds Blax Slaves and the base game, not a made-up id")]
public static void IsActiveWorks()
{
T.Check(Compat.IsActive("blax.slaves"), "Compat.IsActive(\"blax.slaves\") is false while Blax Slaves runs");
T.Check(Compat.IsActive("Blax.Slaves"), "Compat.IsActive is case-sensitive (packageIds aren't)");
T.Check(Compat.IsActive("ludeon.rimworld"), "Compat.IsActive(\"ludeon.rimworld\") is false");
T.Check(!Compat.IsActive("blax.slaves.no.such.mod"), "Compat.IsActive is true for a made-up packageId");
}
// ---- siblings ---------------------------------------------------------------------
[BlaxTest("siblings: Describe returns text, calls without the sibling mods are safe no-ops")]
public static void SiblingsNoOps()
{
bool castes = Compat.IsActive(Siblings.CastesId);
bool zones = Compat.IsActive(Siblings.ZonesId);
string described = Siblings.Describe();
T.Info($"castes active={castes} bound={Siblings.CastesBound} v{Siblings.CastesVersion}, zones active={zones} bound={Siblings.ZonesBound} v{Siblings.ZonesVersion}: \"{described}\"");
T.Check(!described.NullOrEmpty(), "Siblings.Describe() returned nothing");
if (!castes)
T.Check(!Siblings.CastesBound && Siblings.CastesVersion == 0, "Blax Castes isn't active but its API counts as bound");
if (!zones)
T.Check(!Siblings.ZonesBound && Siblings.ZonesVersion == 0, "Blax Zones isn't active but its API counts as bound");
if (!castes && !zones)
T.Equal((string)"BlaxSlaves_CompatNoSiblings".Translate(), described, "Describe() without siblings");
Pawn slave = Fixtures.ColonySlave();
// Null arguments are no-ops whether or not the siblings are bound.
Siblings.CastesNotifyJoined(null, Siblings.ReasonRunawayReturned);
Siblings.CastesHintJoinReason(null, null);
Siblings.CastesNotifyJoinedNextTick(null, Siblings.ReasonRunawayReturned);
T.Check(!Siblings.ZonesTryFindDropSpot(null, slave, out IntVec3 nullMapCell) && nullMapCell == IntVec3.Invalid,
"ZonesTryFindDropSpot with no map found a cell");
T.Check(!Siblings.ZonesTryFindDropSpot(Fixtures.Map, null, out IntVec3 nullThingCell) && nullThingCell == IntVec3.Invalid,
"ZonesTryFindDropSpot with no thing found a cell");
if (Siblings.CastesBound)
T.Info("Blax Castes is bound; skipped the unbound Castes calls so the test pawn doesn't reach it");
else
{
Siblings.CastesNotifyJoined(slave, Siblings.ReasonRunawayReturned);
Siblings.CastesHintJoinReason(slave, Siblings.ReasonRunawayReturned);
int queuedBefore = NotifyQueueCount();
Siblings.CastesNotifyJoinedNextTick(slave, Siblings.ReasonRunawayReturned);
T.Equal(queuedBefore, NotifyQueueCount(), "NotifyJoined queue length after queueing without Blax Castes");
Siblings.Tick();
}
if (Siblings.ZonesBound)
T.Info("Blax Zones is bound; skipped the unbound drop spot check");
else
{
bool found = Siblings.ZonesTryFindDropSpot(Fixtures.Map, slave, out IntVec3 cell);
T.Check(!found && cell == IntVec3.Invalid, $"ZonesTryFindDropSpot without Blax Zones returned {found} with cell {cell}");
}
}
// ---- helpers ----------------------------------------------------------------------
private static FieldInfo[] Fields => typeof(BlaxSlavesSettings).GetFields(BindingFlags.Public | BindingFlags.Instance);
private static IEnumerable<string> AllNames() => Fields.Select(f => f.Name);
/// <summary>The BlaxSlavesSettings instance fields a method reads, writes or passes by ref, from its IL.</summary>
private static List<string> SettingsFieldsUsedBy(MethodInfo method)
{
List<KeyValuePair<OpCode, object>> body = PatchProcessor.ReadMethodBody(method).ToList();
T.Check(body.Count > 0, "could not read the IL of " + method.Name);
return body.Select(op => op.Value).OfType<FieldInfo>()
.Where(f => f.DeclaringType == typeof(BlaxSlavesSettings) && !f.IsStatic && !f.IsLiteral)
.Select(f => f.Name).Distinct().OrderBy(n => n).ToList();
}
private static bool IsMaxOneColumn(object operand) =>
operand is FieldInfo f && f.DeclaringType == typeof(Listing) && f.Name == nameof(Listing.maxOneColumn);
/// <summary>Lays out rows like Listing_Standard but skips Widgets.BeginGroup and EndGroup, which need OnGUI.</summary>
private sealed class LayoutOnlyListing : Listing_Standard
{
public override void Begin(UnityEngine.Rect rect)
{
listingRect = rect;
curX = 0f;
curY = 0f;
}
public override void End() { }
}
/// <summary>Every field moved off its default to a value Clamp keeps.</summary>
private static BlaxSlavesSettings Varied()
{
var defaults = new BlaxSlavesSettings();
var s = new BlaxSlavesSettings();
foreach (FieldInfo f in Fields)
{
switch (f.GetValue(defaults))
{
case bool b:
f.SetValue(s, !b);
break;
case int i:
f.SetValue(s, i + 1);
break;
case float x:
f.SetValue(s, x >= 0.5f ? x - 0.15f : x + 0.15f);
break;
}
}
s.Clamp();
return s;
}
private static BlaxSlavesSettings Copy(BlaxSlavesSettings from)
{
var s = new BlaxSlavesSettings();
foreach (FieldInfo f in Fields)
f.SetValue(s, f.GetValue(from));
return s;
}
private static bool Same(object a, object b) =>
a is float fa && b is float fb ? Math.Abs(fa - fb) < 1e-4f : Equals(a, b);
private static List<string> Diff(BlaxSlavesSettings expected, BlaxSlavesSettings actual, IEnumerable<string> names)
{
var result = new List<string>();
foreach (string name in names)
{
FieldInfo f = typeof(BlaxSlavesSettings).GetField(name, BindingFlags.Public | BindingFlags.Instance);
if (f == null)
{
result.Add(name + ": no such field");
continue;
}
object e = f.GetValue(expected), a = f.GetValue(actual);
if (!Same(e, a))
result.Add($"{name}: expected {e}, got {a}");
}
return result;
}
/// <summary>Where vanilla's Read/WriteModSettings put the test mod's file (LoadedModManager.GetSettingsFilename).</summary>
private static string SettingsPath() =>
Path.Combine(GenFilePaths.ConfigFolderPath, GenText.SanitizeFilename($"Mod_{TestModId}_{Handle}.xml"));
private static BlaxSlavesSettings LoadFile(string xml)
{
string path = SettingsPath();
try
{
File.WriteAllText(path, xml);
BlaxSlavesSettings loaded = LoadedModManager.ReadModSettings<BlaxSlavesSettings>(TestModId, Handle);
StopScribe();
T.NotNull(loaded, "ReadModSettings result");
return loaded;
}
finally
{
StopScribe();
Delete(path);
}
}
/// <summary>A Scribe left mid-load or mid-save would break the runner's save and reload after phase 1.</summary>
private static void StopScribe()
{
if (Scribe.mode == LoadSaveMode.Inactive)
return;
T.Info("Scribe was left in mode " + Scribe.mode + "; forced stop");
Scribe.ForceStop();
}
private static void Delete(string path)
{
try
{
if (File.Exists(path))
File.Delete(path);
}
catch (Exception e)
{
T.Info("could not delete " + path + ": " + e.Message);
}
}
private static int NotifyQueueCount() =>
(AccessTools.Field(typeof(Siblings), "notifyQueue")?.GetValue(null) as ICollection)?.Count ?? 0;
}
}