using System.Collections.Generic; using System.Linq; using System.Reflection; using BlaxSlaves; using HarmonyLib; using RimWorld; using RimWorld.Planet; using Verse; namespace BlaxSlavesTests { /// /// Time as a slave: the counter in GameComponent_TimeAsSlave (no RecordDef, because records are saved by /// def index and an added def shifts other mods' records), the Records tab row drawn by /// Patch_RecordsCardTimeAsSlave (postfix on the private RecordsCardUtility.DrawTimeRecords), the slave /// tab line drawn by Patch_SlaveTabLines (postfix on the private ITab_Pawn_Visitor.DoSlavePriceListing) /// and the SlaveTabLines registry later releases add their lines to. Both tabs need OnGUI, so the tests /// check the patches and the strings the rows show (SlaveTabLines.LabelsFor, TimeAsSlave.RecordValue). /// public static class TimeAsSlaveTests { private const string OldRecordName = "BlaxSlaves_TimeAsColonySlave"; private const int TickSpan = 2500; // one in-game hour private const int Interval = TimeAsSlave.CountInterval; private const string HarmonyId = "blax.slaves"; private static GameComponent_TimeAsSlave Counter => GameComponent_TimeAsSlave.Instance; // ---- no def, component and patches ------------------------------------------------ [BlaxTest("time as slave: Blax Slaves adds no RecordDef; the counter is a GameComponent")] public static void NoRecordDef() { T.Check(DefDatabase.GetNamedSilentFail(OldRecordName) == null, "RecordDef " + OldRecordName + " is loaded again; any RecordDef from this mod shifts later mods' records in existing saves"); ModContentPack ours = LoadedModManager.GetMod()?.Content; T.NotNull(ours, "Blax Slaves' ModContentPack"); List added = DefDatabase.AllDefsListForReading .Where(d => d.modContentPack == ours || (d.defName != null && d.defName.StartsWith("BlaxSlaves_"))) .Select(d => d.defName).ToList(); T.Check(added.Count == 0, "RecordDefs from Blax Slaves: " + string.Join(", ", added)); T.NotNull(Counter, "GameComponent_TimeAsSlave in Current.Game"); T.Check(Current.Game.components.Count(c => c is GameComponent_TimeAsSlave) == 1, "GameComponent_TimeAsSlave is not in the game exactly once"); T.Equal(0, TimeAsSlave.Ticks(null), "TimeAsSlave.Ticks(null)"); foreach (string key in new[] { "BlaxSlaves_TimeAsSlaveRecord", "BlaxSlaves_TimeAsSlaveRecordDesc" }) T.Check(key.CanTranslate(), "Keyed string " + key + " missing"); } [BlaxTest("time as slave: postfixes sit on DoSlavePriceListing and RecordsCardUtility.DrawTimeRecords")] public static void PatchesApplied() { MethodInfo tab = AccessTools.Method(typeof(ITab_Pawn_Visitor), "DoSlavePriceListing"); T.NotNull(tab, "ITab_Pawn_Visitor.DoSlavePriceListing (renamed in this game version?)"); T.Check(HasOurPostfix(tab, typeof(Patch_SlaveTabLines)), "no blax.slaves postfix from Patch_SlaveTabLines on DoSlavePriceListing (patch failed at startup?)"); T.Check(SlaveTabLines.All.Any(l => l.id == TimeAsSlave.LineId), "the time-as-slave line is not registered in SlaveTabLines"); MethodInfo records = AccessTools.Method(typeof(RecordsCardUtility), "DrawTimeRecords"); T.NotNull(records, "RecordsCardUtility.DrawTimeRecords (renamed in this game version?)"); T.Equal(typeof(float), records.ReturnType, "DrawTimeRecords return type (the postfix adds its row height to it)"); T.Check(HasOurPostfix(records, typeof(Patch_RecordsCardTimeAsSlave)), "no blax.slaves postfix from Patch_RecordsCardTimeAsSlave on DrawTimeRecords (patch failed at startup?)"); } [BlaxTest("time as slave: the Records tab row shows the counter as vanilla formats time records")] public static void RecordsTabRow() { Pawn slave = Fixtures.ColonySlave(); Fixtures.Tick(Interval * 2); string label = TimeAsSlave.RecordLabel; string value = TimeAsSlave.RecordValue(slave); T.Info($"row: '{label}' = '{value}'"); T.Check(!label.NullOrEmpty() && !label.Contains("BlaxSlaves_"), "Records tab label shows a raw key: " + label); T.Check(!TimeAsSlave.RecordTooltip.Contains("BlaxSlaves_"), "Records tab tooltip shows a raw key: " + TimeAsSlave.RecordTooltip); T.Check(TimeAsSlave.Ticks(slave) > 0, "counter still 0 after two counting passes"); T.Equal(TimeAsSlave.Ticks(slave).ToStringTicksToPeriod(), value, "Records tab value"); } // ---- counting --------------------------------------------------------------------- [BlaxTest("time as slave: a colony slave's counter grows, a free colonist's and a prisoner's stay 0")] public static void CounterGrows() { Pawn slave = Fixtures.Keep(Fixtures.ColonySlave()); Pawn colonist = Fixtures.Colonist(); Pawn prisoner = Prisoner(); int slaveBefore = TimeAsSlave.Ticks(slave); Fixtures.Tick(TickSpan); int slaveAfter = TimeAsSlave.Ticks(slave); int grown = slaveAfter - slaveBefore; T.Info($"after {TickSpan} ticks: slave {slaveBefore}->{slaveAfter}, colonist {TimeAsSlave.Ticks(colonist)}, prisoner {TimeAsSlave.Ticks(prisoner)}"); T.Check(slave.IsSlaveOfColony, "the slave stopped being a colony slave while ticking"); // One pass every Interval ticks adds Interval; where the span starts can shift one pass. T.Check(grown >= TickSpan - Interval && grown <= TickSpan + Interval, $"counter grew by {grown} over {TickSpan} ticks, expected about {TickSpan} ({Interval} per {Interval} ticks)"); T.Equal(slaveAfter, Counter.TicksOf(slave), "TimeAsSlave.Ticks vs GameComponent_TimeAsSlave.TicksOf"); T.Equal(0, TimeAsSlave.Ticks(colonist), "counter of a free colonist"); T.Equal(0, TimeAsSlave.Ticks(prisoner), "counter of a prisoner of the colony"); T.Check(!Counter.TrackedPawns.Contains(colonist) && !Counter.TrackedPawns.Contains(prisoner), "the counter tracks a free colonist or a prisoner"); T.Carry["timeAsSlave.pawn"] = slave.ThingID; T.Carry["timeAsSlave.ticks"] = slaveAfter.ToString(); } [BlaxTest("time as slave: a freed slave keeps the time counted so far and stops counting")] public static void FreedSlaveKeepsTime() { Pawn slave = Fixtures.ColonySlave(); Fixtures.Tick(Interval * 2); int counted = TimeAsSlave.Ticks(slave); T.Check(counted > 0, "counter still 0 after two counting passes"); slave.guest.SetGuestStatus(null); T.Check(!slave.IsSlaveOfColony, "SetGuestStatus(null) did not free the slave"); Fixtures.Tick(Interval * 2); T.Equal(counted, TimeAsSlave.Ticks(slave), "counter of the freed slave after two more passes"); } [BlaxTest("time as slave: a colony slave in a caravan keeps counting")] public static void CountsInCaravan() { Pawn slave = Fixtures.ColonySlave(); Pawn colonist = Fixtures.Colonist(); Caravan caravan = null; try { caravan = CaravanMaker.MakeCaravan(new List { colonist, slave }, Faction.OfPlayer, Fixtures.Map.Tile, addToWorldPawnsIfNotAlready: true); T.Check(!slave.Spawned && slave.GetCaravan() == caravan, "the slave did not join the caravan"); T.Check(slave.IsSlaveOfColony, "the slave stopped being a colony slave in the caravan"); int before = TimeAsSlave.Ticks(slave); Fixtures.Tick(Interval * 2); int after = TimeAsSlave.Ticks(slave); T.Info($"caravan slave: {before}->{after} over {Interval * 2} ticks"); T.Check(after - before >= Interval, $"counter grew by {after - before} in a caravan over {Interval * 2} ticks, expected at least {Interval}"); } finally { if (caravan != null && !caravan.Destroyed) { caravan.RemoveAllPawns(); caravan.Destroy(); } } } [BlaxTest("time as slave: Purge drops destroyed pawns and keeps living and dead ones")] public static void PurgeDropsDestroyed() { Pawn kept = Fixtures.ColonySlave(); Pawn dead = Fixtures.ColonySlave(); Pawn gone = Fixtures.ColonySlave(); Pawn goneUnpurged = Fixtures.ColonySlave(); Fixtures.Tick(Interval * 2); foreach (Pawn p in new[] { kept, dead, gone, goneUnpurged }) T.Check(Counter.TrackedPawns.Contains(p), p.LabelShort + " not tracked after two counting passes"); dead.Kill(null); int deadTicks = TimeAsSlave.Ticks(dead); gone.Destroy(DestroyMode.Vanish); T.Check(gone.Destroyed, "Destroy(Vanish) left the pawn undestroyed"); Counter.Purge(); T.Check(!Counter.TrackedPawns.Contains(gone), "Purge kept a destroyed pawn"); T.Check(Counter.TrackedPawns.Contains(kept), "Purge dropped a living colony slave"); T.Check(dead.Dead, "Kill left the slave alive"); // Whether a killed pawn reads as Destroyed depends on how the game finalizes the kill; // either way the rule is the same: Purge keeps it while it isn't destroyed, drops it once it is. if (dead.Destroyed) { T.Info("the killed slave reads as Destroyed after Kill, so Purge must drop it"); T.Check(!Counter.TrackedPawns.Contains(dead), "Purge kept a killed slave that reads as Destroyed"); } else { T.Check(Counter.TrackedPawns.Contains(dead) && TimeAsSlave.Ticks(dead) == deadTicks, "Purge dropped a dead slave whose corpse still exists"); } T.Check(Counter.TrackedPawns.All(p => p != null && !p.Destroyed), "a null or destroyed pawn is still tracked after Purge"); // Destroyed after the purge: the save between the phases must drop it (checked after the reload). goneUnpurged.Destroy(DestroyMode.Vanish); T.Carry["timeAsSlave.destroyed"] = goneUnpurged.ThingID; } // ---- slave tab line --------------------------------------------------------------- [BlaxTest("time as slave: slave tab line shows for colony slaves only and follows the setting")] public static void TabLine() { T.Check("BlaxSlaves_TimeAsSlaveLine".CanTranslate(), "Keyed string BlaxSlaves_TimeAsSlaveLine missing"); T.Check("BlaxSlaves_TimeAsSlaveLineTip".CanTranslate(), "Keyed string BlaxSlaves_TimeAsSlaveLineTip missing"); Pawn slave = Fixtures.ColonySlave(); Fixtures.Tick(Interval * 2); string expected = TimeAsSlave.Label(slave); T.Info("line: " + expected); T.Check(expected.Contains(TimeAsSlave.Ticks(slave).ToStringTicksToPeriod()), "line '" + expected + "' doesn't contain the counter's period"); T.Check(!expected.Contains("BlaxSlaves_"), "line shows a raw translation key: " + expected); Fixtures.Settings.showTimeInSlaveTab = true; List shown = SlaveTabLines.LabelsFor(slave); T.Check(shown.Contains(expected), "colony slave: line missing, tab would show [" + string.Join(" | ", shown) + "]"); Fixtures.Settings.showTimeInSlaveTab = false; T.Check(!SlaveTabLines.LabelsFor(slave).Contains(expected), "line still shown with showTimeInSlaveTab off"); int hiddenBefore = TimeAsSlave.Ticks(slave); Fixtures.Tick(Interval * 2); T.Check(TimeAsSlave.Ticks(slave) > hiddenBefore, $"counter stopped with showTimeInSlaveTab off ({hiddenBefore}->{TimeAsSlave.Ticks(slave)}); the setting should only hide the line"); Fixtures.Settings.showTimeInSlaveTab = true; Pawn prisoner = Prisoner(); T.Check(!SlaveTabLines.LabelsFor(prisoner).Contains(TimeAsSlave.Label(prisoner)), "time-as-slave line shown in a prisoner's tab"); T.Check(SlaveTabLines.LabelsFor(Fixtures.Colonist()).Count == 0, "slave tab lines for a free colonist"); T.Check(SlaveTabLines.LabelsFor(null).Count == 0, "slave tab lines for a null pawn"); } [BlaxTest("time as slave: tab lines can be added once, replaced by id and removed")] public static void TabLineRegistry() { const string id = "blax.slaves.test.line"; Fixtures.Settings.showTimeInSlaveTab = true; int before = SlaveTabLines.All.Count; try { SlaveTabLines.Add(new SlaveTabLine(id, p => "first " + p.LabelShort, prisonersToo: true)); SlaveTabLines.Add(new SlaveTabLine(id, p => "second " + p.LabelShort, prisonersToo: true)); T.Equal(before + 1, SlaveTabLines.All.Count, "line count after adding the same id twice"); Pawn prisoner = Prisoner(); List forPrisoner = SlaveTabLines.LabelsFor(prisoner); T.Check(forPrisoner.Contains("second " + prisoner.LabelShort) && !forPrisoner.Any(l => l.StartsWith("first ")), "prisonersToo line: expected the replacement in the prisoner tab, got [" + string.Join(" | ", forPrisoner) + "]"); Pawn slave = Fixtures.ColonySlave(); List forSlave = SlaveTabLines.LabelsFor(slave); int ours = forSlave.IndexOf(TimeAsSlave.Label(slave)); int added = forSlave.IndexOf("second " + slave.LabelShort); T.Check(ours >= 0 && added > ours, "slave tab order: expected time as slave first, then the added line, got [" + string.Join(" | ", forSlave) + "]"); SlaveTabLines.Add(new SlaveTabLine(id + ".hidden", p => "hidden", visible: p => false)); T.Check(!SlaveTabLines.LabelsFor(slave).Contains("hidden"), "line with visible=false shown"); } finally { SlaveTabLines.Remove(id); SlaveTabLines.Remove(id + ".hidden"); } T.Equal(before, SlaveTabLines.All.Count, "line count after removing the test lines"); } [BlaxTest("time as slave: the tab line reads the tab's own pawn (ITab.SelPawn binding)")] public static void TabReadsItsPawn() { Pawn slave = Fixtures.ColonySlave(); var tab = new FixedPawnTab { pawn = slave }; T.Check(Patch_SlaveTabLines.PawnOf(tab) == slave, "Patch_SlaveTabLines.PawnOf ignored the tab's SelPawn override (protected ITab.SelPawn not bound, fell back to the selection)"); } // ---- reload ----------------------------------------------------------------------- [BlaxTest("time as slave (reload): the counter survives save and load", phase: 2)] public static void CounterSurvivesReload() { T.Carry.TryGetValue("timeAsSlave.pawn", out string id); T.Carry.TryGetValue("timeAsSlave.ticks", out string carried); bool parsed = int.TryParse(carried, out int before); if (id == null || !parsed) T.Skip("phase-1 counting test did not carry its slave (failed or skipped)"); T.NotNull(Counter, "GameComponent_TimeAsSlave after reload"); Pawn pawn = Fixtures.FindPawnById(id); T.NotNull(pawn, $"slave {id} after reload (destroyed, or made to leave by a later phase-1 test?)"); int after = TimeAsSlave.Ticks(pawn); T.Info($"{pawn.LabelShort}: {before} ticks before the save, {after} after the reload, slave of colony={pawn.IsSlaveOfColony}"); // Later phase-1 tests keep ticking, so the value may only have grown. T.Check(after >= before && after > 0, $"counter after reload is {after}, below the {before} it had before the save"); } [BlaxTest("time as slave (reload): no null or destroyed pawn comes back from the save", phase: 2)] public static void ReloadHasNoStalePawns() { T.NotNull(Counter, "GameComponent_TimeAsSlave after reload"); T.Check(Counter.TrackedPawns.All(p => p != null), "a null pawn is tracked after the reload"); // Earlier phase-2 tests clean up slaves they killed, so destroyed pawns can be tracked here // until the next purge (every save). Purge must clear them. int destroyed = Counter.TrackedPawns.Count(p => p.Destroyed); Counter.Purge(); T.Check(Counter.TrackedPawns.All(p => p != null && !p.Destroyed), "Purge left a destroyed pawn tracked after the reload"); T.Info($"{destroyed} pawns destroyed by earlier phase-2 tests, cleared by Purge"); T.Carry.TryGetValue("timeAsSlave.destroyed", out string goneId); if (goneId == null) T.Skip("phase-1 purge test did not carry its destroyed slave (failed or skipped)"); T.Check(!Counter.TrackedPawns.Any(p => p.ThingID == goneId), $"destroyed slave {goneId} is tracked again after the reload"); T.Info($"{Counter.TrackedPawns.Count} pawns tracked after the reload"); } // ---- helpers ---------------------------------------------------------------------- private static bool HasOurPostfix(MethodInfo target, System.Type patchClass) { Patches info = Harmony.GetPatchInfo(target); return info != null && info.Postfixes.Any(p => p.owner == HarmonyId && p.PatchMethod.DeclaringType == patchClass); } private static Pawn Prisoner() { Faction from = Fixtures.HostileFaction() ?? Fixtures.FriendlyFaction(); Pawn p = Fixtures.Spawn(Fixtures.Generate(PawnKindDefOf.Slave, from)); p.guest.SetGuestStatus(Faction.OfPlayer, GuestStatus.Prisoner); T.Check(p.IsPrisonerOfColony, "prisoner fixture is not a prisoner of the colony"); return p; } /// A visitor tab whose SelPawn is fixed, so PawnOf must use the virtual getter, not the selection. private class FixedPawnTab : ITab_Pawn_Visitor { public Pawn pawn; protected override Pawn SelPawn => pawn; } } }