using System.Collections.Generic; using System.Linq; using System.Reflection; using BlaxDefaults; using RimWorld; using Verse; namespace BlaxDefaultsTests { /// /// Shared helpers for tests. Things, zones and areas made here are removed after each test unless passed /// to Keep() or KeepZone(). Mod settings and the defaults library are restored after each test (the /// library in memory only, the file is not rewritten), so tests may change them freely. Feature-specific /// helpers belong in the feature's own test file. /// public static class Fixtures { private static readonly List made = new List(); private static readonly HashSet kept = new HashSet(); private static readonly List madeZones = new List(); private static readonly HashSet keptZones = new HashSet(); private static readonly List areas = new List(); private static List librarySnapshot; private static bool keepLibrary; public static Map Map => Find.CurrentMap; public static BlaxDefaultsSettings Settings => BlaxDefaultsMod.Settings; // ---- defaults library ------------------------------------------------------------ /// Saves the entry with DefaultsLibrary.Set and returns it. Restored after the test. public static TE Save(TE entry) where TE : DefaultsEntry { DefaultsLibrary.Set(entry); return entry; } /// A storage template under this key that allows exactly these defs (unlisted Game), not saved. public static StorageTemplate Template(StorageKind kind, StoragePriority priority, params ThingDef[] allow) { StorageSettings s = kind.GameDefault(); s.filter.SetDisallowAll(); foreach (ThingDef d in allow) s.filter.SetAllow(d, true); s.Priority = priority; return kind.Capture(s); } /// Leave the library as this test set it (phase-1 setup for phase-2 checks). public static void KeepLibrary() => keepLibrary = true; public static StorageKind Kind(string thingDefName) => StorageKinds.ForDef(NeedDef(DefDatabase.GetNamedSilentFail(thingDefName), "ThingDef " + thingDefName)); public static StorageKind StockpileKind => StorageKinds.ForStockpile(StorageKinds.VanillaStockpile); public static StorageKind DumpingKind => StorageKinds.ForStockpile(StorageKinds.VanillaDumping); // ---- defs ------------------------------------------------------------------------ /// A def that must exist; fails the test otherwise. public static TD NeedDef(TD def, string what) where TD : Def { T.NotNull(def, what); return def; } public static ThingDef Thing(string defName) => NeedDef(DefDatabase.GetNamedSilentFail(defName), "ThingDef " + defName); /// Skips the test unless the DLC is active: "needs Biotech". public static void NeedDlc(string dlcPackageId) { if (!DlcSupport.IsActive(dlcPackageId)) T.Skip("needs " + DlcSupport.DlcName(dlcPackageId)); } // ---- map, things, zones ---------------------------------------------------------- /// /// A free area of this size near the map centre: in bounds, away from the edge, unfogged, standable, /// heavy-supporting terrain, no zone, nothing but grass or filth, which is removed. Tracked: buildings, /// blueprints, frames, items and zones in it are removed after the test (kept ones stay). /// public static CellRect EmptyArea(int width, int height) { Map map = Map; foreach (IntVec3 origin in GenRadial.RadialCellsAround(map.Center, 40f, useCenter: true)) { var rect = new CellRect(origin.x, origin.z, width, height); if (rect.Cells.All(c => Free(c, map))) { foreach (IntVec3 c in rect.Cells) foreach (Thing t in map.thingGrid.ThingsListAt(c).ToList()) t.Destroy(DestroyMode.Vanish); areas.Add(rect); return rect; } } T.Fail("no empty " + width + "x" + height + " area near the map centre"); return default; } private static bool Free(IntVec3 c, Map map) => c.InBounds(map) && !c.CloseToEdge(map, 5) && !c.Fogged(map) && c.Standable(map) && c.SupportsStructureType(map, TerrainAffordanceDefOf.Heavy) && c.GetZone(map) == null && map.thingGrid.ThingsListAt(c).All(t => (t is Plant plant && !plant.def.plant.IsTree) || t is Filth) && !areas.Any(r => r.Contains(c)); /// Removes the thing after the test unless kept. public static TT Track(TT thing) where TT : Thing { if (thing != null) made.Add(thing); return thing; } public static TZ TrackZone(TZ zone) where TZ : Zone { if (zone != null) madeZones.Add(zone); return zone; } /// Exclude a thing from the per-test cleanup (phase-1 setup for phase-2 checks). public static TT Keep(TT thing) where TT : Thing { kept.Add(thing); return thing; } public static TZ KeepZone(TZ zone) where TZ : Zone { keptZones.Add(zone); return zone; } /// A spawned free colonist of the quick-test colony, to complete frames with. public static Pawn Worker() { Pawn p = Map.mapPawns.FreeColonistsSpawned.FirstOrDefault(); T.NotNull(p, "a spawned free colonist"); return p; } public static Thing FindThingById(string thingId) { if (thingId == null) return null; foreach (Map m in Find.Maps) foreach (Thing t in m.listerThings.AllThings) if (t.ThingID == thingId) return t; return null; } public static Zone FindZoneById(int id) { foreach (Map m in Find.Maps) foreach (Zone z in m.zoneManager.AllZones) if (z.ID == id) return z; return null; } // ---- time ------------------------------------------------------------------------ public static void Tick(int ticks) { for (int i = 0; i < ticks; i++) Find.TickManager.DoSingleTick(); } public static void QuietStoryteller() { Find.Storyteller.incidentQueue.Clear(); Find.Storyteller.storytellerComps.Clear(); } // ---- settings and cleanup (used by the runner) ----------------------------------- public static Dictionary SnapshotSettings() { keepLibrary = false; librarySnapshot = DefaultsLibrary.Snapshot(); var d = new Dictionary(); if (Settings == null) return d; foreach (FieldInfo f in typeof(BlaxDefaultsSettings).GetFields(BindingFlags.Public | BindingFlags.Instance)) { object v = f.GetValue(Settings); d[f] = v is List list ? new List(list) : v; } return d; } public static void RestoreSettings(Dictionary snapshot) { if (Settings != null) { foreach (var kv in snapshot) kv.Key.SetValue(Settings, kv.Value is List list ? new List(list) : kv.Value); } if (!keepLibrary && librarySnapshot != null) DefaultsLibrary.RestoreForTests(librarySnapshot); keepLibrary = false; } public static void Cleanup() { foreach (Thing t in made) { if (t != null && !kept.Contains(t) && !t.Destroyed && t.Spawned) t.Destroy(DestroyMode.Vanish); } made.Clear(); foreach (Zone z in madeZones) { if (z != null && !keptZones.Contains(z) && z.zoneManager != null && z.zoneManager.AllZones.Contains(z)) z.Delete(playSound: false); } madeZones.Clear(); Map map = Map; if (map != null) { foreach (CellRect rect in areas) { foreach (IntVec3 c in rect.Cells) { if (!c.InBounds(map)) continue; Zone z = c.GetZone(map); if (z != null && !keptZones.Contains(z)) z.Delete(playSound: false); foreach (Thing t in map.thingGrid.ThingsListAt(c).ToList()) { if (t is Pawn || kept.Contains(t) || t.Destroyed) continue; if (t is Building || t is Blueprint || t is Frame || t.def.EverHaulable) t.Destroy(DestroyMode.Vanish); } } } } areas.Clear(); } } }