using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using BlaxZones; using HarmonyLib; using RimWorld; using Verse; using Verse.AI.Group; namespace BlaxZonesTests { /// /// Package Camp. Design: 1.0 "Trader caravans camp at a zone" > Tests, and "Headless tests in 1.0" > /// Stand-down tests (one per trading-spot id in Compat.TradingSpots.cs, through SimulatedActive). /// Tests: [BlaxTest("camp: what", phase: N)], phase 1 fresh colony, 2 after save and reload, 3 after the component class was stripped. /// /// Arrivals are forced through the incident workers, the way the storyteller fires them. Everything an /// arrival brings (lords, pawns, letters) leaves the map after the test. Test-only Harmony postfixes on /// CampScope.TryFindCampSpot and the patched RCellFinder overload count what the camp code saw; they /// are removed in Fixtures.OnCleanup. /// public static class CampTests { /// The design's radius, written out so the test doesn't just echo CampScope.Radius. private const int Radius = 6; private const string HarmonyId = "blax.zones.tests.camp"; private const string ForcedFailure = "BlaxZonesTests: forced failure inside TryExecuteWorker"; private const string HospitalityId = "Orion.Hospitality"; /// The ids the stand-down tests below cover; a new id in Compat.TradingSpotMods needs a test here. private static readonly string[] StandDownTested = { Compat.TradingSpotRewritten, Compat.TradingSpotKV, Compat.TradingSpotGMT, Compat.TradingControl, }; private static readonly AccessTools.FieldRef TradeChillSpot = AccessTools.FieldRefAccess("chillSpot"); private static Harmony harmony; private static Harmony H => harmony ??= new Harmony(HarmonyId); // What the observation postfixes saw since Observe(). private static int spotCalls, spotHits, outsideCalls; private static IntVec3 lastSpot = IntVec3.Invalid; private static bool scopeAtFailure; // ---- trader caravans ---------------------------------------------------------------- [BlaxTest("camp: a trader caravan camps within 6 cells of a camp zone")] public static void CaravanCampsAtZone() { Map map = Fixtures.Map; Zone_Delivery zone = Fixtures.DeliveryZone(Fixtures.TestArea(3, 3), camp: true); Observe(); IntVec3 spot = TraderCaravan(); T.Check(spotHits == 1, $"camp spots picked: {spotHits} of {spotCalls} calls, expected 1"); T.Equal(lastSpot, spot, "the lord's chill spot against the camp spot CampScope picked"); T.Check(Near(zone, spot), "chill spot " + spot + " is more than " + Radius + " cells from the zone"); T.Check(spot.Standable(map) && !spot.Roofed(map) && !spot.Fogged(map), "chill spot " + spot + " is not standable, unroofed and unfogged"); } [BlaxTest("camp: a walled-off camp zone keeps the vanilla spot")] public static void WalledOffZoneKeepsVanillaSpot() { CellRect area = Fixtures.TestArea(9, 9); CellRect ring = area.ExpandedBy(Fixtures.AreaMargin); foreach (IntVec3 c in ring.EdgeCells) Fixtures.Wall(c); Zone_Delivery zone = Fixtures.DeliveryZone(CellRect.SingleCell(area.CenterCell), camp: true); CellRect inside = ring.ContractedBy(1); T.Check(GenRadial.RadialCellsAround(area.CenterCell, Radius, true).All(inside.Contains), "the wall ring doesn't enclose every cell within " + Radius); Observe(); IntVec3 spot = TraderCaravan(); T.Check(spotCalls >= 1, "the caravan never asked CampScope for a spot"); T.Equal(0, spotHits, "camp spots picked for a walled-off zone"); T.Check(!ring.Contains(spot), "chill spot " + spot + " is inside the walls"); T.Check(!Near(zone, spot), "chill spot " + spot + " is within " + Radius + " cells of the walled-off zone"); } [BlaxTest("camp: without Caravans camp here or with the global setting off the caravan keeps the vanilla spot")] public static void OptionOffKeepsVanillaSpot() { Zone_Delivery zone = Fixtures.DeliveryZone(Fixtures.TestArea(3, 3), camp: false); Observe(); TraderCaravan(); T.Check(spotCalls >= 1, "zone option off: the caravan never asked CampScope for a spot"); T.Equal(0, spotHits, "zone option off: camp spots picked"); zone.campHere = true; Fixtures.Settings.campAtZones = false; Observe(); TraderCaravan(); T.Check(spotCalls >= 1, "global setting off: the caravan never asked CampScope for a spot"); T.Equal(0, spotHits, "global setting off: camp spots picked"); } [BlaxTest("camp: camp spots are standable, unroofed and within 6 cells, outside enclosed rooms first, and pass the caller's validator")] public static void CampSpotRules() { Map map = Fixtures.Map; CellRect area = Fixtures.TestArea(9, 9); IntVec3 center = area.CenterCell; Zone_Delivery zone = Fixtures.DeliveryZone(CellRect.SingleCell(center), camp: true); CellRect roofed = CellRect.CenteredOn(center, 1); Fixtures.Roof(roofed); // An unroofed walled pocket 3 to 4 cells east of the zone: an enclosed room within the radius. var pocket = new CellRect(center.x + 3, center.z - 1, 2, 3); foreach (IntVec3 c in pocket.ExpandedBy(1).EdgeCells) Fixtures.Wall(c); Room pocketRoom = pocket.CenterCell.GetRoom(map); T.Check(pocketRoom != null && !pocketRoom.TouchesMapEdge, "the walled pocket is not an enclosed room"); Room open = area.Min.GetRoom(map); if (open == null || !open.TouchesMapEdge) T.Skip("the test area lies in an enclosed room on this map, so nothing is outside one"); for (int i = 0; i < 30; i++) { T.Check(CampScope.TryFindCampSpot(map, null, out IntVec3 c), "no camp spot with a null validator (try " + i + ")"); T.Check(Near(zone, c), c + " is more than " + Radius + " cells from the zone"); T.Check(c.Standable(map) && !c.Roofed(map) && !c.Fogged(map), c + " is not standable, unroofed and unfogged"); T.Check(!roofed.Contains(c), c + " is under the roof"); T.Check(!pocket.Contains(c), c + " is in the enclosed pocket although open cells pass"); } T.Check(!CampScope.TryFindCampSpot(map, c => false, out IntVec3 none), "a camp spot passed a validator that refuses every cell"); T.Check(!none.IsValid, "a refused search still set the cell to " + none); T.Check(CampScope.TryFindCampSpot(map, pocket.Contains, out IntVec3 inPocket) && pocket.Contains(inPocket), "the enclosed pocket was not used when only its cells pass"); } // ---- visitors ----------------------------------------------------------------------- [BlaxTest("camp: a visitor group ignores the camp zone")] public static void VisitorGroupIgnoresZone() { Fixtures.DeliveryZone(Fixtures.TestArea(3, 3), camp: true); // Vanilla's worker even when Hospitality replaced the def's worker class: this is the path // that reaches the patched overload (IncidentWorker_VisitorGroup.cs:22-26). var worker = new IncidentWorker_VisitorGroup { def = IncidentDefOf.VisitorGroup }; IncidentParms parms = Parms(worker, "a visitor group"); Observe(); Lord lord = Arrive(worker, parms, "visitor group"); T.Check(lord.LordJob is LordJob_VisitColony, "visitor lord job is " + lord.LordJob?.GetType().FullName); T.Check(outsideCalls >= 1, "the visitor group never reached RCellFinder.TryFindRandomSpotJustOutsideColony"); T.Equal(0, spotCalls, "CampScope.TryFindCampSpot calls during a visitor group"); } [BlaxTest("camp: Hospitality guests ignore the camp zone")] public static void HospitalityGuestsIgnoreZone() { if (!Compat.IsActive(HospitalityId)) T.Skip("needs Hospitality (-Compat)"); Map map = Fixtures.Map; IncidentWorker worker = IncidentDefOf.VisitorGroup.Worker; T.Check(worker.GetType().Namespace == "Hospitality", "VisitorGroup's worker is " + worker.GetType().FullName + ", not Hospitality's"); // Welcome guests without the safety dialog or the wait for guest beds; restored after the test. MapComponent comp = map.components.FirstOrDefault(c => c.GetType().FullName == "Hospitality.Hospitality_MapComponent"); T.NotNull(comp, "Hospitality's map component"); SetForTest(comp, "guestsAreWelcome", true); SetForTest(comp, "askForSafety", false); SetForTest(comp, "refuseGuestsUntilWeHaveBeds", false); Type settings = AccessTools.TypeByName("Hospitality.ModSettings_Hospitality"); if (settings != null) SetForTest(settings, "disableGuests", false); Fixtures.DeliveryZone(Fixtures.TestArea(3, 3), camp: true); IncidentParms parms = Parms(worker, "Hospitality guests"); parms.points = 100f; Observe(); Lord lord = Arrive(worker, parms, "Hospitality guest group"); T.Check(lord.LordJob.GetType().Namespace == "Hospitality", "guest lord job is " + lord.LordJob.GetType().FullName); T.Equal(0, spotCalls, "CampScope.TryFindCampSpot calls during Hospitality's guest arrival"); } // ---- scope --------------------------------------------------------------------------- [BlaxTest("camp: an exception inside TryExecuteWorker leaves CampScope unset")] public static void ExceptionLeavesScopeUnset() { Fixtures.OnCleanup(() => CampScope.Active = false); CampScope.Active = false; IncidentWorker worker = IncidentDefOf.TraderCaravanArrival.Worker; MethodInfo sendLetter = AccessTools.Method(typeof(IncidentWorker_TraderCaravanArrival), "SendLetter"); MethodInfo thrower = AccessTools.Method(typeof(CampTests), nameof(ThrowInsideIncident)); T.NotNull(sendLetter, "IncidentWorker_TraderCaravanArrival.SendLetter"); H.Patch(sendLetter, prefix: new HarmonyMethod(thrower)); Fixtures.OnCleanup(() => H.Unpatch(sendLetter, thrower)); T.ExpectErrors(ForcedFailure, 1); IncidentParms parms = Parms(worker, "a trader caravan"); LeaveAfterTest(); scopeAtFailure = false; try { worker.TryExecute(parms); T.Fail("the forced failure never reached the caller"); } catch (Exception e) when (Mentions(e, ForcedFailure)) { // What the game's tick loop does with an incident that throws (TickManager.cs:420-427). Log.Error(e.ToString()); } T.Check(scopeAtFailure, "CampScope was not set inside TryExecuteWorker"); T.Check(!CampScope.Active, "CampScope is still set after the exception"); } // ---- stand-down ---------------------------------------------------------------------- [BlaxTest("camp: every trading-spot id in Compat has a stand-down test")] public static void StandDownCoverage() { List missing = Compat.TradingSpotMods.Except(StandDownTested).ToList(); T.Check(missing.Count == 0, "trading-spot ids without a stand-down test: " + string.Join(", ", missing)); T.Equal(null, Compat.ActiveTradingSpotMod(), "active trading-spot mod with none installed or simulated"); } [BlaxTest("camp: stands down for Trading Spot Rewritten and logs once")] public static void StandDownRewritten() => StandsDown(Compat.TradingSpotRewritten); [BlaxTest("camp: stands down for [KV] Trading Spot and logs once")] public static void StandDownKV() => StandsDown(Compat.TradingSpotKV); [BlaxTest("camp: stands down for [GMT] Trading Spot and logs once")] public static void StandDownGMT() => StandsDown(Compat.TradingSpotGMT); [BlaxTest("camp: stands down for Trading Control and logs once")] public static void StandDownTradingControl() => StandsDown(Compat.TradingControl); // ---- Royalty ------------------------------------------------------------------------- [BlaxTest("camp: with Royalty a tribute collector camps within 6 cells of the zone")] public static void TributeCollectorCamps() { T.NeedsDlc("Royalty", ModsConfig.RoyaltyActive); IncidentDef def = DefDatabase.GetNamedSilentFail("CaravanArrivalTributeCollector"); T.NotNull(def, "IncidentDef CaravanArrivalTributeCollector"); Faction empire = Faction.OfEmpire; if (empire == null) T.Skip("no Empire in this world"); if (empire.HostileTo(Faction.OfPlayer)) T.Skip("the Empire is hostile to the colony in this world"); Zone_Delivery zone = Fixtures.DeliveryZone(Fixtures.TestArea(3, 3), camp: true); var parms = new IncidentParms { target = Fixtures.Map, forced = true, faction = empire }; Observe(); IntVec3 spot = ChillSpot(Arrive(def.Worker, parms, "tribute collector")); T.Check(spotHits == 1, $"camp spots picked: {spotHits} of {spotCalls} calls, expected 1"); T.Equal(lastSpot, spot, "the tribute collector's chill spot against the camp spot CampScope picked"); T.Check(Near(zone, spot), "chill spot " + spot + " is more than " + Radius + " cells from the zone"); } // ---- helpers ------------------------------------------------------------------------- private static void StandsDown(string id) { Map map = Fixtures.Map; T.Check(Compat.TradingSpotMods.Contains(id), id + " is not in Compat.TradingSpotMods"); Compat.SimulatedActive.Add(id); T.Equal(id, Compat.ActiveTradingSpotMod(), "active trading-spot mod"); Fixtures.DeliveryZone(Fixtures.TestArea(3, 3), camp: true); string message = CampScope.StandDownMessage(id); int before = Logged(message); Observe(); TraderCaravan(); T.Check(spotCalls >= 1, "the caravan never asked CampScope for a spot"); T.Equal(0, spotHits, "camp spots picked while " + id + " is active"); T.Check(!CampScope.TryFindCampSpot(map, null, out _), "a second search camped while " + id + " is active"); T.Equal(1, Logged(message) - before, "stand-down messages for " + id); } /// /// Forces IncidentDefOf.TraderCaravanArrival on the current map with a friendly trader faction and /// returns the chill spot its LordJob_TradeWithColony was made with. The caravan leaves after the test. /// private static IntVec3 TraderCaravan() { IncidentWorker worker = IncidentDefOf.TraderCaravanArrival.Worker; IncidentParms parms = Parms(worker, "a trader caravan"); return ChillSpot(Arrive(worker, parms, "trader caravan")); } private static IntVec3 ChillSpot(Lord lord) { var job = lord.LordJob as LordJob_TradeWithColony; T.NotNull(job, "LordJob_TradeWithColony (the lord has " + lord.LordJob?.GetType().FullName + ")"); return TradeChillSpot(job); } /// Forced parms for the current map with the first friendly faction the worker accepts as the group's source. private static IncidentParms Parms(IncidentWorker worker, string what) { var parms = new IncidentParms { target = Fixtures.Map, forced = true }; var arrive = worker as IncidentWorker_PawnsArrive; T.NotNull(arrive, worker.GetType().FullName + " as IncidentWorker_PawnsArrive"); parms.faction = Find.FactionManager.AllFactionsListForReading .Where(f => !f.IsPlayer && !f.defeated && !f.Hidden && f.def.humanlikeFaction && !f.HostileTo(Faction.OfPlayer) && arrive.FactionCanBeGroupSource(f, parms)) .OrderBy(f => f.loadID) .FirstOrDefault(); if (parms.faction == null) T.Skip("no friendly faction in this world can send " + what); return parms; } /// Fires the worker and returns the one lord it made. private static Lord Arrive(IncidentWorker worker, IncidentParms parms, string what) { HashSet before = LeaveAfterTest(); T.Check(worker.TryExecute(parms), what + " did not fire"); T.Check(!CampScope.Active, "CampScope is still set after the " + what); List made = Fixtures.Map.lordManager.lords.Where(l => !before.Contains(l)).ToList(); T.Equal(1, made.Count, "lords made by the " + what); return made[0]; } /// /// After the test, removes the lords, sends off the pawns and drops the letters that appear on the /// current map from now on. Returns the lords there now. /// private static HashSet LeaveAfterTest() { Map map = Fixtures.Map; var lords = new HashSet(map.lordManager.lords); var pawns = new HashSet(map.mapPawns.AllPawnsSpawned); var letters = new HashSet(Find.LetterStack.LettersListForReading); Fixtures.OnCleanup(() => { foreach (Lord l in map.lordManager.lords.Where(l => !lords.Contains(l)).ToList()) map.lordManager.RemoveLord(l); foreach (Pawn p in map.mapPawns.AllPawnsSpawned.Where(p => !pawns.Contains(p)).ToList()) { if (p.Spawned) p.ExitMap(false, Rot4.Invalid); } foreach (Letter l in Find.LetterStack.LettersListForReading.Where(l => !letters.Contains(l)).ToList()) Find.LetterStack.RemoveLetter(l); }); return lords; } /// Counts calls of CampScope.TryFindCampSpot and the patched RCellFinder overload until the test ends. private static void Observe() { spotCalls = spotHits = outsideCalls = 0; lastSpot = IntVec3.Invalid; MethodInfo find = AccessTools.Method(typeof(CampScope), nameof(CampScope.TryFindCampSpot)); MethodInfo outside = AccessTools.Method(typeof(RCellFinder), nameof(RCellFinder.TryFindRandomSpotJustOutsideColony), new[] { typeof(IntVec3), typeof(Map), typeof(Pawn), typeof(IntVec3).MakeByRefType(), typeof(Predicate) }); MethodInfo onFind = AccessTools.Method(typeof(CampTests), nameof(AfterFindCampSpot)); MethodInfo onOutside = AccessTools.Method(typeof(CampTests), nameof(AfterSpotJustOutsideColony)); T.NotNull(find, "CampScope.TryFindCampSpot"); T.NotNull(outside, "RCellFinder.TryFindRandomSpotJustOutsideColony(IntVec3, Map, Pawn, out IntVec3, Predicate)"); if (Harmony.GetPatchInfo(find)?.Postfixes.Any(p => p.owner == HarmonyId) != true) { H.Patch(find, postfix: new HarmonyMethod(onFind)); Fixtures.OnCleanup(() => H.Unpatch(find, onFind)); } if (Harmony.GetPatchInfo(outside)?.Postfixes.Any(p => p.owner == HarmonyId) != true) { H.Patch(outside, postfix: new HarmonyMethod(onOutside)); Fixtures.OnCleanup(() => H.Unpatch(outside, onOutside)); } } private static void AfterFindCampSpot(bool __result, ref IntVec3 cell) { spotCalls++; if (__result) { spotHits++; lastSpot = cell; } } private static void AfterSpotJustOutsideColony() => outsideCalls++; private static void ThrowInsideIncident() { scopeAtFailure = CampScope.Active; throw new InvalidOperationException(ForcedFailure); } private static bool Mentions(Exception e, string text) { for (Exception x = e; x != null; x = x.InnerException) { if (x.Message != null && x.Message.Contains(text)) return true; } return false; } private static bool Near(Zone zone, IntVec3 c) => zone.Cells.Any(z => z.InHorDistOf(c, Radius)); /// Copies of the text in the log, repeats included. private static int Logged(string text) => Log.Messages.Where(m => m.text != null && m.text.Contains(text)).Sum(m => m.repeats); /// Sets a field (instance on an object, static on a Type) and restores it after the test. private static void SetForTest(object owner, string field, object value) { Type type = owner as Type ?? owner.GetType(); object target = owner is Type ? null : owner; FieldInfo f = AccessTools.Field(type, field); T.NotNull(f, type.FullName + "." + field); object old = f.GetValue(target); f.SetValue(target, value); Fixtures.OnCleanup(() => f.SetValue(target, old)); } } }