using System; using System.Collections.Generic; using System.IO; using System.Linq; using BlaxLaws; using RimWorld; using Verse; namespace BlaxLawsTests { /// /// The court place (design: "Court place", Tests): the switch on a building (hook P), the place per map, its /// way through a crate, deconstruction, the save and the removal, the Laws tab's texts and the picker. Rows /// use an act key no catalogue knows, so a row only makes "a law exists" true and files nothing. Every test /// clears the map's place afterwards; the save test in phase 1 runs last and keeps its table and place. /// public static class CourtPlaceTests { private const string Key = "Ate/BlaxLawsTest_CourtPlace"; private const string CarryPlace = "court.place"; // ---- helpers ----------------------------------------------------------------------------- private static Map Map => Fixtures.Map; private static Law AnyLaw() => DetectionKit.Row(Key, LawStage.DidIt); /// The map has no place before the test and none after it; crates a test left off the map are destroyed. private static void CleanPlace(params Func[] crates) { CourtPlace.Clear(Map); T.Check(CourtPlace.For(Map) == null, "fixture: the map still has a court place: " + CourtPlace.For(Map)); Fixtures.OnCleanup(() => { foreach (Func get in crates) { MinifiedThing crate = get(); if (crate != null && !crate.Destroyed && !crate.Spawned && crate.holdingOwner == null) crate.Destroy(DestroyMode.Vanish); } CourtPlace.Clear(Map); Fixtures.Comp.CleanCourtPlaces(); }); } private static Building Make(ThingDef def, Faction faction = null, ThingDef stuff = null, IntVec3? near = null) { var b = (Building)ThingMaker.MakeThing(def, def.MadeFromStuff ? stuff ?? GenStuff.DefaultStuffFor(def) : null); if (faction != null) b.SetFaction(faction); return DetectionKit.Place(b, DetectionKit.FreeCell(near ?? Fixtures.PawnCell(), def.size)); } private static Building Table(Faction faction = null, IntVec3? near = null) => Make(ThingDefOf.Table1x2c, faction ?? Faction.OfPlayer, ThingDefOf.WoodLog, near); private static void Select(params Thing[] things) { Find.Selector.ClearSelection(); foreach (Thing t in things) Find.Selector.Select(t, playSound: false, forceDesignatorDeselect: false); } /// The switch the building's gizmo bar shows while it alone is selected, or null. private static Command_CourtPlace Switch(Building b) { Select(b); List found = b.GetGizmos().OfType().ToList(); T.Check(found.Count <= 1, b + " shows " + found.Count + " court place switches"); return found.FirstOrDefault(); } private static Command_CourtPlace NeedSwitch(Building b, string what) { Command_CourtPlace cmd = Switch(b); T.NotNull(cmd, "the court place switch on " + what); T.Check(cmd.Building == b, "the switch on " + what + " names " + cmd.Building); return cmd; } private static string No => "BlaxLaws_NoCourtPlace".Translate(); private static string NotRoom => "BlaxLaws_NotProperRoom".Translate(); /// Spawns the building's crate on the map and returns it; the building is inside it, unspawned. private static MinifiedThing Uninstall(Building b, IntVec3 near) { MinifiedThing crate = Fixtures.Track(b.MakeMinified()); T.NotNull(crate, "fixture: the crate of " + b); GenSpawn.Spawn(crate, DetectionKit.FreeCell(near), Map); return crate; } /// Installs the crate's building at a free spot near the cell, as Blueprint_Install.MakeSolidThing does (RimWorld/Blueprint_Install.cs:99-112). private static Building Reinstall(MinifiedThing crate, IntVec3 near, Func also = null) { var inner = (Building)crate.InnerThing; T.NotNull(inner, "fixture: the crate holds nothing"); crate.InnerThing = null; crate.Destroy(DestroyMode.Vanish); GenSpawn.Spawn(inner, DetectionKit.FreeCell(near, inner.def.size, also), Map, Rot4.North); return inner; } /// Runs the component's ExposeData in Saving mode, as a save does (Verse/ScribeSaver.cs:141-176). private static string SaveXml() { T.Equal(LoadSaveMode.Inactive, Scribe.mode, "fixture: Scribe mode before the save"); string xml = Scribe.saver.DebugOutputFor(Fixtures.Comp); T.Equal(LoadSaveMode.Inactive, Scribe.mode, "Scribe mode after the save"); T.Check(!string.IsNullOrEmpty(xml) && xml.Contains(" ">Thing_" + t.ThingID + "<"; private static Building FindBuilding(string thingId) { foreach (Map m in Find.Maps) { foreach (Thing t in m.listerThings.AllThings) { if (t.ThingID == thingId) return t as Building; } } return null; } // ---- the switch -------------------------------------------------------------------------- [BlaxTest("court place: switching it on on a table stores it; on a second table it moves there; off again leaves none")] public static void SwitchStoresAndMoves() { CleanPlace(); AnyLaw(); Building t1 = Table(); Building t2 = Table(near: t1.Position); Command_CourtPlace s1 = NeedSwitch(t1, "the first table"); T.Check(!s1.isActive(), "the switch on the first table is on before it was switched"); s1.toggleAction(); T.Equal(t1, CourtPlace.For(Map), "court place after switching it on on the first table"); T.Check(NeedSwitch(t1, "the first table").isActive(), "the first table's switch is off while it is the place"); NeedSwitch(t2, "the second table").toggleAction(); T.Equal(t2, CourtPlace.For(Map), "court place after switching it on on the second table"); T.Check(!NeedSwitch(t1, "the first table").isActive(), "the first table's switch is still on after the place moved"); T.Check(NeedSwitch(t2, "the second table").isActive(), "the second table's switch is off while it is the place"); T.Equal(1, Fixtures.Comp.CourtPlaceEntries.Count(e => e?.building != null && e.building.MapHeld == Map), "entries stored for the map after the move"); NeedSwitch(t2, "the second table").toggleAction(); T.Equal(null, CourtPlace.For(Map), "court place after switching the second table off"); T.Check(!NeedSwitch(t1, "the first table").isActive(), "switching the second table off put the place back on the first"); } [BlaxTest("court place: the switch shows only while a law exists and the building alone is selected")] public static void SwitchNeedsLawAndSingleSelection() { CleanPlace(); T.Equal(0, Lawbook.Laws.Count, "fixture: rows an earlier test kept"); T.Check(!Watch.AnyLaw, "Watch.AnyLaw is on with an empty lawbook"); Building t1 = Table(); Building t2 = Table(near: t1.Position); T.Check(Switch(t1) == null, "an empty lawbook shows the court place switch"); Law row = AnyLaw(); T.Check(Watch.AnyLaw, "Watch.AnyLaw is off with a row in the book"); NeedSwitch(t1, "a table with a law in the book"); Lawbook.SetEnabled(row, false); T.Check(Watch.AnyLaw, "Watch.AnyLaw is off while the book holds a switched-off row"); NeedSwitch(t1, "a table while the only row is switched off"); Lawbook.SetEnabled(row, true); Select(t1, t2); T.Equal(2, Find.Selector.NumSelected, "fixture: selected tables"); T.Check(!t1.GetGizmos().OfType().Any() && !t2.GetGizmos().OfType().Any(), "two selected tables show the court place switch"); Lawbook.Delete(row); T.Check(!Watch.AnyLaw, "Watch.AnyLaw is still on after the last row was deleted"); T.Check(Switch(t1) == null, "the switch still shows after the last row was deleted"); } [BlaxTest("court place: tables, the party spot and the campfire are offered; walls, enemy and unowned buildings are not")] public static void KindRule() { CleanPlace(); AnyLaw(); IntVec3 near = Fixtures.PawnCell(); Building table = Table(near: near); Building party = Make(ThingDefOf.PartySpot, Faction.OfPlayer, near: near); Building campfire = Make(ThingDefOf.Campfire, Faction.OfPlayer, near: near); Building wall = Make(ThingDefOf.Wall, Faction.OfPlayer, ThingDefOf.WoodLog, near); Faction hostile = Fixtures.HostileFaction(); T.NotNull(hostile, "fixture: a hostile faction"); Building enemy = Table(hostile, near); Building unowned = Make(ThingDefOf.Table1x2c, null, ThingDefOf.WoodLog, near); T.Check(unowned.Faction == null, "fixture: the unowned table belongs to " + unowned.Faction); foreach (var (b, what) in new[] { (table, "a table"), (party, "the party spot"), (campfire, "the campfire") }) { T.Check(CourtPlace.CanBe(b), what + " can't be a court place"); NeedSwitch(b, what); } foreach (var (b, what) in new[] { (wall, "a wall"), (enemy, "an enemy table"), (unowned, "an unowned table") }) { T.Check(!CourtPlace.CanBe(b), what + " can be a court place"); T.Check(Switch(b) == null, what + " shows the court place switch"); T.Check(!CourtPlace.Set(b), "Set took " + what); T.Equal(null, CourtPlace.For(Map), "court place after Set refused " + what); } T.Check(!CourtPlace.EligibleDef(ThingDefOf.Wall), "the wall def passes the kind rule"); T.Check(CourtPlace.EligibleDef(ThingDefOf.PartySpot) && CourtPlace.EligibleDef(ThingDefOf.Campfire) && CourtPlace.EligibleDef(ThingDefOf.Table1x2c), "the party spot, campfire or table def fails the kind rule"); // Minifiable but not furniture (Core Buildings_Power.xml, designation category Power): no court place. T.Check(ThingDefOf.Battery.Minifiable && ThingDefOf.Battery.designationCategory?.defName != "Furniture", "fixture: the battery is not minifiable non-furniture"); T.Check(!CourtPlace.EligibleDef(ThingDefOf.Battery), "the battery def passes the kind rule"); Building battery = Make(ThingDefOf.Battery, Faction.OfPlayer, near: near); T.Check(Switch(battery) == null, "a battery shows the court place switch"); // The impassable rule alone: an eating surface passes while standable and fails while impassable. T.Check(CourtPlace.EligibleDef(EatingSurface(Traversability.Standable)), "a standable eating surface fails the kind rule"); T.Check(!CourtPlace.EligibleDef(EatingSurface(Traversability.Impassable)), "an impassable eating surface passes the kind rule"); } /// A def made for the kind rule only, never spawned: a building with an eating surface. private static ThingDef EatingSurface(Traversability passability) => new ThingDef { defName = "BlaxLawsTest_EatingSurface_" + passability, category = ThingCategory.Building, thingClass = typeof(Building), building = new BuildingProperties(), surfaceType = SurfaceType.Eat, passability = passability, }; [BlaxTest("court place: 200 selected walls get no switch, and the postfix costs under 0.1 ms for all of them per frame")] public static void TwoHundredWalls() { CleanPlace(); AnyLaw(); List walls = WallBlock(10, 20); Select(walls.ToArray()); // Selector.MaxNumSelected is 200 (RimWorld/Selector.cs:22, 377): the block fills the selection. T.Equal(200, Find.Selector.NumSelected, "selected walls"); foreach (Thing w in walls) T.Check(!w.GetGizmos().OfType().Any(), "a selected wall shows the court place switch: " + w); var buildings = walls.Cast().ToArray(); IEnumerable original = Enumerable.Empty(); foreach (Building b in buildings) { IEnumerable r = original; Patch_Building_GetGizmos.Postfix(b, ref r); T.Check(ReferenceEquals(r, original), "the postfix wrapped the gizmos of a wall among 200 selected"); } long best = DetectionKit.BestOf(() => { for (int i = 0; i < buildings.Length; i++) { IEnumerable r = original; Patch_Building_GetGizmos.Postfix(buildings[i], ref r); } }); double limit = 0.0001 * System.Diagnostics.Stopwatch.Frequency; T.Info("hook P on 200 selected walls: " + DetectionKit.Ms(best) + " ms per frame"); T.Check(best <= limit, "hook P on 200 selected walls costs " + DetectionKit.Ms(best) + " ms per frame, over 0.1 ms"); } /// A solid w x h block of player walls on clear ground: solid, so it encloses no room. private static List WallBlock(int w, int h) { Map map = Map; IntVec3 anchor = Fixtures.PawnCell(); District district = anchor.GetDistrict(map); CellRect Rect(IntVec3 o) => new CellRect(o.x, o.z, w, h); bool Fits(IntVec3 o) => Rect(o).Cells.All(c => Fixtures.Buildable(c, map, district) && c.GetFirstPawn(map) == null); if (!CellFinder.TryFindRandomCellNear(anchor, map, 60, Fits, out IntVec3 origin)) T.Fail("fixture: no clear " + w + "x" + h + " block near the colony"); Fixtures.ClearGround(Rect(origin).Cells, map); var walls = new List(); foreach (IntVec3 c in Rect(origin).Cells) { Thing wall = ThingMaker.MakeThing(ThingDefOf.Wall, ThingDefOf.WoodLog); wall.SetFaction(Faction.OfPlayer); walls.Add(DetectionKit.Place(wall, c)); } return walls; } // ---- crates, deconstruction, losing it --------------------------------------------------- [BlaxTest("court place: uninstalled into a crate it reads as no place; installed elsewhere it is the place again; a place set meanwhile replaces it")] public static void CrateFollowsTheBuilding() { MinifiedThing crate = null; CleanPlace(() => crate); Building t1 = Table(); Building t2 = Table(near: t1.Position); T.Check(CourtPlace.Set(t1), "Set refused the first table"); string id = t1.ThingID; IntVec3 before = t1.Position; crate = Uninstall(t1, t1.Position); T.Check(!t1.Spawned && crate.InnerThing == t1, "fixture: the table is not inside its crate"); T.Equal(null, CourtPlace.For(Map), "court place while the table is in its crate"); T.Equal(No, CourtPlaceUi.Line(Map), "tab line while the table is in its crate"); T.Check(CourtPlaceUi.CanClear(Map), "Clear is not offered while the crated place is stored"); // Never the old footprint, which is free once the table is in its crate. CellRect old = GenAdj.OccupiedRect(before, Rot4.North, t1.def.size); bool AwayFromOld(IntVec3 c) => !GenAdj.OccupiedRect(c, Rot4.North, t1.def.size).Overlaps(old); Building back = Reinstall(crate, t2.Position + new IntVec3(6, 0, 0), AwayFromOld); T.Equal(id, back.ThingID, "fixture: the installed table"); T.Check(back.Position != before, "fixture: the table went back to its old spot " + before); T.Equal(t1, CourtPlace.For(Map), "court place after the table was installed elsewhere"); // Crated again; the second table is set meanwhile on the same map, so the crated place is dropped. crate = Uninstall(t1, t1.Position); T.Check(CourtPlace.Set(t2), "Set refused the second table"); Reinstall(crate, t1.Position); T.Equal(t2, CourtPlace.For(Map), "court place after the old place was installed again"); T.Check(!SaveXml().Contains(Ref(t1)), "the save still names the old place after a newer one was set"); } [BlaxTest("court place: a crate from elsewhere installed on a map that has a place: the place set last wins, and the save keeps only it")] public static void ArrivingCrateLoses() { MinifiedThing crate = null; CleanPlace(() => crate); Building t1 = Table(); Building t2 = Table(near: t1.Position); T.Check(CourtPlace.Set(t1), "Set refused the first table"); // Off this map: the crate is in no holder on this map, as in a caravan or on another map (MapHeld null). crate = Fixtures.Track(t1.MakeMinified()); T.Check(crate.MapHeld == null && t1.MapHeld == null, "fixture: the crate is still on the map"); Fixtures.Tick(1); T.Check(CourtPlace.Set(t2), "Set refused the second table"); T.Check(Fixtures.Comp.CourtPlaceEntries.Any(e => e?.building == t1), "fixture: the place set on the first table was dropped while it was away"); Building arrived = Reinstall(crate, t1.Position); T.Equal(t1, arrived, "fixture: the arrived table"); T.Equal(t2, CourtPlace.For(Map), "court place after an older place arrived in a crate"); AnyLawOnce(); T.Check(!NeedSwitch(t1, "the arrived table").isActive(), "the arrived table's switch is on"); T.Check(!Fixtures.Comp.CourtPlaceEntries.Any(e => e?.building == t1), "the place that arrived in a crate is still stored after it lost"); string xml = SaveXml(); T.Check(xml.Contains(Ref(t2)), "the save doesn't name the place set last"); T.Check(!xml.Contains(Ref(t1)), "the save still names the place that arrived in a crate"); T.Equal(t2, CourtPlace.For(Map), "court place after the save"); } [BlaxTest("court place: after a crate lost on arrival, destroying the winner before any save leaves no place, never the older one")] public static void ArrivedLoserNeverFallsBack() { MinifiedThing crate = null; CleanPlace(() => crate); Building t1 = Table(); Building t2 = Table(near: t1.Position); T.Check(CourtPlace.Set(t1), "Set refused the first table"); crate = Fixtures.Track(t1.MakeMinified()); T.Check(crate.MapHeld == null, "fixture: the crate is still on the map"); Fixtures.Tick(1); T.Check(CourtPlace.Set(t2), "Set refused the second table"); Reinstall(crate, t1.Position); T.Equal(t2, CourtPlace.For(Map), "court place after an older place arrived in a crate"); t2.Destroy(DestroyMode.Vanish); T.Equal(null, CourtPlace.For(Map), "court place after the winner was destroyed, before any save"); T.Check(!CourtPlace.IsPlace(t1), "the older place that arrived in a crate came back"); T.Equal(No, CourtPlaceUi.Line(Map), "tab line after the winner was destroyed"); } [BlaxTest("court place: a crate set later elsewhere wins on arrival; uninstalled again before any save, the map has no place")] public static void ArrivingCrateWins() { MinifiedThing crate = null, again = null; CleanPlace(() => crate, () => again); Building t1 = Table(); Building t2 = Table(near: t1.Position); T.Check(CourtPlace.Set(t1), "Set refused the first table"); crate = Fixtures.Track(t1.MakeMinified()); T.Check(crate.MapHeld == null, "fixture: the crate is still on the map"); T.Check(CourtPlace.Set(t2), "Set refused the second table"); // As if the first table had been set later on another map before it was crated and carried here. CourtPlaceEntry crated = Fixtures.Comp.CourtPlaceEntries.FirstOrDefault(e => e?.building == t1); CourtPlaceEntry stays = Fixtures.Comp.CourtPlaceEntries.FirstOrDefault(e => e?.building == t2); T.Check(crated != null && stays != null, "fixture: the entries of both tables"); crated.setTick = stays.setTick + 1; Reinstall(crate, t1.Position); T.Equal(t1, CourtPlace.For(Map), "court place after a newer place arrived in a crate"); T.Check(!Fixtures.Comp.CourtPlaceEntries.Any(e => e?.building == t2), "the older place is still stored after a newer one arrived"); again = Uninstall(t1, t1.Position); T.Equal(null, CourtPlace.For(Map), "court place after the winner went back into its crate, before any save"); T.Check(!CourtPlace.IsPlace(t2), "the older place came back after the winner was uninstalled"); } private static bool NeedSwitchOrNull(Building b) { AnyLawOnce(); Command_CourtPlace cmd = Switch(b); return cmd != null && cmd.isActive(); } private static void AnyLawOnce() { if (Lawbook.Find(Key, null, LawStage.DidIt) == null) AnyLaw(); } [BlaxTest("court place: deconstructed, the tab reads 'No court place' at once, and a save written after it holds no reference")] public static void DeconstructClearsAtOnce() { CleanPlace(); Building t1 = Table(); T.Check(CourtPlace.Set(t1), "Set refused the table"); T.Check(SaveXml().Contains(Ref(t1)), "the save doesn't name the place before the deconstruction"); var items = new HashSet(Map.listerThings.ThingsInGroup(ThingRequestGroup.HaulableEver)); Fixtures.OnCleanup(() => { foreach (Thing t in Map.listerThings.ThingsInGroup(ThingRequestGroup.HaulableEver).ToList()) { if (!items.Contains(t) && !t.Destroyed && !Fixtures.IsFixtureThing(t)) t.Destroy(DestroyMode.Vanish); } }); t1.Destroy(DestroyMode.Deconstruct); T.Equal(null, CourtPlace.For(Map), "court place right after the deconstruction"); T.Equal(No, CourtPlaceUi.Line(Map), "tab line right after the deconstruction"); T.Check(!CourtPlaceUi.CanClear(Map), "Clear is still offered for a deconstructed place"); // A destroyed thing saves as "null" anyway (Verse/Scribe_References.cs:60-68): check the save's own drop. string xml = SaveXml(); T.Check(!xml.Contains(Ref(t1)), "the save names the deconstructed place"); T.Check(!Fixtures.Comp.CourtPlaceEntries.Any(e => e?.building == t1), "the deconstructed place is still stored after a save"); T.Check(!xml.Contains("null"), "the save wrote an entry for the deconstructed place: " + xml); } [BlaxTest("court place: claimed by another faction it reads as no place; Clear works with an empty lawbook")] public static void ClaimedReadsAsNone() { CleanPlace(); T.Equal(0, Lawbook.Laws.Count, "fixture: rows an earlier test kept"); Building t1 = Table(); T.Check(CourtPlace.Set(t1), "Set refused the table with an empty lawbook"); T.Equal(t1, CourtPlace.For(Map), "court place"); T.Check(CourtPlace.IsPlace(t1), "IsPlace is false for the place"); Faction hostile = Fixtures.HostileFaction(); T.NotNull(hostile, "fixture: a hostile faction"); t1.SetFaction(hostile); T.Equal(null, CourtPlace.For(Map), "court place after another faction claimed it"); T.Check(!CourtPlace.IsPlace(t1), "IsPlace is true for a claimed place"); T.Equal(No, CourtPlaceUi.Line(Map), "tab line for a claimed place"); T.Check(CourtPlaceUi.CanClear(Map), "Clear is not offered for a claimed place"); CourtPlace.Clear(Map); T.Check(!CourtPlaceUi.CanClear(Map), "Clear is still offered after Clear"); t1.SetFaction(Faction.OfPlayer); T.Equal(null, CourtPlace.For(Map), "court place after Clear and a reclaim"); } // ---- the Laws tab ------------------------------------------------------------------------ [BlaxTest("court place: the tab line reads no place, the place with 'Not a proper room' outdoors, and the room's role, impressiveness label and number in a room")] public static void TabLine() { CleanPlace(); T.Equal(No, CourtPlaceUi.Line(Map), "tab line without a place"); T.Check(!CourtPlaceUi.CanClear(Map), "Clear is offered without a place"); Building outdoor = Table(); T.Check(CourtPlace.Set(outdoor), "Set refused the outdoor table"); T.Equal(null, CourtPlace.RoomOf(outdoor), "court room of a table on open ground"); string line = CourtPlaceUi.Line(Map); T.Check(line.Contains(outdoor.LabelCap) && line.Contains(NotRoom), "tab line for a table on open ground: " + line); T.Check(CourtPlaceUi.CanClear(Map), "Clear is not offered with a place"); PrisonRoom cell = EnforceFixtures.PrisonCell(); var inRoom = (Building)ThingMaker.MakeThing(ThingDefOf.Table1x2c, ThingDefOf.WoodLog); inRoom.SetFaction(Faction.OfPlayer); Room room = cell.bed.GetRoom(); DetectionKit.Place(inRoom, DetectionKit.FreeCell(cell.inside, ThingDefOf.Table1x2c.size, c => c.GetRoom(Map) == room)); Map.regionAndRoomUpdater.TryRebuildDirtyRegionsAndRooms(); T.Check(CourtPlace.Set(inRoom), "Set refused the table in the room"); T.Equal(inRoom, CourtPlace.For(Map), "court place after setting the table in the room"); Room court = CourtPlace.RoomOf(inRoom); T.Check(court != null && court == inRoom.GetRoom() && CourtPlace.IsProperRoom(court), "court room of the table in the room: " + court); float stat = court.GetStat(RoomStatDefOf.Impressiveness); string stage = RoomStatDefOf.Impressiveness.GetScoreStage(stat)?.label; string number = RoomStatDefOf.Impressiveness.ScoreToString(stat); string role = court.Role.PostProcessedLabelCap(court); line = CourtPlaceUi.Line(Map); T.Check(!stage.NullOrEmpty(), "fixture: the room's impressiveness has no stage label"); T.Check(line.Contains(inRoom.LabelCap) && line.Contains(role) && line.Contains(stage) && line.Contains("(" + number + ")") && !line.Contains(NotRoom), "tab line for the table in the room: '" + line + "', expected " + role + ", " + stage + " (" + number + ")"); T.Check(NeedSwitchOrNull(inRoom), "the switch on the place in the room is off"); T.Check(NeedSwitchDesc(inRoom).Contains(stage), "the switch's tooltip doesn't name the room's impressiveness"); } private static string NeedSwitchDesc(Building b) => NeedSwitch(b, "the table").Desc; [BlaxTest("court place: the picker takes the player's tables and party spot, refuses walls, enemy tables and pawns, and a pick sets the place")] public static void Picker() { CleanPlace(); Fixtures.OnCleanup(() => { if (Find.Targeter.IsTargeting) Find.Targeter.StopTargeting(); Find.MainTabsRoot?.EscapeCurrentTab(false); }); IntVec3 near = Fixtures.PawnCell(); Building table = Table(near: near); Building party = Make(ThingDefOf.PartySpot, Faction.OfPlayer, near: near); Building wall = Make(ThingDefOf.Wall, Faction.OfPlayer, ThingDefOf.WoodLog, near); Faction hostile = Fixtures.HostileFaction(); T.NotNull(hostile, "fixture: a hostile faction"); Building enemy = Table(hostile, near); Pawn colonist = Fixtures.Colonist(); TargetingParameters tp = CourtPlace.TargetParams(); T.Check(tp.CanTarget(new TargetInfo(table)), "the picker refuses a table"); T.Check(tp.CanTarget(new TargetInfo(party)), "the picker refuses the party spot"); T.Check(!tp.CanTarget(new TargetInfo(wall)), "the picker takes a wall"); T.Check(!tp.CanTarget(new TargetInfo(enemy)), "the picker takes an enemy table"); T.Check(!tp.CanTarget(new TargetInfo(colonist)), "the picker takes a colonist"); CourtPlaceUi.BeginPick(); T.Check(Find.Targeter.IsTargeting, "'Pick court place' started no targeting"); Find.Targeter.StopTargeting(); CourtPlaceUi.Pick(new LocalTargetInfo(wall)); T.Equal(null, CourtPlace.For(Map), "court place after picking a wall"); CourtPlaceUi.Pick(new LocalTargetInfo(party)); T.Equal(party, CourtPlace.For(Map), "court place after picking the party spot"); T.Check(Find.MainTabsRoot.OpenTab == BlaxLawsDefOf.BlaxLaws_Laws, "the pick didn't reopen the Laws tab"); } // ---- guards ------------------------------------------------------------------------------------ [BlaxTest("court place: a throw in hook P's gizmo postfix or in the switch logs once and the gizmo bar keeps vanilla's gizmos")] public static void ThrowKeepsGizmoBar() { CleanPlace(); AnyLaw(); Building t1 = Table(); Select(t1); List plain = t1.GetGizmos().Where(g => !(g is Command_CourtPlace)).ToList(); T.Check(plain.Count > 0, "fixture: the table shows no vanilla gizmo"); LawsLog.ResetOnce(); foreach (var (what, where) in new[] { ("switch", Patch_Building_GetGizmos.Where + ", the switch failed"), ("postfix", Patch_Building_GetGizmos.Where + " failed") }) { LawsTestHooks.CourtSwitchThrows = what == "switch"; LawsTestHooks.CourtGizmoThrows = what == "postfix"; T.ExpectErrors(where, 1); for (int i = 0; i < 3; i++) { List shown = null; try { shown = t1.GetGizmos().ToList(); } catch (Exception e) { T.Fail("a throw in the " + what + " broke the gizmo bar: " + e.GetType().Name + ": " + e.Message); } T.Check(!shown.OfType().Any(), "the gizmo bar shows the switch while the " + what + " throws"); T.Equal(plain.Count, shown.Count, "vanilla gizmos while the " + what + " throws"); } } LawsTestHooks.CourtSwitchThrows = false; LawsTestHooks.CourtGizmoThrows = false; NeedSwitch(t1, "the table after the throws stopped"); } [BlaxTest("court place save: a 1.0.0 save without the courtPlaces node loads with no warning or error, an empty list and no place")] public static void OldSaveWithoutNode() { CleanPlace(); GameComponent_BlaxLaws game = Fixtures.Comp; T.NotNull(game, "fixture: the game's component"); // The component's node as 1.0.0 wrote it: no courtPlaces. string path = Path.Combine(Path.GetTempPath(), "BlaxLawsTest_court_1.0.0_" + Guid.NewGuid().ToString("N") + ".xml"); File.WriteAllText(path, "\n" + " \n" + " 12345\n" + " 1\n" + " \n" + " 1\n" + " \n" + " \n" + "\n"); Fixtures.OnCleanup(() => { if (Scribe.mode != LoadSaveMode.Inactive) Scribe.ForceStop(); GameComponent_BlaxLaws.Remember(game, Current.Game); File.Delete(path); }); var logged = new List(); UnityEngine.Application.LogCallback listen = (text, stack, type) => { if (type != UnityEngine.LogType.Log) lock (logged) logged.Add(type + ": " + text); }; GameComponent_BlaxLaws old = null; UnityEngine.Application.logMessageReceivedThreaded += listen; try { Scribe.loader.InitLoading(path); Scribe_Deep.Look(ref old, "saveable"); Scribe.loader.FinalizeLoading(); } finally { UnityEngine.Application.logMessageReceivedThreaded -= listen; GameComponent_BlaxLaws.Remember(game, Current.Game); } T.Equal(LoadSaveMode.Inactive, Scribe.mode, "Scribe mode after the load"); T.Check(logged.Count == 0, "loading the 1.0.0 node logged: " + string.Join(" | ", logged.Take(3))); T.NotNull(old, "the component loaded from the 1.0.0 node"); T.Check(old.CourtPlaceEntries != null, "the court place list is null after loading a 1.0.0 save"); T.Equal(0, old.CourtPlaceEntries.Count, "court place entries after loading a 1.0.0 save"); T.Equal(null, old.CourtPlaceOn(Map), "court place of the 1.0.0 save"); T.Check(ReferenceEquals(game, GameComponent_BlaxLaws.Instance), "fixture: the game's component was not given back"); } // ---- DLC buildings ------------------------------------------------------------------------- [BlaxTest("court place: a throne gets the switch with Royalty; without it there is no throne def")] public static void Throne() { ThingDef def = DefDatabase.GetNamedSilentFail("Throne"); if (!ModsConfig.RoyaltyActive) T.Check(def == null, "a Throne def exists without Royalty"); T.NeedsDlc("Royalty", ModsConfig.RoyaltyActive); CleanPlace(); AnyLaw(); T.NotNull(def, "the Throne def"); Building throne = Make(def, Faction.OfPlayer); T.Check(throne is Building_Throne, "fixture: the throne is a " + throne.GetType().Name); NeedSwitch(throne, "a throne").toggleAction(); T.Equal(throne, CourtPlace.For(Map), "court place after switching it on on a throne"); } [BlaxTest("court place: the lectern and the ritual spot get the switch with Ideology; without it neither def exists")] public static void LecternAndRitualSpot() { if (!ModsConfig.IdeologyActive) { T.Check(ThingDefOf.Lectern == null && DefDatabase.GetNamedSilentFail("Lectern") == null, "a Lectern def exists without Ideology"); T.Check(ThingDefOf.RitualSpot == null && DefDatabase.GetNamedSilentFail("RitualSpot") == null, "a RitualSpot def exists without Ideology"); } T.NeedsDlc("Ideology", ModsConfig.IdeologyActive); CleanPlace(); AnyLaw(); IntVec3 near = Fixtures.PawnCell(); foreach (ThingDef def in new[] { ThingDefOf.Lectern, ThingDefOf.RitualSpot }) { T.NotNull(def, "a ritual def"); Building b = Make(def, Faction.OfPlayer, near: near); NeedSwitch(b, def.defName).toggleAction(); T.Equal(b, CourtPlace.For(Map), "court place after switching it on on the " + def.defName); } } // ---- save and removal ------------------------------------------------------------------------ [BlaxTest("court place save: a table is the court place at the first save (setup)", Order = 1000)] public static void SaveSetup() { CourtPlace.Clear(Map); Building table = Table(); Fixtures.Keep(table); T.Check(CourtPlace.Set(table), "Set refused the kept table"); T.Carry[CarryPlace] = table.ThingID; } [BlaxTest("court place save: after the reload the same table is the court place", phase: 2, Order = -1)] public static void SaveKeepsPlace() { T.Check(T.Carry.TryGetValue(CarryPlace, out string id), "the setup carried no court place"); Building place = CourtPlace.For(Map); T.NotNull(place, "court place after the reload"); T.Equal(id, place.ThingID, "court place after the reload"); T.Check(CourtPlace.Valid(place) && CourtPlace.IsPlace(place), "the reloaded place fails the validity check"); string line = CourtPlaceUi.Line(Map); T.Check(line.Contains(place.LabelCap) && !line.Contains(No), "tab line after the reload: " + line); } [BlaxTest("removal: a save with a court place loads with exactly the two removal errors, and the table stays the player's", phase: 3)] public static void RemovalWithPlace() { T.Check(T.Carry.TryGetValue(CarryPlace, out string id), "the setup carried no court place"); string xml = File.ReadAllText(GenFilePaths.FilePathForSavedGame(TestRunner.Phase3SaveName)); T.Check(xml.Contains("") && xml.Contains(">Thing_" + id + "<"), "the phase-3 save holds no court place naming Thing_" + id); T.Equal(2, T.Phase3LoadErrors.Count, "errors while loading the phase-3 save (" + string.Join(" | ", T.Phase3LoadErrors.Take(3)) + ")"); Building table = FindBuilding(id); T.NotNull(table, "the court place's table after the removal load"); T.Check(table.Spawned && table.Faction == Faction.OfPlayer, "the table after the removal load: spawned " + table.Spawned + ", faction " + table.Faction); T.Equal(null, CourtPlace.For(table.Map), "court place in the fresh component"); } } }