using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using BlaxCastes;
using HarmonyLib;
using RimWorld;
using RimWorld.Planet;
using Verse;
namespace BlaxCastesTests
{
///
/// Status changes between player colonist, slave and prisoner go through the status rows, and a
/// pawn that comes back gets its previous caste. Arrests and imprisonments go through
/// Pawn_GuestTracker.CapturedBy, as the arrest job does. Joins are applied with Fixtures.ApplyJoins,
/// because fixture prisoners must not be ticked.
///
public static class StatusTests
{
private static ApparelPolicy Worker() => Fixtures.Need(Fixtures.Outfit("OutfitWorker"), "Worker outfit");
private static ApparelPolicy Nudist() => Fixtures.Need(Fixtures.Outfit("OutfitNudist"), "Nudist outfit");
private static FoodPolicy Simple() => Fixtures.Need(Fixtures.Food("FoodRestrictionSimple"), "Simple food policy");
private static FoodPolicy Fine() => Fixtures.Need(Fixtures.Food("FoodRestrictionFine"), "Fine food policy");
private static FoodPolicy Paste() => Fixtures.Need(Fixtures.Food("FoodRestrictionPaste"), "Paste food policy");
private static FoodPolicy Lavish() => Fixtures.Need(Fixtures.Food("FoodRestrictionLavish"), "Lavish food policy");
private static Caste Make(string label, ApparelPolicy apparel, FoodPolicy food)
{
Caste c = Fixtures.NewCaste(label);
if (apparel != null)
CasteManager.SetSlot(c, CasteSlot.Apparel, apparel);
CasteManager.SetSlot(c, CasteSlot.Food, food);
return c;
}
private static void Row(string reason, Caste caste) =>
T.Check(CasteManager.SetJoinRow(reason, JoinRowMode.SpecificCaste, caste), "setup: SetJoinRow " + reason + " failed");
private static void NoCasteRow(string reason) =>
T.Check(CasteManager.SetJoinRow(reason, JoinRowMode.NoCaste), "setup: SetJoinRow " + reason + " failed");
private static string Who(Pawn p) => p.LabelShort + " [" + p.ThingID + "]";
private static string State(Pawn p)
{
CasteMembership m = Fixtures.Comp.MembershipOf(p);
return m == null ? "no record" : $"caste={m.caste?.label ?? "none"}, auto={m.auto}, reason={m.reason}";
}
private static void CheckIn(Pawn p, Caste caste, string reason, string when)
{
CasteMembership m = Fixtures.Comp.MembershipOf(p);
T.Check(m != null && m.caste == caste, Who(p) + " " + when + ": expected " + caste.label + ", got " + State(p));
if (reason != null)
T.Equal(reason, m.reason, Who(p) + "'s membership reason " + when);
}
private static Pawn Warden() => Fixtures.Colonist();
/// A spawned slave whose own faction is the colony, so freeing it keeps it as a colonist.
private static Pawn HomeSlave()
{
if (!ModsConfig.IdeologyActive)
T.Skip("needs Ideology (slaves)");
Pawn p = Fixtures.Spawn(Fixtures.Generate(PawnKindDefOf.Slave, Faction.OfPlayer));
p.guest.SetGuestStatus(Faction.OfPlayer, GuestStatus.Slave);
T.Check(p.IsSlaveOfColony && p.HomeFaction == Faction.OfPlayer, "setup: home slave fixture: slave=" + p.IsSlaveOfColony + ", home=" + p.HomeFaction);
Fixtures.Unqueue(p);
return p;
}
// ---- every transition goes through the status rows ---------------------------------------
[BlaxTest("status: an arrested Miner colonist goes to the new-prisoner caste, and once released returns to Miner")]
public static void ArrestAndRelease()
{
Caste miner = Make("Miner (status test)", Worker(), Fine());
Caste prisoners = Make("Prisoners (status test)", null, Paste());
Caste wrong = Make("Wrong row (status test)", Nudist(), Lavish());
Row(JoinReason.NewPrisoner, prisoners);
Row(JoinReason.NewColonist, wrong);
Pawn p = Fixtures.Colonist();
Fixtures.Unqueue(p);
T.Check(CasteManager.Assign(p, miner, false, JoinReason.Manual), "setup: Assign Miner failed");
p.guest.CapturedBy(Faction.OfPlayer, Warden());
T.Check(p.IsPrisonerOfColony && p.Faction == Faction.OfPlayer, Who(p) + " is not an arrested colonist after CapturedBy");
FormerCaste record = Fixtures.Comp.FormerOf(p);
T.NotNull(record, Who(p) + "'s former-caste record after the arrest");
T.Check(record.casteId == miner.id && record.side == JoinSide.Colonist && !record.auto, "former-caste record: " + record);
T.Equal(JoinDefaults.StatusFallback, JoinDefaults.QueuedFor(p)?.reason, "queued reason after the arrest");
Fixtures.ApplyJoins(p);
CheckIn(p, prisoners, JoinReason.NewPrisoner, "after the arrest");
T.Check(p.foodRestriction.CurrentFoodPolicy == Paste(), Who(p) + " does not eat the prisoner food");
GenGuest.PrisonerRelease(p);
T.Check(p.IsColonist && !p.IsPrisoner, Who(p) + " is not a free colonist after the release");
T.Check(JoinDefaults.IsQueued(p), Who(p) + " was not queued by the release");
Fixtures.ApplyJoins(p);
CheckIn(p, miner, JoinReason.PreviousCaste, "after the release");
T.Check(!Fixtures.Comp.MembershipOf(p).auto, "the restored hand-picked caste is marked as set by a join row");
T.Check(p.foodRestriction.CurrentFoodPolicy == Fine() && p.outfits.CurrentApparelPolicy == Worker(), Who(p) + " does not have Miner's policies back");
T.Check(Fixtures.Comp.FormerOf(p) == null, "the used former-caste record is still there");
}
[BlaxTest("status: freeing a slave whose home is the colony lands in the new-colonist row and leaves no record")]
public static void FreedSlave()
{
Caste slaves = Make("Slaves (freed test)", null, Paste());
Caste colonists = Make("Colonists (freed test)", Worker(), Fine());
Row(JoinReason.NewColonist, colonists);
Pawn p = HomeSlave();
T.Check(CasteManager.Assign(p, slaves, true, JoinReason.NewSlave), "setup: Assign failed");
GenGuest.EmancipateSlave(Warden(), p);
T.Check(p.IsColonist && !p.IsSlave, Who(p) + " is not a free colonist after EmancipateSlave");
T.Check(Fixtures.Comp.FormerOf(p) == null, "freeing a slave wrote a former-caste record");
Fixtures.ApplyJoins(p);
CheckIn(p, colonists, JoinReason.NewColonist, "after being freed");
T.Check(p.foodRestriction.CurrentFoodPolicy == Fine(), Who(p) + " still eats the slave food");
}
[BlaxTest("status: imprisoning a slave (the Imprison mode's arrest) goes to the new-prisoner row and records its slave caste")]
public static void ImprisonedSlave()
{
Caste minerSlaves = Make("Miner slaves (imprison test)", null, Simple());
Caste prisoners = Make("Prisoners (imprison test)", null, Paste());
Row(JoinReason.NewPrisoner, prisoners);
Pawn p = Fixtures.ColonySlave();
Fixtures.Unqueue(p);
T.Check(CasteManager.Assign(p, minerSlaves, true, JoinReason.NewSlave), "setup: Assign failed");
p.guest.CapturedBy(Faction.OfPlayer, Warden());
T.Check(p.IsPrisonerOfColony, Who(p) + " is not a prisoner of the colony after CapturedBy");
FormerCaste record = Fixtures.Comp.FormerOf(p);
T.Check(record != null && record.casteId == minerSlaves.id && record.side == JoinSide.Slave, "former-caste record: " + (record?.ToString() ?? "none"));
Fixtures.ApplyJoins(p);
CheckIn(p, prisoners, JoinReason.NewPrisoner, "after being imprisoned");
T.Check(p.foodRestriction.CurrentFoodPolicy == Paste(), Who(p) + " does not eat the prisoner food");
}
[BlaxTest("status: an arrested colonist who is then enslaved goes to the new-slave row, not its old colonist caste")]
public static void ArrestedThenEnslaved()
{
if (!ModsConfig.IdeologyActive)
T.Skip("needs Ideology (slaves)");
Caste miner = Make("Miner (enslave test)", Worker(), Fine());
Caste prisoners = Make("Prisoners (enslave test)", null, Paste());
Caste slaves = Make("Slaves (enslave test)", null, Simple());
Row(JoinReason.NewPrisoner, prisoners);
Row(JoinReason.NewSlave, slaves);
Pawn p = Fixtures.Colonist();
Fixtures.Unqueue(p);
CasteManager.Assign(p, miner, false, JoinReason.Manual);
Pawn warden = Warden();
p.guest.CapturedBy(Faction.OfPlayer, warden);
Fixtures.ApplyJoins(p);
CheckIn(p, prisoners, JoinReason.NewPrisoner, "after the arrest");
GenGuest.EnslavePrisoner(warden, p);
T.Check(p.IsSlaveOfColony, Who(p) + " is not a slave after EnslavePrisoner");
Fixtures.ApplyJoins(p);
CheckIn(p, slaves, JoinReason.NewSlave, "after being enslaved");
T.Check(p.foodRestriction.CurrentFoodPolicy == Simple(), Who(p) + " does not eat the slave food");
}
[BlaxTest("status: a Miner slave sold and bought back returns to Miner slave, not the bought-as-slave row")]
public static void SoldAndBoughtBack()
{
if (!ModsConfig.IdeologyActive)
T.Skip("needs Ideology (slaves)");
Caste minerSlaves = Make("Miner slaves (sale test)", Worker(), Simple());
Caste wrong = Make("Wrong row (sale test)", Nudist(), Paste());
Row(JoinReason.BoughtSlave, wrong);
Row(JoinReason.NewColonist, wrong);
Row(JoinReason.NewSlave, wrong);
Pawn p = Fixtures.ColonySlave();
Fixtures.Unqueue(p);
T.Check(CasteManager.Assign(p, minerSlaves, true, JoinReason.NewSlave), "setup: Assign failed");
p.foodRestriction.CurrentFoodPolicy = Fine(); // by hand
var trader = new JoinTests.TestTrader();
Pawn negotiator = Fixtures.Colonist();
p.PreTraded(TradeAction.PlayerSells, negotiator, trader);
T.Check(p.Faction != Faction.OfPlayer, Who(p) + " is still in the player faction after being sold");
T.Equal(0, JoinScopes.Depth, "open join scopes after the sale");
T.Check(!JoinDefaults.IsQueued(p), "the sale queued a join (the slave-to-free step inside the sale)");
FormerCaste record = Fixtures.Comp.FormerOf(p);
T.Check(record != null && record.casteId == minerSlaves.id && record.side == JoinSide.Slave, "former-caste record after the sale: " + (record?.ToString() ?? "none"));
Fixtures.ApplyJoins(p);
T.Check(Fixtures.Comp.MembershipOf(p) == null, "the sold slave kept its membership: " + State(p));
p.guest.Recruitable = true;
p.guest.joinStatus = JoinStatus.JoinAsSlave;
p.PreTraded(TradeAction.PlayerBuys, negotiator, trader);
T.Check(p.IsSlaveOfColony, Who(p) + " is not a slave of the colony after the purchase");
T.Equal(JoinScopes.Bought, JoinDefaults.QueuedFor(p)?.reason, "queued reason after buying back");
T.Check(JoinDefaults.WillChange(p), "the bought-back slave does not show as pending");
Fixtures.ApplyJoins(p);
CheckIn(p, minerSlaves, JoinReason.PreviousCaste, "after buying it back");
T.Check(Fixtures.Comp.MembershipOf(p).auto, "the restored row-set caste is marked as set by hand");
T.Check(p.outfits.CurrentApparelPolicy == Worker(), Who(p) + " does not have Miner slave's outfit back: " + p.outfits.CurrentApparelPolicy.label);
T.Check(p.foodRestriction.CurrentFoodPolicy == Fine(), Who(p) + " lost its hand-set food: " + p.foodRestriction.CurrentFoodPolicy.label);
}
[BlaxTest("status: a former-caste record older than formerCasteDays is ignored and pruned; with the setting off the row applies")]
public static void StaleRecordIgnored()
{
Caste miner = Make("Miner (stale test)", Worker(), Fine());
Caste prisoners = Make("Prisoners (stale test)", null, Paste());
Caste colonists = Make("Colonists (stale test)", Nudist(), Simple());
Row(JoinReason.NewPrisoner, prisoners);
Row(JoinReason.NewColonist, colonists);
GameComponent_BlaxCastes comp = Fixtures.Comp;
Pawn p = Fixtures.Colonist();
Fixtures.Unqueue(p);
CasteManager.Assign(p, miner, false, JoinReason.Manual);
p.guest.CapturedBy(Faction.OfPlayer, Warden());
Fixtures.ApplyJoins(p);
FormerCaste record = comp.FormerOf(p);
T.NotNull(record, "setup: former-caste record after the arrest");
record.tick = Find.TickManager.TicksGame - (Fixtures.Settings.formerCasteDays + 1) * GenDate.TicksPerDay;
T.Check(JoinDefaults.PreviousCasteFor(p) == null, "a stale record still gives a previous caste");
GenGuest.PrisonerRelease(p);
Fixtures.ApplyJoins(p);
CheckIn(p, colonists, JoinReason.NewColonist, "after the release with a stale record");
T.Check(comp.PruneFormerCastes() >= 1 && comp.FormerOf(p) == null, "the stale record was not pruned");
// The setting off: a fresh record is ignored too.
Fixtures.Settings.returnToPreviousCaste = false;
Pawn q = Fixtures.Colonist();
Fixtures.Unqueue(q);
CasteManager.Assign(q, miner, false, JoinReason.Manual);
q.guest.CapturedBy(Faction.OfPlayer, Warden());
Fixtures.ApplyJoins(q);
T.NotNull(comp.FormerOf(q), "no record was written with returnToPreviousCaste off (records are kept for when it is turned on)");
GenGuest.PrisonerRelease(q);
Fixtures.ApplyJoins(q);
CheckIn(q, colonists, JoinReason.NewColonist, "after the release with returnToPreviousCaste off");
}
[BlaxTest("status: deleting a caste drops the former-caste records that point at it")]
public static void DeletedCasteDropsRecords()
{
Caste doomed = Make("Doomed (record test)", null, Fine());
Pawn p = Fixtures.Colonist();
Fixtures.Unqueue(p);
CasteManager.Assign(p, doomed, false, JoinReason.Manual);
Faction other = Fixtures.FriendlyFaction();
T.NotNull(other, "a friendly faction");
p.SetFaction(other);
T.NotNull(Fixtures.Comp.FormerOf(p), "leaving the faction wrote no former-caste record");
CasteManager.DeleteCaste(doomed);
T.Check(Fixtures.Comp.FormerOf(p) == null, "the record of a deleted caste survived");
}
// ---- hand changes survive a return ----------------------------------------------------
private static DrugPolicy NoDrugs() => Fixtures.Need(Fixtures.Drug("NoDrugs"), "No drugs policy");
private static DrugPolicy Social() => Fixtures.Need(Fixtures.Drug("SocialDrugs"), "Social drugs policy");
/// Work from 22 to 5, sleep the rest: nothing like the starting schedule.
private static List NightShift() =>
Enumerable.Range(0, ScheduleSlot.Hours).Select(h => (h >= 22 || h <= 5 ? TimeAssignmentDefOf.Work : TimeAssignmentDefOf.Sleep).defName).ToList();
[BlaxTest("status: an arrested and released colonist gets its caste back with its hand changes; followed slots get the caste's value")]
public static void ReturnKeepsHandChanges()
{
Caste colonists = Make("Colonists (hand change test)", Worker(), Fine());
CasteManager.SetSlot(colonists, CasteSlot.Drug, NoDrugs());
CasteManager.SetSlot(colonists, CasteSlot.MedCare, MedicalCareCategory.NoMeds);
CasteManager.SetSlot(colonists, CasteSlot.Schedule, NightShift());
Caste prisoners = Make("Prisoners (hand change test)", null, Paste());
Caste wrong = Make("Wrong row (hand change test)", Nudist(), Lavish());
Row(JoinReason.NewPrisoner, prisoners);
Row(JoinReason.NewColonist, wrong);
Pawn p = Fixtures.Colonist();
Fixtures.Unqueue(p);
T.Check(CasteManager.Assign(p, colonists, true, JoinReason.NewColonist), "setup: Assign failed");
// By hand: another outfit, Social drugs, best care and one hour of the schedule.
p.outfits.CurrentApparelPolicy = Nudist();
p.drugs.CurrentPolicy = Social();
p.playerSettings.medCare = MedicalCareCategory.Best;
TimeAssignmentDef hour3 = TimeAssignmentDefOf.Joy;
p.timetable.SetAssignment(3, hour3);
T.Equal(4, CasteManager.Overrides(p).Count, "setup: hand changes (" + string.Join(", ", CasteManager.Overrides(p)) + ")");
p.guest.CapturedBy(Faction.OfPlayer, Warden());
FormerCaste record = Fixtures.Comp.FormerOf(p);
T.NotNull(record, "former-caste record after the arrest");
T.Check(record.Followed(CasteSlot.Food) && !record.Followed(CasteSlot.Apparel) && !record.Followed(CasteSlot.MedCare),
"followed slots in the record: " + string.Join(", ", record.followed));
T.Equal((int)MedicalCareCategory.Best, record.medCare, "medical care in the record (taken before the game's reset)");
Fixtures.ApplyJoins(p);
CheckIn(p, prisoners, JoinReason.NewPrisoner, "after the arrest");
T.Check(p.foodRestriction.CurrentFoodPolicy == Paste(), Who(p) + " does not eat the prisoner food");
// While it was away the caste's food changed: a follower gets the new value.
CasteManager.SetSlot(colonists, CasteSlot.Food, Simple());
GenGuest.PrisonerRelease(p);
Fixtures.ApplyJoins(p);
CheckIn(p, colonists, JoinReason.PreviousCaste, "after the release");
T.Check(Fixtures.Comp.MembershipOf(p).auto, "the restored row-set caste is marked as set by hand");
T.Check(p.outfits.CurrentApparelPolicy == Nudist(), Who(p) + " lost its hand-set outfit: " + p.outfits.CurrentApparelPolicy.label);
T.Check(p.drugs.CurrentPolicy == Social(), Who(p) + " lost its hand-set drug policy: " + p.drugs.CurrentPolicy.label);
T.Equal(MedicalCareCategory.Best, p.playerSettings.medCare, Who(p) + "'s hand-set medical care");
T.Equal(hour3, p.timetable.GetAssignment(3), Who(p) + "'s hand-set hour 3");
T.Equal(TimeAssignmentDefOf.Work, p.timetable.GetAssignment(23), Who(p) + "'s hour 23 (the caste's)");
T.Check(p.foodRestriction.CurrentFoodPolicy == Simple(), Who(p) + " does not follow the caste's new food: " + p.foodRestriction.CurrentFoodPolicy.label);
}
[BlaxTest("status: with No caste rows, an arrest and release rewrites nothing on a pawn that never left its caste")]
public static void NeverLeftKeepsHandChanges()
{
Caste miner = Make("Miner (never left test)", Worker(), Fine());
CasteManager.SetSlot(miner, CasteSlot.Schedule, NightShift());
NoCasteRow(JoinReason.NewPrisoner);
NoCasteRow(JoinReason.NewColonist);
Pawn p = Fixtures.Colonist();
Fixtures.Unqueue(p);
CasteManager.Assign(p, miner, false, JoinReason.Manual);
p.outfits.CurrentApparelPolicy = Nudist();
p.foodRestriction.CurrentFoodPolicy = Lavish();
p.timetable.SetAssignment(12, TimeAssignmentDefOf.Joy);
p.guest.CapturedBy(Faction.OfPlayer, Warden());
Fixtures.ApplyJoins(p);
CheckIn(p, miner, JoinReason.Manual, "after the arrest with a No caste prisoner row");
GenGuest.PrisonerRelease(p);
Fixtures.ApplyJoins(p);
CheckIn(p, miner, JoinReason.PreviousCaste, "after the release");
T.Check(!Fixtures.Comp.MembershipOf(p).auto, "the hand-picked caste is marked as set by a join row");
T.Check(p.outfits.CurrentApparelPolicy == Nudist() && p.foodRestriction.CurrentFoodPolicy == Lavish(),
Who(p) + " lost its hand-set policies: " + p.outfits.CurrentApparelPolicy.label + ", " + p.foodRestriction.CurrentFoodPolicy.label);
T.Equal(TimeAssignmentDefOf.Joy, p.timetable.GetAssignment(12), Who(p) + "'s hand-set hour 12");
}
[BlaxTest("status: a pawn set to No caste goes back to No caste after an arrest and release, with its own policies")]
public static void CastelessComesBack()
{
Caste prisoners = Make("Prisoners (casteless test)", null, Paste());
Caste colonists = Make("Colonists (casteless test)", Worker(), Fine());
Row(JoinReason.NewPrisoner, prisoners);
Row(JoinReason.NewColonist, colonists);
Pawn p = Fixtures.Colonist();
Fixtures.Unqueue(p);
p.outfits.CurrentApparelPolicy = Nudist();
p.foodRestriction.CurrentFoodPolicy = Lavish();
T.Check(CasteManager.MakeCasteless(p), "setup: MakeCasteless failed");
p.guest.CapturedBy(Faction.OfPlayer, Warden());
FormerCaste record = Fixtures.Comp.FormerOf(p);
T.Check(record != null && record.casteless && record.side == JoinSide.Colonist, "former-caste record: " + (record?.ToString() ?? "none"));
Fixtures.ApplyJoins(p);
CheckIn(p, prisoners, JoinReason.NewPrisoner, "after the arrest");
T.Check(p.foodRestriction.CurrentFoodPolicy == Paste(), Who(p) + " does not eat the prisoner food");
GenGuest.PrisonerRelease(p);
T.Check(JoinDefaults.WillChange(p), Who(p) + " does not show as pending before going back to No caste");
Fixtures.ApplyJoins(p);
CasteMembership m = Fixtures.Comp.MembershipOf(p);
T.Check(m != null && m.Casteless, Who(p) + " is not back at No caste: " + State(p));
T.Check(p.outfits.CurrentApparelPolicy == Nudist(), Who(p) + "'s outfit: " + p.outfits.CurrentApparelPolicy.label);
T.Check(p.foodRestriction.CurrentFoodPolicy == Lavish(), Who(p) + "'s food (the prisoner caste's should be undone): " + p.foodRestriction.CurrentFoodPolicy.label);
T.Check(!CasteManager.PawnsToAssignByStatus().Contains(p), "Assign by status offers the pawn set to No caste");
}
[BlaxTest("status: the prisoner caste's food is undone when the pawn returns to a caste that leaves food alone")]
public static void PrisonerFoodUndone()
{
Caste miner = Make("Miner (food undo test)", Worker(), null);
CasteManager.SetSlot(miner, CasteSlot.Food, null);
T.Check(!miner.IsManaged(CasteSlot.Food), "setup: the Miner caste manages food");
Caste prisoners = Make("Prisoners (food undo test)", null, Paste());
Row(JoinReason.NewPrisoner, prisoners);
Pawn p = Fixtures.Colonist();
Fixtures.Unqueue(p);
CasteManager.Assign(p, miner, false, JoinReason.Manual);
p.foodRestriction.CurrentFoodPolicy = Fine();
p.guest.CapturedBy(Faction.OfPlayer, Warden());
Fixtures.ApplyJoins(p);
T.Check(p.foodRestriction.CurrentFoodPolicy == Paste(), Who(p) + " does not eat the prisoner food");
GenGuest.PrisonerRelease(p);
Fixtures.ApplyJoins(p);
CheckIn(p, miner, JoinReason.PreviousCaste, "after the release");
T.Check(p.foodRestriction.CurrentFoodPolicy == Fine(), Who(p) + " kept the prisoner food: " + p.foodRestriction.CurrentFoodPolicy.label);
}
[BlaxTest("status: a row that moves a pawn on from a row-set caste resets what that caste set and the new one leaves alone")]
public static void RowMoveRevertsOldCaste()
{
FoodPolicy defaultFood = Current.Game.foodRestrictionDatabase.DefaultFoodRestriction();
T.Check(defaultFood != Paste(), "setup: Paste is the default food");
Caste prisoners = Make("Prisoners (row move test)", null, Paste());
Caste colonists = Make("Colonists (row move test)", Worker(), null);
CasteManager.SetSlot(colonists, CasteSlot.Food, null);
Row(JoinReason.NewPrisoner, prisoners);
Row(JoinReason.NewColonist, colonists);
// No record at all, so nothing comes back: the rows move it.
Pawn p = Fixtures.Colonist();
Fixtures.Unqueue(p);
T.Check(Fixtures.Comp.MembershipOf(p) == null, "setup: the colonist has a membership record");
p.guest.CapturedBy(Faction.OfPlayer, Warden());
T.Check(Fixtures.Comp.FormerOf(p) == null, "a pawn without a record left a former-caste record");
Fixtures.ApplyJoins(p);
CheckIn(p, prisoners, JoinReason.NewPrisoner, "after the arrest");
GenGuest.PrisonerRelease(p);
Fixtures.ApplyJoins(p);
CheckIn(p, colonists, JoinReason.NewColonist, "after the release");
T.Check(p.foodRestriction.CurrentFoodPolicy == defaultFood, Who(p) + " kept the prisoner food: " + p.foodRestriction.CurrentFoodPolicy.label);
// revertOnLeave off: the food stays.
Fixtures.Settings.revertOnLeave = false;
Pawn q = Fixtures.Colonist();
Fixtures.Unqueue(q);
q.guest.CapturedBy(Faction.OfPlayer, Warden());
Fixtures.ApplyJoins(q);
GenGuest.PrisonerRelease(q);
Fixtures.ApplyJoins(q);
CheckIn(q, colonists, JoinReason.NewColonist, "after the release with revertOnLeave off");
T.Check(q.foodRestriction.CurrentFoodPolicy == Paste(), Who(q) + "'s food with revertOnLeave off: " + q.foodRestriction.CurrentFoodPolicy.label);
}
// ---- the No caste rows ---------------------------------------------------------------
[BlaxTest("status: with No caste rows, an arrested and released colonist keeps its hand-picked caste and its policies")]
public static void HandPickSurvivesNoCasteRows()
{
Caste miner = Make("Miner (no caste rows test)", Worker(), Fine());
CasteManager.SetSlot(miner, CasteSlot.MedCare, MedicalCareCategory.HerbalOrWorse);
NoCasteRow(JoinReason.NewPrisoner);
NoCasteRow(JoinReason.NewColonist);
Pawn p = Fixtures.Colonist();
Fixtures.Unqueue(p);
CasteManager.Assign(p, miner, false, JoinReason.Manual);
p.guest.CapturedBy(Faction.OfPlayer, Warden());
Fixtures.ApplyJoins(p);
CheckIn(p, miner, JoinReason.Manual, "after the arrest with a No caste prisoner row");
T.Check(p.foodRestriction.CurrentFoodPolicy == Fine(), Who(p) + "'s food changed: " + p.foodRestriction.CurrentFoodPolicy.label);
GenGuest.PrisonerRelease(p);
Fixtures.ApplyJoins(p);
T.Check(Fixtures.Comp.CasteOf(p) == miner, Who(p) + " lost Miner after the release: " + State(p));
T.Check(p.foodRestriction.CurrentFoodPolicy == Fine() && p.outfits.CurrentApparelPolicy == Worker(), Who(p) + " lost Miner's policies");
}
[BlaxTest("status: a No caste row reverts only the slots still on the caste's value; a hand-changed slot stays")]
public static void RevertKeepsHandChanges()
{
Caste slaves = Make("Slaves (revert test)", Worker(), Paste());
NoCasteRow(JoinReason.NewColonist);
ApparelPolicy defaultOutfit = Current.Game.outfitDatabase.DefaultOutfit();
T.Check(defaultOutfit != Worker(), "setup: Worker is the default outfit");
// Freeing a home slave changes neither faction nor medical care, so only Castes touches the policies.
Pawn p = HomeSlave();
T.Check(CasteManager.Assign(p, slaves, true, JoinReason.NewSlave), "setup: Assign failed");
p.foodRestriction.CurrentFoodPolicy = Lavish(); // by hand
GenGuest.EmancipateSlave(Warden(), p);
Fixtures.ApplyJoins(p);
T.Check(Fixtures.Comp.MembershipOf(p) == null, Who(p) + " is still in a caste: " + State(p));
T.Check(p.outfits.CurrentApparelPolicy == defaultOutfit, Who(p) + "'s outfit did not return to the default: " + p.outfits.CurrentApparelPolicy.label);
T.Check(p.foodRestriction.CurrentFoodPolicy == Lavish(), Who(p) + " lost its hand-set food: " + p.foodRestriction.CurrentFoodPolicy.label);
}
// ---- what changed while the pawn was away ----------------------------------------------
private static WorkTypeDef Firefighter() => Fixtures.NeedDef(DefDatabase.GetNamedSilentFail("Firefighter"), "work type Firefighter");
/// A spawned colonist that can do the work type (backstories and traits can disable some).
private static Pawn ColonistThatCan(WorkTypeDef def)
{
for (int i = 0; i < 12; i++)
{
Pawn p = Fixtures.Colonist();
Fixtures.Unqueue(p);
if (WorkSlot.CanDo(p, def))
return p;
}
T.Fail("no generated colonist could do " + def.defName + " in 12 tries");
return null;
}
[BlaxTest("status: a slot and a work type the caste starts managing while the pawn is away reach it on its return; an older record keeps its own values")]
public static void ReturnGetsNewlyManagedSlots()
{
PlaySettings play = Find.PlaySettings;
bool manual = play.useWorkPriorities;
play.useWorkPriorities = true;
try
{
WorkTypeDef fire = Firefighter();
Caste colonists = Make("Colonists (newly managed test)", Worker(), Fine());
Caste prisoners = Make("Prisoners (newly managed test)", null, Paste());
Caste wrong = Make("Wrong row (newly managed test)", Nudist(), Lavish());
Row(JoinReason.NewPrisoner, prisoners);
Row(JoinReason.NewColonist, wrong);
T.Check(!colonists.IsManaged(CasteSlot.Schedule) && colonists.WorkPriorityOf(fire.defName) == null, "setup: the caste manages the schedule or Firefighter");
Pawn p = ColonistThatCan(fire);
Pawn old = ColonistThatCan(fire);
foreach (Pawn pawn in new[] { p, old })
{
T.Check(CasteManager.Assign(pawn, colonists, true, JoinReason.NewColonist), "setup: Assign failed");
pawn.timetable.SetAssignment(3, TimeAssignmentDefOf.Joy); // its own day: the caste leaves the schedule alone
pawn.workSettings.SetPriority(fire, 3);
pawn.outfits.CurrentApparelPolicy = Nudist(); // by hand, on a slot the caste manages
pawn.guest.CapturedBy(Faction.OfPlayer, Warden());
}
FormerCaste record = Fixtures.Comp.FormerOf(p);
T.NotNull(record, "former-caste record after the arrest");
T.Check(record.WasManaged(CasteSlot.Apparel) && !record.WasManaged(CasteSlot.Schedule), "managed slots in the record: " + string.Join(", ", record.managed ?? new List()));
T.Check(!record.WasListed(fire.defName), "the record lists Firefighter");
// A record saved before Castes kept the managed slots: read as "managed then", so the pawn keeps its own.
FormerCaste oldRecord = Fixtures.Comp.FormerOf(old);
T.NotNull(oldRecord, "former-caste record of the second pawn");
oldRecord.managed = null;
oldRecord.listedWork = null;
Fixtures.ApplyJoins(p, old);
CheckIn(p, prisoners, JoinReason.NewPrisoner, "after the arrest");
// While they are away, the caste starts managing the schedule and lists Firefighter: every member gets both.
CasteManager.SetSlot(colonists, CasteSlot.Schedule, NightShift());
CasteManager.SetWorkPriority(colonists, fire.defName, 1);
foreach (Pawn pawn in new[] { p, old })
GenGuest.PrisonerRelease(pawn);
Fixtures.ApplyJoins(p, old);
CheckIn(p, colonists, JoinReason.PreviousCaste, "after the release");
T.Equal(TimeAssignmentDefOf.Work, p.timetable.GetAssignment(3), Who(p) + "'s hour 3 (the caste's schedule, not its own Joy)");
T.Equal(TimeAssignmentDefOf.Sleep, p.timetable.GetAssignment(12), Who(p) + "'s hour 12 (the caste's schedule)");
T.Equal(1, p.workSettings.GetPriority(fire), Who(p) + "'s Firefighter (listed by the caste while it was away)");
T.Check(p.outfits.CurrentApparelPolicy == Nudist(), Who(p) + " lost its hand-set outfit: " + p.outfits.CurrentApparelPolicy.label);
List overrides = CasteManager.Overrides(p);
T.Check(overrides.Count == 1 && overrides[0] == CasteSlot.Apparel, Who(p) + "'s overrides: " + string.Join(", ", overrides));
CheckIn(old, colonists, JoinReason.PreviousCaste, "after the release with an older record");
T.Equal(TimeAssignmentDefOf.Joy, old.timetable.GetAssignment(3), Who(old) + "'s own hour 3 (older record)");
T.Equal(3, old.workSettings.GetPriority(fire), Who(old) + "'s own Firefighter (older record)");
}
finally
{
play.useWorkPriorities = manual;
}
}
[BlaxTest("status: a hand-set policy deleted while the pawn is away is skipped on return, even when a new policy got its id")]
public static void ReturnSkipsDeletedPolicy()
{
FoodRestrictionDatabase db = Current.Game.foodRestrictionDatabase;
FoodPolicy custom = db.MakeNewFoodRestriction();
custom.label = "Blax test custom food";
FoodPolicy reused = null;
try
{
Caste colonists = Make("Colonists (deleted policy test)", Worker(), Fine());
Caste prisoners = Make("Prisoners (deleted policy test)", null, Paste());
Row(JoinReason.NewPrisoner, prisoners);
Pawn p = Fixtures.Colonist();
Fixtures.Unqueue(p);
T.Check(CasteManager.Assign(p, colonists, true, JoinReason.NewColonist), "setup: Assign failed");
p.foodRestriction.CurrentFoodPolicy = custom; // by hand
p.guest.CapturedBy(Faction.OfPlayer, Warden());
FormerCaste record = Fixtures.Comp.FormerOf(p);
T.Check(record != null && record.food == custom, "the record's food: " + (record?.food?.label ?? "none"));
Fixtures.ApplyJoins(p);
T.Check(p.foodRestriction.CurrentFoodPolicy == Paste(), Who(p) + " does not eat the prisoner food");
int id = custom.id;
AcceptanceReport deleted = db.TryDelete(custom);
T.Check(deleted.Accepted, "the game refused to delete the custom food policy: " + deleted.Reason);
reused = db.MakeNewFoodRestriction();
T.Equal(id, reused.id, "setup: the new food policy's id (the game gives the highest id plus one)");
GenGuest.PrisonerRelease(p);
Fixtures.ApplyJoins(p);
CheckIn(p, colonists, JoinReason.PreviousCaste, "after the release");
T.Check(p.foodRestriction.CurrentFoodPolicy != reused, Who(p) + " got the new policy that reused the deleted one's id");
T.Check(p.foodRestriction.CurrentFoodPolicy == Fine(), Who(p) + " should fall back to the caste's food: " + p.foodRestriction.CurrentFoodPolicy.label);
}
finally
{
if (db.AllFoodRestrictions.Contains(custom))
db.TryDelete(custom);
if (reused != null && db.AllFoodRestrictions.Contains(reused))
db.TryDelete(reused);
}
}
// ---- leaving the map ------------------------------------------------------------------
[BlaxTest("status: a freed slave from another faction that walks off the map leaves its caste with a slave record; nothing joins")]
public static void FreedForeignSlaveWalksOff()
{
Caste slaves = Make("Slaves (walk off test)", null, Simple());
Caste colonists = Make("Colonists (walk off test)", Worker(), Fine());
Row(JoinReason.NewColonist, colonists);
Pawn p = Fixtures.ColonySlave();
Fixtures.Unqueue(p);
T.Check(p.SlaveFaction != null && p.SlaveFaction != Faction.OfPlayer, "setup: the slave's own faction is " + p.SlaveFaction);
T.Check(CasteManager.Assign(p, slaves, true, JoinReason.NewSlave), "setup: Assign failed");
GenGuest.EmancipateSlave(Warden(), p);
T.Check(p.IsSlave && p.guest.Released, Who(p) + " should walk off still a slave: slave " + p.IsSlave + ", released " + p.guest.Released);
T.Check(!JoinDefaults.IsQueued(p), "freeing a slave from another faction queued a join before it left");
p.ExitMap(true, Rot4.North);
T.Equal(0, JoinScopes.Depth, "open join scopes after ExitMap");
T.Check(!p.Spawned, Who(p) + " is still on the map");
T.Check(!JoinDefaults.IsQueued(p), "walking off the map queued a join (" + JoinDefaults.QueuedFor(p)?.reason + ")");
FormerCaste record = Fixtures.Comp.FormerOf(p);
T.Check(record != null && record.casteId == slaves.id && record.side == JoinSide.Slave, "former-caste record: " + (record?.ToString() ?? "none"));
Fixtures.ApplyJoins(p);
T.Check(Fixtures.Comp.MembershipOf(p) == null, Who(p) + " kept a membership: " + State(p));
T.Check(!CasteManager.LiveMembers(slaves).Contains(p) && !CasteManager.LiveMembers(colonists).Contains(p), Who(p) + " still counts as a member");
T.Info("faction after leaving: " + (p.Faction?.Name ?? "none"));
}
[BlaxTest("status: an escaped slave and an escaped prisoner that leave the map leave their caste")]
public static void EscapedPawnsLeave()
{
Caste slaves = Make("Slaves (escape test)", null, Simple());
Caste prisoners = Make("Prisoners (escape test)", null, Paste());
Pawn prisoner = Fixtures.Prisoner();
Fixtures.Unqueue(prisoner);
T.Check(CasteManager.Assign(prisoner, prisoners, true, JoinReason.NewPrisoner), "setup: Assign the prisoner failed");
prisoner.ExitMap(true, Rot4.North);
T.Equal(0, JoinScopes.Depth, "open join scopes after the prisoner left");
T.Check(Fixtures.Comp.MembershipOf(prisoner) == null, Who(prisoner) + " kept a membership: " + State(prisoner));
T.Check(!CasteManager.LiveMembers(prisoners).Contains(prisoner), "the escaped prisoner still counts as a member");
T.Check(!JoinDefaults.IsQueued(prisoner), "the escaped prisoner was queued");
T.Info("escaped prisoner still a prisoner of the colony in the world: " + prisoner.IsPrisonerOfColony);
if (!ModsConfig.IdeologyActive)
T.Skip("needs Ideology (slaves); the escaped prisoner check passed");
Pawn slave = Fixtures.ColonySlave();
Fixtures.Unqueue(slave);
T.Check(CasteManager.Assign(slave, slaves, true, JoinReason.NewSlave), "setup: Assign the slave failed");
slave.ExitMap(true, Rot4.North);
T.Equal(0, JoinScopes.Depth, "open join scopes after the slave left");
T.Check(!JoinDefaults.IsQueued(slave), "the escaped slave was queued (" + JoinDefaults.QueuedFor(slave)?.reason + ")");
FormerCaste record = Fixtures.Comp.FormerOf(slave);
T.Check(record != null && record.casteId == slaves.id && record.side == JoinSide.Slave, "former-caste record: " + (record?.ToString() ?? "none"));
Fixtures.ApplyJoins(slave);
T.Check(Fixtures.Comp.MembershipOf(slave) == null, Who(slave) + " kept a membership: " + State(slave));
T.Check(!CasteManager.LiveMembers(slaves).Contains(slave), "the escaped slave still counts as a member");
}
[BlaxTest("status: a colonist that leaves in a caravan, or is kidnapped, keeps its caste")]
public static void CaravanAndKidnapKeepCaste()
{
Caste miner = Make("Miner (caravan test)", Worker(), Fine());
Pawn p = Fixtures.Colonist();
Fixtures.Unqueue(p);
T.Check(CasteManager.Assign(p, miner, false, JoinReason.Manual), "setup: Assign failed");
Map map = Fixtures.Map;
Caravan caravan = CaravanExitMapUtility.ExitMapAndCreateCaravan(new[] { p }, Faction.OfPlayer, map.Tile, map.Tile, PlanetTile.Invalid, sendMessage: false);
T.NotNull(caravan, "the caravan");
T.Equal(0, JoinScopes.Depth, "open join scopes after leaving in a caravan");
T.Check(p.IsCaravanMember() && p.Faction == Faction.OfPlayer, Who(p) + " is not a player caravan member");
T.Check(Fixtures.Comp.CasteOf(p) == miner, Who(p) + " lost its caste in the caravan: " + State(p));
T.Check(Fixtures.Comp.FormerOf(p) == null, "leaving in a caravan wrote a former-caste record");
T.Check(!JoinDefaults.IsQueued(p), "leaving in a caravan queued a join");
Fixtures.ApplyJoins(p);
T.Check(Fixtures.Comp.CasteOf(p) == miner, Who(p) + " lost its caste on the next tick: " + State(p));
CaravanEnterMapUtility.Enter(caravan, map, CaravanEnterMode.Edge);
T.Check(p.Spawned && Fixtures.Comp.CasteOf(p) == miner, Who(p) + " back from the caravan: spawned " + p.Spawned + ", " + State(p));
Faction raiders = Fixtures.HostileFaction();
if (raiders == null)
{
T.Info("no hostile faction: kidnapping not checked");
return;
}
Pawn q = Fixtures.Colonist();
Fixtures.Unqueue(q);
T.Check(CasteManager.Assign(q, miner, false, JoinReason.Manual), "setup: Assign the second colonist failed");
raiders.kidnapped.Kidnap(q, null);
try
{
T.Check(q.IsKidnapped(), "setup: " + Who(q) + " is not kidnapped");
Fixtures.ApplyJoins(q);
T.Check(Fixtures.Comp.CasteOf(q) == miner, Who(q) + " lost its caste when kidnapped: " + State(q));
T.Check(Fixtures.Comp.FormerOf(q) == null, "being kidnapped wrote a former-caste record");
}
finally
{
raiders.kidnapped.RemoveKidnappedPawn(q);
}
}
[BlaxTest("status: a slave left on a closing map leaves its caste with a slave record; nothing joins")]
public static void SlaveLostWithClosingMap()
{
Caste slaves = Make("Slaves (closing map test)", null, Simple());
Caste colonists = Make("Colonists (closing map test)", Worker(), Fine());
Row(JoinReason.NewColonist, colonists);
Pawn p = Fixtures.ColonySlave();
Fixtures.Unqueue(p);
T.Check(CasteManager.Assign(p, slaves, true, JoinReason.NewSlave), "setup: Assign failed");
// The hook around MapDeiniter.PassPawnsToWorld, with that method's body for this one pawn (closing the test map would end the run).
MethodInfo target = AccessTools.Method(typeof(MapDeiniter), "PassPawnsToWorld");
T.NotNull(target, "MapDeiniter.PassPawnsToWorld");
var info = Harmony.GetPatchInfo(target);
T.Check(info != null && info.Prefixes.Any(x => x.owner == BlaxCastesStartup.HarmonyId) && info.Finalizers.Any(x => x.owner == BlaxCastesStartup.HarmonyId),
"Blax Castes did not patch MapDeiniter.PassPawnsToWorld");
Type patch = AccessTools.TypeByName("BlaxCastes.Patch_MapDeiniter_PassPawnsToWorld");
T.NotNull(patch, "the closing map patch class");
MethodInfo cleanUp = AccessTools.Method(typeof(MapDeiniter), "CleanUpAndPassToWorld");
T.NotNull(cleanUp, "MapDeiniter.CleanUpAndPassToWorld");
object[] prefixArgs = { Fixtures.Map, null };
AccessTools.Method(patch, "Prefix").Invoke(null, prefixArgs);
try
{
p.DeSpawnOrDeselect();
cleanUp.Invoke(null, new object[] { p });
}
finally
{
AccessTools.Method(patch, "Finalizer").Invoke(null, new object[] { null, prefixArgs[1] });
}
T.Equal(0, JoinScopes.Depth, "open join scopes after the map closed");
T.Check(!JoinDefaults.IsQueued(p), "the lost slave was queued (" + JoinDefaults.QueuedFor(p)?.reason + ")");
FormerCaste record = Fixtures.Comp.FormerOf(p);
T.Check(record != null && record.casteId == slaves.id && record.side == JoinSide.Slave, "former-caste record: " + (record?.ToString() ?? "none"));
Fixtures.ApplyJoins(p);
T.Check(Fixtures.Comp.MembershipOf(p) == null, Who(p) + " kept a membership: " + State(p));
}
/// Runs a leaving patch's prefix and finalizer around body, the way Harmony does (the patched method itself must not run: it would close the test map).
private static void AroundLeavingPatch(Type target, string method, string patchClass, Action body)
{
MethodInfo original = AccessTools.Method(target, method);
T.NotNull(original, target.Name + "." + method);
var info = Harmony.GetPatchInfo(original);
T.Check(info != null && info.Prefixes.Any(x => x.owner == BlaxCastesStartup.HarmonyId) && info.Finalizers.Any(x => x.owner == BlaxCastesStartup.HarmonyId),
"Blax Castes did not patch " + target.Name + "." + method);
Type patch = AccessTools.TypeByName("BlaxCastes." + patchClass);
T.NotNull(patch, "the patch class " + patchClass);
object[] prefixArgs = { Fixtures.Map, null };
AccessTools.Method(patch, "Prefix").Invoke(null, prefixArgs);
try
{
body();
}
finally
{
AccessTools.Method(patch, "Finalizer").Invoke(null, new object[] { null, prefixArgs[1] });
}
T.Equal(0, JoinScopes.Depth, "open join scopes after " + method);
}
[BlaxTest("status: a prisoner left on a closing map leaves its caste; nothing joins (no DLC needed)")]
public static void PrisonerLostWithClosingMap()
{
Caste prisoners = Make("Prisoners (closing map test)", null, Paste());
Pawn p = Fixtures.Prisoner();
Fixtures.Unqueue(p);
T.Check(CasteManager.Assign(p, prisoners, true, JoinReason.NewPrisoner), "setup: Assign failed");
MethodInfo cleanUp = AccessTools.Method(typeof(MapDeiniter), "CleanUpAndPassToWorld");
T.NotNull(cleanUp, "MapDeiniter.CleanUpAndPassToWorld");
AroundLeavingPatch(typeof(MapDeiniter), "PassPawnsToWorld", "Patch_MapDeiniter_PassPawnsToWorld", () =>
{
p.DeSpawnOrDeselect();
cleanUp.Invoke(null, new object[] { p });
});
T.Check(!JoinDefaults.IsQueued(p), "the lost prisoner was queued (" + JoinDefaults.QueuedFor(p)?.reason + ")");
Fixtures.ApplyJoins(p);
T.Check(Fixtures.Comp.MembershipOf(p) == null, Who(p) + " kept a membership: " + State(p));
T.Check(!CasteManager.LiveMembers(prisoners).Contains(p), "the lost prisoner still counts as a member");
}
[BlaxTest("status: a gravship that leaves its map (Odyssey) takes the prisoner left behind out of its caste; a colonist left behind keeps its caste")]
public static void GravshipLeavesPawnsBehind()
{
Caste prisoners = Make("Prisoners (gravship test)", null, Paste());
Caste miner = Make("Miner (gravship test)", Worker(), Fine());
Pawn prisoner = Fixtures.Prisoner();
Fixtures.Unqueue(prisoner);
T.Check(CasteManager.Assign(prisoner, prisoners, true, JoinReason.NewPrisoner), "setup: Assign the prisoner failed");
Pawn colonist = Fixtures.Colonist();
Fixtures.Unqueue(colonist);
T.Check(CasteManager.Assign(colonist, miner, false, JoinReason.Manual), "setup: Assign the colonist failed");
// GravshipUtility.AbandonMap's body for these two pawns: despawned and passed to the world, with no status change.
AroundLeavingPatch(typeof(GravshipUtility), nameof(GravshipUtility.AbandonMap), "Patch_GravshipUtility_AbandonMap", () =>
{
foreach (Pawn pawn in new[] { prisoner, colonist })
{
pawn.DeSpawn();
pawn.DestroyOrPassToWorld();
}
});
T.Check(prisoner.IsWorldPawn() && colonist.IsWorldPawn(), "setup: the pawns are not world pawns");
T.Info("prisoner left behind still a prisoner of the colony: " + prisoner.IsPrisonerOfColony);
T.Check(Fixtures.Comp.MembershipOf(prisoner) == null, Who(prisoner) + " kept a membership: " + State(prisoner));
T.Check(!JoinDefaults.IsQueued(prisoner) && !JoinDefaults.IsQueued(colonist), "a pawn left behind was queued");
CheckIn(colonist, miner, JoinReason.Manual, "after being left behind");
if (!ModsConfig.OdysseyActive)
T.Info("Odyssey is off: AbandonMap returns at once in this game, so only the hook's body ran");
}
[BlaxTest("status: a No caste row reverts only the slots still on the caste's value for recruited prisoners; a hand-changed slot stays (no DLC needed)")]
public static void RevertKeepsHandChangesOnRecruit()
{
Caste prisoners = Make("Prisoners (revert test)", null, Paste());
NoCasteRow(JoinReason.NewColonist);
FoodPolicy defaultFood = Current.Game.foodRestrictionDatabase.DefaultFoodRestriction();
T.Check(defaultFood != Paste(), "setup: Paste is the default food");
Pawn follows = Fixtures.Prisoner();
Pawn changed = Fixtures.Prisoner();
foreach (Pawn p in new[] { follows, changed })
{
Fixtures.Unqueue(p);
T.Check(CasteManager.Assign(p, prisoners, true, JoinReason.NewPrisoner), "setup: Assign failed");
}
changed.foodRestriction.CurrentFoodPolicy = Lavish(); // by hand
foreach (Pawn p in new[] { follows, changed })
{
RecruitUtility.Recruit(p, Faction.OfPlayer, Warden());
T.Check(p.IsColonist, Who(p) + " is not a colonist after Recruit");
}
Fixtures.ApplyJoins(follows, changed);
T.Check(Fixtures.Comp.MembershipOf(follows) == null && Fixtures.Comp.MembershipOf(changed) == null,
"still in a caste after the No caste row: " + State(follows) + " / " + State(changed));
T.Check(follows.foodRestriction.CurrentFoodPolicy == defaultFood, Who(follows) + "'s food did not return to the default: " + follows.foodRestriction.CurrentFoodPolicy.label);
T.Check(changed.foodRestriction.CurrentFoodPolicy == Lavish(), Who(changed) + " lost its hand-set food: " + changed.foodRestriction.CurrentFoodPolicy.label);
}
// ---- save and reload -----------------------------------------------------------------
// The successor policy takes the deleted one's id and label, so both have the same load ID: a
// reference to the deleted policy left in the save would load as the successor.
[BlaxTest("status: set up a former-caste record whose own policy is deleted before the save, and a new policy with its id and label")]
public static void DeletedPolicyReloadSetup()
{
FoodRestrictionDatabase db = Current.Game.foodRestrictionDatabase;
FoodPolicy doomed = db.MakeNewFoodRestriction();
doomed.label = "Blax test doomed reload food";
Caste c = Fixtures.KeepCaste(Make("Deleted policy reload test", null, Fine()));
Pawn p = Fixtures.Colonist(); // destroyed by the cleanup: the record is keyed by ThingID
Fixtures.Unqueue(p);
CasteManager.Assign(p, c, true, JoinReason.NewColonist);
p.foodRestriction.CurrentFoodPolicy = doomed;
p.drugs.CurrentPolicy = Social();
Faction other = Fixtures.FriendlyFaction();
T.NotNull(other, "a friendly faction");
p.SetFaction(other);
FormerCaste record = Fixtures.Comp.FormerOf(p);
T.Check(record != null && record.food == doomed, "setup: the record's food: " + (record?.food?.label ?? "none"));
if (p.foodRestriction != null)
p.foodRestriction.CurrentFoodPolicy = Fine();
AcceptanceReport deleted = db.TryDelete(doomed);
T.Check(deleted.Accepted, "the game refused to delete the food policy: " + deleted.Reason);
FoodPolicy successor = db.MakeNewFoodRestriction(); // kept for phase 2, deleted there
T.Equal(doomed.id, successor.id, "setup: the new food policy's id (the game gives the highest id plus one)");
successor.label = doomed.label;
T.Equal(doomed.GetUniqueLoadID(), successor.GetUniqueLoadID(), "setup: the new food policy's load ID");
T.Check(record.food == doomed, "setup: the record's food after the new policy was made: " + (record.food?.label ?? "none"));
T.Carry["deletedPolicyPawn"] = p.ThingID;
T.Carry["deletedPolicyLabel"] = doomed.label;
T.Carry["deletedPolicySuccessor"] = successor.id.ToString();
T.Carry["deletedPolicyDrug"] = Social().id.ToString();
}
[BlaxTest("status: a record whose own policy was deleted loads without that policy, not as the new policy with its load ID, and without warnings", phase: 2)]
public static void DeletedPolicyRecordLoads()
{
FoodRestrictionDatabase db = Current.Game.foodRestrictionDatabase;
FoodPolicy successor = null;
try
{
string label = null, successorId = null;
T.Check(T.Carry.TryGetValue("deletedPolicyPawn", out string pawnId) && T.Carry.TryGetValue("deletedPolicyLabel", out label)
&& T.Carry.TryGetValue("deletedPolicySuccessor", out successorId), "phase 1 setup did not run");
successor = db.AllFoodRestrictions.FirstOrDefault(f => f.id.ToString() == successorId);
T.Check(successor != null && successor.label == label, "the new food policy with the deleted one's id and label did not survive the reload: " + (successor?.label ?? "none"));
T.Check(Fixtures.Comp.FormerCastes.TryGetValue(pawnId, out FormerCaste record), "the record for " + pawnId + " did not survive the reload");
T.Check(record.food != successor, "the record's deleted food policy came back as the new policy with its load ID (" + successor.GetUniqueLoadID() + ")");
T.Check(record.food == null, "the record's deleted food policy came back as " + record.food?.label);
T.Equal(T.Carry["deletedPolicyDrug"], record.drug?.id.ToString(), "the record's drug policy (still in the game) after the reload");
List problems = Log.Messages
.Where(m => (m.type == LogMessageType.Error || m.type == LogMessageType.Warning) && m.text != null && m.text.Contains(label))
.Select(m => m.type + ": " + m.text).ToList();
T.Check(problems.Count == 0, "errors or warnings about the deleted policy: " + string.Join(" | ", problems.Take(2)));
}
finally
{
if (successor != null && db.AllFoodRestrictions.Contains(successor))
db.TryDelete(successor);
}
}
// Runs last in this class (source order): the record is checked after the reload.
[BlaxTest("status: set up a former-caste record for the reload")]
public static void ReloadSetup()
{
Caste c = Fixtures.KeepCaste(Make("Former caste reload test", null, Fine()));
Pawn p = Fixtures.Colonist(); // destroyed by the cleanup: the record is keyed by ThingID, not by reference
Fixtures.Unqueue(p);
CasteManager.Assign(p, c, true, JoinReason.NewColonist);
Faction other = Fixtures.FriendlyFaction();
T.NotNull(other, "a friendly faction");
p.SetFaction(other);
FormerCaste record = Fixtures.Comp.FormerOf(p);
T.NotNull(record, "setup: no former-caste record");
T.Check(record.Followed(CasteSlot.Food) && record.food == Fine(), "setup: the record's food: " + record.food?.label + ", followed " + string.Join(", ", record.followed));
T.Carry["formerPawn"] = p.ThingID;
T.Carry["formerCaste"] = c.id.ToString();
T.Carry["formerFood"] = record.food.id.ToString();
T.Carry["formerManaged"] = string.Join(",", record.managed);
T.Carry["formerSchedule"] = record.schedule == null ? "none" : string.Join(",", record.schedule);
}
[BlaxTest("status: former-caste records survive save and reload, keyed by ThingID", phase: 2)]
public static void RecordSurvives()
{
string casteId = null;
T.Check(T.Carry.TryGetValue("formerPawn", out string pawnId) && T.Carry.TryGetValue("formerCaste", out casteId), "phase 1 setup did not run");
T.Check(Fixtures.Comp.FormerCastes.TryGetValue(pawnId, out FormerCaste record), "the record for " + pawnId + " did not survive the reload");
T.Equal(casteId, record.casteId.ToString(), "record caste id");
T.Equal(JoinSide.Colonist, record.side, "record status");
T.Check(record.auto, "record auto flag");
T.NotNull(Fixtures.Comp.CasteById(record.casteId), "the record's caste after the reload");
T.Check(!record.casteless, "record turned into a No caste record");
T.Equal(T.Carry["formerFood"], record.food?.id.ToString(), "record food policy");
T.Check(record.Followed(CasteSlot.Food), "record lost its followed slots: " + string.Join(", ", record.followed));
T.Equal(T.Carry["formerManaged"], record.managed == null ? "null" : string.Join(",", record.managed), "record managed slots");
T.Equal(T.Carry["formerSchedule"], record.schedule == null ? "none" : string.Join(",", record.schedule), "record schedule");
}
}
}