656 lines
40 KiB
C#
656 lines
40 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Reflection;
|
|
using BlaxLaws;
|
|
using RimWorld;
|
|
using Verse;
|
|
using Verse.AI;
|
|
|
|
namespace BlaxLawsTests
|
|
{
|
|
/// <summary>
|
|
/// "Jail for N days": the arrest, hook K, "Maintain only" two ticks after the capture, the release, the
|
|
/// old bed, a late arrest, no prisoner bed, the holds and fallbacks, the early end, and a jailed colonist
|
|
/// through the save and the removal.
|
|
/// </summary>
|
|
public static class JailTests
|
|
{
|
|
private const string PrisonLaborId = "avius.prisonlabor"; // Prison Labor's About.xml (Workshop 1899474310), read 2026-12-01
|
|
private const string CastesId = "blax.castes";
|
|
|
|
private static int Now => Find.TickManager.TicksGame;
|
|
|
|
// ---- the sentence -----------------------------------------------------------------
|
|
|
|
[BlaxTest("jail: a did-it binge case with jail 3 days: a prisoner within 2500 ticks, the break over without catharsis, guilt for the sentence plus a day, Maintain only two ticks after the capture; at the release tick Release, a warden releases it with WasImprisoned and the same work priorities")]
|
|
public static void JailThreeDays()
|
|
{
|
|
EnforceFixtures.PrisonCell();
|
|
Pawn o = EnforceFixtures.Offender();
|
|
EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 2f, 6f));
|
|
Dictionary<WorkTypeDef, int> priorities = EnforceFixtures.Priorities(o);
|
|
EnforceFixtures.ForceBreak(o, EnforceFixtures.DrugBinge, causedByMood: true);
|
|
LawCase c = EnforceFixtures.BreakCase(o, "Jail", LawStage.DidIt, 3);
|
|
Enforcement.Enqueue(c, LawStage.DidIt);
|
|
|
|
int arrestStart = -1;
|
|
bool jailed = EnforceFixtures.RunUntil(() =>
|
|
{
|
|
if (arrestStart < 0 && c.status == CaseStatus.Enforcing)
|
|
arrestStart = Now;
|
|
return o.IsPrisonerOfColony;
|
|
}, EnforceFixtures.SubdueTicks);
|
|
T.Check(jailed, "not a prisoner within 2500 ticks; case " + c + ", wait " + c.waitReason);
|
|
T.Equal(CaseStatus.Jailed, c.status, "the case's status at the capture");
|
|
T.Equal(Now, c.captureTick, "the capture tick");
|
|
T.Equal(c.captureTick + 3 * GenDate.TicksPerDay, c.releaseTick, "the release tick");
|
|
T.Check(o.MentalState == null, "the break goes on in jail: " + o.MentalStateDef?.defName);
|
|
T.Check(o.needs.mood.thoughts.memories.GetFirstMemoryOfDef(ThoughtDefOf.Catharsis) == null, "the jailed pawn has Catharsis");
|
|
int minGuilt = 4 * GenDate.TicksPerDay - (Now - arrestStart) - 30;
|
|
T.Check(o.guilt.TicksUntilInnocent >= minGuilt, "guilt " + o.guilt.TicksUntilInnocent + ", expected at least " + minGuilt);
|
|
|
|
Fixtures.Tick(2);
|
|
T.Equal(PrisonerInteractionModeDefOf.MaintainOnly, o.guest.ExclusiveInteractionMode, "the mode two ticks after the capture");
|
|
bool labor = LaborOn(o);
|
|
T.Check(c.maintainOnlyDone, "maintainOnlyDone after the write");
|
|
|
|
c.releaseTick = Now;
|
|
EnforceFixtures.TickPastSentenceSweep();
|
|
T.Equal(PrisonerInteractionModeDefOf.Release, o.guest.ExclusiveInteractionMode, "the mode at the release tick");
|
|
bool released = EnforceFixtures.RunUntil(() => !o.IsPrisonerOfColony, 4000);
|
|
T.Check(released, "no warden released the pawn");
|
|
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);
|
|
}
|
|
|
|
[BlaxTest("jail: a mode written at capture plus 1 (Enslave with Ideology, else Reduce resistance) reads Maintain only at capture plus 2, with Laws' component first")]
|
|
public static void MaintainOnlyLandsLast()
|
|
{
|
|
MoveLawsComponentFirst();
|
|
EnforceFixtures.PrisonCell();
|
|
Pawn o = EnforceFixtures.Offender();
|
|
EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 2f, 6f));
|
|
LawCase c = EnforceFixtures.ActCase(o, "Jail", 3);
|
|
Enforcement.Enqueue(c, LawStage.DidIt);
|
|
T.Check(EnforceFixtures.RunUntil(() => o.IsPrisonerOfColony, EnforceFixtures.SubdueTicks), "not a prisoner; case " + c + ", wait " + c.waitReason);
|
|
T.Equal(Now, c.captureTick, "the capture tick");
|
|
Fixtures.Tick(1);
|
|
PrisonerInteractionModeDef other = ModsConfig.IdeologyActive && PrisonerInteractionModeDefOf.Enslave != null
|
|
? PrisonerInteractionModeDefOf.Enslave
|
|
: PrisonerInteractionModeDefOf.ReduceResistance;
|
|
o.guest.SetExclusiveInteraction(other);
|
|
T.Equal(other, o.guest.ExclusiveInteractionMode, "the mode written at capture plus 1");
|
|
Fixtures.Tick(1);
|
|
T.Equal(PrisonerInteractionModeDefOf.MaintainOnly, o.guest.ExclusiveInteractionMode, "the mode at capture plus 2");
|
|
}
|
|
|
|
/// <summary>Puts Laws' component before Castes' in Game.components for the test (Castes writes its default a tick after the capture).</summary>
|
|
private static void MoveLawsComponentFirst()
|
|
{
|
|
List<GameComponent> list = Current.Game.components;
|
|
GameComponent_BlaxLaws laws = Fixtures.Comp;
|
|
int at = list.FindIndex(x => x.GetType().FullName == "BlaxCastes.GameComponent_BlaxCastes");
|
|
int mine = list.IndexOf(laws);
|
|
if (at < 0 || mine < 0 || mine < at)
|
|
return;
|
|
List<GameComponent> before = list.ToList();
|
|
list.Remove(laws);
|
|
list.Insert(at, laws);
|
|
Fixtures.OnCleanup(() =>
|
|
{
|
|
list.Clear();
|
|
list.AddRange(before);
|
|
});
|
|
}
|
|
|
|
[BlaxTest("jail: with Prison Labor's work option off the released pawn has the work priorities it had before the arrest; with it on only the work types Prison Labor bars prisoners from are off (needs Prison Labor)")]
|
|
public static void PrisonLaborKeepsPriorities()
|
|
{
|
|
if (!Compat.IsActive(PrisonLaborId))
|
|
T.Skip("needs Prison Labor");
|
|
PrisonerInteractionModeDef work = DefDatabase<PrisonerInteractionModeDef>.GetNamedSilentFail("PrisonLabor_workOption");
|
|
T.NotNull(work, "Prison Labor's PrisonLabor_workOption mode");
|
|
foreach (bool on in new[] { false, true })
|
|
{
|
|
Pawn o = EnforceFixtures.Offender();
|
|
Dictionary<WorkTypeDef, int> priorities = EnforceFixtures.Priorities(o);
|
|
LawCase c = JailAndRelease(o, () => o.guest.ToggleNonExclusiveInteraction(work, on));
|
|
string diff = PriorityDiff(priorities, o, on);
|
|
T.Check(diff == null, "work priorities changed with the work option " + (on ? "on" : "off") + ": " + diff);
|
|
T.Check(c.IsClosed, "the case after the release: " + c);
|
|
}
|
|
}
|
|
|
|
/// <summary>Prison Labor's work option is on for the prisoner (PrisonLaborUtility.LaborEnabled in its 1.7 PrisonLabor.dll).</summary>
|
|
private static bool LaborOn(Pawn o)
|
|
{
|
|
PrisonerInteractionModeDef work = DefDatabase<PrisonerInteractionModeDef>.GetNamedSilentFail("PrisonLabor_workOption");
|
|
return work != null && o.guest != null && o.guest.IsInteractionEnabled(work);
|
|
}
|
|
|
|
/// <summary>
|
|
/// The changed work priorities, or null. While Prison Labor's work option is on, its JobGiver_Labor runs
|
|
/// WorkSettings.InitWorkSettings, which disables every work type its settings bar prisoners from
|
|
/// (WorkSettings.WorkDisabled, Pawn_WorkSettings.Disable), 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.
|
|
/// </summary>
|
|
private static string PriorityDiff(Dictionary<WorkTypeDef, int> before, Pawn o, bool labor)
|
|
{
|
|
Func<WorkTypeDef, bool> 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);
|
|
}
|
|
|
|
[BlaxTest("jail: with Blax Castes the released pawn is back in its old caste (needs Blax Castes)")]
|
|
public static void CastesKeepsCaste()
|
|
{
|
|
if (!Compat.IsActive(CastesId))
|
|
T.Skip("needs Blax Castes");
|
|
GameComponent castes = Current.Game.components.FirstOrDefault(x => x.GetType().FullName == "BlaxCastes.GameComponent_BlaxCastes");
|
|
T.NotNull(castes, "Castes' game component");
|
|
MethodInfo casteOf = castes.GetType().GetMethod("CasteOf", new[] { typeof(Pawn) });
|
|
T.NotNull(casteOf, "GameComponent_BlaxCastes.CasteOf(Pawn)");
|
|
// A generated colonist joins no caste (Castes' join hooks see no SetFaction or SetGuestStatus), so the
|
|
// offender is put into a caste of its own, which no join row names: only "back to its old caste"
|
|
// brings it back there after the release.
|
|
Type manager = GenTypes.GetTypeInAnyAssembly("BlaxCastes.CasteManager");
|
|
MethodInfo create = manager?.GetMethod("CreateCaste", BindingFlags.Public | BindingFlags.Static);
|
|
MethodInfo assign = manager?.GetMethod("Assign", BindingFlags.Public | BindingFlags.Static);
|
|
MethodInfo delete = manager?.GetMethod("DeleteCaste", BindingFlags.Public | BindingFlags.Static);
|
|
T.Check(create != null && assign != null && delete != null, "CasteManager.CreateCaste, Assign and DeleteCaste");
|
|
object caste = create.Invoke(null, new object[] { "BlaxLawsTest caste" });
|
|
T.NotNull(caste, "the test caste");
|
|
Fixtures.OnCleanup(() => delete.Invoke(null, new[] { caste }));
|
|
Pawn o = EnforceFixtures.Offender();
|
|
T.Check((bool)assign.Invoke(null, new object[] { o, caste, false, null }), "fixture: the offender can't join the test caste");
|
|
Fixtures.Tick(2);
|
|
object before = casteOf.Invoke(castes, new object[] { o });
|
|
T.Check(Equals(before, caste), "fixture: the offender isn't in the test caste: " + before);
|
|
JailAndRelease(o, null);
|
|
Fixtures.Tick(5);
|
|
object after = casteOf.Invoke(castes, new object[] { o });
|
|
T.Check(Equals(before, after), "the caste after the release isn't the old one: " + before + " to " + after);
|
|
}
|
|
|
|
/// <summary>Jails the pawn through a 1-day row and releases it through the fallback. atJail runs while it is jailed.</summary>
|
|
private static LawCase JailAndRelease(Pawn o, Action atJail)
|
|
{
|
|
// The fallback below backdates the release tick by a day. Before day 2 that tick would be negative,
|
|
// which Sentences.Check reads as "not set yet" and recomputes from the capture, so the game clock
|
|
// is moved past a day first, before anything of this test is scheduled.
|
|
if (Now < 2 * Sentences.FallbackTicks)
|
|
Find.TickManager.DebugSetTicksGame(2 * Sentences.FallbackTicks);
|
|
EnforceFixtures.PrisonCell();
|
|
EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 2f, 6f));
|
|
LawCase c = EnforceFixtures.ActCase(o, "Jail", 1);
|
|
Enforcement.Enqueue(c, LawStage.DidIt);
|
|
// An arrested colonist turns prisoner when the warden picks it up (JobDriver_TakeToBed.cs:124-129) and
|
|
// stays held, not spawned, until it is tucked in; the fallback releases only a spawned pawn. atJail runs
|
|
// at the pick-up, before the prisoner thinks once (Prison Labor's default work option is set there).
|
|
T.Check(EnforceFixtures.RunUntil(() => o.IsPrisonerOfColony, EnforceFixtures.SubdueTicks), "not a prisoner; case " + c + ", wait " + c.waitReason);
|
|
atJail?.Invoke();
|
|
T.Check(EnforceFixtures.RunUntil(() => o.Spawned && o.InBed(), EnforceFixtures.SubdueTicks),
|
|
"the prisoner isn't in its bed; case " + c + ", prisoner " + o.IsPrisonerOfColony + ", spawned " + o.Spawned);
|
|
Fixtures.Tick(5);
|
|
c.releaseTick = Now - Sentences.FallbackTicks - 1;
|
|
Sentences.Check(c);
|
|
T.Check(!o.IsPrisonerOfColony, "the fallback didn't release the pawn; case " + c + ", spawned " + o.Spawned + ", in bed " + o.InBed());
|
|
return c;
|
|
}
|
|
|
|
// ---- the arrest -------------------------------------------------------------------
|
|
|
|
[BlaxTest("jail: an arrest interrupted after its first toil leaves the colonist its old bed by the next sweep; a bed someone else claimed meanwhile stays theirs")]
|
|
public static void OldBedBack()
|
|
{
|
|
PrisonRoom room = EnforceFixtures.PrisonCell();
|
|
Pawn o = EnforceFixtures.Offender();
|
|
EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 4f, 8f));
|
|
Building_Bed own = EnforceFixtures.ColonistBed(o.Position);
|
|
T.Check(o.ownership.ClaimBedIfNonMedical(own), "fixture: the colonist can't claim its bed");
|
|
// Bystanders without a bed would take the freed bed when they go to sleep before the sweep: the case
|
|
// of a bed someone else claimed, which the second half tests on purpose.
|
|
EnforceFixtures.BedsForBystanders(o);
|
|
LawCase c = EnforceFixtures.ActCase(o, "Jail", 3);
|
|
EnforceFixtures.Dispatch(c, LawStage.DidIt);
|
|
T.Check(JailFlow.ArrestRuns(c), "no arrest started; wait " + c.waitReason);
|
|
T.Equal(own, c.oldBed, "the old bed noted in the case");
|
|
T.Check(o.ownership.OwnedBed == room.bed, "the arrest's first toil didn't claim the prisoner bed: " + o.ownership.OwnedBed);
|
|
|
|
Pawn raider = EnforceFixtures.Raider(); // keeps the retry waiting, so the sweep's give-back shows
|
|
c.enforcer.jobs.EndCurrentJob(JobCondition.InterruptForced);
|
|
Fixtures.Tick(Enforcement.SweepInterval + 1);
|
|
T.Check(o.ownership.OwnedBed == own, "the colonist doesn't own its old bed after the sweep: it owns " + (o.ownership.OwnedBed?.ToString() ?? "no bed") +
|
|
", the old bed's owners " + Owners(own) + "; case " + c + ", wait " + c.waitReason + ", arrest runs " + JailFlow.ArrestRuns(c));
|
|
T.Equal(WaitReasons.Danger, c.waitReason, "the case's wait while the raider is on the map");
|
|
|
|
raider.Destroy(DestroyMode.Vanish);
|
|
T.Check(EnforceFixtures.RunUntil(() => JailFlow.ArrestRuns(c), Enforcement.SweepInterval + 5), "no second arrest; wait " + c.waitReason);
|
|
T.Check(o.ownership.OwnedBed == room.bed, "the second arrest didn't claim the prisoner bed");
|
|
Pawn other = EnforceFixtures.Offender(EnforceFixtures.CellNear(o.Position, 6f, 12f));
|
|
T.Check(other.ownership.ClaimBedIfNonMedical(own), "fixture: another colonist can't claim the free old bed");
|
|
EnforceFixtures.Raider();
|
|
c.enforcer.jobs.EndCurrentJob(JobCondition.InterruptForced);
|
|
Fixtures.Tick(Enforcement.SweepInterval + 1);
|
|
T.Check(own.OwnersForReading.Contains(other), "the other colonist lost the bed it claimed");
|
|
T.Check(!own.OwnersForReading.Contains(o), "the offender took back a bed someone else claimed");
|
|
}
|
|
|
|
[BlaxTest("jail: a raid that lands while the arrest walks to the colonist calls it off, gives the old bed back and waits for the danger; after the raid the sweep arrests")]
|
|
public static void RaidCallsOffArrest()
|
|
{
|
|
PrisonRoom room = EnforceFixtures.PrisonCell();
|
|
Pawn o = EnforceFixtures.Offender();
|
|
EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 4f, 8f));
|
|
Building_Bed own = EnforceFixtures.ColonistBed(o.Position);
|
|
T.Check(o.ownership.ClaimBedIfNonMedical(own), "fixture: the colonist can't claim its bed");
|
|
EnforceFixtures.BedsForBystanders(o);
|
|
LawCase c = EnforceFixtures.ActCase(o, "Jail", 3);
|
|
EnforceFixtures.Dispatch(c, LawStage.DidIt);
|
|
T.Check(JailFlow.ArrestRuns(c), "fixture: no arrest started; wait " + c.waitReason);
|
|
T.Check(!c.enforcer.IsCarryingPawn(o), "fixture: the warden already carries the colonist");
|
|
Pawn raider = EnforceFixtures.Raider();
|
|
// The worker's sweep directly, so the arrest can't finish between the raid and the check.
|
|
BlaxLawsDefOf.Jail.Worker.Sweep(c);
|
|
T.Check(!JailFlow.ArrestRuns(c), "the arrest still runs during the raid");
|
|
T.Check(!EnforceFixtures.AnyEnforcementJobOn(o), "an enforcement job on the colonist during the raid");
|
|
T.Equal(CaseStatus.Open, c.status, "status during the raid");
|
|
T.Equal(WaitReasons.Danger, c.waitReason, "wait reason during the raid");
|
|
T.Check(!o.IsPrisonerOfColony, "a prisoner during the raid");
|
|
T.Check(o.ownership.OwnedBed == own, "the old bed wasn't given back: owns " + (o.ownership.OwnedBed?.ToString() ?? "no bed"));
|
|
raider.Destroy(DestroyMode.Vanish);
|
|
T.Check(EnforceFixtures.RunUntil(() => JailFlow.ArrestRuns(c) || o.IsPrisonerOfColony, Enforcement.SweepInterval + 5), "no arrest after the raid; wait " + c.waitReason);
|
|
T.Check(o.ownership.OwnedBed == room.bed || o.IsPrisonerOfColony, "the second arrest didn't claim the prisoner bed");
|
|
}
|
|
|
|
[BlaxTest("jail: a raid that lands while the warden already carries the arrested colonist doesn't call the arrest off: the carry finishes and the case is jailed")]
|
|
public static void RaidLetsCarryFinish()
|
|
{
|
|
PrisonRoom room = EnforceFixtures.PrisonCell();
|
|
Pawn o = EnforceFixtures.Offender();
|
|
EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 4f, 8f));
|
|
EnforceFixtures.BedsForBystanders(o);
|
|
LawCase c = EnforceFixtures.ActCase(o, "Jail", 3);
|
|
EnforceFixtures.Dispatch(c, LawStage.DidIt);
|
|
T.Check(JailFlow.ArrestRuns(c), "fixture: no arrest started; wait " + c.waitReason);
|
|
Pawn enforcer = c.enforcer;
|
|
T.Check(EnforceFixtures.RunUntil(() => enforcer.IsCarryingPawn(o), EnforceFixtures.SubdueTicks),
|
|
"fixture: the warden never carried the colonist; case " + c + ", warden on " + (enforcer.CurJobDef?.defName ?? "no job"));
|
|
EnforceFixtures.Raider();
|
|
// A carried pawn is despawned, so the raider counts through the enforcer's map (Raider() checks the threat).
|
|
T.Check(GenHostility.AnyHostileActiveThreatToPlayer(enforcer.Map), "fixture: the raider is no threat on the warden's map");
|
|
// The worker's sweep directly, while the warden carries the colonist.
|
|
BlaxLawsDefOf.Jail.Worker.Sweep(c);
|
|
T.Check(JailFlow.ArrestRuns(c), "the arrest was called off mid-carry");
|
|
T.Check(enforcer.IsCarryingPawn(o), "the warden dropped the colonist");
|
|
T.Check(c.waitReason != WaitReasons.Danger, "the case waits for the danger while the carry goes on");
|
|
T.Check(EnforceFixtures.RunUntil(() => c.status == CaseStatus.Jailed, EnforceFixtures.SubdueTicks),
|
|
"the carry didn't end in a jailing with the raider on the map; case " + c + ", wait " + c.waitReason);
|
|
T.Check(o.IsPrisonerOfColony && o.ownership.OwnedBed == room.bed, "the colonist isn't a prisoner owning the cell's bed: " + (o.ownership.OwnedBed?.ToString() ?? "no bed"));
|
|
}
|
|
|
|
private static string Owners(Building_Bed bed)
|
|
{
|
|
List<Pawn> owners = bed.OwnersForReading;
|
|
if (owners.Count == 0)
|
|
return "none";
|
|
return string.Join(", ", owners.Select(p => p.LabelShort + (p.Awake() ? " (awake)" : " (asleep)")));
|
|
}
|
|
|
|
[BlaxTest("jail: a 5-day row whose guilt ran out while no prisoner bed existed: once a bed is built the arrest is accepted against Social 0 and the release comes 5 days after the capture")]
|
|
public static void LateArrest()
|
|
{
|
|
Pawn o = EnforceFixtures.Offender();
|
|
EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 2f, 6f));
|
|
SocialZeroForAll();
|
|
LawCase c = EnforceFixtures.ActCase(o, "Jail", 5);
|
|
EnforceFixtures.Dispatch(c, LawStage.DidIt);
|
|
T.Equal(WaitReasons.NoBed, c.waitReason, "the wait without a prisoner bed");
|
|
T.Check(o.guilt.TicksUntilInnocent >= 5 * GenDate.TicksPerDay - 30, "no guilt for the sentence at filing: " + o.guilt.TicksUntilInnocent);
|
|
o.guilt.Notify_Guilty(0); // the six days without a bed: the guilt from filing has run out
|
|
T.Check(!o.guilt.IsGuilty, "fixture: the guilt didn't run out");
|
|
|
|
EnforceFixtures.PrisonCell();
|
|
int guiltAtArrest = -1;
|
|
bool jailed = EnforceFixtures.RunUntil(() =>
|
|
{
|
|
if (guiltAtArrest < 0 && JailFlow.ArrestRuns(c))
|
|
guiltAtArrest = o.guilt.TicksUntilInnocent;
|
|
return o.IsPrisonerOfColony || o.InMentalState;
|
|
}, Enforcement.SentenceInterval + EnforceFixtures.SubdueTicks);
|
|
T.Check(guiltAtArrest >= 6 * GenDate.TicksPerDay - 30, "guilt when the arrest started: " + guiltAtArrest);
|
|
T.Check(!o.InMentalState, "the arrest was refused: " + o.MentalStateDef?.defName);
|
|
T.Check(jailed, "no arrest after the bed was built; case " + c + ", wait " + c.waitReason);
|
|
T.Equal(c.captureTick + 5 * GenDate.TicksPerDay, c.releaseTick, "the release tick");
|
|
}
|
|
|
|
/// <summary>Every free colonist's Social at 0 for the test, restored after.</summary>
|
|
private static void SocialZeroForAll()
|
|
{
|
|
var old = new List<(SkillRecord skill, int level)>();
|
|
foreach (Pawn p in EnforceFixtures.Map.mapPawns.FreeColonistsSpawned)
|
|
{
|
|
SkillRecord s = p.skills?.GetSkill(SkillDefOf.Social);
|
|
if (s == null)
|
|
continue;
|
|
old.Add((s, s.Level));
|
|
s.Level = 0;
|
|
}
|
|
Fixtures.OnCleanup(() =>
|
|
{
|
|
foreach (var (skill, level) in old)
|
|
skill.Level = level;
|
|
});
|
|
}
|
|
|
|
[BlaxTest("jail: no prisoner bed gives one letter and no arrest; building one leads to the arrest at the next sweep")]
|
|
public static void NoPrisonerBed()
|
|
{
|
|
Pawn o = EnforceFixtures.Offender();
|
|
EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 2f, 6f));
|
|
LawCase c = EnforceFixtures.ActCase(o, "Jail", 3);
|
|
string label = "BlaxLaws_LetterNoBedLabel".Translate(c.OffenderLabel);
|
|
EnforceFixtures.Dispatch(c, LawStage.DidIt);
|
|
T.Equal(WaitReasons.NoBed, c.waitReason, "the wait without a prisoner bed");
|
|
EnforceFixtures.TickPastSentenceSweep();
|
|
EnforceFixtures.TickPastSentenceSweep();
|
|
T.Equal(1, EnforceFixtures.LettersLabeled(label), "no-bed letters");
|
|
T.Check(!EnforceFixtures.AnyEnforcementJobOn(o), "an arrest started without a bed");
|
|
EnforceFixtures.PrisonCell();
|
|
bool arrest = EnforceFixtures.RunUntil(() => JailFlow.ArrestRuns(c) || o.IsPrisonerOfColony, Enforcement.SentenceInterval + 5);
|
|
T.Check(arrest, "no arrest after the bed was built; wait " + c.waitReason);
|
|
}
|
|
|
|
// ---- holds and fallbacks ----------------------------------------------------------
|
|
|
|
[BlaxTest("jail: a role holder gets no arrest and one letter; Arrest now arrests (needs Ideology)")]
|
|
public static void HoldRoleHolder()
|
|
{
|
|
T.NeedsDlc("Ideology", ModsConfig.IdeologyActive);
|
|
Pawn o = null;
|
|
for (int i = 0; i < 10 && o == null; i++)
|
|
{
|
|
Pawn candidate = EnforceFixtures.Offender();
|
|
if (GiveRole(candidate))
|
|
o = candidate;
|
|
}
|
|
if (o == null)
|
|
T.Skip("ten generated colonists met the requirements of no role of their ideoligion");
|
|
Fixtures.Tick(1);
|
|
T.Check(DlcSupport.HoldsRole(o), "fixture: the colonist holds no role after a tick");
|
|
CheckHoldAndArrestNow(o);
|
|
}
|
|
|
|
[BlaxTest("jail: a mechanitor with a mech gets no arrest and one letter; Arrest now arrests (needs Biotech)")]
|
|
public static void HoldMechanitor()
|
|
{
|
|
T.NeedsDlc("Biotech", ModsConfig.BiotechActive);
|
|
Pawn o = EnforceFixtures.Offender();
|
|
MakeMechanitor(o, keep: false);
|
|
CheckHoldAndArrestNow(o);
|
|
}
|
|
|
|
[BlaxTest("jail: a pawn that becomes a mechanitor with a mech while its case waits for a bed is held, not arrested (needs Biotech)")]
|
|
public static void HoldAfterOtherWait()
|
|
{
|
|
T.NeedsDlc("Biotech", ModsConfig.BiotechActive);
|
|
Pawn o = EnforceFixtures.Offender();
|
|
EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 2f, 6f));
|
|
LawCase c = EnforceFixtures.ActCase(o, "Jail", 3);
|
|
EnforceFixtures.Dispatch(c, LawStage.DidIt);
|
|
T.Equal(WaitReasons.NoBed, c.waitReason, "fixture: the wait without a prisoner bed");
|
|
MakeMechanitor(o, keep: false);
|
|
EnforceFixtures.PrisonCell();
|
|
JailFlow.TryArrest(c, ignoreHold: false);
|
|
T.Equal(WaitReasons.Hold, c.waitReason, "the wait after the pawn got a mech");
|
|
T.Check(!JailFlow.ArrestRuns(c) && !o.IsPrisonerOfColony, "Laws arrested a mechanitor on its own after a bed wait");
|
|
T.Check(!c.holdLifted, "the hold counts as lifted without Arrest now");
|
|
}
|
|
|
|
/// <summary>
|
|
/// Gives the colonist a mechlink and a lifter it oversees (needs Biotech). With keep the mech stays for
|
|
/// phase 2 and the relation is left in place; otherwise the cleanup removes the relation.
|
|
/// </summary>
|
|
private static void MakeMechanitor(Pawn o, bool keep)
|
|
{
|
|
o.health.AddHediff(HediffDefOf.MechlinkImplant, o.health.hediffSet.GetBrain());
|
|
T.Check(MechanitorUtility.IsMechanitor(o), "fixture: the mechlink made no mechanitor");
|
|
PawnKindDef kind = DefDatabase<PawnKindDef>.GetNamedSilentFail("Mech_Lifter");
|
|
T.NotNull(kind, "PawnKindDef Mech_Lifter");
|
|
Pawn mech = Fixtures.Spawn(Fixtures.Generate(kind, Faction.OfPlayer), EnforceFixtures.CellNear(o.Position, 2f, 5f));
|
|
o.relations.AddDirectRelation(PawnRelationDefOf.Overseer, mech);
|
|
o.mechanitor.Notify_BandwidthChanged(); // rebuilds ControlledPawns from the control groups (Pawn_MechanitorTracker.cs:268-290)
|
|
if (keep)
|
|
Fixtures.Keep(mech);
|
|
else
|
|
Fixtures.OnCleanup(() =>
|
|
{
|
|
if (o.relations.DirectRelationExists(PawnRelationDefOf.Overseer, mech))
|
|
o.relations.RemoveDirectRelation(PawnRelationDefOf.Overseer, mech);
|
|
});
|
|
T.Check(DlcSupport.IsMechanitorWithMechs(o), "fixture: the mechanitor controls no mech");
|
|
}
|
|
|
|
private static void CheckHoldAndArrestNow(Pawn o)
|
|
{
|
|
EnforceFixtures.PrisonCell();
|
|
EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 2f, 6f));
|
|
LawCase c = EnforceFixtures.ActCase(o, "Jail", 3);
|
|
string label = "BlaxLaws_LetterHoldLabel".Translate(c.OffenderLabel);
|
|
EnforceFixtures.Dispatch(c, LawStage.DidIt);
|
|
T.Equal(WaitReasons.Hold, c.waitReason, "the wait of a held pawn");
|
|
Fixtures.Tick(Enforcement.SweepInterval + 1);
|
|
T.Check(!EnforceFixtures.AnyEnforcementJobOn(o), "a held pawn was arrested");
|
|
T.Equal(1, EnforceFixtures.LettersLabeled(label), "hold letters");
|
|
T.Check(Sentences.CanArrestNow(c), "Arrest now isn't offered");
|
|
o.guilt.Notify_Guilty(0);
|
|
Sentences.ArrestNow(c);
|
|
T.Check(JailFlow.ArrestRuns(c), "Arrest now started no arrest; wait " + c.waitReason);
|
|
T.Check(o.guilt.TicksUntilInnocent >= 4 * GenDate.TicksPerDay - 30, "Arrest now didn't renew the guilt: " + o.guilt.TicksUntilInnocent);
|
|
Fixtures.Tick(Enforcement.SweepInterval + 1);
|
|
T.Check(JailFlow.ArrestRuns(c) || o.IsPrisonerOfColony, "the sweep put the hold back; wait " + c.waitReason);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Gives the colonist a role of its ideoligion whose requirements it meets, a multi role when there is
|
|
/// one, among the active roles; undone before the cleanup. Returns false when no role fits. A role whose requirements the pawn
|
|
/// misses (a skill, not a child) is taken away again on the next role tick (Precept_RoleSingle.cs:66-70;
|
|
/// Precept_Role.cs:508-520, 582-597).
|
|
/// </summary>
|
|
private static bool GiveRole(Pawn o)
|
|
{
|
|
Ideo ideo = o.Ideo;
|
|
if (ideo == null)
|
|
return false;
|
|
Precept_Role role = ideo.PreceptsListForReading.OfType<Precept_RoleMulti>().FirstOrDefault(r => r.Active && r.RequirementsMet(o))
|
|
?? (Precept_Role)ideo.PreceptsListForReading.OfType<Precept_RoleSingle>().FirstOrDefault(r => r.Active && r.RequirementsMet(o));
|
|
if (role == null)
|
|
return false;
|
|
Pawn previous = (role as Precept_RoleSingle)?.ChosenPawnValue;
|
|
role.Assign(o, addThoughts: false);
|
|
Fixtures.OnCleanup(() =>
|
|
{
|
|
if (role.IsAssigned(o))
|
|
role.Unassign(o, generateThoughts: false);
|
|
if (previous != null && !previous.Destroyed && role is Precept_RoleSingle single && single.ChosenPawnValue == null)
|
|
single.Assign(previous, addThoughts: false);
|
|
});
|
|
return true;
|
|
}
|
|
|
|
[BlaxTest("jail: a slave in a binge with a jail row is subdued; the same row outside a break warns (needs Ideology)")]
|
|
public static void SlaveFallsBack()
|
|
{
|
|
Pawn slave = EnforceFixtures.Ready(Fixtures.ColonySlave());
|
|
EnforceFixtures.Warden(EnforceFixtures.CellNear(slave.Position, 2f, 5f));
|
|
LawCase quiet = EnforceFixtures.ActCase(slave, "Jail", 3);
|
|
EnforceFixtures.Dispatch(quiet, LawStage.DidIt);
|
|
T.Check(quiet.IsClosed && quiet.outcome == CaseOutcomes.Warned, "the slave's case outside a break: " + quiet);
|
|
T.Check(!slave.IsPrisoner && !EnforceFixtures.AnyEnforcementJobOn(slave), "the slave was arrested outside a break");
|
|
|
|
EnforceFixtures.ForceBreak(slave, EnforceFixtures.DrugBinge);
|
|
LawCase binge = EnforceFixtures.BreakCase(slave, "Jail", LawStage.DidIt, 3);
|
|
EnforceFixtures.Dispatch(binge, LawStage.DidIt);
|
|
T.Equal("Subdue", binge.activePunishment, "the binging slave's punishment");
|
|
T.Check(SubdueFlow.Runs(binge), "no subdue for the binging slave; wait " + binge.waitReason);
|
|
T.Check(!slave.IsPrisoner, "the slave was jailed");
|
|
}
|
|
|
|
// ---- the early end and the fallback -----------------------------------------------
|
|
|
|
[BlaxTest("jail: recruiting the jailed pawn closes the sentence as released early")]
|
|
public static void RecruitEndsEarly()
|
|
{
|
|
Pawn o = EnforceFixtures.Offender();
|
|
Pawn warden = EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 2f, 5f));
|
|
LawCase c = EnforceFixtures.JailDirect(o, warden, 3);
|
|
RecruitUtility.Recruit(o, Faction.OfPlayer, warden);
|
|
T.Check(!o.IsPrisonerOfColony, "fixture: the recruited pawn is still a prisoner");
|
|
Sentences.Check(c);
|
|
T.Check(c.IsClosed && c.outcome == CaseOutcomes.ReleasedEarly, "the case after the recruitment: " + c);
|
|
}
|
|
|
|
[BlaxTest("jail: a day after the sentence without a release, Laws releases the pawn in place")]
|
|
public static void FallbackRelease()
|
|
{
|
|
// A release tick a day and a tick in the past must be a real tick (-1 means "not set yet").
|
|
if (Now < Sentences.FallbackTicks + 1)
|
|
Fixtures.Tick(Sentences.FallbackTicks + 1 - Now);
|
|
Pawn o = EnforceFixtures.Offender();
|
|
Pawn warden = EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 2f, 5f));
|
|
LawCase c = EnforceFixtures.JailDirect(o, warden, 3);
|
|
c.releaseTick = Now - Sentences.FallbackTicks - 1;
|
|
Sentences.Check(c);
|
|
T.Check(!o.IsPrisonerOfColony && o.IsFreeColonist, o.LabelShort + " isn't free after the fallback");
|
|
T.NotNull(o.needs.mood.thoughts.memories.GetFirstMemoryOfDef(ThoughtDefOf.WasImprisoned), "WasImprisoned after the fallback");
|
|
T.Check(c.IsClosed && c.outcome == CaseOutcomes.Served, "the case after the fallback: " + c);
|
|
}
|
|
|
|
[BlaxTest("jail: repealing the law of a jailed pawn sets Release on it")]
|
|
public static void RepealReleases()
|
|
{
|
|
Pawn o = EnforceFixtures.Offender();
|
|
Pawn warden = EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 2f, 5f));
|
|
LawCase c = EnforceFixtures.JailDirect(o, warden, 3);
|
|
Sentences.WriteMaintainOnly(c);
|
|
string confirm = LawbookUi.DeleteConfirmText(c.LawFor(LawStage.DidIt)) ?? "";
|
|
T.Check(confirm.Contains("Release"), "the delete confirmation doesn't say the jailed pawn is set to Release: " + confirm);
|
|
T.Equal(1, Lawbook.Delete(c.LawFor(LawStage.DidIt)), "cases the repeal closed");
|
|
T.Check(c.IsClosed && c.outcome == CaseOutcomes.Repealed, "the case after the repeal: " + c);
|
|
T.Equal(PrisonerInteractionModeDefOf.Release, o.guest.ExclusiveInteractionMode, "the jailed pawn's mode after the repeal");
|
|
}
|
|
|
|
// ---- save and removal ---------------------------------------------------------------
|
|
|
|
private const string JailSaveKey = "jail.savedPrisoner";
|
|
|
|
[BlaxTest("jail save: a colonist jailed for 50 days at the first save (setup)")]
|
|
public static void JailSaveSetup()
|
|
{
|
|
T.CarryAtSave(JailSaveKey, JailForSave);
|
|
}
|
|
|
|
private static string JailForSave()
|
|
{
|
|
PrisonRoom room = EnforceFixtures.PrisonCell(keep: true);
|
|
Pawn o = Fixtures.Keep(EnforceFixtures.Offender(room.inside));
|
|
Pawn warden = Fixtures.Keep(EnforceFixtures.Warden());
|
|
LawCase c = EnforceFixtures.JailDirect(o, warden, 50);
|
|
Fixtures.KeepLaw(c.LawFor(LawStage.DidIt));
|
|
Sentences.WriteMaintainOnly(c);
|
|
return c.id + "|" + o.ThingID + "|" + c.captureTick;
|
|
}
|
|
|
|
[BlaxTest("jail save: the jailed colonist is still Laws' prisoner on Maintain only after the reload", phase: 2)]
|
|
public static void JailSaveRoundTrip()
|
|
{
|
|
T.Check(T.Carry.TryGetValue(JailSaveKey, out string carry) && !carry.NullOrEmpty(), "the phase-1 jail setup did not run");
|
|
string[] parts = carry.Split('|');
|
|
LawCase c = Fixtures.Comp.CaseById(int.Parse(parts[0]));
|
|
Pawn o = Fixtures.FindPawnById(parts[1]);
|
|
T.NotNull(c, "the jail case after the reload");
|
|
T.NotNull(o, "the jailed colonist after the reload");
|
|
T.Check(c.offender == o, "the case's offender didn't resolve");
|
|
T.Equal(CaseStatus.Jailed, c.status, "the case's status");
|
|
T.Equal(int.Parse(parts[2]), c.captureTick, "the capture tick");
|
|
T.Equal(c.captureTick + 50 * GenDate.TicksPerDay, c.releaseTick, "the release tick");
|
|
T.Check(c.maintainOnlyDone, "maintainOnlyDone after the reload");
|
|
T.Check(o.IsPrisonerOfColony, o.LabelShort + " isn't a prisoner after the reload");
|
|
T.Equal(PrisonerInteractionModeDefOf.MaintainOnly, o.guest.ExclusiveInteractionMode, "the mode after the reload");
|
|
}
|
|
|
|
private const string HoldSaveKey = "jail.holdLifted";
|
|
|
|
[BlaxTest("jail save: a mechanitor's case with Arrest now pressed at the first save (setup, needs Biotech)")]
|
|
public static void HoldLiftSaveSetup()
|
|
{
|
|
T.NeedsDlc("Biotech", ModsConfig.BiotechActive);
|
|
T.CarryAtSave(HoldSaveKey, HoldLiftForSave);
|
|
}
|
|
|
|
private static string HoldLiftForSave()
|
|
{
|
|
Pawn o = Fixtures.Keep(EnforceFixtures.Offender());
|
|
Fixtures.Keep(EnforceFixtures.Warden(EnforceFixtures.CellNear(o.Position, 2f, 6f)));
|
|
MakeMechanitor(o, keep: true);
|
|
LawCase c = EnforceFixtures.ActCase(o, "Jail", 3);
|
|
Fixtures.KeepLaw(c.LawFor(LawStage.DidIt));
|
|
EnforceFixtures.Dispatch(c, LawStage.DidIt);
|
|
if (c.waitReason != WaitReasons.Hold)
|
|
throw new InvalidOperationException("the mechanitor's case waits for " + (c.waitReason ?? "nothing") + ", not the hold");
|
|
Sentences.ArrestNow(c);
|
|
// The state a failed arrest leaves (PunishmentWorker_Jail.Sweep): no job, Open, no wait.
|
|
JailFlow.EndArrest(c);
|
|
c.status = CaseStatus.Open;
|
|
c.waitReason = null;
|
|
return c.id + "|" + o.ThingID;
|
|
}
|
|
|
|
[BlaxTest("jail save: Arrest now still holds after the reload; a failed arrest retries without a second hold", phase: 2)]
|
|
public static void HoldLiftRoundTrip()
|
|
{
|
|
T.NeedsDlc("Biotech", ModsConfig.BiotechActive);
|
|
T.Check(T.Carry.TryGetValue(HoldSaveKey, out string carry) && !carry.NullOrEmpty(), "the phase-1 hold setup did not run");
|
|
string[] parts = carry.Split('|');
|
|
T.Check(parts.Length == 2, "carry: " + carry);
|
|
LawCase c = Fixtures.Comp.CaseById(int.Parse(parts[0]));
|
|
Pawn o = Fixtures.FindPawnById(parts[1]);
|
|
T.NotNull(c, "the held case after the reload");
|
|
T.NotNull(o, "the mechanitor after the reload");
|
|
T.Check(DlcSupport.IsMechanitorWithMechs(o), "fixture: the mechanitor lost its mech in the reload");
|
|
T.Check(c.holdLifted, "holdLifted after the reload");
|
|
T.Check(c.waitReason != WaitReasons.Hold, "a sweep after the reload put the hold back");
|
|
if (!JailFlow.ArrestRuns(c) && !o.IsPrisonerOfColony)
|
|
{
|
|
c.status = CaseStatus.Open;
|
|
c.waitReason = null;
|
|
JailFlow.TryArrest(c, ignoreHold: false);
|
|
T.Check(c.waitReason != WaitReasons.Hold && !Sentences.CanArrestNow(c), "the retry after the reload went back to the hold; wait " + c.waitReason);
|
|
}
|
|
}
|
|
|
|
[BlaxTest("removal: the colonist Laws jailed is still a prisoner of the colony", phase: 3)]
|
|
public static void JailedAfterRemoval()
|
|
{
|
|
T.Check(T.Carry.TryGetValue(JailSaveKey, out string carry) && !carry.NullOrEmpty(), "the phase-1 jail setup did not run");
|
|
Pawn o = Fixtures.FindPawnById(carry.Split('|')[1]);
|
|
T.NotNull(o, "the jailed colonist after the removal");
|
|
T.Check(o.IsPrisonerOfColony, o.LabelShort + " isn't a prisoner of the colony after the removal");
|
|
T.Equal(0, Fixtures.Comp.Cases.Count, "cases in the fresh component");
|
|
}
|
|
}
|
|
}
|