using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using BlaxZones; using RimWorld; using UnityEngine; using Verse; namespace BlaxZonesTests { /// /// Package Tab. Design: 1.0 "Delivery zone" > Tests (default filter, filter/priority/orbital/camp persist in phase 2, copy/paste). /// Tests: [BlaxTest("tab: what", phase: N)], phase 1 fresh colony, 2 after save and reload, 3 after the component class was stripped. /// FillTab needs the GUI, so these test what it draws from: the dropdown entries, the tooltips, the hidden defs. /// public static class TabTests { private const string PersistKey = "tab.persistZone"; private static readonly string[] TabKeys = { "BlaxZones_TabDelivery", "BlaxZones_PriorityTip", "BlaxZones_AcceptOrbital", "BlaxZones_AcceptOrbitalTip", "BlaxZones_AcceptOrbitalSlavesTip", "BlaxZones_AcceptOrbitalOffTip", "BlaxZones_AcceptOrbitalOffSlavesTip", "BlaxZones_CampHere", "BlaxZones_CampHereTip", "BlaxZones_CampHereOffTip", "BlaxZones_CampHereStandDownTip", "BlaxZones_CopySettings", "BlaxZones_CopySettingsDesc", "BlaxZones_PasteSettings", "BlaxZones_PasteSettingsDesc", "BlaxZones_SettingsCopied", "BlaxZones_SettingsPasted", "BlaxZones_NothingCopied", }; // ---- default filter ---------------------------------------------------------------- [BlaxTest("tab: the default filter allows silver, medicine and steel and hides every corpse")] public static void DefaultFilterAllowsGoods() { Zone_Delivery zone = Fixtures.DeliveryZone(Fixtures.TestArea(2, 2)); foreach (ThingDef def in new[] { ThingDefOf.Silver, ThingDefOf.MedicineHerbal, ThingDefOf.MedicineIndustrial, ThingDefOf.Steel }) { T.Check(zone.filter.Allows(def), "default filter refuses " + def.defName); T.Check(zone.Accepts(Fixtures.Stack(def, 10)), "zone refuses a stack of " + def.defName); } List hidden = ITab_Delivery.HiddenDefs(); int corpses = 0; foreach (ThingDef corpse in ThingCategoryDefOf.Corpses.DescendantThingDefs) { corpses++; T.Check(!zone.filter.Allows(corpse), "default filter allows " + corpse.defName); T.Check(!DeliveryFilters.Parent.Allows(corpse), "parent filter allows " + corpse.defName); T.Check(hidden.Contains(corpse), "tab doesn't hide " + corpse.defName); } T.Check(corpses > 0, "no corpse defs found under ThingCategoryDefOf.Corpses"); } [BlaxTest("tab: the default filter refuses Wastepack, also after Allow all and a category checkbox")] public static void DefaultFilterRefusesWastepack() { T.NeedsDlc("Biotech", ModsConfig.BiotechActive); ThingDef wastepack = ThingDefOf.Wastepack; T.NotNull(wastepack, "ThingDefOf.Wastepack with Biotech"); Zone_Delivery zone = Fixtures.DeliveryZone(Fixtures.TestArea(2, 2)); T.Check(!zone.filter.Allows(wastepack), "default filter allows Wastepack"); T.Check(!DeliveryFilters.Parent.Allows(wastepack), "parent filter allows Wastepack"); T.Check(!zone.Accepts(Fixtures.Stack(wastepack, 1)), "zone accepts a Wastepack"); T.Check(ITab_Delivery.HiddenDefs().Contains(wastepack), "tab doesn't hide Wastepack"); // What the tab's buttons do: "Allow all" (SetAllowAll(parent)) and a category checkbox // (SetAllow(category, true, forceHiddenDefs)), ThingFilterUI.cs and Listing_TreeThingFilter.cs:177. zone.filter.SetDisallowAll(ITab_Delivery.HiddenDefs()); zone.filter.SetAllowAll(DeliveryFilters.Parent); T.Check(!zone.filter.Allows(wastepack), "Allow all let Wastepack in"); foreach (ThingCategoryDef cat in wastepack.thingCategories ?? new List()) { zone.filter.SetAllow(cat, true, ITab_Delivery.HiddenDefs()); T.Check(!zone.filter.Allows(wastepack), "ticking category " + cat.defName + " let Wastepack in"); } T.Check(!zone.Accepts(Fixtures.Stack(wastepack, 1)), "zone accepts a Wastepack after the filter buttons"); } [BlaxTest("tab: without Biotech a delivery zone, its filter, tab and gizmos build with no error")] public static void BuildsWithoutBiotech() { if (ModsConfig.BiotechActive) T.Skip("runs without Biotech only"); T.Check(ThingDefOf.Wastepack == null, "ThingDefOf.Wastepack is set without Biotech"); var errors = new List(); Application.LogCallback hook = (text, stack, type) => { if (type == LogType.Error || type == LogType.Exception) lock (errors) errors.Add(text); }; Application.logMessageReceivedThreaded += hook; try { Zone_Delivery zone = Fixtures.DeliveryZone(Fixtures.TestArea(2, 2)); T.Check(zone.filter.Allows(ThingDefOf.Steel), "default filter refuses steel"); T.Check(zone.Accepts(Fixtures.Stack(ThingDefOf.Steel, 10)), "zone refuses steel"); T.Check(ITab_Delivery.HiddenDefs().All(d => d != null), "hidden defs hold a null"); T.Check(zone.GetInspectTabs().Single() is ITab_Delivery, "tab is not ITab_Delivery"); T.Check(zone.GetGizmos().Count() >= 2, "gizmos missing"); T.Check(!ITab_Delivery.OrbitalTip().NullOrEmpty(), "orbital tooltip empty"); T.Check(!ITab_Delivery.CampTip().NullOrEmpty(), "camp tooltip empty"); DeliveryClipboard.Copy(zone); DeliveryClipboard.PasteInto(zone); } finally { Application.logMessageReceivedThreaded -= hook; } T.Check(errors.Count == 0, "errors while building: " + string.Join(" | ", errors.Take(3))); } // ---- persistence (needs package Store; green at integration) ------------------------- [BlaxTest("tab: filter, priority, orbital and camp flags set up for the reload")] public static void PersistSetup() { Zone_Delivery zone = Fixtures.KeepZone(Fixtures.DeliveryZone(Fixtures.TestArea(3, 2), Fixtures.FilterOf(ThingDefOf.MedicineIndustrial, ThingDefOf.Silver), StoragePriority.Critical, orbital: false, camp: false)); T.Carry[PersistKey + ".defs"] = zone.filter.AllowedDefCount.ToString(); // "Caravans camp here" goes on only right before the save, so no later phase-1 camp test meets // a stray camp zone. Orbital is off, so the router never picks this zone either. T.CarryAtSave(PersistKey, () => { zone.campHere = true; return zone.ID.ToString(); }); } [BlaxTest("tab: filter, priority, orbital and camp flags persist", phase: 2)] public static void PersistCheck() { int zoneId = -1; if (!T.Carry.TryGetValue(PersistKey, out string id) || !int.TryParse(id, out zoneId)) T.Fail("phase 1 carried no zone ID"); var zone = Fixtures.FindZoneById(zoneId) as Zone_Delivery; T.NotNull(zone, "delivery zone " + zoneId + " after the reload"); Fixtures.OnCleanup(() => zone.campHere = false); // no stray camp zone for later phase-2 tests T.Equal(6, zone.CellCount, "cells"); T.Equal(StoragePriority.Critical, zone.priority, "priority"); T.Equal(false, zone.acceptOrbital, "orbital checkbox"); T.Equal(true, zone.campHere, "camp checkbox"); T.NotNull(zone.filter, "filter"); if (T.Carry.TryGetValue(PersistKey + ".defs", out string defs)) T.Equal(defs, zone.filter.AllowedDefCount.ToString(), "allowed defs"); T.Check(zone.filter.Allows(ThingDefOf.MedicineIndustrial), "filter lost industrial medicine"); T.Check(zone.filter.Allows(ThingDefOf.Silver), "filter lost silver"); T.Check(!zone.filter.Allows(ThingDefOf.Steel), "filter allows steel"); } // ---- copy and paste -------------------------------------------------------------------- [BlaxTest("tab: copy then paste moves filter, priority, orbital and camp to another zone, never its cells")] public static void CopyPaste() { Map map = Fixtures.Map; CellRect ra = Fixtures.TestArea(3, 2); CellRect rb = Fixtures.TestArea(2, 2); Zone_Delivery a = Fixtures.DeliveryZone(ra, Fixtures.FilterOf(ThingDefOf.MedicineIndustrial), StoragePriority.Important, orbital: false, camp: true); Zone_Delivery b = Fixtures.DeliveryZone(rb); List bCells = b.Cells.ToList(); string bLabel = b.label; int bId = b.ID; int copiedDefs = a.filter.AllowedDefCount; DeliveryClipboard.Copy(a); T.Check(DeliveryClipboard.HasCopy, "HasCopy after Copy"); // Change the source after copying: the clipboard must hold a detached copy. a.filter.SetAllow(ThingDefOf.Steel, true); a.priority = StoragePriority.Low; a.acceptOrbital = true; a.campHere = false; DeliveryClipboard.PasteInto(b); T.Equal(StoragePriority.Important, b.priority, "pasted priority"); T.Equal(false, b.acceptOrbital, "pasted orbital checkbox"); T.Equal(true, b.campHere, "pasted camp checkbox"); T.Check(b.filter.Allows(ThingDefOf.MedicineIndustrial), "pasted filter refuses industrial medicine"); T.Check(!b.filter.Allows(ThingDefOf.Steel), "pasted filter allows steel, changed on the source after the copy"); T.Equal(copiedDefs, b.filter.AllowedDefCount, "pasted filter's allowed defs"); T.Check(!ReferenceEquals(a.filter, b.filter), "paste shared the source's filter object"); T.Equal(bCells.Count, b.CellCount, "target cells after paste"); T.Check(bCells.All(b.ContainsCell), "target lost a cell"); T.Check(bCells.All(c => map.zoneManager.ZoneAt(c) == b), "a target cell left the target zone"); T.Check(ra.Cells.All(c => map.zoneManager.ZoneAt(c) == a), "a source cell left the source zone"); T.Equal(6, a.CellCount, "source cells after paste"); T.Equal(bLabel, b.label, "target label"); T.Equal(bId, b.ID, "target ID"); T.Check(!b.Cells.Any(ra.Contains), "paste moved source cells"); foreach (FieldInfo f in typeof(DeliveryClipboard).GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)) { T.Check(!typeof(Zone).IsAssignableFrom(f.FieldType), "DeliveryClipboard." + f.Name + " is typed " + f.FieldType.Name); AssertNoZone(f.GetValue(null), "DeliveryClipboard." + f.Name, depth: 2); } } /// Fails if the value is a Zone, holds one in a collection or a delegate target, or in its own fields, down to levels. private static void AssertNoZone(object value, string where, int depth) { if (value == null) return; T.Check(!(value is Zone), where + " holds a Zone"); if (value is Delegate d) { foreach (Delegate inv in d.GetInvocationList()) T.Check(!(inv.Target is Zone), where + " is a delegate bound to a Zone"); if (depth > 0) foreach (Delegate inv in d.GetInvocationList()) AssertNoZone(inv.Target, where + ".Target", depth - 1); return; } Type type = value.GetType(); if (type.IsPrimitive || type.IsEnum || value is string || value is Def || value is UnityEngine.Object) return; if (value is IEnumerable list) { foreach (object item in list) { T.Check(!(item is Zone), where + " lists a Zone"); if (depth > 0) AssertNoZone(item, where + "[]", depth - 1); } return; } if (depth <= 0) return; for (Type t = type; t != null && t != typeof(object); t = t.BaseType) { foreach (FieldInfo f in t.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly)) AssertNoZone(f.GetValue(value), where + "." + f.Name, depth - 1); } } // ---- tab and gizmos -------------------------------------------------------------------- [BlaxTest("tab: GetInspectTabs returns the shared ITab_Delivery, which shows the selected zone")] public static void InspectTab() { Zone_Delivery zone = Fixtures.DeliveryZone(Fixtures.TestArea(2, 2)); List tabs = zone.GetInspectTabs()?.ToList(); T.NotNull(tabs, "GetInspectTabs()"); T.Equal(1, tabs.Count, "tab count"); var tab = tabs[0] as ITab_Delivery; T.NotNull(tab, "the tab as ITab_Delivery (got " + tabs[0]?.GetType().Name + ")"); T.Check(ReferenceEquals(tab, InspectTabManager.GetSharedInstance(typeof(ITab_Delivery))), "tab is not the shared instance"); T.Equal("BlaxZones_TabDelivery", tab.labelKey, "labelKey"); Find.Selector.ClearSelection(); Find.Selector.Select(zone, playSound: false, forceDesignatorDeselect: false); T.Check(tab.SelZone == zone, "SelZone is not the selected zone"); T.Check(tab.IsVisible, "tab hidden while a delivery zone is selected"); Find.Selector.ClearSelection(); T.Check(tab.SelZone == null, "SelZone set with nothing selected"); } [BlaxTest("tab: GetGizmos holds the base zone gizmos plus copy and paste")] public static void Gizmos() { Zone_Delivery zone = Fixtures.DeliveryZone(Fixtures.TestArea(2, 2)); List gizmos = zone.GetGizmos().ToList(); string deleteLabel = "CommandDeleteZoneLabel".Translate(); T.Check(gizmos.OfType().Any(c => c.defaultLabel == deleteLabel), "base delete command missing"); Command_Action copy = FindCommand(gizmos, "BlaxZones_CopySettings"); Command_Action paste = FindCommand(gizmos, "BlaxZones_PasteSettings"); T.NotNull(copy, "copy command"); T.NotNull(paste, "paste command"); T.NotNull(copy.action, "copy action"); T.NotNull(paste.action, "paste action"); T.Check(gizmos.IndexOf(copy) < gizmos.IndexOf(paste), "paste comes before copy"); T.Equal(!DeliveryClipboard.HasCopy, paste.Disabled, "paste disabled exactly while nothing is copied"); DeliveryClipboard.Copy(zone); Command_Action pasteAfter = FindCommand(zone.GetGizmos().ToList(), "BlaxZones_PasteSettings"); T.NotNull(pasteAfter, "paste command after a copy"); T.Check(!pasteAfter.Disabled, "paste disabled after a copy"); } private static Command_Action FindCommand(List gizmos, string labelKey) { string label = labelKey.Translate(); return gizmos.OfType().FirstOrDefault(c => c.defaultLabel == label); } [BlaxTest("tab: the priority dropdown lists Low to Critical and sets the zone's priority")] public static void PriorityDropdown() { Zone_Delivery zone = Fixtures.DeliveryZone(Fixtures.TestArea(2, 2)); StoragePriority[] expected = { StoragePriority.Low, StoragePriority.Normal, StoragePriority.Preferred, StoragePriority.Important, StoragePriority.Critical, }; T.Check(ITab_Delivery.Priorities().SequenceEqual(expected), "priorities: " + string.Join(", ", ITab_Delivery.Priorities())); List options = ITab_Delivery.PriorityMenuOptions(zone); T.Equal(expected.Length, options.Count, "dropdown entries"); for (int i = 0; i < expected.Length; i++) { T.Equal(expected[i].Label().CapitalizeFirst(), options[i].Label, "entry " + i); options[i].action(); T.Equal(expected[i], zone.priority, "priority after picking entry " + i); } T.Check(ITab_Delivery.PriorityButtonLabel(StoragePriority.Important).Contains(StoragePriority.Important.Label().CapitalizeFirst()), "button label doesn't name the priority"); } // ---- strings and tooltips -------------------------------------------------------------- [BlaxTest("tab: the tab label, tooltip and gizmo keys translate")] public static void KeysTranslate() { var missing = TabKeys.Where(k => !k.CanTranslate()).ToList(); T.Check(missing.Count == 0, "strings missing from Keyed: " + string.Join(", ", missing)); T.Check("Priority".CanTranslate(), "vanilla key Priority missing"); T.Equal("BlaxZones_TabDelivery", new ITab_Delivery().labelKey, "labelKey of a new tab"); } [BlaxTest("tab: the orbital tooltip adds the Blax Slaves line only while Slaves is active")] public static void SlavesTooltip() { string slavesLine = "BlaxZones_AcceptOrbitalSlavesTip".Translate(); Fixtures.OnCleanup(() => Compat.SimulatedActive.Remove(Compat.BlaxSlaves)); bool slavesReallyActive = ModLister.GetActiveModWithIdentifier(Compat.BlaxSlaves, ignorePostfix: true) != null; if (slavesReallyActive) T.Info("Blax Slaves is loaded in this run; the tooltip-without-Slaves check is skipped"); else T.Check(!ITab_Delivery.OrbitalTip().Contains(slavesLine), "Slaves line shown without Blax Slaves"); Compat.SimulatedActive.Add(Compat.BlaxSlaves); T.Check(ITab_Delivery.OrbitalTip().Contains(slavesLine), "Slaves line missing while Blax Slaves is active"); } [BlaxTest("tab: the orbital and camp tooltips say when the mod settings turn them off")] public static void SettingsOffTooltips() { BlaxZonesSettings s = Fixtures.Settings; // With Blax Slaves loaded in this run the off note names its payouts (tested below). string orbitalOff = (Compat.SlavesActive ? "BlaxZones_AcceptOrbitalOffSlavesTip" : "BlaxZones_AcceptOrbitalOffTip").Translate(); string campOff = "BlaxZones_CampHereOffTip".Translate(); s.routeOrbital = true; s.campAtZones = true; T.Check(!ITab_Delivery.OrbitalTip().Contains(orbitalOff), "orbital off note while routing is on"); T.Check(!ITab_Delivery.CampTip().Contains(campOff), "camp off note while camping is on"); s.routeOrbital = false; s.campAtZones = false; T.Check(ITab_Delivery.OrbitalTip().Contains(orbitalOff), "orbital off note missing while routing is off"); T.Check(ITab_Delivery.CampTip().Contains(campOff), "camp off note missing while camping is off"); } [BlaxTest("tab: with Blax Slaves active and orbital routing off, the tooltip says Slaves payouts still land")] public static void SlavesOffTooltip() { string plainOff = "BlaxZones_AcceptOrbitalOffTip".Translate(); string slavesOff = "BlaxZones_AcceptOrbitalOffSlavesTip".Translate(); Fixtures.OnCleanup(() => Compat.SimulatedActive.Remove(Compat.BlaxSlaves)); Compat.SimulatedActive.Add(Compat.BlaxSlaves); Fixtures.Settings.routeOrbital = false; string tip = ITab_Delivery.OrbitalTip(); T.Check(tip.Contains(slavesOff), "the off note doesn't say Blax Slaves payouts still land"); T.Check(!tip.Contains(plainOff), "the tooltip says nothing lands here, though Blax Slaves payouts still do"); Fixtures.Settings.routeOrbital = true; T.Check(!ITab_Delivery.OrbitalTip().Contains(slavesOff), "orbital off note while routing is on"); } } }