using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using BlaxLaws; using RimWorld; using Verse; namespace BlaxLawsTests { /// /// The "Nobody to enforce" letter (CaseLetters.NoEnforcer): sent when a case waits because nobody on the /// map can ever enforce it, once per case, never again on later sweeps or when the case flips to another /// wait and back, and not at all with "Letters for jailings" off. Nobody is able because "Wardens only" is /// on and no colonist has Warden work (EnforceFixtures.OnlyWardens with no warden). /// public static class NoEnforcerLetterTests { [BlaxTest("no-enforcer letter: a jail case nobody can enforce sends one 'Nobody to enforce' letter naming the offender and the law; later sweeps send no second")] public static void JailCaseOneLetter() { Pawn o = EnforceFixtures.Offender(); EnforceFixtures.OnlyWardens(); HashSet before = LettersNow(); LawCase c = EnforceFixtures.ActCase(o, "Jail", 3); string label = LabelFor(c); EnforceFixtures.Dispatch(c, LawStage.DidIt); EnforceFixtures.CheckWait(c, WaitReasons.NoEnforcer, "the wait with nobody able"); List sent = Since(before, label); T.Equal(1, sent.Count, "'Nobody to enforce' letters after the dispatch"); Letter l = sent[0]; T.Check(l.def == LetterDefOf.NegativeEvent, "the letter's def: " + (l.def?.defName ?? "null")); string text = (l as ChoiceLetter)?.Text.ToString() ?? ""; T.Check(text.Contains(c.OffenderLabel) && text.Contains(c.Label), "the letter names neither the offender nor the law: " + text); T.Check(l.lookTargets != null && l.lookTargets.targets.Any(t => t.Thing == o), "the letter doesn't point at the offender"); Fixtures.Tick(3 * Enforcement.SweepInterval + 1); T.Check(!c.IsClosed, "the case closed: " + c); EnforceFixtures.CheckWait(c, WaitReasons.NoEnforcer, "the wait after three sweeps"); T.Equal(1, Since(before, label).Count, "'Nobody to enforce' letters after three sweeps"); T.Check(!EnforceFixtures.AnyEnforcementJobOn(o), "someone was sent although nobody can enforce"); } [BlaxTest("no-enforcer letter: a jail case that waits for nobody to enforce, then for a prisoner bed, then for nobody to enforce again gets no second letter")] public static void FlipBackNoSecondLetter() { Pawn o = EnforceFixtures.Offender(); Pawn warden = EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 2f, 6f)); EnforceFixtures.OnlyWardens(warden); warden.workSettings.SetPriority(WorkTypeDefOf.Warden, 0); HashSet before = LettersNow(); LawCase c = EnforceFixtures.ActCase(o, "Jail", 3); string label = LabelFor(c); EnforceFixtures.Dispatch(c, LawStage.DidIt); EnforceFixtures.CheckWait(c, WaitReasons.NoEnforcer, "the first wait with the warden's work off"); T.Equal(1, Since(before, label).Count, "'Nobody to enforce' letters after the first wait"); // The warden can enforce again; the map has no prisoner bed, so the case waits for one. warden.workSettings.SetPriority(WorkTypeDefOf.Warden, 1); JailFlow.TryArrest(c, ignoreHold: false); EnforceFixtures.CheckWait(c, WaitReasons.NoBed, "fixture: the wait with the warden back and no prisoner bed; " + EnforceFixtures.EnforcerStory(warden, c)); // Nobody again: the wait reason changes back, so only the once-per-case record can hold the letter. warden.workSettings.SetPriority(WorkTypeDefOf.Warden, 0); JailFlow.TryArrest(c, ignoreHold: false); EnforceFixtures.CheckWait(c, WaitReasons.NoEnforcer, "the wait with the warden's work off again"); T.Equal(1, Since(before, label).Count, "'Nobody to enforce' letters after the case waited for nobody a second time"); Fixtures.Tick(Enforcement.SweepInterval + 1); T.Equal(1, Since(before, label).Count, "'Nobody to enforce' letters after the next sweep"); T.Check(!EnforceFixtures.AnyEnforcementJobOn(o), "someone was sent although nobody can enforce"); } [BlaxTest("no-enforcer letter: a subdue case in a drug binge that nobody can enforce sends one letter; later sweeps send no second, neither after the wait flips to another reason and back nor without the session's letter record")] public static void SubdueCaseOneLetter() { // No drug to binge on and no social fight: either could down the binger or end its break during the wait. DetectionKit.ClearDrugsOnMap(); DetectionKit.QuietSocialFights(); Pawn o = EnforceFixtures.Offender(); EnforceFixtures.OnlyWardens(); HashSet before = LettersNow(); EnforceFixtures.ForceBreak(o, EnforceFixtures.DrugBinge); LawCase c = EnforceFixtures.BreakCase(o, "Subdue", LawStage.Planning, 3); string label = LabelFor(c); EnforceFixtures.Dispatch(c, LawStage.Planning); EnforceFixtures.CheckWait(c, WaitReasons.NoEnforcer, "the wait with nobody able"); T.Equal(1, Since(before, label).Count, "'Nobody to enforce' letters after the dispatch"); Fixtures.Tick(3 * Enforcement.SweepInterval + 1); T.Check(!c.IsClosed && o.InMentalState, "fixture: the binge or the case ended during the sweeps: " + c + ", break " + (o.MentalStateDef?.defName ?? "none")); EnforceFixtures.CheckWait(c, WaitReasons.NoEnforcer, "the wait after three sweeps"); T.Equal(1, Since(before, label).Count, "'Nobody to enforce' letters after three sweeps"); T.Check(!SubdueFlow.Runs(c) && !EnforceFixtures.AnyEnforcementJobOn(o), "someone was sent although nobody can enforce"); // The wait flips to another reason and back: Set reports a change, so only the once-per-case record // (SubdueFlow.TryIssue's CaseLetters.Once) can hold the letter. c.waitReason = WaitReasons.Busy; Fixtures.Tick(Enforcement.SweepInterval + 1); T.Check(!c.IsClosed && o.InMentalState, "fixture: the binge or the case ended during the flip: " + c + ", break " + (o.MentalStateDef?.defName ?? "none")); EnforceFixtures.CheckWait(c, WaitReasons.NoEnforcer, "the wait after the flip and a sweep"); T.Equal(1, Since(before, label).Count, "'Nobody to enforce' letters after the wait flipped back to nobody"); // Without the session's letter record, as after a reload: only the unchanged wait (WaitReasons.Set) // can hold the letter. T.Check(LetterRecord().Remove(c), "fixture: the subdue case had no letter record after its letter"); Fixtures.Tick(Enforcement.SweepInterval + 1); T.Check(!c.IsClosed && o.InMentalState, "fixture: the binge or the case ended without the record: " + c + ", break " + (o.MentalStateDef?.defName ?? "none")); EnforceFixtures.CheckWait(c, WaitReasons.NoEnforcer, "the wait after a sweep without the session record"); T.Equal(1, Since(before, label).Count, "'Nobody to enforce' letters after a sweep without the session record"); } /// CaseLetters' per-session record of the letters sent per case. private static ConditionalWeakTable> LetterRecord() { FieldInfo field = typeof(CaseLetters).GetField("sent", BindingFlags.NonPublic | BindingFlags.Static); T.NotNull(field, "fixture: CaseLetters.sent"); var table = field.GetValue(null) as ConditionalWeakTable>; T.NotNull(table, "fixture: CaseLetters.sent as a ConditionalWeakTable>"); return table; } [BlaxTest("no-enforcer letter: without the session's letter record, as after a reload, the unchanged wait alone keeps later sweeps from sending a second letter")] public static void SavedWaitStopsRepeat() { Pawn o = EnforceFixtures.Offender(); EnforceFixtures.OnlyWardens(); HashSet before = LettersNow(); LawCase c = EnforceFixtures.ActCase(o, "Jail", 3); string label = LabelFor(c); EnforceFixtures.Dispatch(c, LawStage.DidIt); EnforceFixtures.CheckWait(c, WaitReasons.NoEnforcer, "the wait with nobody able"); T.Equal(1, Since(before, label).Count, "'Nobody to enforce' letters after the dispatch"); // A reload makes new LawCase objects, so CaseLetters' per-session record knows none of them; only the // saved waitReason is left. Drop this case's record the same way. T.Check(LetterRecord().Remove(c), "fixture: the case had no letter record after its letter"); Fixtures.Tick(3 * Enforcement.SweepInterval + 1); T.Check(!c.IsClosed, "the case closed: " + c); EnforceFixtures.CheckWait(c, WaitReasons.NoEnforcer, "the wait after three sweeps"); T.Equal(1, Since(before, label).Count, "'Nobody to enforce' letters after three sweeps without the session record"); } [BlaxTest("no-enforcer letter: none with 'Letters for jailings' off; the case still waits for nobody to enforce")] public static void NoLetterWhenLettersOff() { Pawn o = EnforceFixtures.Offender(); EnforceFixtures.OnlyWardens(); Fixtures.Settings.jailLetters = false; HashSet before = LettersNow(); LawCase c = EnforceFixtures.ActCase(o, "Jail", 3); string label = LabelFor(c); EnforceFixtures.Dispatch(c, LawStage.DidIt); EnforceFixtures.CheckWait(c, WaitReasons.NoEnforcer, "the wait with nobody able"); Fixtures.Tick(Enforcement.SweepInterval + 1); EnforceFixtures.CheckWait(c, WaitReasons.NoEnforcer, "the wait after a sweep"); T.Equal(0, Since(before, label).Count, "'Nobody to enforce' letters with letters off"); } // ---- through a real reload ---------------------------------------------------------- private const string ReloadKey = "letters.noEnforcerReload"; [BlaxTest("no-enforcer letter: a jail case waits for nobody to enforce at the first save, with its one letter (setup)", Order = -1)] public static void ReloadSetup() { // Runs first so its save-time setup runs before the others: it ticks, and they must not be ticked. T.CarryAtSave(ReloadKey, NoEnforcerForSave); } /// /// Built right before the save, after every phase-1 test. Mod settings aren't saved with the game, so the /// setup puts "Wardens only" and the Warden work back before the save; a sweep under the defaults would /// find an enforcer. So it first ticks just past a sweep: the next one is 250 ticks away, more than the /// runner's settle frames after the load tick (at most 2 ticks a frame, TickManager.cs:341). /// private static string NoEnforcerForSave() { Fixtures.Tick(Enforcement.SweepInterval - EnforceFixtures.Now % Enforcement.SweepInterval + 1); BlaxLawsSettings s = Fixtures.Settings; EnforcerMode mode = s.enforcers; bool letters = s.jailLetters; var old = new List<(Pawn pawn, int priority)>(); try { Pawn o = Fixtures.Keep(EnforceFixtures.Offender()); s.enforcers = EnforcerMode.WardensOnly; s.jailLetters = true; foreach (Pawn p in EnforceFixtures.Map.mapPawns.FreeColonistsSpawned) { if (!Enforcers.IsWarden(p)) continue; old.Add((p, p.workSettings.GetPriority(WorkTypeDefOf.Warden))); p.workSettings.SetPriority(WorkTypeDefOf.Warden, 0); } LawCase c = EnforceFixtures.ActCase(o, "Jail", 3); Fixtures.KeepLaw(c.LawFor(LawStage.DidIt)); string label = LabelFor(c); int before = Find.LetterStack.LettersListForReading.Count(l => l.Label.ToString() == label); EnforceFixtures.Dispatch(c, LawStage.DidIt); if (c.waitReason != WaitReasons.NoEnforcer) throw new System.InvalidOperationException("the case waits for " + (c.waitReason ?? "nothing") + ", not for nobody to enforce"); int after = Find.LetterStack.LettersListForReading.Count(l => l.Label.ToString() == label); if (after != before + 1) throw new System.InvalidOperationException("the dispatch sent " + (after - before) + " 'Nobody to enforce' letters, not 1"); return c.id + "|" + o.ThingID + "|" + after + "|" + EnforceFixtures.Now; } finally { foreach (var (pawn, priority) in old) pawn.workSettings.SetPriority(WorkTypeDefOf.Warden, priority); s.enforcers = mode; s.jailLetters = letters; } } [BlaxTest("no-enforcer letter: after a reload the case still waits for nobody to enforce, and later sweeps send no second letter", phase: 2, Order = -1)] public static void ReloadNoSecondLetter() { T.Check(T.Carry.TryGetValue(ReloadKey, out string carry) && !carry.NullOrEmpty(), "the phase-1 setup did not run"); string[] parts = carry.Split('|'); T.Check(parts.Length == 4, "carry: " + carry); LawCase c = Fixtures.Comp.CaseById(int.Parse(parts[0])); Pawn o = Fixtures.FindPawnById(parts[1]); T.NotNull(c, "the waiting case after the reload"); T.NotNull(o, "the offender after the reload"); T.Check(c.offender == o, "the case's offender didn't resolve"); string label = LabelFor(c); Fixtures.OnCleanup(() => { // Nobody may arrest the kept offender in a later test. if (!c.IsClosed) Fixtures.Comp.CloseCase(c, CaseOutcomes.Repealed); Law row = c.LawFor(LawStage.DidIt); if (row != null) Lawbook.Delete(row); foreach (Letter l in Find.LetterStack.LettersListForReading.Where(l => l.Label.ToString() == label).ToList()) { Find.LetterStack.RemoveLetter(l); Find.Archive.Remove(l); } }); int saveTick = int.Parse(parts[3]); T.Check(EnforceFixtures.Now / Enforcement.SweepInterval == saveTick / Enforcement.SweepInterval, "fixture: a sweep ran under the default settings between the save at tick " + saveTick + " and this test at tick " + EnforceFixtures.Now); EnforceFixtures.CheckWait(c, WaitReasons.NoEnforcer, "the wait after the reload"); int letters = int.Parse(parts[2]); T.Equal(letters, Count(label), "'Nobody to enforce' letters after the reload"); // Three sweeps of this case, each what Enforcement.Sweep runs for it (Enforcement.cs:235-236), a tick // apart: real sweeps 250 ticks apart would run the other phase-2 setups with every warden off. EnforceFixtures.OnlyWardens(); PunishmentDef active = Enforcement.ActiveOf(c); T.Check(active != null && active.defName == "Jail", "the case's punishment in progress after the reload: " + (active?.defName ?? "none")); for (int i = 1; i <= 3; i++) { active.Worker.Sweep(c); Fixtures.Tick(1); T.Check(!c.IsClosed, "the case closed: " + c); EnforceFixtures.CheckWait(c, WaitReasons.NoEnforcer, "the wait after sweep " + i + " after the reload"); T.Equal(letters, Count(label), "'Nobody to enforce' letters after sweep " + i + " after the reload"); } T.Check(!EnforceFixtures.AnyEnforcementJobOn(o), "someone was sent although nobody can enforce"); } // ---- helpers --------------------------------------------------------------------- private static int Count(string label) => Find.LetterStack.LettersListForReading.Count(l => l.Label.ToString() == label); /// The letters on the stack now; the letters a test adds after this go from the stack and the archive after the test. private static HashSet LettersNow() { var before = new HashSet(Find.LetterStack.LettersListForReading); Fixtures.OnCleanup(() => { foreach (Letter l in Find.LetterStack.LettersListForReading.Where(l => !before.Contains(l)).ToList()) { Find.LetterStack.RemoveLetter(l); Find.Archive.Remove(l); } }); return before; } private static string LabelFor(LawCase c) => "BlaxLaws_LetterNoEnforcerLabel".Translate(c.OffenderLabel); /// The letters with this label sent since the snapshot. private static List Since(HashSet before, string label) => Find.LetterStack.LettersListForReading.Where(l => !before.Contains(l) && l.Label.ToString() == label).ToList(); } }