using System.Collections.Generic; using System.Linq; using BlaxLaws; using HarmonyLib; using RimWorld; using Verse; namespace BlaxLawsTests { /// The skeleton and the harness work: patches, settings, defs, the component, the empty book, all three phases. public static class SmokeTests { private static readonly string[] SharedKeys = { "BlaxLaws_NeedsDlc", "BlaxLaws_MissingMod", "BlaxLaws_Stage_Planning", "BlaxLaws_Stage_DidIt", "BlaxLaws_Severity_Minor", "BlaxLaws_Severity_Moderate", "BlaxLaws_Severity_Serious", "BlaxLaws_Severity_Grave", "BlaxLaws_Status_Open", "BlaxLaws_Status_Enforcing", "BlaxLaws_Status_Jailed", "BlaxLaws_Status_Closed", "BlaxLaws_Outcome_Repealed", "BlaxLaws_Outcome_BreakEnded", "BlaxLaws_Outcome_NotEnforced", "BlaxLaws_DrugOption_Any", "BlaxLaws_DrugOption_Hard", "BlaxLaws_DrugOption_Social", "BlaxLaws_EmptyBook", "BlaxLaws_CaseFiled", "BlaxLaws_SettingEnforceLaws", "BlaxLaws_SettingShowTab", "BlaxLaws_SettingCaseMessages", "BlaxLaws_SettingJailLetters", "BlaxLaws_SettingEnforcers", "BlaxLaws_EnforcersWardensFirst", "BlaxLaws_EnforcersWardensOnly", "BlaxLaws_SettingSubdueCatharsis", "BlaxLaws_SettingPlayerOrdersExempt", "BlaxLaws_SettingCooldownDays", "BlaxLaws_SettingKeepClosedDays", "BlaxLaws_SettingsReset", }; [BlaxTest("startup: every patch class applied and logged, no errors mentioning Blax Laws")] public static void StartupLogged() { int ours = Harmony.GetAllPatchedMethods() .Select(Harmony.GetPatchInfo) .Where(info => info != null) .SelectMany(info => info.Prefixes.Concat(info.Postfixes).Concat(info.Finalizers).Concat(info.Transpilers)) .Count(p => p.owner == BlaxLawsStartup.HarmonyId); T.Info("patch classes applied: " + BlaxLawsStartup.Applied + ", Harmony patches owned by " + BlaxLawsStartup.HarmonyId + ": " + ours); T.Check(BlaxLawsStartup.FailedPatches.Count == 0, "patch classes failed: " + string.Join(", ", BlaxLawsStartup.FailedPatches)); // Only what was logged before the first test: later tests log expected errors on purpose. var startup = TestRunner.StartupLog; string line = startup.FirstOrDefault(m => m.text != null && m.text.Contains("[Blax Laws]") && m.text.Contains("patches applied"))?.text; T.Check(line != null, "startup line '[Blax Laws] N patches applied' not in the log"); T.Check(line.Contains("[Blax Laws] " + BlaxLawsStartup.Applied + " patches applied"), "startup line names another count: " + line); var errors = startup.Where(m => m.type == LogMessageType.Error && m.text != null && (m.text.Contains("Blax Laws") || m.text.Contains("BlaxLaws"))).ToList(); T.Check(errors.Count == 0, "errors mentioning Blax Laws at startup: " + string.Join(" | ", errors.Take(3).Select(e => e.text))); var warnings = startup.Where(m => m.type == LogMessageType.Warning && m.text != null && (m.text.Contains("Blax Laws") || m.text.Contains("BlaxLaws"))).ToList(); T.Check(warnings.Count == 0, "warnings mentioning Blax Laws at startup: " + string.Join(" | ", warnings.Take(3).Select(e => e.text))); } [BlaxTest("startup: every Blax Laws finalizer returns void, so Harmony rethrows exceptions with their stack trace")] public static void FinalizersReturnVoid() { // One finalizer returning Exception on a method makes Harmony "throw ex" instead of "rethrow" // (0Harmony EmitFinalizers), which cuts the inner frames off every exception passing through it. var finalizers = Harmony.GetAllPatchedMethods() .Select(Harmony.GetPatchInfo) .Where(info => info != null) .SelectMany(info => info.Finalizers) .Where(p => p.owner == BlaxLawsStartup.HarmonyId) .ToList(); T.Info("Blax Laws finalizers: " + finalizers.Count); var bad = finalizers.Where(p => p.PatchMethod.ReturnType != typeof(void)).Select(p => p.PatchMethod.DeclaringType?.Name).ToList(); T.Check(bad.Count == 0, "finalizers that return a value: " + string.Join(", ", bad)); } [BlaxTest("startup: settings, shared strings, defs and exactly one game component")] public static void Loaded() { T.NotNull(BlaxLawsMod.Settings, "BlaxLawsMod.Settings"); var missing = SharedKeys.Where(k => !k.CanTranslate()).ToList(); T.Check(missing.Count == 0, "strings missing from Keyed: " + string.Join(", ", missing)); T.NotNull(BlaxLawsDefOf.Warn, "PunishmentDef Warn"); T.NotNull(BlaxLawsDefOf.Guilty, "PunishmentDef Guilty"); T.NotNull(BlaxLawsDefOf.Subdue, "PunishmentDef Subdue"); T.NotNull(BlaxLawsDefOf.Jail, "PunishmentDef Jail"); T.NotNull(BlaxLawsDefOf.SubdueThenJail, "PunishmentDef SubdueThenJail"); T.NotNull(BlaxLawsDefOf.BlaxLaws_Subdue, "JobDef BlaxLaws_Subdue"); T.Check(!BlaxLawsDefOf.BlaxLaws_Subdue.suspendable, "BlaxLaws_Subdue is suspendable, so an interrupt would queue it into the save"); T.NotNull(BlaxLawsDefOf.BlaxLaws_Laws, "MainButtonDef BlaxLaws_Laws"); foreach (string cat in ActCategories.All) T.NotNull(DefDatabase.GetNamedSilentFail(cat), "ActCategoryDef " + cat); foreach (string act in new[] { SpecialActs.SetFire, SpecialActs.DisplayedCorpse, SpecialActs.StartedSocialFight }) T.NotNull(DefDatabase.GetNamedSilentFail(act), "ActDef " + act); T.Equal(6, DefDatabase.DefCount, "BreakLinkDefs"); int comps = Current.Game.components.Count(c => c is GameComponent_BlaxLaws); T.Equal(1, comps, "GameComponent_BlaxLaws in the game"); T.NotNull(GameComponent_BlaxLaws.Instance, "GameComponent_BlaxLaws.Instance"); T.Check(GameComponent_BlaxLaws.Instance == Current.Game.GetComponent(), "Instance is not the game's component"); T.Check(GameComponent_BlaxLaws.Instance.SaveToken != 0, "the save token is 0"); } [BlaxTest("new game: an empty book, no cases, every watch flag off, nothing queued")] public static void EmptyBook() { // The new game as the suite found it, before any test ran (tests of other classes run first). TestRunner.NewGameState start = TestRunner.AtStart; T.NotNull(start, "the state at the start of the suite"); T.Equal(0, start.laws, "rows in a new game"); T.Equal(0, start.cases, "cases in a new game"); T.Check(!start.watchAny, "Watch.Any is on for an empty book"); T.Check(!start.categoryFlag, "a category flag is on for an empty book"); T.Check(!start.specialFlag, "a special act flag is on for an empty book"); T.Equal(0, start.pending, "queued enforcement entries"); // The book is empty again between tests: the flags are off and an act files nothing. GameComponent_BlaxLaws comp = GameComponent_BlaxLaws.Instance; T.Equal(0, comp.Laws.Count, "rows left by earlier tests"); T.Check(!Watch.Any, "Watch.Any is on for an empty book"); int cases = comp.Cases.Count; Pawn p = Fixtures.Colonist(); T.Check(CaseFiler.Report(new ActEvent(ActCategories.Ate, ThingDefOf.MealSimple, p)) == null, "an act against an empty book filed a case"); Fixtures.Tick(Enforcement.SweepInterval + 1); T.Equal(cases, comp.Cases.Count, "cases after ticking an empty book"); } [BlaxTest("settings: cooldown clamps to 0..7 days, kept cases to 7..360, defaults")] public static void SettingClamps() { BlaxLawsSettings s = Fixtures.Settings; var d = new BlaxLawsSettings(); T.Equal(1, d.cooldownDays, "default cooldown days"); T.Equal(60, d.keepClosedDays, "default kept days"); T.Check(d.enforceLaws && d.showLawsTab && d.caseMessages && d.jailLetters && d.subdueRemovesCatharsis && d.playerOrdersExempt, "a default toggle is off"); T.Equal(EnforcerMode.WardensFirst, d.enforcers, "default enforcers"); s.cooldownDays = -3; T.Equal(0, s.CooldownDaysClamped, "cooldown -3 clamped"); s.cooldownDays = 99; T.Equal(7, s.CooldownDaysClamped, "cooldown 99 clamped"); T.Equal(7 * GenDate.TicksPerDay, s.CooldownTicks, "cooldown ticks at 7 days"); s.keepClosedDays = 1; T.Equal(7, s.KeepClosedDaysClamped, "kept days 1 clamped"); s.keepClosedDays = 999; T.Equal(360, s.KeepClosedDaysClamped, "kept days 999 clamped"); } [BlaxTest("settings: Show Laws tab off hides the button at once, on shows it")] public static void ShowTabLive() { MainButtonDef button = BlaxLawsDefOf.BlaxLaws_Laws; Fixtures.Settings.showLawsTab = false; BlaxLawsMod.ApplyTabVisibility(); T.Check(!button.buttonVisible, "buttonVisible stays true with the setting off"); Fixtures.Settings.showLawsTab = true; BlaxLawsMod.ApplyTabVisibility(); T.Check(button.buttonVisible, "buttonVisible stays false with the setting on"); } [BlaxTest("harness: colonist, prisoner, colony slave and child fixtures stand in a district")] public static void PawnFixtures() { Pawn c = Fixtures.Colonist(); T.Check(c.Spawned && c.IsFreeColonist, "colonist fixture is not a spawned free colonist"); T.Check(c.GetDistrict() != null, "colonist fixture stands in no district"); T.Check(Offenders.IsCovered(c), "a free colonist isn't covered by the laws"); Pawn pr = Fixtures.Prisoner(); T.Check(pr.IsPrisonerOfColony, "prisoner fixture is not a prisoner of the colony"); T.Check(!Offenders.IsCovered(pr), "a prisoner is covered by the laws"); if (ModsConfig.IdeologyActive) { Pawn s = Fixtures.ColonySlave(); T.Check(Offenders.IsCovered(s), "a colony slave isn't covered by the laws"); } if (ModsConfig.BiotechActive) { Pawn ch = Fixtures.Child(); T.Check(Offenders.IsCovered(ch), "a colony child isn't covered by the laws"); T.Check(DlcSupport.IsChild(ch), "DlcSupport.IsChild is false for the child fixture"); } if (!ModsConfig.IdeologyActive || !ModsConfig.BiotechActive) T.Info("slave fixture needs Ideology, child fixture needs Biotech; skipped what is off"); } [BlaxTest("harness: exactly one component after the reload", phase: 2)] public static void ComponentAfterReload() { T.Equal(1, Current.Game.components.Count(c => c is GameComponent_BlaxLaws), "GameComponent_BlaxLaws after the reload"); T.Check(GameComponent_BlaxLaws.Instance == Current.Game.GetComponent(), "Instance is not the reloaded game's component"); } [BlaxTest("harness: the reload logs no 'Could not resolve reference' warning except for vanilla's unsaved tale pawns, pawns the new world left unsaved and Hospitality's stale lords", phase: 2)] public static void ReloadResolvesEveryReference() { // A reference Blax Laws saves but can't load would show here. Three leaks of other code are excused // by name: // - vanilla: a pawn TaleData_Pawn.GenerateRandom made for a book or tale and never saved; // - vanilla: a pawn a relation already named, with no save holding it, when the suite began (world // generation, before any test and with an empty lawbook); // - Hospitality (-Compat): CompGuest.PostSpawnSetup stores Pawn.GetLord() on every humanlike pawn and // saves it with Scribe_References, and nothing clears it when the pawn leaves the map // (Hospitality Source/CompGuest.cs, lord). Blax Laws saves no Lord reference. List all = T.Phase2ResolveWarnings; List vanilla = all.Where(T.NamesVanillaTalePawn).ToList(); List atStart = all.Where(w => !vanilla.Contains(w) && T.NamesPawnUnsavedAtStart(w)).ToList(); bool hospitality = Compat.IsActive("Orion.Hospitality"); List staleLords = hospitality ? all.Where(w => w.Contains("of type Verse.AI.Group.Lord.")).ToList() : new List(); List rest = all.Where(w => !vanilla.Contains(w) && !atStart.Contains(w) && !staleLords.Contains(w)).ToList(); T.Info(all.Count + " warning(s) on the reload: " + vanilla.Count + " for pawns vanilla made for books or tales and never saved, " + atStart.Count + " for pawns the new world left unsaved, " + staleLords.Count + " for lords Hospitality's CompGuest still names"); T.Equal(0, rest.Count, "other 'Could not resolve reference' warnings while the phase-1 save loaded (first: " + string.Join(" | ", rest.Take(3)) + ")"); } [BlaxTest("harness: phase 3 loads with exactly the two removal errors and a fresh, empty component", phase: 3)] public static void Phase3Removal() { T.Equal(1, TestRunner.Phase3ReplacedCount, "component nodes replaced in the phase-3 save"); T.ExpectErrors("Could not find class " + TestRunner.RemovedComponentClass, 1); T.ExpectErrors("Can't load abstract class Verse.GameComponent", 1); T.Info("load errors: " + T.Phase3LoadErrors.Count + ", resolve warnings: " + T.Phase3ResolveWarnings); T.Equal(2, T.Phase3LoadErrors.Count, "errors while loading the phase-3 save"); T.Equal(1, Current.Game.components.Count(c => c is GameComponent_BlaxLaws), "fresh GameComponent_BlaxLaws"); GameComponent_BlaxLaws comp = GameComponent_BlaxLaws.Instance; T.Equal(0, comp.Laws.Count, "rows in the fresh component"); T.Equal(0, comp.Cases.Count, "cases in the fresh component"); T.Check(!Watch.Any, "Watch.Any is on after the removal load"); } } }