using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using BlaxLaws; using RimWorld; using Verse; using Verse.AI; namespace BlaxLawsTests { /// /// The release's headline path in one test, with no fixture case and no fixture row: the starter lawbook, /// a wake-up binge whose dose hook C files, the starter's "jail 5 days", the sentence running out in game /// time, the release by a colonist and the colonist back at work. /// public static class EndToEndJailTests { private static int Now => Find.TickManager.TicksGame; [BlaxTest("end to end: under the starter lawbook a wake-up binger doses before any warden can reach it; the dose files the starter's did-it jail through the ingest hook, a warden arrests it into a prisoner bed on Maintain only with release at capture plus 5 days, the sentence runs out in game time, a colonist releases it through the release job and it is a free colonist with its old work priorities")] public static void StarterDoseServesFiveDays() { T.Check(ActCatalogue.Get(ActKey.OfGroup(ActCategories.Break, ActGroups.AnyDrugBinge)) != null, "the catalogue has no 'any drug binge' entry: the starter rows need the catalogue and detection packages"); EnforceFixtures.PrisonCell(); DetectionKit.ClearDrugsOnMap(); Pawn o = EnforceFixtures.Offender(); // No warden on the map until the dose: "Wardens only" with Warden work off for every colonist (the // offender included), so the planning subdue finds nobody and the binger doses first every time. EnforceFixtures.OnlyWardens(); colonistsAtStart = new HashSet(EnforceFixtures.Map.mapPawns.FreeColonistsSpawned.Select(p => p.ThingID)); // After OnlyWardens, which may have turned the offender's own Warden work off until the cleanup: Warden // stays as it is, every other work type gets a priority a reset can't reproduce. Dictionary priorities = EnforceFixtures.DistinctPriorities(o, WorkTypeDefOf.Warden); Lawbook.AddStarter(); string bingeKey = ActKey.OfGroup(ActCategories.Break, ActGroups.AnyDrugBinge); Law planningRow = Lawbook.Find(bingeKey, DrugOptions.Any, LawStage.Planning); Law didItRow = Lawbook.Find(bingeKey, DrugOptions.Any, LawStage.DidIt); T.NotNull(planningRow, "starter row 'any drug binge, planning'"); T.NotNull(didItRow, "starter row 'any drug binge, did it'"); T.Equal("Jail", didItRow.punishment, "the starter did-it row's punishment"); T.Equal(5, didItRow.days, "the starter did-it row's days"); ThingDef wakeUp = DefDatabase.GetNamed("WakeUp"); DetectionKit.NoOverdose(wakeUp); Thing drug = Fixtures.Track(GenSpawn.Spawn(ThingMaker.MakeThing(wakeUp), EnforceFixtures.CellNear(o.Position, 1f, 1.9f), EnforceFixtures.Map)); int drugBefore = drug.stackCount; EnforceFixtures.ForceBreak(o, DefDatabase.GetNamed("Binging_DrugExtreme")); ((MentalState_BingingDrug)o.MentalState).chemical = wakeUp.GetCompProperties().chemical; LawCase c = Fixtures.Comp.CasesOf(o).LastOrDefault(x => x.IsBreakCase && !x.IsClosed); T.NotNull(c, "the binge opened no planning case (hook A)"); T.Equal(LawStage.Planning, c.stage, "the binge case's stage at the start"); T.Equal(planningRow.id, c.planningLawId, "the binge case's planning row"); // ---- the dose, filed by hook C ---- HashSet injuriesBefore = EnforceFixtures.Injuries(o); bool enforcedBeforeDose = false; var jobs = new List(); string lastJob = null; bool dosed = EnforceFixtures.RunUntil(() => { if (EnforceFixtures.AnyEnforcementJobOn(o)) enforcedBeforeDose = true; string job = o.CurJobDef?.defName ?? "none"; if (job != lastJob) { lastJob = job; jobs.Add(job + "@" + Now); } return c.stage == LawStage.DidIt; }, 2000); string doseStory = "case " + c + ", wait " + c.waitReason + ", the binger's jobs " + string.Join(" > ", jobs) + ", wake-up left " + (drug.Destroyed ? 0 : drug.stackCount) + ", mental state " + (o.MentalStateDef?.defName ?? "none"); T.Check(dosed, "no did-it within 2000 ticks of the binge; " + doseStory); T.Check(!enforcedBeforeDose && c.enforcer == null && EnforceFixtures.NewInjuries(o, injuriesBefore).Count == 0, "fixture: someone reached the binger before its dose; " + doseStory); T.Check(drug.Destroyed || drug.stackCount < drugBefore, "the did-it was filed without a wake-up eaten; " + doseStory); T.Equal(wakeUp.defName, c.matchedDef, "the act the did-it was filed on"); T.Check(c.count >= 1, "the dose counted no act: count " + c.count); T.Equal(didItRow.id, c.didItLawId, "the binge case's did-it row"); T.Equal(1, Fixtures.Comp.CasesOf(o).Count, "cases of the binger (the dose goes into the binge's case)"); // ---- the arrest ---- Pawn warden = EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 2f, 6f)); bool everColonistBed = false; void WatchBed() { if (o.InBed() && !o.CurrentBed().ForPrisoners) everColonistBed = true; } bool jailed = EnforceFixtures.RunUntil(() => { WatchBed(); return o.IsPrisonerOfColony; }, Enforcement.SweepInterval + EnforceFixtures.SubdueTicks); T.Check(jailed, "not a prisoner within " + (Enforcement.SweepInterval + EnforceFixtures.SubdueTicks) + " ticks of the warden's arrival; case " + c + ", wait " + c.waitReason + "; " + EnforceFixtures.EnforcerStory(warden, c)); T.Equal(CaseStatus.Jailed, c.status, "the case's status at the capture (hook K)"); T.Check(c.enforcer == warden, "the capture went to " + (c.enforcer?.LabelShort ?? "nobody") + ", not the only warden"); T.Equal(Now, c.captureTick, "the capture tick"); T.Equal(c.captureTick + 5 * GenDate.TicksPerDay, c.releaseTick, "the release tick (the starter row's 5 days from the capture)"); Fixtures.Tick(2); T.Equal(PrisonerInteractionModeDefOf.MaintainOnly, o.guest.ExclusiveInteractionMode, "the mode two ticks after the capture"); T.Check(c.maintainOnlyDone, "maintainOnlyDone after the write"); T.Check(o.MentalState == null, "the binge goes on in jail: " + o.MentalStateDef?.defName); bool labor = LaborOn(o); bool inPrisonBed = EnforceFixtures.RunUntil(() => { WatchBed(); labor |= LaborOn(o); return o.Spawned && o.InBed() && o.CurrentBed().ForPrisoners; }, EnforceFixtures.CarryTicks); T.Check(inPrisonBed, "the prisoner never lay in a prisoner bed; case " + c + ", spawned " + o.Spawned + (o.Spawned ? "" : ", held by " + Holder(o, warden)) + ", the warden " + (warden.CurJobDef?.defName ?? "no job") + " at " + warden.Position + ", owns " + (o.ownership?.OwnedBed?.ToString() ?? "no bed") + "; " + EnforceFixtures.WalkStory(o.CarriedBy ?? warden)); T.Check(!everColonistBed, "the binger lay in a colonist or medical bed"); // ---- the sentence ---- // Five days of ticks would take minutes, so the clock jumps (as JailTests.JailAndRelease does) to just // over one sentence sweep before the release tick; from there real ticks run through at least one // sweep before the release tick, which must leave the pawn on Maintain only, and the first sweep at // or after it, which must set Release. int jumpTo = c.releaseTick - Enforcement.SentenceInterval - 10; T.Check(jumpTo > Now, "fixture: the release tick " + c.releaseTick + " is not a sweep ahead of now " + Now); Find.TickManager.DebugSetTicksGame(jumpTo); EnforceFixtures.Ready(o); EnforceFixtures.Ready(warden); int sweepsBefore = 0; bool earlyRelease = false; bool releaseSet = EnforceFixtures.RunUntil(() => { labor |= LaborOn(o); bool release = o.IsPrisonerOfColony && o.guest.ExclusiveInteractionMode == PrisonerInteractionModeDefOf.Release; if (Now < c.releaseTick) { if (release || !o.IsPrisonerOfColony) earlyRelease = true; if (Now > jumpTo && Now % Enforcement.SentenceInterval == 0) sweepsBefore++; } return release || !o.IsPrisonerOfColony; }, 2 * Enforcement.SentenceInterval + 20); T.Check(!earlyRelease, "the pawn was set to Release or let go at " + Now + ", before the release tick " + c.releaseTick + "; case " + c); T.Check(sweepsBefore >= 1, "fixture: no sentence sweep ran between the jump and the release tick"); T.Check(releaseSet && o.IsPrisonerOfColony, "no Release within two sweeps of the release tick; case " + c + ", mode " + (o.guest?.ExclusiveInteractionMode?.defName ?? "none") + ", prisoner " + o.IsPrisonerOfColony); T.Check(Now >= c.releaseTick && Now <= c.releaseTick + Enforcement.SentenceInterval, "Release set at " + Now + ", expected at the first sweep at or after the release tick " + c.releaseTick); T.Check(!c.IsClosed && c.status == CaseStatus.Jailed, "the case before the release: " + c); // ---- the release ---- // Vanilla's release work takes it: in 1.7 WorkGiver_Warden_ReleasePrisoner runs under Warden work and, // as BasicReleasePrisoner, under Basic work (Data/Core/Defs/WorkGiverDefs/WorkGivers.xml:242-246), so // any free colonist may carry it out (Verse.AI/JobDriver_ReleasePrisoner.cs:26-37). Pawn releaser = null; Pawn lastOnRelease = null; int lastOnReleaseTick = -1; var releaseStory = new List(); string lastState = null; bool free = EnforceFixtures.RunUntil(() => { labor |= LaborOn(o); Pawn carrier = (o.ParentHolder as Pawn_CarryTracker)?.pawn; if (carrier != null && carrier.CurJobDef == JobDefOf.ReleasePrisoner && carrier.CurJob.targetA.Thing == o) releaser = carrier; // The carry can be short (the prisoner wanders next to the release cell), so the job counts too: any // pawn whose release job on this prisoner ran in the tick the prisoner went free. foreach (Pawn p in EnforceFixtures.Map.mapPawns.AllPawnsSpawned) { if (p.CurJobDef == JobDefOf.ReleasePrisoner && p.CurJob.targetA.Thing == o) { lastOnRelease = p; lastOnReleaseTick = Now; } } string state = "warden " + (warden.CurJobDef?.defName ?? "none") + ", pawn " + (o.CurJobDef?.defName ?? "none") + (o.Spawned ? "" : " held by " + Holder(o, warden)) + (o.Dead ? " dead" : "") + (o.MentalStateDef != null ? " " + o.MentalStateDef.defName : "") + (o.guest != null && o.guest.Released ? " released" : "") + (PrisonBreakUtility.IsPrisonBreaking(o) ? " breaking out" : "") + (o.IsPrisonerOfColony ? "" : " free"); if (state != lastState) { lastState = state; releaseStory.Add(state + "@" + Now); } return !o.IsPrisonerOfColony; }, 4000); string story = string.Join(" > ", releaseStory.Skip(Math.Max(0, releaseStory.Count - 12))); if (releaser == null && free && lastOnRelease != null && Now - lastOnReleaseTick <= 1) releaser = lastOnRelease; T.Check(free, "nobody released the pawn within 4000 ticks; " + EnforceFixtures.EnforcerStory(warden, c) + ", prisoner mental state " + (o.MentalStateDef?.defName ?? "none") + ", downed " + o.Downed + "; " + story); T.Check(releaser != null && releaser.IsFreeColonist, "the pawn went free without a colonist's release job; " + story + "; case " + c); T.Info("released by " + releaser.LabelShort + (releaser == warden ? ", the warden" : ", Warden work " + Enforcers.IsWarden(releaser))); T.Check(Now < c.releaseTick + Sentences.FallbackTicks, "the release came from the fallback, not a colonist"); T.Check(o.IsFreeColonist, o.LabelShort + " isn't a free colonist after the release"); T.NotNull(o.needs.mood.thoughts.memories.GetFirstMemoryOfDef(ThoughtDefOf.WasImprisoned), "WasImprisoned after the release"); string diff = PriorityDiff(priorities, o, labor); T.Check(diff == null, "work priorities changed: " + diff); EnforceFixtures.TickPastSentenceSweep(); T.Check(c.IsClosed && c.outcome == CaseOutcomes.Served, "the case after the release: " + c); } /// Who holds the pawn: the carrier's name, job and Warden work, or the holder. private static HashSet colonistsAtStart = new HashSet(); private static string Holder(Pawn o, Pawn warden) { if (!(o.ParentHolder is Pawn_CarryTracker carry) || carry.pawn == null) return o.ParentHolder?.ToString() ?? "nothing"; Pawn p = carry.pawn; return p.LabelShort + (p == warden ? " (the warden)" : "") + " " + (p.CurJobDef?.defName ?? "no job") + ", Warden work " + Enforcers.IsWarden(p) + ", slave " + p.IsSlave + ", free colonist " + p.IsFreeColonist + ", " + p.ThingID + ", kind " + p.kindDef?.defName + ", Warden priority " + p.workSettings?.GetPriority(WorkTypeDefOf.Warden) + ", Warden disabled " + p.WorkTypeIsDisabled(WorkTypeDefOf.Warden) + ", a free colonist on the map when the test began " + colonistsAtStart.Contains(p.ThingID); } /// Prison Labor's work option is on for the prisoner (PrisonLaborUtility.LaborEnabled in its 1.7 PrisonLabor.dll). private static bool LaborOn(Pawn o) { PrisonerInteractionModeDef work = DefDatabase.GetNamedSilentFail("PrisonLabor_workOption"); return work != null && o.guest != null && o.guest.IsInteractionEnabled(work); } /// /// The changed work priorities, or null. While Prison Labor's work option is on, Prison Labor disables the /// work types its settings bar prisoners from, and those stay at 0 after the release: Prison Labor's call, /// not Laws' (design: "Jail for N days", Overlaps). Only those may read 0 afterwards. /// private static string PriorityDiff(Dictionary before, Pawn o, bool labor) { Func barred = _ => false; if (labor) { MethodInfo m = GenTypes.GetTypeInAnyAssembly("PrisonLabor.Core.LaborWorkSettings.WorkSettings")? .GetMethod("WorkDisabled", BindingFlags.Public | BindingFlags.Static, null, new[] { typeof(WorkTypeDef) }, null); T.NotNull(m, "Prison Labor's WorkSettings.WorkDisabled(WorkTypeDef)"); barred = wt => (bool)m.Invoke(null, new object[] { wt }); } var diff = before.Where(kv => o.workSettings.GetPriority(kv.Key) != kv.Value && !(o.workSettings.GetPriority(kv.Key) == 0 && barred(kv.Key))) .Select(kv => kv.Key.defName + " " + kv.Value + " to " + o.workSettings.GetPriority(kv.Key)).ToList(); return diff.Count == 0 ? null : string.Join(", ", diff); } } }