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 Caravan. Design: 1.1 "Caravan purchases appear in the zone" > Tests. /// Tests: [BlaxTest("caravan: what", phase: N)], phase 1 fresh colony, 2 after save and reload, 3 after the component class was stripped. /// Nothing is saved by this feature, so every test is phase 1 (the caravan checkbox persists in TabTests and StoreTests). /// /// Each test forces a trader caravan, puts a known stack on one of its pack animals and buys it through the /// trader's Pawn_TraderTracker, as Tradeable.ResolveTrade does (Tradeable.cs:472-478). The caravan leaves /// after the test. Each test turns the caravan checkbox off on delivery zones other tests left on the map. /// public static class CaravanTests { private const string HarmonyId = "blax.zones.tests.caravan"; private const string HospitalityId = "Orion.Hospitality"; /// How far from the carrier vanilla's Near placement puts a stack on open ground, with some slack. private const int NextToCarrier = 3; private static Harmony harmony; private static Harmony H => harmony ??= new Harmony(HarmonyId); /// Texts of messages sent since ObserveMessages(). private static readonly List messages = new List(); // ---- into the zone -------------------------------------------------------------------- [BlaxTest("caravan: an item bought from a trader caravan appears in the zone and is in the lord's extraForbiddenThings")] public static void ItemAppearsInZone() { Fixtures.OnlyThisTestsZones(DeliverySource.Caravan); Zone_Delivery zone = Fixtures.DeliveryZone(Fixtures.TestArea(3, 3)); Lord lord = Fixtures.TraderCaravan(); Pawn trader = Fixtures.TraderOf(lord); Pawn carrier = Fixtures.CarrierOf(lord); Thing steel = Fixtures.GoodsOnCarrier(carrier, ThingDefOf.Steel, 30); T.Check(trader.trader.Goods.Contains(steel), "the steel on the carrier is not one of the trader's goods"); trader.trader.GiveSoldThingToPlayer(steel, steel.stackCount, Fixtures.Negotiator()); T.Check(steel.Spawned, "the steel is not on the map; it is in " + steel.ParentHolder); T.Check(zone.ContainsCell(steel.Position), "the steel lies at " + steel.Position + ", not in the zone"); T.Equal(30, steel.stackCount, "steel count"); T.Check(lord.extraForbiddenThings.Contains(steel), "the steel is not in the lord's extraForbiddenThings"); T.Check(steel.Faction == null || steel.Faction == Faction.OfPlayer, "the steel belongs to " + steel.Faction); } [BlaxTest("caravan: a fully roofed zone still receives caravan goods")] public static void RoofedZoneReceives() { Fixtures.OnlyThisTestsZones(DeliverySource.Caravan); CellRect area = Fixtures.TestArea(3, 3); Zone_Delivery zone = Fixtures.DeliveryZone(area); Fixtures.Roof(area); T.Check(area.Cells.All(c => c.Roofed(Fixtures.Map)), "the zone is not fully roofed"); Lord lord = Fixtures.TraderCaravan(); Pawn trader = Fixtures.TraderOf(lord); Thing medicine = Fixtures.GoodsOnCarrier(Fixtures.CarrierOf(lord), ThingDefOf.MedicineIndustrial, 5); trader.trader.GiveSoldThingToPlayer(medicine, medicine.stackCount, Fixtures.Negotiator()); T.Check(medicine.Spawned && zone.ContainsCell(medicine.Position), "the medicine lies at " + medicine.PositionHeld + ", not in the roofed zone"); } [BlaxTest("caravan: medicine goes to a medicine-only zone at Important, steel to the general zone")] public static void FilterAndPriority() { Fixtures.OnlyThisTestsZones(DeliverySource.Caravan); CellRect area = Fixtures.TestArea(7, 2); // The general zone is made first, so a lower ID can't be why medicine picks the other one. Zone_Delivery general = Fixtures.DeliveryZone(new CellRect(area.minX, area.minZ, 2, 2)); Zone_Delivery medical = Fixtures.DeliveryZone(new CellRect(area.maxX - 1, area.minZ, 2, 2), Fixtures.FilterOf(ThingDefOf.MedicineIndustrial), StoragePriority.Important); Lord lord = Fixtures.TraderCaravan(); Pawn trader = Fixtures.TraderOf(lord); Pawn carrier = Fixtures.CarrierOf(lord); Thing medicine = Fixtures.GoodsOnCarrier(carrier, ThingDefOf.MedicineIndustrial, 5); Thing steel = Fixtures.GoodsOnCarrier(carrier, ThingDefOf.Steel, 30); Pawn negotiator = Fixtures.Negotiator(); trader.trader.GiveSoldThingToPlayer(medicine, medicine.stackCount, negotiator); trader.trader.GiveSoldThingToPlayer(steel, steel.stackCount, negotiator); T.Check(medicine.Spawned && medical.ContainsCell(medicine.Position), "medicine lies at " + medicine.PositionHeld + ", not in the medicine zone"); T.Check(steel.Spawned && general.ContainsCell(steel.Position), "steel lies at " + steel.PositionHeld + ", not in the general zone"); } [BlaxTest("caravan: with every zone cell holding another item the goods land next to the zone and the message says so; with overflow off they land next to the carrier")] public static void FullZoneLandsNextToIt() { Fixtures.OnlyThisTestsZones(DeliverySource.Caravan); Fixtures.Settings.overflowNearZone = true; CellRect area = Fixtures.TestArea(2, 2); Zone_Delivery zone = Fixtures.DeliveryZone(area); foreach (IntVec3 c in area) GenSpawn.Spawn(Fixtures.Stack(ThingDefOf.WoodLog, 10), c, Fixtures.Map); Lord lord = Fixtures.TraderCaravan(); Pawn trader = Fixtures.TraderOf(lord); Pawn carrier = Fixtures.CarrierOf(lord); Pawn negotiator = Fixtures.Negotiator(); Thing steel = Fixtures.GoodsOnCarrier(carrier, ThingDefOf.Steel, 30); string nextTo = CaravanDeliveries.MessageText(new[] { zone }, nextToZone: true); T.Check(nextTo.Contains(zone.label) && nextTo != CaravanDeliveries.MessageText(new[] { zone }), "the next-to message '" + nextTo + "' doesn't name " + zone.label + " or reads like the in-zone one"); ObserveMessages(); trader.trader.GiveSoldThingToPlayer(steel, steel.stackCount, negotiator); T.Check(steel.Spawned, "the steel is not on the map"); T.Check(!zone.ContainsCell(steel.Position), "the steel lies on a full zone cell " + steel.Position); int d = Fixtures.DistanceToZone(zone, steel.Position); T.Check(d <= 2, "the steel lies " + d + " cells from the zone, at " + steel.Position); T.Check(Fixtures.Chebyshev(steel.Position, carrier.Position) > NextToCarrier, "the steel lies next to the carrier, not next to the zone"); T.Equal(1, messages.Count(m => m == nextTo), "messages saying the goods lie next to the zone (all: " + string.Join(" | ", messages) + ")"); T.Equal(1, messages.Count, "messages after one purchase"); // Overflow off: the full zone sends the next purchase to vanilla's spot, with no message. Fixtures.Settings.overflowNearZone = false; Thing cloth = Fixtures.GoodsOnCarrier(carrier, ThingDefOf.Cloth, 20); trader.trader.GiveSoldThingToPlayer(cloth, cloth.stackCount, negotiator); NextToCarrierCheck(cloth, carrier, lord); T.Equal(1, messages.Count, "messages after a purchase that went to the carrier"); } [BlaxTest("caravan: silver from a sale too big for the first zone splits over two zones, and the message counts both")] public static void SplitPayoutNamesBothZones() { Map map = Fixtures.Map; Fixtures.OnlyThisTestsZones(DeliverySource.Caravan); CellRect area = Fixtures.TestArea(5, 1); // A: one cell at Important takes one full stack of silver; B gets the rest. Zone_Delivery a = Fixtures.DeliveryZone(new CellRect(area.minX, area.minZ, 1, 1), priority: StoragePriority.Important); Zone_Delivery b = Fixtures.DeliveryZone(new CellRect(area.minX + 2, area.minZ, 3, 1)); Lord lord = Fixtures.TraderCaravan(); Pawn trader = Fixtures.TraderOf(lord); Pawn carrier = Fixtures.CarrierOf(lord); int total = ThingDefOf.Silver.stackLimit * 2 + 200; // Sale silver comes through the same call as a purchase (Tradeable.cs:472-478); one stack over the limit, as a big sale pays. Thing silver = ThingMaker.MakeThing(ThingDefOf.Silver); silver.stackCount = total; Fixtures.Track(silver); T.Check(carrier.inventory.innerContainer.TryAdd(silver, canMergeWithExistingStacks: false), "could not put the silver on " + carrier.LabelShort); ObserveMessages(); trader.trader.GiveSoldThingToPlayer(silver, silver.stackCount, Fixtures.Negotiator()); List inA = map.listerThings.ThingsOfDef(ThingDefOf.Silver).Where(t => t.Spawned && a.ContainsCell(t.Position)).ToList(); List inB = map.listerThings.ThingsOfDef(ThingDefOf.Silver).Where(t => t.Spawned && b.ContainsCell(t.Position)).ToList(); foreach (Thing t in inA.Concat(inB)) Fixtures.Track(t); T.Equal(ThingDefOf.Silver.stackLimit, inA.Sum(t => t.stackCount), "silver in zone A"); T.Equal(total - ThingDefOf.Silver.stackLimit, inB.Sum(t => t.stackCount), "silver in zone B"); string expected = CaravanDeliveries.MessageText(new[] { a, b }); T.Equal(1, messages.Count(m => m == expected), "messages naming 2 delivery zones (all: " + string.Join(" | ", messages) + ")"); T.Equal(1, messages.Count, "messages after one payout"); } // ---- vanilla paths --------------------------------------------------------------------- [BlaxTest("caravan: with no zones the goods land next to the carrier")] public static void NoZonesNextToCarrier() { Fixtures.OnlyThisTestsZones(DeliverySource.Caravan); Lord lord = Fixtures.TraderCaravan(); Pawn trader = Fixtures.TraderOf(lord); Pawn carrier = Fixtures.CarrierOf(lord); Thing steel = Fixtures.GoodsOnCarrier(carrier, ThingDefOf.Steel, 30); trader.trader.GiveSoldThingToPlayer(steel, steel.stackCount, Fixtures.Negotiator()); NextToCarrierCheck(steel, carrier, lord); } [BlaxTest("caravan: with Route caravan purchases off or the zone's checkbox off the goods land next to the carrier")] public static void SwitchesOffNextToCarrier() { Fixtures.OnlyThisTestsZones(DeliverySource.Caravan); Zone_Delivery zone = Fixtures.DeliveryZone(Fixtures.TestArea(3, 3)); Lord lord = Fixtures.TraderCaravan(); Pawn trader = Fixtures.TraderOf(lord); Pawn carrier = Fixtures.CarrierOf(lord); Pawn negotiator = Fixtures.Negotiator(); Fixtures.Settings.routeCaravan = false; Thing steel = Fixtures.GoodsOnCarrier(carrier, ThingDefOf.Steel, 30); trader.trader.GiveSoldThingToPlayer(steel, steel.stackCount, negotiator); NextToCarrierCheck(steel, carrier, lord); Fixtures.Settings.routeCaravan = true; zone.acceptCaravan = false; Thing wood = Fixtures.GoodsOnCarrier(carrier, ThingDefOf.WoodLog, 30); trader.trader.GiveSoldThingToPlayer(wood, wood.stackCount, negotiator); NextToCarrierCheck(wood, carrier, lord); } [BlaxTest("caravan: a bought animal doesn't move")] public static void AnimalDoesNotMove() { Fixtures.OnlyThisTestsZones(DeliverySource.Caravan); Zone_Delivery zone = Fixtures.DeliveryZone(Fixtures.TestArea(3, 3)); Lord lord = Fixtures.TraderCaravan(); Pawn trader = Fixtures.TraderOf(lord); Pawn animal = lord.ownedPawns.Where(p => p.GetTraderCaravanRole() == TraderCaravanRole.Chattel && p.RaceProps.Animal) .OrderBy(p => p.thingIDNumber).FirstOrDefault(); if (animal == null) { // No animal for sale in this caravan: a chicken of the caravan's faction joins it as chattel. IntVec3 near = CellFinder.RandomClosewalkCellNear(trader.Position, Fixtures.Map, 3); animal = Fixtures.Spawn(Fixtures.Generate(DefDatabase.AllDefsListForReading.First(k => k.race == ThingDefOf.Chicken), trader.Faction), near); lord.AddPawn(animal); T.Equal(TraderCaravanRole.Chattel, animal.GetTraderCaravanRole(), "the chicken's caravan role"); } T.Check(trader.trader.Goods.Contains(animal), "the animal is not one of the trader's goods"); IntVec3 before = animal.Position; trader.trader.GiveSoldThingToPlayer(animal, 1, Fixtures.Negotiator()); T.Check(animal.Spawned, "the bought animal left the map"); T.Equal(before, animal.Position, "the bought animal's cell"); T.Check(!zone.ContainsCell(animal.Position), "the bought animal stands in the zone"); } [BlaxTest("caravan: when the router throws the item lands next to the carrier, nothing is destroyed, and Zones logs one error")] public static void RouterThrowsFallsBack() { Fixtures.OnlyThisTestsZones(DeliverySource.Caravan); Fixtures.DeliveryZone(Fixtures.TestArea(3, 3)); Lord lord = Fixtures.TraderCaravan(); Pawn trader = Fixtures.TraderOf(lord); Pawn carrier = Fixtures.CarrierOf(lord); Thing steel = Fixtures.GoodsOnCarrier(carrier, ThingDefOf.Steel, 30); ZonesLog.ResetOnce(); Fixtures.OnCleanup(ZonesLog.ResetOnce); ZonesTestHooks.RouterThrows = true; T.ExpectErrors("[Blax Zones] Caravan delivery failed", 1); trader.trader.GiveSoldThingToPlayer(steel, steel.stackCount, Fixtures.Negotiator()); T.Check(!steel.Destroyed, "the steel was destroyed"); T.Equal(30, steel.stackCount, "steel count"); NextToCarrierCheck(steel, carrier, lord); } // ---- one message per trade ----------------------------------------------------------- [BlaxTest("caravan: buying 3 stacks in one TradeDeal.TryExecute posts exactly 1 message that names the zone")] public static void OneMessagePerTrade() { Map map = Fixtures.Map; Fixtures.OnlyThisTestsZones(DeliverySource.Caravan); Zone_Delivery zone = Fixtures.DeliveryZone(Fixtures.TestArea(3, 3)); Lord lord = Fixtures.TraderCaravan(); Pawn trader = Fixtures.TraderOf(lord); Pawn carrier = Fixtures.CarrierOf(lord); var bought = new List { Fixtures.GoodsOnCarrier(carrier, ThingDefOf.Steel, 20), Fixtures.GoodsOnCarrier(carrier, ThingDefOf.MedicineHerbal, 3), Fixtures.GoodsOnCarrier(carrier, ThingDefOf.Cloth, 20), }; ColonySilverNear(trader, 1500); Pawn negotiator = Fixtures.Negotiator(); TradeSession.SetupWith(trader, negotiator, giftMode: false); Fixtures.OnCleanup(() => { TradeSession.Close(); TradeSession.deal = null; }); foreach (Thing t in bought) { Tradeable tradeable = TradeSession.deal.AllTradeables.FirstOrDefault(x => x.thingsTrader.Contains(t)); T.NotNull(tradeable, "a tradeable for " + t.def.defName); tradeable.ForceToSource(t.stackCount); T.Equal(TradeAction.PlayerBuys, tradeable.ActionToDo, t.def.defName + " trade action"); } ObserveMessages(); T.Check(TradeSession.deal.TryExecute(out bool traded), "TradeDeal.TryExecute refused the trade (the colony's silver: " + TradeSession.deal.CurrencyTradeable?.CountHeldBy(Transactor.Colony) + ")"); T.Check(traded, "TryExecute traded nothing"); int inZone = map.listerThings.AllThings.Count(t => t.Spawned && zone.ContainsCell(t.Position) && bought.Any(b => b.def == t.def)); T.Check(inZone >= 3, "stacks of the bought defs in the zone: " + inZone + ", expected at least 3"); string expected = CaravanDeliveries.MessageText(new[] { zone }); T.Check(expected.Contains(zone.label), "the message text '" + expected + "' doesn't name " + zone.label); T.Equal(1, messages.Count(m => m == expected), "messages naming the zone (all: " + string.Join(" | ", messages) + ")"); T.Equal(1, messages.Count(m => m.Contains(zone.label)), "messages mentioning " + zone.label); T.Check(CaravanDeliveries.Current == null, "a caravan message batch is still open after the trade"); } [BlaxTest("caravan: a purchase outside a trade sends its own message, and none with Message when goods arrive off")] public static void MessageOutsideTrade() { Fixtures.OnlyThisTestsZones(DeliverySource.Caravan); Zone_Delivery zone = Fixtures.DeliveryZone(Fixtures.TestArea(3, 3)); Lord lord = Fixtures.TraderCaravan(); Pawn trader = Fixtures.TraderOf(lord); Pawn carrier = Fixtures.CarrierOf(lord); Pawn negotiator = Fixtures.Negotiator(); string expected = CaravanDeliveries.MessageText(new[] { zone }); ObserveMessages(); Thing steel = Fixtures.GoodsOnCarrier(carrier, ThingDefOf.Steel, 30); trader.trader.GiveSoldThingToPlayer(steel, steel.stackCount, negotiator); T.Equal(1, messages.Count(m => m == expected), "messages after one purchase outside a trade"); Fixtures.Settings.caravanMessage = false; Thing wood = Fixtures.GoodsOnCarrier(carrier, ThingDefOf.WoodLog, 30); trader.trader.GiveSoldThingToPlayer(wood, wood.stackCount, negotiator); T.Check(wood.Spawned && zone.ContainsCell(wood.Position), "with the message off the wood lies at " + wood.PositionHeld + ", not in the zone"); T.Equal(1, messages.Count(m => m == expected), "messages after a purchase with the message setting off"); } // ---- Hospitality --------------------------------------------------------------------------- [BlaxTest("caravan: with Hospitality a purchase from a guest lands in the zone")] public static void HospitalityGuestPurchase() { 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.OnlyThisTestsZones(DeliverySource.Caravan); Zone_Delivery zone = Fixtures.DeliveryZone(Fixtures.TestArea(3, 3)); var parms = new IncidentParms { target = map, forced = true, points = 100f }; var arrive = (IncidentWorker_PawnsArrive)worker; 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 guests"); Lord lord = Fixtures.Arrive(worker, parms, "Hospitality guest group"); T.Check(lord.LordJob.GetType().Namespace == "Hospitality", "guest lord job is " + lord.LordJob.GetType().FullName); Pawn guest = lord.ownedPawns.Where(p => p.RaceProps.Humanlike).OrderBy(p => p.thingIDNumber).FirstOrDefault(); T.NotNull(guest, "a humanlike guest"); if (guest.trader == null) { MethodInfo convert = AccessTools.Method(AccessTools.TypeByName("Hospitality.Utilities.GuestUtility") ?? AccessTools.TypeByName("Hospitality.GuestUtility"), "ConvertToTrader"); T.NotNull(convert, "Hospitality's GuestUtility.ConvertToTrader"); convert.Invoke(null, new object[] { guest, true }); } T.NotNull(guest.trader, "the guest's trader tracker"); Thing steel = Fixtures.Stack(ThingDefOf.Steel, 30); T.Check(guest.inventory.innerContainer.TryAdd(steel, canMergeWithExistingStacks: false), "could not put steel into the guest's inventory"); guest.GiveSoldThingToPlayer(steel, steel.stackCount, Fixtures.Negotiator()); T.Check(steel.Spawned && zone.ContainsCell(steel.Position), "the steel bought from the guest lies at " + steel.PositionHeld + ", not in the zone"); } // ---- patch --------------------------------------------------------------------------------- [BlaxTest("caravan: the transpiler replaced exactly one TryPlaceThing call and logged no call-count error")] public static void TranspilerCount() { T.Equal(1, Patch_Pawn_TraderTracker_GiveSoldThingToPlayer.LastCallCount, "Patch_Pawn_TraderTracker_GiveSoldThingToPlayer.LastCallCount"); // Errors only: the runner logs test names as messages, and a name may contain the phrase. bool logged = Log.Messages.Any(m => m.type == LogMessageType.Error && m.text != null && m.text.Contains("[Blax Zones]") && m.text.Contains("unexpected call count")); T.Check(!logged, "the log has an 'unexpected call count' error"); MethodInfo give = AccessTools.Method(typeof(Pawn_TraderTracker), nameof(Pawn_TraderTracker.GiveSoldThingToPlayer)); Patches info = Harmony.GetPatchInfo(give); T.Check(info != null && info.Transpilers.Any(p => p.owner == BlaxZonesStartup.HarmonyId), "no Blax Zones transpiler on Pawn_TraderTracker.GiveSoldThingToPlayer"); T.Check(Patch_Pawn_TraderTracker_GiveSoldThingToPlayer.TryPlaceThing != null, "the 8-argument GenPlace.TryPlaceThing overload is gone"); Patches place = Harmony.GetPatchInfo(Patch_Pawn_TraderTracker_GiveSoldThingToPlayer.TryPlaceThing); bool ours = place != null && place.Prefixes.Concat(place.Postfixes).Concat(place.Transpilers).Concat(place.Finalizers) .Any(p => p.owner == BlaxZonesStartup.HarmonyId); T.Check(!ours, "Blax Zones patches GenPlace.TryPlaceThing"); } // ---- helpers ------------------------------------------------------------------------------- /// Vanilla's spot: on the map, next to the carrier, in no delivery zone, in the lord's extraForbiddenThings. private static void NextToCarrierCheck(Thing thing, Pawn carrier, Lord lord) { T.Check(thing.Spawned, thing.def.defName + " is not on the map; it is in " + thing.ParentHolder); int d = Fixtures.Chebyshev(thing.Position, carrier.Position); T.Check(d <= NextToCarrier, thing.def.defName + " lies " + d + " cells from the carrier, at " + thing.Position); T.Check(!Fixtures.InDeliveryZone(thing.Position), thing.def.defName + " lies in a delivery zone at " + thing.Position); T.Check(lord.extraForbiddenThings.Contains(thing), thing.def.defName + " is not in the lord's extraForbiddenThings"); } /// Silver stacks the colony can pay with: spawned next to the trader on home-area cells (restored after the test). private static void ColonySilverNear(Pawn trader, int total) { Map map = Fixtures.Map; Area home = map.areaManager.Home; int left = total; int tries = 0; while (left > 0 && tries++ < 50) { IntVec3 c = CellFinder.RandomClosewalkCellNear(trader.Position, map, 4, x => x.GetFirstItem(map) == null && !x.Fogged(map)); if (!c.IsValid || c.GetFirstItem(map) != null) continue; int n = Math.Min(left, ThingDefOf.Silver.stackLimit); Thing silver = Fixtures.Stack(ThingDefOf.Silver, n); GenSpawn.Spawn(silver, c, map); if (!home[c]) { home[c] = true; IntVec3 cell = c; Fixtures.OnCleanup(() => home[cell] = false); } left -= n; } T.Check(left <= 0, "could not lay out " + total + " silver next to the trader"); } /// Records the text of every Messages.Message(string, LookTargets, MessageTypeDef, bool) call until the test ends. private static void ObserveMessages() { messages.Clear(); MethodInfo target = AccessTools.Method(typeof(Messages), nameof(Messages.Message), new[] { typeof(string), typeof(LookTargets), typeof(MessageTypeDef), typeof(bool) }); T.NotNull(target, "Messages.Message(string, LookTargets, MessageTypeDef, bool)"); MethodInfo prefix = AccessTools.Method(typeof(CaravanTests), nameof(OnMessage)); H.Patch(target, prefix: new HarmonyMethod(prefix)); Fixtures.OnCleanup(() => H.Unpatch(target, prefix)); } private static void OnMessage(string text) { if (text != null) messages.Add(text); } /// 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)); } } }