using System; using System.Collections.Generic; using System.Linq; using BlaxDefaults; using RimWorld; using Verse; namespace BlaxDefaultsTests { /// /// Work package "bills". The tests of design.md: Values for every new bill. /// Methods: [BlaxTest(": ", phase: N)] public static void X(). Skip DLC-only checks with /// Fixtures.NeedDlc(DlcSupport.Biotech) ("skipped: needs Biotech"). /// Headless tests call BillUtility.MakeNewBill directly; whether the Bills tab's add menu reaches the /// postfix (the JIT may inline MakeNewBill there) needs a manual check in game. /// public static class BillsTests { private const string StoveCarry = "bills.stove"; // ---- the postfix on MakeNewBill ------------------------------------------------------------------ [BlaxTest("bills: drop on floor, radius 30, do until 20 on a new simple meal bill; values not set stay vanilla")] public static void EveryBillValues() { Fixtures.Save(DropRadiusUntil20()); RecipeDef recipe = Recipe("CookMealSimple"); Bill_Production bill = MakeNew(recipe); T.Equal(typeof(Bill_Production), bill.GetType(), "bill type"); T.Equal(BillStoreModeDefOf.DropOnFloor, bill.GetStoreMode(), "store mode"); T.Check(bill.GetSlotGroup() == null, "the bill has a store group"); T.Equal(30f, bill.ingredientSearchRadius, "ingredient radius"); T.Equal(BillRepeatModeDefOf.TargetCount, bill.repeatMode, "repeat mode"); T.Equal(20, bill.targetCount, "target count"); SameExcept(bill, new Bill_Production(recipe), "storeMode", "ingredientSearchRadius", "repeatMode", "targetCount"); } [BlaxTest("bills: a bill with an unfinished thing (Bill_ProductionWithUft) gets the values too")] public static void UftBill() { Fixtures.Save(DropRadiusUntil20()); RecipeDef recipe = DefDatabase.GetNamedSilentFail("Make_ComponentIndustrial") ?? DefDatabase.AllDefs.FirstOrDefault(r => VanillaBillType(r) == typeof(Bill_ProductionWithUft)); Fixtures.NeedDef(recipe, "a recipe with an unfinished thing"); Bill_Production bill = MakeNew(recipe); T.Equal(typeof(Bill_ProductionWithUft), bill.GetType(), "bill type of " + recipe.defName); T.Equal(BillStoreModeDefOf.DropOnFloor, bill.GetStoreMode(), "store mode"); T.Equal(30f, bill.ingredientSearchRadius, "ingredient radius"); T.Equal(BillRepeatModeDefOf.TargetCount, bill.repeatMode, "repeat mode"); T.Equal(20, bill.targetCount, "target count"); } [BlaxTest("bills: every value is applied when set")] public static void EveryValueApplied() { Fixtures.Save(AllSet()); Bill_Production bill = MakeNew(Recipe("CookMealSimple")); T.Equal(BillRepeatModeDefOf.Forever, bill.repeatMode, "repeat mode"); T.Equal(3, bill.repeatCount, "repeat count"); T.Equal(7, bill.targetCount, "target count"); T.Equal(true, bill.pauseWhenSatisfied, "pause when satisfied"); T.Equal(2, bill.unpauseWhenYouHave, "resume at"); T.Equal(45f, bill.ingredientSearchRadius, "ingredient radius"); T.Equal(new IntRange(4, 12), bill.allowedSkillRange, "allowed skill range"); T.Equal(BillStoreModeDefOf.DropOnFloor, bill.GetStoreMode(), "store mode"); T.Equal(true, bill.includeEquipped, "count equipped"); T.Equal(true, bill.includeTainted, "count tainted"); T.Equal(new FloatRange(0.5f, 1f), bill.hpRange, "hit points range"); T.Equal(new QualityRange(QualityCategory.Good, QualityCategory.Legendary), bill.qualityRange, "quality range"); } [BlaxTest("bills: a recipe whose counter can't count products gets do X times, with the count when set")] public static void CantCountGetsRepeatCount() { RecipeDef recipe = Recipe("CremateCorpse"); Fixtures.Save(DropRadiusUntil20()); Bill_Production bill = MakeNew(recipe); T.Equal(typeof(Bill_Production), bill.GetType(), "bill type"); T.Check(!recipe.WorkerCounter.CanCountProducts(bill), "CremateCorpse can count its products; pick another recipe"); T.Equal(BillRepeatModeDefOf.RepeatCount, bill.repeatMode, "repeat mode without a count"); T.Equal(1, bill.repeatCount, "repeat count without a count (the game's)"); T.Equal(30f, bill.ingredientSearchRadius, "ingredient radius"); var withCount = DropRadiusUntil20(); withCount.setRepeatCount = true; withCount.repeatCount = 4; Fixtures.Save(withCount); bill = MakeNew(recipe); T.Equal(BillRepeatModeDefOf.RepeatCount, bill.repeatMode, "repeat mode with a count"); T.Equal(4, bill.repeatCount, "repeat count with a count"); } [BlaxTest("bills: a saved SpecificStockpile or an unknown mode name is skipped without an error")] public static void BadNamesSkipped() { Fixtures.Save(new BillValues(DefaultsKeys.EveryBill) { storeMode = "SpecificStockpile", repeatMode = "BlaxTest_Missing", setIngredientSearchRadius = true, ingredientSearchRadius = 20f, }); Bill_Production bill = MakeNew(Recipe("CookMealSimple")); T.Equal(BillStoreModeDefOf.BestStockpile, bill.GetStoreMode(), "store mode"); T.Equal(BillRepeatModeDefOf.RepeatCount, bill.repeatMode, "repeat mode"); T.Equal(20f, bill.ingredientSearchRadius, "ingredient radius"); T.Check(T.ErrorsSoFar().Count == 0, "errors logged: " + string.Join(" | ", T.ErrorsSoFar().Take(3))); } [BlaxTest("bills: a pasted bill (Bill.Clone) keeps its source's values when the saved values change")] public static void CloneKeepsSource() { RecipeDef recipe = Recipe("CookMealSimple"); Fixtures.Save(DropRadiusUntil20()); Bill_Production source = MakeNew(recipe); Fixtures.Save(new BillValues(DefaultsKeys.EveryBill) { storeMode = "BestStockpile", setIngredientSearchRadius = true, ingredientSearchRadius = 50f, repeatMode = "Forever", }); // As ITab_Bills pastes: Clone, then a new load id. var pasted = (Bill_Production)source.Clone(); pasted.InitializeAfterClone(); T.Equal(BillStoreModeDefOf.DropOnFloor, pasted.GetStoreMode(), "pasted store mode"); T.Equal(30f, pasted.ingredientSearchRadius, "pasted ingredient radius"); T.Equal(BillRepeatModeDefOf.TargetCount, pasted.repeatMode, "pasted repeat mode"); T.Equal(20, pasted.targetCount, "pasted target count"); Bill_Production fresh = MakeNew(recipe); T.Equal(50f, fresh.ingredientSearchRadius, "a new bill's radius after the change"); T.Equal(BillRepeatModeDefOf.Forever, fresh.repeatMode, "a new bill's repeat mode after the change"); } [BlaxTest("bills: surgery bills from HealthCardUtility.CreateSurgeryBill are untouched")] public static void SurgeryUntouched() { Fixtures.Save(AllSet()); Pawn pawn = Fixtures.Worker(); RecipeDef recipe = Recipe("Anesthetize"); Bill_Medical bill = HealthCardUtility.CreateSurgeryBill(pawn, recipe, null, null, sendMessages: false); try { T.NotNull(bill, "the surgery bill"); T.Check(!BillDefaults.AppliesTo(bill), "AppliesTo is true for a Bill_Medical"); var vanilla = new Bill_Medical(recipe, null); T.Equal(vanilla.ingredientSearchRadius, bill.ingredientSearchRadius, "surgery ingredient radius"); T.Equal(vanilla.allowedSkillRange, bill.allowedSkillRange, "surgery skill range"); BillDefaults.OnNewBill(bill); T.Equal(vanilla.ingredientSearchRadius, bill.ingredientSearchRadius, "surgery ingredient radius after OnNewBill"); T.Equal(vanilla.allowedSkillRange, bill.allowedSkillRange, "surgery skill range after OnNewBill"); } finally { if (bill != null && pawn.BillStack.Bills.Contains(bill)) pawn.BillStack.Delete(bill); } } [BlaxTest("bills: only exact Bill_Production and Bill_ProductionWithUft get the values, not their mech and forming subclasses")] public static void ExactTypesOnly() { Fixtures.Save(AllSet()); RecipeDef recipe = Recipe("CookMealSimple"); foreach (Type type in new[] { typeof(Bill_Autonomous), typeof(Bill_ProductionMech), typeof(Bill_ResurrectMech) }) { Bill_Production bill = Construct(type, recipe); T.Check(!BillDefaults.AppliesTo(bill), "AppliesTo is true for " + type.Name); BillDefaults.OnNewBill(bill); SameExcept(bill, Construct(type, recipe)); } foreach (Type type in new[] { typeof(Bill_Production), typeof(Bill_ProductionWithUft) }) { Bill_Production bill = Construct(type, recipe); T.Check(BillDefaults.AppliesTo(bill), "AppliesTo is false for " + type.Name); BillDefaults.OnNewBill(bill); T.Equal(45f, bill.ingredientSearchRadius, type.Name + " ingredient radius after OnNewBill"); } } [BlaxTest("bills: mech gestation and mech resurrection bills from MakeNewBill keep vanilla values (Biotech)")] public static void MechBillsVanilla() { Fixtures.NeedDlc(DlcSupport.Biotech); Fixtures.Save(AllSet()); foreach (Type type in new[] { typeof(Bill_ProductionMech), typeof(Bill_ResurrectMech) }) { RecipeDef recipe = DefDatabase.AllDefs.FirstOrDefault(r => VanillaBillType(r) == type); Fixtures.NeedDef(recipe, "a recipe that makes a " + type.Name); Bill_Production bill = MakeNew(recipe); T.Equal(type, bill.GetType(), "bill type of " + recipe.defName); SameExcept(bill, Construct(type, recipe)); } } [BlaxTest("bills: a forming bill (Bill_Autonomous) from MakeNewBill keeps vanilla values, where a recipe makes one")] public static void FormingBillsVanilla() { Fixtures.Save(AllSet()); RecipeDef recipe = DefDatabase.AllDefs.FirstOrDefault(r => VanillaBillType(r) == typeof(Bill_Autonomous)); if (recipe == null) { // In the installed DLCs every forming recipe also gestates; ExactTypesOnly covers the class. T.Info("no loaded recipe makes a Bill_Autonomous; checked by ExactTypesOnly only"); return; } Bill_Production bill = MakeNew(recipe); T.Equal(typeof(Bill_Autonomous), bill.GetType(), "bill type of " + recipe.defName); SameExcept(bill, Construct(typeof(Bill_Autonomous), recipe)); } [BlaxTest("bills: with billDefaults or enabled off, new bills keep the game's values")] public static void OffAppliesNothing() { Fixtures.Save(AllSet()); RecipeDef recipe = Recipe("CookMealSimple"); Fixtures.Settings.billDefaults = false; T.Check(!BlaxDefaultsMod.BillsOn, "BillsOn with billDefaults off"); SameExcept(MakeNew(recipe), new Bill_Production(recipe)); Fixtures.Settings.billDefaults = true; Fixtures.Settings.enabled = false; T.Check(!BlaxDefaultsMod.BillsOn, "BillsOn with enabled off"); SameExcept(MakeNew(recipe), new Bill_Production(recipe)); Fixtures.Settings.enabled = true; T.Equal(45f, MakeNew(recipe).ingredientSearchRadius, "ingredient radius with both on again"); } [BlaxTest("bills: no saved values, no change")] public static void NothingSaved() { DefaultsLibrary.Forget(DefaultsKeys.EveryBill); RecipeDef recipe = Recipe("CookMealSimple"); SameExcept(MakeNew(recipe), new Bill_Production(recipe)); } // ---- the settings section's logic ---------------------------------------------------------------- [BlaxTest("bills section: setting then clearing every value forgets the bill:* entry")] public static void SectionForgetsWhenNothingSet() { DefaultsLibrary.Forget(DefaultsKeys.EveryBill); T.Check(BillValuesSection.Store(new BillValues(DefaultsKeys.EveryBill)), "storing values with nothing set failed"); T.Check(!DefaultsLibrary.Has(DefaultsKeys.EveryBill), "storing values with nothing set added an entry"); foreach (BillField f in BillValuesSection.Fields) { T.Check(BillValuesSection.Edit(v => BillValuesSection.Change(v, f)), "storing " + f + " failed"); T.Check(BillValuesSection.IsSet(BillDefaults.Values, f), f + " is not set after Change"); } BillValues all = BillDefaults.Values; T.Equal(BillValuesSection.Fields.Length, BillValuesSection.Fields.Count(f => BillValuesSection.IsSet(all, f)), "values set"); T.Equal(DefaultsKeys.EveryBill, all.key, "key"); // Change starts from the game's value: a bill made now matches a vanilla bill. RecipeDef recipe = Recipe("CookMealSimple"); SameExcept(MakeNew(recipe), new Bill_Production(recipe)); BillValuesSection.Edit(v => { v.ingredientSearchRadius = 30f; v.repeatMode = "Forever"; }); T.Equal(30f, BillDefaults.Values.ingredientSearchRadius, "radius after an edit"); BillField last = BillValuesSection.Fields.Last(); foreach (BillField f in BillValuesSection.Fields) { T.Check(BillValuesSection.Edit(v => BillValuesSection.Clear(v, f)), "storing the cleared " + f + " failed"); if (f == last) break; BillValues now = BillDefaults.Values; T.NotNull(now, "the entry after clearing " + f + " while other values are set"); T.Check(!BillValuesSection.IsSet(now, f), f + " is still set after Clear"); if (f == BillField.IngredientSearchRadius) T.Equal(999f, now.ingredientSearchRadius, "radius after Clear (the game's)"); } T.Check(!DefaultsLibrary.Has(DefaultsKeys.EveryBill), "bill:* is still saved after every value was cleared"); T.Check(BillValuesSection.Working().key == DefaultsKeys.EveryBill && !BillValuesSection.Working().AnySet, "Working after forgetting"); } [BlaxTest("bills section: every row label and text of the section is in Keyed")] public static void SectionStrings() { var keys = BillValuesSection.Fields.Select(f => "BlaxDefaults_Bills_" + f).Concat(new[] { "BlaxDefaults_Bills_Intro", "BlaxDefaults_Bills_Off", "BlaxDefaults_Bills_TargetNote", "BlaxDefaults_Bills_ResumeNote", "BlaxDefaults_Bills_RepeatCountTip", "BlaxDefaults_Bills_TargetOnlyTip", "BlaxDefaults_Bills_GameDefault", "BlaxDefaults_Bills_Change", "BlaxDefaults_Bills_UseGameDefault", "BlaxDefaults_Bills_ValueOn", "BlaxDefaults_Bills_ValueOff", "BlaxDefaults_Bills_Unlimited", "BlaxDefaults_Bills_Range", "BlaxDefaults_Bills_AnyQuality", "BlaxDefaults_Bills_ResetAll", "BlaxDefaults_Bills_ResetAllConfirm", }); var missing = keys.Where(k => !k.CanTranslate()).ToList(); T.Check(missing.Count == 0, "strings missing from Keyed: " + string.Join(", ", missing)); } [BlaxTest("bills section: the resume note shows when resume at is not below the target")] public static void SectionPauseNote() { var v = new BillValues(DefaultsKeys.EveryBill) { setPauseWhenSatisfied = true, pauseWhenSatisfied = true }; T.Check(!BillValuesSection.PauseNeverStarts(v), "flagged with the game's target 10 and resume 5"); v.setTargetCount = true; v.targetCount = 5; T.Check(BillValuesSection.PauseNeverStarts(v), "not flagged with target 5 and the game's resume 5"); v.setUnpauseWhenYouHave = true; v.unpauseWhenYouHave = 4; T.Check(!BillValuesSection.PauseNeverStarts(v), "flagged with target 5 and resume 4"); } [BlaxTest("bills section: forget all removes the entry, and storing unchanged values writes nothing new")] public static void SectionForgetAll() { Fixtures.Save(DropRadiusUntil20()); BillValues live = BillDefaults.Values; T.Check(BillValuesSection.Store(BillValuesSection.Working()), "storing unchanged values failed"); T.Check(ReferenceEquals(live, BillDefaults.Values), "storing unchanged values replaced the entry"); BillValuesSection.ForgetAll(); T.Check(!DefaultsLibrary.Has(DefaultsKeys.EveryBill), "bill:* is still saved after ForgetAll"); } // ---- save and reload ----------------------------------------------------------------------------- [BlaxTest("bills: a new bill on a stove keeps its values in the save (setup)")] public static void SavedBillSetup() { Fixtures.Save(new BillValues(DefaultsKeys.EveryBill) { storeMode = "DropOnFloor", setIngredientSearchRadius = true, ingredientSearchRadius = 30f, repeatMode = "Forever", }); CellRect area = Fixtures.EmptyArea(3, 3); var stove = (Building_WorkTable)ThingMaker.MakeThing(Fixtures.Thing("FueledStove")); stove.SetFactionDirect(Faction.OfPlayer); GenSpawn.Spawn(stove, area.CenterCell, Fixtures.Map); Fixtures.Keep(Fixtures.Track(stove)); Bill bill = Recipe("CookMealSimple").MakeNewBill(); bill.suspended = true; // nobody cooks during the other tests stove.billStack.AddBill(bill); T.Equal(BillStoreModeDefOf.DropOnFloor, ((Bill_Production)bill).GetStoreMode(), "store mode before the save"); T.Carry[StoveCarry] = stove.ThingID; } [BlaxTest("bills: a new bill on a stove keeps its values in the save", phase: 2)] public static void SavedBillReloaded() { T.Check(T.Carry.TryGetValue(StoveCarry, out string id), "phase 1 carried no stove"); var stove = Fixtures.FindThingById(id) as Building_WorkTable; T.NotNull(stove, "the stove after reload"); Bill_Production bill = stove.billStack.Bills.OfType().FirstOrDefault(b => b.recipe?.defName == "CookMealSimple"); T.NotNull(bill, "the simple meal bill after reload"); T.Equal(BillStoreModeDefOf.DropOnFloor, bill.GetStoreMode(), "store mode after reload"); T.Equal(30f, bill.ingredientSearchRadius, "ingredient radius after reload"); T.Equal(BillRepeatModeDefOf.Forever, bill.repeatMode, "repeat mode after reload"); } // ---- helpers ------------------------------------------------------------------------------------- private static RecipeDef Recipe(string defName) => Fixtures.NeedDef(DefDatabase.GetNamedSilentFail(defName), "RecipeDef " + defName); private static Bill_Production MakeNew(RecipeDef recipe) { Bill bill = recipe.MakeNewBill(); T.Check(bill is Bill_Production, "MakeNewBill(" + recipe.defName + ") returned " + (bill?.GetType().Name ?? "null")); return (Bill_Production)bill; } /// A bill of this class made with its constructor, as MakeNewBill would before the postfix. private static Bill_Production Construct(Type type, RecipeDef recipe) => (Bill_Production)Activator.CreateInstance(type, recipe, null); /// The class BillUtility.MakeNewBill picks for the recipe (RimWorld/BillUtility.cs:36-55). private static Type VanillaBillType(RecipeDef r) { if (r.UsesUnfinishedThing) return typeof(Bill_ProductionWithUft); if (r.mechResurrection) return typeof(Bill_ResurrectMech); if (r.gestationCycles > 0) return typeof(Bill_ProductionMech); if (r.formingTicks > 0) return typeof(Bill_Autonomous); return typeof(Bill_Production); } /// "Drop on floor, radius 30, do until 20", the design's example. private static BillValues DropRadiusUntil20() => new BillValues(DefaultsKeys.EveryBill) { storeMode = "DropOnFloor", setIngredientSearchRadius = true, ingredientSearchRadius = 30f, repeatMode = "TargetCount", setTargetCount = true, targetCount = 20, }; /// Every value set, each to something other than the game's value. private static BillValues AllSet() => new BillValues(DefaultsKeys.EveryBill) { repeatMode = "Forever", setRepeatCount = true, repeatCount = 3, setTargetCount = true, targetCount = 7, setPauseWhenSatisfied = true, pauseWhenSatisfied = true, setUnpauseWhenYouHave = true, unpauseWhenYouHave = 2, setIngredientSearchRadius = true, ingredientSearchRadius = 45f, setAllowedSkillRange = true, allowedSkillRange = new IntRange(4, 12), storeMode = "DropOnFloor", setIncludeEquipped = true, includeEquipped = true, setIncludeTainted = true, includeTainted = true, setHpRange = true, hpRange = new FloatRange(0.5f, 1f), setQualityRange = true, qualityRange = new QualityRange(QualityCategory.Good, QualityCategory.Legendary), }; /// The values a bill default can set, by name, as text. private static Dictionary Describe(Bill_Production b) => new Dictionary { ["repeatMode"] = b.repeatMode?.defName, ["repeatCount"] = b.repeatCount.ToString(), ["targetCount"] = b.targetCount.ToString(), ["pauseWhenSatisfied"] = b.pauseWhenSatisfied.ToString(), ["unpauseWhenYouHave"] = b.unpauseWhenYouHave.ToString(), ["ingredientSearchRadius"] = b.ingredientSearchRadius.ToString("R"), ["allowedSkillRange"] = b.allowedSkillRange.ToString(), ["storeMode"] = b.GetStoreMode()?.defName, ["storeGroup"] = (b.GetSlotGroup() != null).ToString(), ["includeEquipped"] = b.includeEquipped.ToString(), ["includeTainted"] = b.includeTainted.ToString(), ["hpRange"] = b.hpRange.ToString(), ["qualityRange"] = b.qualityRange.ToString(), }; /// Fails when the bill differs from the vanilla bill in any value other than those named. private static void SameExcept(Bill_Production actual, Bill_Production vanilla, params string[] except) { Dictionary a = Describe(actual), v = Describe(vanilla); var diffs = a.Keys.Where(k => !except.Contains(k) && a[k] != v[k]).Select(k => k + " " + a[k] + " (vanilla " + v[k] + ")").ToList(); T.Check(diffs.Count == 0, actual.GetType().Name + " " + actual.recipe?.defName + " differs from vanilla: " + string.Join(", ", diffs)); } } }