rimworld-blax-laws/Tests/BlaxLawsTests/Source/SentenceEndTests.cs

580 lines
38 KiB
C#
Raw Permalink Normal View History

using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using BlaxLaws;
using RimWorld;
using RimWorld.Planet;
using Verse;
using Verse.AI.Group;
namespace BlaxLawsTests
{
/// <summary>
/// "Jail for N days", the early end (CHANGELOG 1.0.0: "A jailed colonist that is recruited, released by
/// you or another mod, escapes or dies closes its sentence"). Recruitment is JailTests.RecruitEndsEarly;
/// these cover the release through GenGuest.PrisonerRelease (a warden on your order, Prisoner Sentencing
/// or Prison Expanded, design: "Compat runs"), a prison break that leaves the map, and death. Each case
/// closes at the real 2500-tick sentence sweep with its own outcome and one message, and leaves nothing
/// behind: no running punishment, no wait, no countdown, no queued task, no open case for the pawn.
/// </summary>
public static class SentenceEndTests
{
private static int Now => Find.TickManager.TicksGame;
[BlaxTest("jail end: a jailed colonist released through GenGuest.PrisonerRelease before its release day (by your warden, Prisoner Sentencing or Prison Expanded) closes as released early at the next sentence sweep with one message; capturing it again by hand later doesn't reopen the case")]
public static void PrisonerReleaseEndsEarly()
{
LawCase c = JailInCell(out Pawn o, out Pawn warden);
string text = "BlaxLaws_MsgReleasedEarly".Translate(c.OffenderLabel).Resolve();
int messages = EnforceFixtures.MessagesWith(text);
GenGuest.PrisonerRelease(o);
T.Check(!o.IsPrisonerOfColony && o.IsFreeColonist && o.Spawned, "fixture: " + o.LabelShort + " isn't a free colonist on the map after PrisonerRelease");
T.Check(c.releaseTick > Now + Enforcement.SentenceInterval, "fixture: the sentence would be served by the next sweep; release tick " + c.releaseTick + ", now " + Now);
EnforceFixtures.TickPastSentenceSweep();
CheckClosedClean(c, o, CaseOutcomes.ReleasedEarly, "after the release");
T.Equal(1, EnforceFixtures.MessagesWith(text) - messages, "released-early messages");
T.Check(o.IsFreeColonist, o.LabelShort + " isn't a free colonist after the case closed");
T.Check(!EnforceFixtures.AnyEnforcementJobOn(o), "an enforcement job on the released colonist");
// A later capture by the same warden (by hand, or another mod) is not Laws' capture of a closed case.
int closedAt = c.closeTick;
o.guest.CapturedBy(Faction.OfPlayer, warden);
T.Check(o.IsPrisonerOfColony, "fixture: the capture by hand left " + o.LabelShort + " free");
T.Check(c.IsClosed && c.outcome == CaseOutcomes.ReleasedEarly, "the capture by hand reopened the case: " + c);
T.Check(!Enforcement.IsQueued(c, CaseTask.MaintainOnly), "the capture by hand queued Maintain only for the closed case");
Fixtures.Tick(Enforcement.MaintainOnlyDelay + 1);
T.Check(c.IsClosed && c.outcome == CaseOutcomes.ReleasedEarly, "the case after the capture by hand and two ticks: " + c);
T.Equal(closedAt, c.closeTick, "the close tick after the capture by hand");
T.Check(Fixtures.Comp.CasesOf(o).All(x => x.IsClosed), "an open case for the prisoner taken by hand: " + string.Join(", ", Fixtures.Comp.CasesOf(o).Select(x => x.ToString())));
T.Equal(1, EnforceFixtures.MessagesWith(text) - messages, "released-early messages after the capture by hand");
}
[BlaxTest("jail end: a jailed colonist in a prison break stays jailed while it is on the map; once it leaves the map the next sentence sweep closes the case as escaped with one message, and a later sweep past its release day changes nothing")]
public static void EscapeEndsSentence()
{
LawCase c = JailInCell(out Pawn o, out _);
NoWorldPawnGcBeforeNextSweep();
Map map = o.Map;
StartPrisonBreak(o, map);
Sentences.Check(c);
T.Equal(CaseStatus.Jailed, c.status, "the case's status while the escapee is still on the map");
T.Check(o.IsPrisonerOfColony && o.Spawned, "fixture: " + o.LabelShort + " is no prisoner on the map before it leaves");
string text = "BlaxLaws_MsgEscaped".Translate(c.OffenderLabel).Resolve();
int messages = EnforceFixtures.MessagesWith(text);
// Every escape ends in a Goto with exitMapOnArrival (JobGiver_PrisonerEscape.cs:12-23; the prison break's
// LordToil_ExitMap), which leaves the map this way (Verse.AI/JobDriver_Goto.cs:67-80). A home map uses no
// exit grid, so no caravan forms and the pawn passes to the world (Verse/Pawn.cs:2513-2605).
o.ExitMap(true, CellRect.WholeMap(map).GetClosestEdge(o.Position));
T.Check(!o.Spawned && !o.Dead && o.IsWorldPawn(), "fixture: " + o.LabelShort + " didn't leave the map for the world");
T.Info("the escapee off the map: prisoner of the colony " + o.IsPrisonerOfColony + ", faction " + o.Faction);
EnforceFixtures.TickPastSentenceSweep();
T.Check(!o.Discarded, "fixture: the world discarded the escapee before the sweep; EscapeDiscardedEndsSentence covers that path");
CheckClosedClean(c, o, EnforcementOutcomes.Escaped, "after the escape");
T.Equal(1, EnforceFixtures.MessagesWith(text) - messages, "escape messages");
int closedAt = c.closeTick;
c.releaseTick = Now - Sentences.FallbackTicks - 1;
EnforceFixtures.TickPastSentenceSweep();
T.Check(c.IsClosed && c.outcome == EnforcementOutcomes.Escaped && c.closeTick == closedAt, "a sweep past the release day changed the closed case: " + c);
T.Equal(1, EnforceFixtures.MessagesWith(text) - messages, "escape messages after a second sweep");
T.Check(!o.Spawned, "a sweep brought the escapee back");
}
[BlaxTest("jail end: a jailed colonist that leaves the map and is discarded by the world before the next sentence sweep still closes as escaped with one message, not as offender gone")]
public static void EscapeDiscardedEndsSentence()
{
LawCase c = JailInCell(out Pawn o, out _);
Map map = o.Map;
string text = "BlaxLaws_MsgEscaped".Translate(c.OffenderLabel).Resolve();
int messages = EnforceFixtures.MessagesWith(text);
o.ExitMap(true, CellRect.WholeMap(map).GetClosestEdge(o.Position));
T.Check(!o.Spawned && !o.Dead && o.IsWorldPawn(), "fixture: " + o.LabelShort + " didn't leave the map for the world");
// What WorldPawnGC does to a world pawn nothing keeps, at its next 15000-tick pass
// (RimWorld.Planet/WorldPawnGC.cs:20, 28-30), possibly before the 2500-tick sentence sweep.
Find.WorldPawns.RemoveAndDiscardPawnViaGC(o);
T.Check(c.escapedTick >= 0, "the escape hook didn't note the escape");
T.Check(o.Discarded, "fixture: the escapee wasn't discarded");
EnforceFixtures.TickPastSentenceSweep();
T.Check(c.IsClosed, "the case of the discarded escapee isn't closed: " + c);
T.Equal(EnforcementOutcomes.Escaped, c.outcome, "the outcome after the escapee was discarded");
T.Equal(1, EnforceFixtures.MessagesWith(text) - messages, "escape messages");
}
[BlaxTest("jail end: a jailed colonist that escapes and dies off the map before the next sentence sweep closes as escaped with one escape message and no died-in-jail message")]
public static void EscapeeDiesOffMap()
{
EscapeeDiesOffMap(discard: false);
}
[BlaxTest("jail end: a jailed colonist that escapes, dies off the map and is discarded by the world before the next sentence sweep closes as escaped with one escape message, not as offender gone or died in jail")]
public static void EscapeeDiesOffMapDiscarded()
{
EscapeeDiesOffMap(discard: true);
}
/// <summary>
/// An escapee stays a prisoner of the colony off the map (Pawn.ExitMap clears the guest status only for a
/// released prisoner, Verse/Pawn.cs:2556-2589), and world pawns keep ticking (RimWorld.Planet/WorldPawns.cs:73-101),
/// so a bleeding escapee can die there before the sweep. A world pawn dies with no corpse
/// (Verse/Pawn.cs:2221-2224) and stays a world pawn among the dead.
/// </summary>
private static void EscapeeDiesOffMap(bool discard)
{
LawCase c = JailInCell(out Pawn o, out _);
NoWorldPawnGcBeforeNextSweep();
string escaped = "BlaxLaws_MsgEscaped".Translate(c.OffenderLabel).Resolve();
string died = "BlaxLaws_MsgDiedInJail".Translate(c.OffenderLabel).Resolve();
int escapedBefore = EnforceFixtures.MessagesWith(escaped);
int diedBefore = EnforceFixtures.MessagesWith(died);
o.ExitMap(true, CellRect.WholeMap(o.Map).GetClosestEdge(o.Position));
T.Check(!o.Spawned && o.IsWorldPawn() && c.escapedTick >= 0, "fixture: the escape isn't noted off the map: spawned " + o.Spawned +
", world pawn " + o.IsWorldPawn() + ", note " + c.escapedTick);
o.Kill(null);
T.Check(o.Dead && o.Corpse == null && o.IsWorldPawn(), "fixture: " + o.LabelShort + " isn't a dead world pawn without a corpse: dead " + o.Dead +
", corpse " + o.Corpse + ", world pawn " + o.IsWorldPawn());
if (discard)
{
Find.WorldPawns.RemoveAndDiscardPawnViaGC(o);
T.Check(o.Discarded, "fixture: the dead escapee wasn't discarded");
}
EnforceFixtures.TickPastSentenceSweep();
T.Check(c.IsClosed, "the case of the escapee that died off the map isn't closed: " + c);
T.Equal(EnforcementOutcomes.Escaped, c.outcome, "the outcome of an escapee that died off the map, discarded " + discard);
T.Equal(1, EnforceFixtures.MessagesWith(escaped) - escapedBefore, "escape messages");
T.Equal(0, EnforceFixtures.MessagesWith(died) - diedBefore, "died-in-jail messages");
}
[BlaxTest("jail end: a jailed colonist destroyed in its cell alive (another mod, a dev tool), not escaped, closes as offender gone at the next sentence sweep with no escape message, also when the world discards it before that sweep")]
public static void DestroyedInCellIsGone()
{
LawCase c = JailInCell(out Pawn o, out _);
string text = "BlaxLaws_MsgEscaped".Translate(c.OffenderLabel).Resolve();
int messages = EnforceFixtures.MessagesWith(text);
T.Check(c.releaseTick > Now + Enforcement.SentenceInterval, "fixture: the sentence would be served by the next sweep; release tick " + c.releaseTick + ", now " + Now);
o.Destroy(DestroyMode.Vanish);
T.Check(o.Destroyed && !o.Dead && !o.Discarded, "fixture: " + o.LabelShort + " isn't destroyed alive and undiscarded: destroyed " + o.Destroyed + ", dead " + o.Dead + ", discarded " + o.Discarded);
// Pawn.Destroy passes it to the world (Verse/Pawn.cs:2392-2395), and nothing keeps it there, so the next
// WorldPawnGC pass discards it (RimWorld.Planet/WorldPawnGC.cs:153-177), possibly before the 2500-tick
// sentence sweep: discarded alive, as an escapee the GC took is. Done here so every run covers it.
Find.WorldPawns.RemoveAndDiscardPawnViaGC(o);
T.Check(o.Discarded && !o.Dead, "fixture: the destroyed prisoner wasn't discarded alive");
EnforceFixtures.TickPastSentenceSweep();
T.Check(c.IsClosed, "the case of the destroyed prisoner isn't closed: " + c);
T.Equal(CaseOutcomes.OffenderGone, c.outcome, "the outcome after the prisoner was destroyed in its cell");
T.Equal(0, EnforceFixtures.MessagesWith(text) - messages, "escape messages");
}
[BlaxTest("jail end: a jailed colonist that dies closes as died in jail at the next sentence sweep, not as offender gone, with one message and nothing left queued")]
public static void DeathEndsSentence()
{
LawCase c = JailInCell(out Pawn o, out _);
string text = "BlaxLaws_MsgDiedInJail".Translate(c.OffenderLabel).Resolve();
int messages = EnforceFixtures.MessagesWith(text);
Fixtures.CheckAlive(o, "the kill");
o.Kill(null);
T.Check(o.Dead && o.Corpse != null && o.Corpse.Spawned, "fixture: " + o.LabelShort + " isn't a dead pawn with a corpse on the map");
// The 250-tick sweep leaves a jailed case to the sentence sweep (Enforcement.Sweep).
Fixtures.Tick(Enforcement.SweepInterval + 1);
if (!c.IsClosed)
EnforceFixtures.TickPastSentenceSweep();
CheckClosedClean(c, o, EnforcementOutcomes.Died, "after the death");
T.Equal(1, EnforceFixtures.MessagesWith(text) - messages, "died-in-jail messages");
int closedAt = c.closeTick;
EnforceFixtures.TickPastSentenceSweep();
T.Check(c.IsClosed && c.outcome == EnforcementOutcomes.Died && c.closeTick == closedAt, "a second sweep changed the closed case: " + c);
T.Equal(1, EnforceFixtures.MessagesWith(text) - messages, "died-in-jail messages after a second sweep");
}
[BlaxTest("jail end: a jailed colonist that escapes after its release tick, while Release waits for a colonist, closes as escaped with one message, not as served")]
public static void EscapeAfterReleaseTick()
{
LawCase c = JailInCell(out Pawn o, out _);
string escaped = "BlaxLaws_MsgEscaped".Translate(c.OffenderLabel).Resolve();
string served = "BlaxLaws_MsgBackAtWork".Translate(c.OffenderLabel).Resolve();
int escapedBefore = EnforceFixtures.MessagesWith(escaped);
int servedBefore = EnforceFixtures.MessagesWith(served);
// Served, the fallback a day off: the sweep sets Release and nobody has released it yet.
c.releaseTick = Now - 10;
Sentences.Check(c);
T.Check(o.IsPrisonerOfColony && o.Spawned && !c.IsClosed, "fixture: the served prisoner isn't a jailed prisoner on the map; case " + c);
T.Equal(PrisonerInteractionModeDefOf.Release, o.guest.ExclusiveInteractionMode, "fixture: the mode once the sentence is served");
T.Check(!o.guest.Released, "fixture: the prisoner is released already");
o.ExitMap(true, CellRect.WholeMap(o.Map).GetClosestEdge(o.Position));
T.Check(!o.Spawned && !o.Dead, "fixture: " + o.LabelShort + " didn't leave the map");
T.Check(c.escapedTick >= 0, "the escape hook didn't note the escape on Release");
Sentences.Check(c);
T.Check(c.IsClosed, "the case of the escapee isn't closed: " + c);
T.Equal(EnforcementOutcomes.Escaped, c.outcome, "the outcome of an escape after the release tick");
T.Equal(1, EnforceFixtures.MessagesWith(escaped) - escapedBefore, "escape messages");
T.Equal(0, EnforceFixtures.MessagesWith(served) - servedBefore, "served messages");
}
[BlaxTest("jail end: a jailed colonist released early that is off on a caravan at the next sentence sweep closes as released early, not as escaped")]
public static void ReleasedEarlyThenCaravan()
{
LawCase c = JailInCell(out Pawn o, out _);
string early = "BlaxLaws_MsgReleasedEarly".Translate(c.OffenderLabel).Resolve();
string escaped = "BlaxLaws_MsgEscaped".Translate(c.OffenderLabel).Resolve();
int earlyBefore = EnforceFixtures.MessagesWith(early);
int escapedBefore = EnforceFixtures.MessagesWith(escaped);
GenGuest.PrisonerRelease(o);
T.Check(o.IsFreeColonist, "fixture: " + o.LabelShort + " isn't free after PrisonerRelease");
Caravan caravan = IntoCaravan(o);
T.Check(o.IsCaravanMember() && !o.Spawned, "fixture: " + o.LabelShort + " isn't in the caravan");
Sentences.Check(c);
T.Check(c.IsClosed, "the case isn't closed: " + c);
T.Equal(CaseOutcomes.ReleasedEarly, c.outcome, "the outcome of a colonist released early and off on a caravan");
T.Equal(1, EnforceFixtures.MessagesWith(early) - earlyBefore, "released-early messages");
T.Equal(0, EnforceFixtures.MessagesWith(escaped) - escapedBefore, "escape messages");
T.Check(caravan.ContainsPawn(o), "the colonist left the caravan");
}
[BlaxTest("jail end: a jailed colonist taken along in a caravan is released there a day after its release tick: the case closes as served and the colonist is a free caravan member")]
public static void CaravanFallbackReleases()
{
LawCase c = JailInCell(out Pawn o, out _);
Caravan caravan = IntoCaravan(o);
T.Check(o.IsPrisonerOfColony && o.IsCaravanMember() && !o.Spawned, "fixture: " + o.LabelShort + " isn't a prisoner in the caravan");
Sentences.Check(c);
T.Equal(CaseStatus.Jailed, c.status, "the case's status in the caravan before the release tick");
c.releaseTick = Now - Sentences.FallbackTicks - 1;
Sentences.Check(c);
T.Check(c.IsClosed, "the case of the prisoner in the caravan isn't closed a day past its release tick: " + c + ", prisoner " + o.IsPrisonerOfColony);
T.Equal(CaseOutcomes.Served, c.outcome, "the outcome in the caravan");
T.Check(!o.IsPrisonerOfColony && o.IsFreeColonist, o.LabelShort + " isn't a free colonist after the release in the caravan");
T.Check(caravan.ContainsPawn(o) && o.IsCaravanMember(), o.LabelShort + " is no member of the caravan after the release");
}
[BlaxTest("jail end: a jailed colonist sold to an orbital trader closes as offender gone with a left-custody message and no escape message")]
public static void SoldToOrbitalTraderIsGone()
{
LawCase c = JailInCell(out Pawn o, out Pawn warden);
TraderKindDef kind = DefDatabase<TraderKindDef>.AllDefsListForReading.FirstOrDefault(d => d.orbital);
T.NotNull(kind, "an orbital trader kind");
var ship = new TradeShip(kind);
string escaped = "BlaxLaws_MsgEscaped".Translate(c.OffenderLabel).Resolve();
string left = "BlaxLaws_MsgLeftCustody".Translate(c.OffenderLabel).Resolve();
int escapedBefore = EnforceFixtures.MessagesWith(escaped);
int leftBefore = EnforceFixtures.MessagesWith(left);
Fixtures.OnCleanup(() => DropTales(o));
// What the trade dialog does with a sold prisoner (TradeShip.cs:181-196): no ExitMap, no escape.
ship.GiveSoldThingToTrader(o, 1, warden);
T.Check(!o.Spawned && !o.IsPrisonerOfColony && o.Faction == null && o.ParentHolder == ship,
"fixture: the sold colonist isn't held by the ship without a faction: spawned " + o.Spawned + ", prisoner " + o.IsPrisonerOfColony +
", faction " + o.Faction + ", held by " + o.ParentHolder);
T.Equal(-1, c.escapedTick, "the escape note after the sale");
Sentences.Check(c);
T.Check(c.IsClosed, "the case of the sold colonist isn't closed: " + c);
T.Equal(CaseOutcomes.OffenderGone, c.outcome, "the outcome after the sale");
T.Equal(0, EnforceFixtures.MessagesWith(escaped) - escapedBefore, "escape messages");
T.Equal(1, EnforceFixtures.MessagesWith(left) - leftBefore, "left-custody messages");
}
[BlaxTest("jail end: a jailed colonist kidnapped by another faction closes as offender gone with a left-custody message and no escape message")]
public static void KidnappedIsGone()
{
LawCase c = JailInCell(out Pawn o, out _);
Faction f = Fixtures.HostileFaction() ?? Fixtures.FriendlyFaction();
if (f == null)
T.Skip("this world has no other humanlike faction");
string escaped = "BlaxLaws_MsgEscaped".Translate(c.OffenderLabel).Resolve();
string left = "BlaxLaws_MsgLeftCustody".Translate(c.OffenderLabel).Resolve();
int escapedBefore = EnforceFixtures.MessagesWith(escaped);
int leftBefore = EnforceFixtures.MessagesWith(left);
Fixtures.OnCleanup(() =>
{
if (f.kidnapped.KidnappedPawnsListForReading.Contains(o))
f.kidnapped.RemoveKidnappedPawn(o);
});
// A raider carrying a downed colonist off the map ends here (Pawn.cs:2531-2535); the victim never calls ExitMap.
f.kidnapped.Kidnap(o, null);
T.Check(!o.Spawned && !o.IsPrisonerOfColony && f.kidnapped.KidnappedPawnsListForReading.Contains(o),
"fixture: " + o.LabelShort + " isn't kidnapped: spawned " + o.Spawned + ", prisoner " + o.IsPrisonerOfColony);
T.Equal(-1, c.escapedTick, "the escape note after the kidnap");
Sentences.Check(c);
T.Check(c.IsClosed, "the case of the kidnapped colonist isn't closed: " + c);
T.Equal(CaseOutcomes.OffenderGone, c.outcome, "the outcome after the kidnap");
T.Equal(0, EnforceFixtures.MessagesWith(escaped) - escapedBefore, "escape messages");
T.Equal(1, EnforceFixtures.MessagesWith(left) - leftBefore, "left-custody messages");
}
[BlaxTest("jail end: a jailed colonist given away by transport pod to another faction's settlement stays jailed in the pod, then closes as offender gone with a left-custody message and no escape or released-early message")]
public static void GivenAwayByPodIsGone()
{
LawCase c = JailInCell(out Pawn o, out _);
Settlement s = Find.WorldObjects.Settlements.FirstOrDefault(x => x.Faction != null && !x.Faction.IsPlayer && x.Faction.def.humanlikeFaction);
if (s == null)
T.Skip("this world has no other faction's settlement");
Faction f = s.Faction;
// The gift raises goodwill (FactionGiftUtility.cs:63, HistoryEventDefOf.GaveGift, which Laws records no
// act for: CatalogueRules). Put the relation back after the test.
FactionRelation theirs = f.RelationWith(Faction.OfPlayer);
FactionRelation ours = Faction.OfPlayer.RelationWith(f);
int goodwill = theirs.baseGoodwill;
FactionRelationKind kind = theirs.kind;
Fixtures.OnCleanup(() =>
{
theirs.baseGoodwill = ours.baseGoodwill = goodwill;
theirs.kind = ours.kind = kind;
});
Fixtures.OnCleanup(() => DropTales(o));
string escaped = "BlaxLaws_MsgEscaped".Translate(c.OffenderLabel).Resolve();
string left = "BlaxLaws_MsgLeftCustody".Translate(c.OffenderLabel).Resolve();
string early = "BlaxLaws_MsgReleasedEarly".Translate(c.OffenderLabel).Resolve();
int escapedBefore = EnforceFixtures.MessagesWith(escaped);
int leftBefore = EnforceFixtures.MessagesWith(left);
int earlyBefore = EnforceFixtures.MessagesWith(early);
// Loaded into a pod: still the colony's prisoner, in flight.
o.DeSpawnOrDeselect();
var pod = new ActiveTransporterInfo();
T.Check(pod.innerContainer.TryAdd(o), "fixture: the prisoner didn't go into the pod");
T.Check(o.IsPrisonerOfColony && !o.Spawned, "fixture: " + o.LabelShort + " isn't a prisoner in the pod");
Sentences.Check(c);
T.Check(!c.IsClosed && c.status == CaseStatus.Jailed, "the case of the prisoner in the pod in flight: " + c);
// What the pod's arrival as a gift does (RimWorld.Planet/FactionGiftUtility.cs:46-76): SplitOff,
// SetFaction (which ends the guest status, Verse/Pawn.cs:2702-2710), then DestroyOrPassToWorld.
FactionGiftUtility.GiveGift(new List<ActiveTransporterInfo> { pod }, s);
T.Check(o.Faction == f && !o.IsPrisonerOfColony && o.IsWorldPawn() && !o.Spawned,
"fixture: the gift isn't a world pawn of " + f + ": faction " + o.Faction + ", prisoner " + o.IsPrisonerOfColony + ", world pawn " + o.IsWorldPawn() + ", spawned " + o.Spawned);
T.Equal(-1, c.escapedTick, "the escape note after the gift");
Sentences.Check(c);
T.Check(c.IsClosed, "the case of the colonist given away isn't closed: " + c);
T.Equal(CaseOutcomes.OffenderGone, c.outcome, "the outcome after the gift");
T.Equal(1, EnforceFixtures.MessagesWith(left) - leftBefore, "left-custody messages");
T.Equal(0, EnforceFixtures.MessagesWith(escaped) - escapedBefore, "escape messages");
T.Equal(0, EnforceFixtures.MessagesWith(early) - earlyBefore, "released-early messages");
}
[BlaxTest("jail end: a jailed colonist lost with an abandoned or closed map closes as offender gone with a left-custody message and no escape or released-early message")]
public static void LostWithMapIsGone()
{
LawCase c = JailInCell(out Pawn o, out _);
// Vanilla's own per-pawn step of a map's deinit (Verse/MapDeiniter.cs:218-237, reached from
// Game.DeinitAndRemoveMap through PassPawnsToWorld, :142), run on the one prisoner: no second map needed.
MethodInfo cleanUp = typeof(MapDeiniter).GetMethod("CleanUpAndPassToWorld", BindingFlags.NonPublic | BindingFlags.Static);
T.NotNull(cleanUp, "fixture: MapDeiniter.CleanUpAndPassToWorld");
Fixtures.OnCleanup(() => DropTales(o));
string escaped = "BlaxLaws_MsgEscaped".Translate(c.OffenderLabel).Resolve();
string left = "BlaxLaws_MsgLeftCustody".Translate(c.OffenderLabel).Resolve();
string early = "BlaxLaws_MsgReleasedEarly".Translate(c.OffenderLabel).Resolve();
int escapedBefore = EnforceFixtures.MessagesWith(escaped);
int leftBefore = EnforceFixtures.MessagesWith(left);
int earlyBefore = EnforceFixtures.MessagesWith(early);
o.DeSpawnOrDeselect();
cleanUp.Invoke(null, new object[] { o });
T.Check(o.IsWorldPawn() && !o.IsPrisonerOfColony && !o.Spawned, "fixture: the prisoner isn't a free world pawn after the deinit: world pawn " + o.IsWorldPawn() +
", prisoner " + o.IsPrisonerOfColony + ", spawned " + o.Spawned);
T.Equal(-1, c.escapedTick, "the escape note after the map loss");
// Pawn.Notify_PassedToWorld (Verse/Pawn.cs:1859-1888) gives a free colonist a random other faction, or none.
T.Info("the faction after the map loss: " + (o.Faction?.Name ?? "none"));
Sentences.Check(c);
T.Check(c.IsClosed, "the case of the colonist lost with the map isn't closed: " + c);
T.Equal(CaseOutcomes.OffenderGone, c.outcome, "the outcome after the map loss");
T.Equal(1, EnforceFixtures.MessagesWith(left) - leftBefore, "left-custody messages");
T.Equal(0, EnforceFixtures.MessagesWith(escaped) - escapedBefore, "escape messages");
T.Equal(0, EnforceFixtures.MessagesWith(early) - earlyBefore, "released-early messages");
}
private const string InPlaySaveName = "BlaxLawsTestEscapeSave";
[BlaxTest("jail end: an escapee discarded by the world and then saved before the next sentence sweep (the save drops the reference) still closes as escaped with one message")]
public static void EscapeDiscardedThenSavedInPlay()
{
LawCase c = JailInCell(out Pawn o, out _);
string text = "BlaxLaws_MsgEscaped".Translate(c.OffenderLabel).Resolve();
int messages = EnforceFixtures.MessagesWith(text);
o.ExitMap(true, CellRect.WholeMap(o.Map).GetClosestEdge(o.Position));
Find.WorldPawns.RemoveAndDiscardPawnViaGC(o);
T.Check(o.Discarded && c.escapedTick >= 0, "fixture: the escapee isn't discarded with the escape noted: discarded " + o.Discarded + ", note " + c.escapedTick);
string path = GenFilePaths.FilePathForSavedGame(InPlaySaveName);
try
{
// The same synchronous full save the autosave makes.
GameDataSaveLoader.SaveGame(InPlaySaveName);
}
finally
{
try
{
if (System.IO.File.Exists(path))
System.IO.File.Delete(path);
}
catch (System.IO.IOException)
{
}
}
T.Check(c.offender == null, "fixture: the save kept the reference to the discarded escapee");
T.Equal(CaseStatus.Jailed, c.status, "fixture: the case's status after the save");
Sentences.Check(c);
T.Check(c.IsClosed, "the case isn't closed: " + c);
T.Equal(EnforcementOutcomes.Escaped, c.outcome, "the outcome after the save dropped the discarded escapee");
T.Equal(1, EnforceFixtures.MessagesWith(text) - messages, "escape messages");
}
private const string EscapeSaveKey = "jail.escapeDiscardedSave";
[BlaxTest("jail end save: a jailed colonist escapes and is discarded right before the first save (setup)")]
public static void EscapeSaveSetup()
{
// Built right before the save, after every phase-1 test, so no sweep sees the case before the save.
T.CarryAtSave(EscapeSaveKey, EscapeForSave);
}
private static string EscapeForSave()
{
Pawn o = Fixtures.Keep(EnforceFixtures.Offender());
Pawn by = EnforceFixtures.Map.mapPawns.FreeColonistsSpawned.First(p => p != o);
LawCase c = EnforceFixtures.JailDirect(o, by, 3);
Fixtures.KeepLaw(c.LawFor(LawStage.DidIt));
o.ExitMap(true, CellRect.WholeMap(o.Map).GetClosestEdge(o.Position));
Find.WorldPawns.RemoveAndDiscardPawnViaGC(o);
return c.id + "|" + c.escapedTick + "|" + o.Discarded + "|" + c.OffenderLabel;
}
[BlaxTest("jail end save: after the reload the case of the discarded escapee has no offender reference and still closes as escaped with one message", phase: 2, Order = -1)]
public static void EscapeSaveRoundTrip()
{
T.Check(T.Carry.TryGetValue(EscapeSaveKey, out string carry) && !carry.NullOrEmpty(), "the phase-1 escape setup did not run");
string[] parts = carry.Split('|');
T.Check(parts.Length == 4 && int.Parse(parts[1]) >= 0 && parts[2] == "True", "fixture: the escape wasn't noted and discarded at the save: " + carry);
LawCase c = Fixtures.Comp.CaseById(int.Parse(parts[0]));
T.NotNull(c, "the escape case after the reload");
Fixtures.Settings.caseMessages = true;
if (!c.IsClosed)
{
T.Check(c.offender == null, "the save kept a reference to the discarded escapee");
T.Check(c.escapedTick >= 0, "the escape note didn't survive the reload");
string text = "BlaxLaws_MsgEscaped".Translate(parts[3]).Resolve();
int messages = EnforceFixtures.MessagesWith(text);
Sentences.Check(c);
T.Equal(1, EnforceFixtures.MessagesWith(text) - messages, "escape messages");
}
T.Check(c.IsClosed, "the case isn't closed: " + c);
T.Equal(EnforcementOutcomes.Escaped, c.outcome, "the outcome after the reload");
}
// ---- helpers ------------------------------------------------------------------------
/// <summary>
/// Takes the pawn off the map into a new player caravan on the map's tile with a fixture colonist, as a
/// formed caravan holds a prisoner (Pawn.cs:2520-2524 keeps its guest status). The caravan is removed after
/// the test and the runner discards its pawns.
/// </summary>
private static Caravan IntoCaravan(Pawn p)
{
Map map = p.Map;
Pawn escort = Fixtures.Colonist();
escort.DeSpawnOrDeselect();
p.DeSpawnOrDeselect();
Caravan caravan = CaravanMaker.MakeCaravan(new List<Pawn> { escort, p }, Faction.OfPlayer, map.Tile, true);
Fixtures.OnCleanup(() =>
{
caravan.RemoveAllPawns();
if (!caravan.Destroyed)
caravan.Destroy();
});
return caravan;
}
/// <summary>Drops the tales about a fixture pawn (a sale records one), so no tale names it once it is discarded.</summary>
private static void DropTales(Pawn p)
{
Find.TaleManager.AllTalesListForReading.RemoveAll(t => t.Concerns(p));
}
/// <summary>
/// A colonist jailed by Laws for 3 days in a prison cell (a closed door keeps it from escaping on its own),
/// past the "Maintain only" write. Case messages on. Each death of a fixture pawn is logged with its stack
/// during the test (Fixtures.LogKills, vanilla's logCauseOfDeath on), and a pawn that died during the setup
/// fails as a named fixture error, not as a double-kill error of the test.
/// </summary>
private static LawCase JailInCell(out Pawn offender, out Pawn warden)
{
Fixtures.Settings.caseMessages = true;
Fixtures.LogKillsDuringTest();
PrisonRoom room = EnforceFixtures.PrisonCell();
offender = EnforceFixtures.Offender(room.inside);
warden = EnforceFixtures.Warden();
LawCase c = EnforceFixtures.JailDirect(offender, warden, 3);
Fixtures.Tick(Enforcement.MaintainOnlyDelay + 1);
T.Check(c.maintainOnlyDone, "fixture: Maintain only wasn't written; case " + c);
T.Equal(CaseStatus.Jailed, c.status, "fixture: the case's status after the capture");
T.Check(offender.IsPrisonerOfColony, "fixture: " + offender.LabelShort + " isn't a prisoner after the capture");
Fixtures.CheckAlive(offender, "the jail setup");
return c;
}
/// <summary>
/// Starts a vanilla prison break from the offender (RimWorld/PrisonBreakUtility.cs:214), without its letter.
/// A pawn a gene keeps from breaking out (:149-193), or a break that finds no exit (:336), only notes it:
/// the escape off the map is what the test checks. The break's lord is removed after the test if the
/// game hasn't.
/// </summary>
private static void StartPrisonBreak(Pawn o, Map map)
{
if (!PrisonBreakUtility.CanParticipateInPrisonBreak(o))
{
T.Info(o.LabelShort + " can't take part in a prison break; the escape leaves the map without one");
return;
}
PrisonBreakUtility.StartPrisonBreak(o, out _, out _, out _, out List<Pawn> escaping);
Lord lord = o.GetLord();
if (lord != null)
{
Fixtures.OnCleanup(() =>
{
if (map.lordManager.lords.Contains(lord))
map.lordManager.RemoveLord(lord);
});
}
if (escaping == null || !escaping.Contains(o) || !PrisonBreakUtility.IsPrisonBreaking(o))
T.Info("the prison break didn't start for " + o.LabelShort + "; the escape leaves the map without one");
}
/// <summary>
/// Moves the clock so no world pawn GC pass (every 15000 ticks, run over several ticks: RimWorld.Planet/
/// WorldPawnGC.cs:28-31, 47-58) can run between now and the next sentence sweep: any pass due is let finish,
/// and a 15000 boundary closer than a sentence interval is ticked past first. A pawn that leaves the map now
/// then reaches that sweep undiscarded, on the off-map branch, every run.
/// </summary>
private static void NoWorldPawnGcBeforeNextSweep()
{
const int gcInterval = 15000;
FieldInfo last = typeof(WorldPawnGC).GetField("lastSuccessfulGCTick", BindingFlags.NonPublic | BindingFlags.Instance);
T.NotNull(last, "fixture: WorldPawnGC.lastSuccessfulGCTick");
WorldPawnGC gc = Find.WorldPawns.gc;
bool Done() => (int)last.GetValue(gc) >= Now / gcInterval * gcInterval;
if (Now % gcInterval >= gcInterval - Enforcement.SentenceInterval)
Fixtures.Tick(gcInterval - Now % gcInterval + 1);
T.Check(EnforceFixtures.RunUntil(Done, 5000), "fixture: the world pawn GC pass due at " + Now / gcInterval * gcInterval + " didn't finish within 5000 ticks");
T.Check(Now % gcInterval < gcInterval - Enforcement.SentenceInterval, "fixture: a GC boundary is within a sentence interval of now " + Now);
}
/// <summary>The case closed with the outcome and nothing of it left running or queued.</summary>
private static void CheckClosedClean(LawCase c, Pawn o, string outcome, string when)
{
T.Check(c.IsClosed, "the case isn't closed " + when + ": " + c + ", release tick " + c.releaseTick + ", now " + Now +
", prisoner of the colony " + o.IsPrisonerOfColony + ", spawned " + o.Spawned + ", dead " + o.Dead);
T.Equal(outcome, c.outcome, "the outcome " + when);
T.Check(c.closeTick >= 0 && c.closeTick <= Now, "the close tick " + when + ": " + c.closeTick + ", now " + Now);
T.Check(c.activePunishment == null, "a punishment still runs " + when + ": " + c.activePunishment);
T.Check(c.waitReason == null, "the case still waits " + when + ": " + c.waitReason);
T.Equal(-1, Sentences.TicksLeft(c), "the sentence countdown " + when);
T.Check(!Enforcement.IsQueued(c, CaseTask.MaintainOnly) && !Enforcement.IsQueued(c, CaseTask.Punish), "a task is still queued for the case " + when);
T.Check(Fixtures.Comp.CasesOf(o).All(x => x.IsClosed), "an open case for " + o.LabelShort + " " + when + ": " +
string.Join(", ", Fixtures.Comp.CasesOf(o).Where(x => !x.IsClosed).Select(x => x.ToString())));
}
}
}