using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using BlaxCastes;
using HarmonyLib;
using RimWorld;
using Verse;
namespace BlaxCastesTests
{
///
/// Join defaults: classification in the SetFaction, SetGuestStatus and PreTraded hooks, the one-tick
/// deferral, the rows, the No caste revert, the settings and the window. Fixture prisoners are never
/// ticked while they are still prisoners: outside a prison cell vanilla's prisoner job givers throw.
///
public static class JoinTests
{
private const string TaSoC = "Rhajiit.tradepurchasemode";
// ---- policies and castes -------------------------------------------------------------
private static ApparelPolicy SlaveOrSoldier() =>
Fixtures.Need(Fixtures.Outfit(ModsConfig.IdeologyActive ? "OutfitSlave" : "OutfitSoldier"), "Slave or Soldier outfit");
private static ApparelPolicy Worker() => Fixtures.Need(Fixtures.Outfit("OutfitWorker"), "Worker 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");
/// A caste managing apparel and food.
private static Caste RowCaste(string label, ApparelPolicy apparel, FoodPolicy food)
{
Caste c = Fixtures.NewCaste(label);
CasteManager.SetSlot(c, CasteSlot.Apparel, apparel);
CasteManager.SetSlot(c, CasteSlot.Food, food);
T.Check(c.IsManaged(CasteSlot.Apparel) && c.IsManaged(CasteSlot.Food), "setup: " + label + " does not manage apparel and food");
return c;
}
/// A caste managing food only, plus medical care when given.
private static Caste FoodCaste(string label, FoodPolicy food, MedicalCareCategory? care = null)
{
Caste c = Fixtures.NewCaste(label);
CasteManager.SetSlot(c, CasteSlot.Food, food);
if (care.HasValue)
CasteManager.SetSlot(c, CasteSlot.MedCare, care.Value);
return c;
}
private static void Row(string reason, Caste caste) =>
T.Check(CasteManager.SetJoinRow(reason, JoinRowMode.SpecificCaste, caste), "setup: SetJoinRow " + reason + " failed");
private static string Who(Pawn p) => p.LabelShort + " [" + p.ThingID + "]";
private static string Policies(Pawn p) =>
string.Join(", ", CasteUtility.AllSlots.Select(s => s + "=" + CasteUtility.ValueLabel(s, CasteUtility.CurrentValue(p, s))));
private static void CheckMember(Pawn p, Caste caste, string reason)
{
CasteMembership m = Fixtures.Comp.MembershipOf(p);
T.NotNull(m, Who(p) + "'s membership after the join");
T.Check(m.caste == caste, Who(p) + " is in " + (m.caste?.label ?? "no caste") + ", expected " + caste.label);
T.Check(m.auto, Who(p) + "'s membership is not marked as set by a join row");
T.Equal(reason, m.reason, Who(p) + "'s membership reason");
}
private static void Unqueue(Pawn p) => Fixtures.Comp.JoinQueue.RemoveAll(q => q != null && q.pawn == p);
// ---- trading -------------------------------------------------------------------------
///
/// A trader that hands pawns over the way Pawn_TraderTracker does (PreTraded, nothing else), so
/// Tradeable_Pawn.ResolveTrade and the buy-mode patches on it run without a ship or a caravan.
///
internal sealed class TestTrader : ITrader
{
private readonly Faction faction;
private readonly TraderKindDef kind;
public TestTrader()
{
faction = Fixtures.FriendlyFaction();
kind = DefDatabase.AllDefs.FirstOrDefault(k => k.defName != "RD_PawnTrader" && k.WillTrade(ThingDefOf.Human))
?? DefDatabase.AllDefs.FirstOrDefault();
}
public TraderKindDef TraderKind => kind;
public IEnumerable Goods => Enumerable.Empty();
public int RandomPriceFactorSeed => 1;
public string TraderName => "Blax Castes test trader";
public bool CanTradeNow => true;
public float TradePriceImprovementOffsetForPlayer => 0f;
public Faction Faction => faction;
public TradeCurrency TradeCurrency => TradeCurrency.Silver;
public IEnumerable ColonyThingsWillingToBuy(Pawn playerNegotiator) => Enumerable.Empty();
public void GiveSoldThingToTrader(Thing toGive, int countToGive, Pawn playerNegotiator) =>
toGive.PreTraded(TradeAction.PlayerSells, playerNegotiator, this);
public void GiveSoldThingToPlayer(Thing toGive, int countToGive, Pawn playerNegotiator) =>
toGive.PreTraded(TradeAction.PlayerBuys, playerNegotiator, this);
}
/// An unspawned, recruitable pawn as trader stock holds it.
internal static Pawn StockPawn(JoinStatus status)
{
Faction from = Fixtures.FriendlyFaction();
if (from == null)
T.Skip("no friendly faction to buy from");
Pawn p = Fixtures.Generate(PawnKindDefOf.Slave, from);
p.guest.Recruitable = true;
p.guest.joinStatus = status;
return p;
}
/// Buys the pawn through vanilla Pawn.PreTraded(PlayerBuys), then lets it arrive on the map.
internal static void Buy(Pawn p, Pawn negotiator, ITrader trader)
{
p.PreTraded(TradeAction.PlayerBuys, negotiator, trader);
if (!p.Spawned)
Fixtures.Spawn(p);
}
private static readonly FieldInfo LiveMessages = AccessTools.Field(typeof(Messages), "liveMessages");
internal static bool MessageShown(string part)
{
T.NotNull(LiveMessages, "Messages.liveMessages (renamed in this game version?)");
var live = (List)LiveMessages.GetValue(null);
return live.Any(m => m.text != null && m.text.Contains(part));
}
// ---- buying --------------------------------------------------------------------------
[BlaxTest("join: a pawn bought as slave through PreTraded(PlayerBuys) is queued, then after one tick wears and eats its caste's policies")]
public static void BoughtAsSlave()
{
if (!ModsConfig.IdeologyActive)
T.Skip("needs Ideology (slaves)");
Caste bought = RowCaste("Bought slaves join test", SlaveOrSoldier(), Simple());
Caste wrong = FoodCaste("Wrong row (bought slave)", Paste());
Row(JoinReason.BoughtSlave, bought);
Row(JoinReason.BoughtColonist, wrong);
Row(JoinReason.NewSlave, wrong);
Pawn negotiator = Fixtures.Colonist();
Pawn p = StockPawn(JoinStatus.JoinAsSlave);
p.PreTraded(TradeAction.PlayerBuys, negotiator, new TestTrader());
T.Check(p.IsSlaveOfColony, Who(p) + " is not a slave of the colony after the purchase");
T.Equal(0, JoinScopes.Depth, "open join scopes after PreTraded");
QueuedJoin q = JoinDefaults.QueuedFor(p);
T.NotNull(q, Who(p) + "'s queued join");
T.Equal(JoinScopes.Bought, q.reason, "queued reason");
T.Check(Fixtures.Comp.MembershipOf(p) == null, "the join was applied inside PreTraded instead of on the next tick");
Fixtures.Spawn(p);
Fixtures.Tick(1);
T.Check(!JoinDefaults.IsQueued(p), Who(p) + " is still queued after one tick");
CheckMember(p, bought, JoinReason.BoughtSlave);
T.Check(p.outfits.CurrentApparelPolicy == bought.ApparelPolicy && p.foodRestriction.CurrentFoodPolicy == Simple(),
Who(p) + " does not wear and eat its caste's policies: " + Policies(p));
T.Check(MessageShown(bought.label), "no message names the caste " + bought.label);
}
[BlaxTest("join: a pawn bought as colonist ends in the bought-as-colonist caste, and no message shows with messages off")]
public static void BoughtAsColonist()
{
Caste bought = RowCaste("Bought colonists join test", Worker(), Fine());
Caste wrong = FoodCaste("Wrong row (bought colonist)", Paste());
Row(JoinReason.BoughtColonist, bought);
Row(JoinReason.BoughtSlave, wrong);
Row(JoinReason.NewColonist, wrong);
Fixtures.Settings.joinMessages = false;
Pawn p = StockPawn(JoinStatus.JoinAsColonist);
Buy(p, Fixtures.Colonist(), new TestTrader());
T.Check(p.IsColonist && !p.IsSlave, Who(p) + " is not a free colonist after the purchase");
T.Equal(JoinScopes.Bought, JoinDefaults.QueuedFor(p)?.reason, "queued reason");
Fixtures.Tick(1);
CheckMember(p, bought, JoinReason.BoughtColonist);
T.Check(p.outfits.CurrentApparelPolicy == Worker() && p.foodRestriction.CurrentFoodPolicy == Fine(),
Who(p) + " does not have its caste's policies: " + Policies(p));
T.Check(!MessageShown(bought.label), "a join message showed with joinMessages off");
}
// ---- status changes ------------------------------------------------------------------
[BlaxTest("join: GenGuest.EnslavePrisoner puts a prisoner into the new-slave caste")]
public static void EnslavedPrisoner()
{
if (!ModsConfig.IdeologyActive)
T.Skip("needs Ideology (slaves)");
Caste slaves = RowCaste("New slaves join test", SlaveOrSoldier(), Simple());
Caste wrong = FoodCaste("Wrong row (enslaved)", Paste());
Row(JoinReason.NewSlave, slaves);
Row(JoinReason.NewPrisoner, wrong);
Row(JoinReason.BoughtSlave, wrong);
Pawn warden = Fixtures.Colonist();
Pawn p = Fixtures.Prisoner();
GenGuest.EnslavePrisoner(warden, p);
T.Check(p.IsSlaveOfColony, Who(p) + " is not a slave of the colony after EnslavePrisoner");
T.Check(JoinDefaults.IsQueued(p), Who(p) + " was not queued");
T.Check(Fixtures.Comp.MembershipOf(p) == null, "the join was applied before the next tick");
Fixtures.Tick(1);
CheckMember(p, slaves, JoinReason.NewSlave);
T.Check(p.outfits.CurrentApparelPolicy == slaves.ApparelPolicy && p.foodRestriction.CurrentFoodPolicy == Simple(),
Who(p) + " does not have the new-slave caste's policies: " + Policies(p));
}
[BlaxTest("join: RecruitUtility.Recruit moves a prisoner from the prisoner caste into the new-colonist caste")]
public static void RecruitedPrisoner()
{
Caste prisoners = FoodCaste("Prisoners join test", Paste());
Caste colonists = RowCaste("New colonists join test", Worker(), Fine());
Row(JoinReason.NewPrisoner, prisoners);
Row(JoinReason.NewColonist, colonists);
Pawn p = Fixtures.Prisoner();
// In the prisoner caste the way its join would put it (applied directly: see the class comment).
T.Check(CasteManager.Assign(p, prisoners, true, JoinReason.NewPrisoner), "setup: Assign to the prisoner caste failed");
T.Check(p.foodRestriction.CurrentFoodPolicy == Paste(), "setup: the prisoner does not eat the prisoner caste's food");
RecruitUtility.Recruit(p, Faction.OfPlayer, Fixtures.Colonist());
T.Check(p.IsColonist, Who(p) + " is not a colonist after Recruit");
T.Check(JoinDefaults.IsQueued(p), Who(p) + " was not queued");
Fixtures.Tick(1);
CheckMember(p, colonists, JoinReason.NewColonist);
T.Check(p.foodRestriction.CurrentFoodPolicy != Paste(), Who(p) + " still eats the prisoner food");
T.Check(p.foodRestriction.CurrentFoodPolicy == Fine() && p.outfits.CurrentApparelPolicy == Worker(),
Who(p) + " does not have the new-colonist caste's policies: " + Policies(p));
}
[BlaxTest("join: CapturedBy on a downed raider puts it into the new-prisoner caste, after vanilla's medical care reset")]
public static void CapturedRaider()
{
Faction hostile = Fixtures.HostileFaction();
if (hostile == null)
T.Skip("no hostile faction to take a raider from");
Caste captured = FoodCaste("Captured join test", Simple(), MedicalCareCategory.NoMeds);
Row(JoinReason.NewPrisoner, captured);
// Some generated raiders shrug off DamageUntilDowned (pain-blocking genes or implants), so try a few.
Pawn raider = null;
for (int i = 0; i < 5 && raider == null; i++)
{
Pawn candidate = Fixtures.Spawn(Fixtures.Generate(hostile.def.basicMemberKind ?? PawnKindDefOf.Slave, hostile));
HealthUtility.DamageUntilDowned(candidate, allowBleedingWounds: false);
if (candidate.Downed && !candidate.Dead)
raider = candidate;
}
if (raider == null)
T.Skip("no generated raider could be downed alive in 5 tries");
T.Check(raider.Downed, "setup: the raider is not downed");
raider.guest.CapturedBy(Faction.OfPlayer, Fixtures.Colonist());
T.Check(raider.IsPrisonerOfColony, Who(raider) + " is not a prisoner of the colony after CapturedBy");
T.Equal(JoinDefaults.StatusFallback, JoinDefaults.QueuedFor(raider)?.reason, "queued reason");
Fixtures.Tick(1);
CheckMember(raider, captured, JoinReason.NewPrisoner);
T.Check(raider.foodRestriction.CurrentFoodPolicy == Simple(), Who(raider) + " does not eat the caste's food: " + Policies(raider));
T.Equal(MedicalCareCategory.NoMeds, raider.playerSettings.medCare, Who(raider) + "'s medical care");
}
[BlaxTest("join: SetGuestStatus on existing members (null on a colonist, the same status on a slave or prisoner) queues nothing")]
public static void ExistingMembersNotRequeued()
{
Caste c = FoodCaste("Existing members join test", Simple());
var members = new List();
Pawn colonist = Fixtures.Colonist();
members.Add(colonist);
Pawn prisoner = Fixtures.Prisoner();
members.Add(prisoner);
Pawn slave = ModsConfig.IdeologyActive ? Fixtures.ColonySlave() : null;
if (slave != null)
members.Add(slave);
foreach (Pawn p in members)
{
T.Check(CasteManager.Assign(p, c, false, JoinReason.Manual), "setup: Assign failed for " + Who(p));
Unqueue(p);
}
colonist.guest.SetGuestStatus(null);
prisoner.guest.SetGuestStatus(Faction.OfPlayer, GuestStatus.Prisoner);
slave?.guest.SetGuestStatus(Faction.OfPlayer, GuestStatus.Slave);
foreach (Pawn p in members)
{
T.Check(!JoinDefaults.IsQueued(p), Who(p) + " was queued again by a status call that changed nothing");
T.Check(Fixtures.Comp.CasteOf(p) == c, Who(p) + " lost its caste");
}
if (slave == null)
T.Skip("needs Ideology (slaves); the colonist and prisoner checks passed");
}
[BlaxTest("join: a pawn sold between queue and apply is dropped without errors, and a sold member leaves its caste")]
public static void SoldBeforeApply()
{
Caste c = RowCaste("Sold join test", Worker(), Simple());
Row(JoinReason.BoughtColonist, c);
var trader = new TestTrader();
Pawn negotiator = Fixtures.Colonist();
Pawn p = StockPawn(JoinStatus.JoinAsColonist);
Buy(p, negotiator, trader);
T.Check(JoinDefaults.IsQueued(p), "setup: the bought pawn was not queued");
p.PreTraded(TradeAction.PlayerSells, negotiator, trader);
T.Check(p.Faction != Faction.OfPlayer, Who(p) + " is still in the player faction after being sold");
Pawn member = Fixtures.Colonist();
T.Check(CasteManager.Assign(member, c, false, JoinReason.Manual), "setup: Assign failed");
member.PreTraded(TradeAction.PlayerSells, negotiator, trader);
T.Check(Fixtures.Comp.CasteOf(member) == c, "the membership ended inside PreTraded instead of on the next tick");
Fixtures.Tick(1);
T.Check(!JoinDefaults.IsQueued(p), "the sold pawn is still queued");
T.Check(Fixtures.Comp.MembershipOf(p) == null, "the sold pawn got a caste: " + Fixtures.Comp.CasteOf(p));
T.Check(Fixtures.Comp.MembershipOf(member) == null, "the sold member kept its caste");
}
[BlaxTest("join: an exception inside the buy scope leaves the scope stack empty")]
public static void ScopeSurvivesException()
{
MethodInfo preTraded = AccessTools.Method(typeof(Pawn), nameof(Pawn.PreTraded));
Patches info = Harmony.GetPatchInfo(preTraded);
T.Check(info != null && info.Prefixes.Any(x => x.owner == BlaxCastesStartup.HarmonyId) && info.Finalizers.Any(x => x.owner == BlaxCastesStartup.HarmonyId),
"Pawn.PreTraded has no Blax Castes prefix and finalizer");
Pawn p = StockPawn(JoinStatus.JoinAsColonist);
// Without needs, vanilla throws inside PreTraded right after the scope opened.
Pawn_NeedsTracker needs = p.needs;
p.needs = null;
Exception thrown = null;
try
{
p.PreTraded(TradeAction.PlayerBuys, Fixtures.Colonist(), new TestTrader());
}
catch (Exception e)
{
thrown = e;
}
finally
{
p.needs = needs;
}
T.NotNull(thrown, "PreTraded without needs did not throw (vanilla changed); the test needs another way to throw inside the scope");
T.Info("thrown inside the scope: " + thrown.GetType().Name);
T.Equal(0, JoinScopes.Depth, "open join scopes after the exception");
Fixtures.Spawn(p);
// A scope left open inside another is closed with it.
Pawn other = Fixtures.Colonist();
int outer = JoinScopes.Push("outer test scope");
JoinScopes.Push("inner test scope", p);
T.Equal("inner test scope", JoinScopes.ReasonFor(p), "innermost scope for its pawn");
T.Equal("outer test scope", JoinScopes.ReasonFor(other), "scope for another pawn (the inner one is bound to its pawn)");
JoinScopes.Pop(outer);
T.Equal(0, JoinScopes.Depth, "open join scopes after popping the outer scope");
JoinScopes.Pop(0);
T.Equal(0, JoinScopes.Depth, "Pop(0) changed the stack");
}
// ---- rows and settings ---------------------------------------------------------------
[BlaxTest("join: a No caste row takes a recruited prisoner out of its caste and resets its policies; revertOnLeave off keeps them")]
public static void NoCasteReverts()
{
Caste prisoners = FoodCaste("Revert join test", Paste(), MedicalCareCategory.NoMeds);
Row(JoinReason.NewPrisoner, prisoners);
T.Check(CasteManager.SetJoinRow(JoinReason.NewColonist, JoinRowMode.NoCaste), "setup: SetJoinRow failed");
FoodPolicy defaultFood = Current.Game.foodRestrictionDatabase.DefaultFoodRestriction();
T.Check(defaultFood != Paste(), "setup: Paste is the default food policy");
Pawn p = Fixtures.Prisoner();
T.Check(CasteManager.Assign(p, prisoners, true, JoinReason.NewPrisoner), "setup: Assign failed");
T.Equal(MedicalCareCategory.NoMeds, p.playerSettings.medCare, "setup: prisoner's medical care");
RecruitUtility.Recruit(p, Faction.OfPlayer);
Fixtures.Tick(1);
T.Check(Fixtures.Comp.MembershipOf(p) == null, Who(p) + " is still in " + Fixtures.Comp.CasteOf(p));
T.Check(p.foodRestriction.CurrentFoodPolicy == defaultFood, Who(p) + "'s food did not return to the default: " + Policies(p));
T.Equal(Find.PlaySettings.defaultCareForColonist, p.playerSettings.medCare, Who(p) + "'s medical care after the revert");
Fixtures.Settings.revertOnLeave = false;
Pawn kept = Fixtures.Prisoner();
T.Check(CasteManager.Assign(kept, prisoners, true, JoinReason.NewPrisoner), "setup: Assign failed");
RecruitUtility.Recruit(kept, Faction.OfPlayer);
Fixtures.Tick(1);
T.Check(Fixtures.Comp.MembershipOf(kept) == null, Who(kept) + " is still in " + Fixtures.Comp.CasteOf(kept));
T.Check(kept.foodRestriction.CurrentFoodPolicy == Paste(), Who(kept) + " lost the caste's food with revertOnLeave off: " + Policies(kept));
}
[BlaxTest("join: with join defaults off, buying, capturing and recruiting queue nothing")]
public static void DisabledQueuesNothing()
{
Caste c = RowCaste("Disabled join test", Worker(), Fine());
foreach (string reason in JoinReason.Rows)
Row(reason, c);
Fixtures.Settings.enableJoinDefaults = false;
Pawn bought = StockPawn(JoinStatus.JoinAsColonist);
Buy(bought, Fixtures.Colonist(), new TestTrader());
Pawn prisoner = Fixtures.Prisoner();
T.Check(!JoinDefaults.IsQueued(prisoner), "a captured prisoner was queued with join defaults off");
RecruitUtility.Recruit(prisoner, Faction.OfPlayer);
JoinDefaults.Enqueue(bought, JoinReason.NewColonist);
foreach (Pawn p in new[] { bought, prisoner })
T.Check(!JoinDefaults.IsQueued(p), Who(p) + " was queued with join defaults off");
Fixtures.Settings.enableJoinDefaults = true;
Fixtures.Settings.enabled = false;
JoinDefaults.Enqueue(bought, JoinReason.NewColonist);
T.Check(!JoinDefaults.IsQueued(bought), "a pawn was queued with Castes off");
Fixtures.Tick(1);
foreach (Pawn p in new[] { bought, prisoner })
T.Check(Fixtures.Comp.MembershipOf(p) == null, Who(p) + " got a caste with join defaults off");
}
[BlaxTest("join: a specific reason beats a status fallback when a pawn is queued twice; reasons resolve to rows by final status")]
public static void SpecificBeatsFallback()
{
Pawn p = Fixtures.Colonist();
Unqueue(p);
JoinDefaults.Enqueue(p, JoinDefaults.StatusFallback);
T.Equal(JoinDefaults.StatusFallback, JoinDefaults.QueuedFor(p)?.reason, "first reason");
JoinDefaults.Enqueue(p, JoinScopes.Bought);
T.Equal(JoinScopes.Bought, JoinDefaults.QueuedFor(p)?.reason, "reason after a specific one");
JoinDefaults.Enqueue(p, JoinDefaults.StatusFallback);
T.Equal(JoinScopes.Bought, JoinDefaults.QueuedFor(p)?.reason, "reason after a second status fallback");
T.Equal(1, Fixtures.Comp.JoinQueue.Count(q => q != null && q.pawn == p), "queue entries for one pawn");
Unqueue(p);
T.Equal(JoinReason.BoughtColonist, JoinDefaults.RowFor(JoinScopes.Bought, p), "bought colonist row");
T.Equal(JoinReason.NewColonist, JoinDefaults.RowFor(JoinDefaults.StatusFallback, p), "status row of a colonist");
T.Equal(JoinReason.NewSlave, JoinDefaults.RowFor(JoinReason.NewSlave, p), "a row id resolves to itself");
Pawn prisoner = Fixtures.Prisoner();
T.Equal(JoinReason.NewPrisoner, JoinDefaults.RowFor(JoinDefaults.StatusFallback, prisoner), "status row of a prisoner");
T.Equal(JoinReason.NewPrisoner, JoinDefaults.RowFor(JoinScopes.Bought, prisoner), "bought row of a prisoner falls back to its status");
Unqueue(prisoner);
if (!ModsConfig.IdeologyActive)
T.Skip("needs Ideology (slaves); colonist and prisoner rows passed");
Pawn slave = Fixtures.ColonySlave();
T.Equal(JoinReason.BoughtSlave, JoinDefaults.RowFor(JoinScopes.Bought, slave), "bought slave row");
T.Equal(JoinReason.NewSlave, JoinDefaults.RowFor(JoinDefaults.StatusFallback, slave), "status row of a slave");
Unqueue(slave);
}
[BlaxTest("join: babies and quest lodgers are never queued")]
public static void BabiesAndLodgersSkipped()
{
Pawn lodger = Fixtures.QuestLodger();
JoinDefaults.Enqueue(lodger, JoinDefaults.StatusFallback);
T.Check(!JoinDefaults.IsQueued(lodger), "a quest lodger was queued");
if (!ModsConfig.BiotechActive)
T.Skip("needs Biotech (babies); the lodger check passed");
Pawn baby = Fixtures.Baby();
JoinDefaults.Enqueue(baby, JoinDefaults.StatusFallback);
T.Check(!JoinDefaults.IsQueued(baby), "a baby was queued");
Faction other = Fixtures.FriendlyFaction();
T.NotNull(other, "a friendly faction");
Pawn foreignBaby = Fixtures.Spawn(Fixtures.Generate(PawnKindDefOf.Colonist, other, DevelopmentalStage.Baby));
foreignBaby.SetFaction(Faction.OfPlayer);
T.Check(!JoinDefaults.IsQueued(foreignBaby), "a baby that joined the colony was queued");
}
[BlaxTest("join: a caste picked by hand before the join is applied wins over the row")]
public static void HandPickWins()
{
Caste rowCaste = FoodCaste("Row caste (hand pick test)", Paste());
Caste handCaste = FoodCaste("Hand caste (hand pick test)", Fine());
Row(JoinReason.BoughtColonist, rowCaste);
Pawn p = StockPawn(JoinStatus.JoinAsColonist);
Buy(p, Fixtures.Colonist(), new TestTrader());
T.Check(JoinDefaults.IsQueued(p), "setup: the bought pawn was not queued");
T.Check(CasteManager.Assign(p, handCaste, false, JoinReason.Manual), "setup: Assign failed");
Fixtures.Tick(1);
T.Check(Fixtures.Comp.CasteOf(p) == handCaste, Who(p) + " is in " + Fixtures.Comp.CasteOf(p) + ", not the hand-picked caste");
T.Check(p.foodRestriction.CurrentFoodPolicy == Fine(), Who(p) + " lost the hand-picked caste's food: " + Policies(p));
}
[BlaxTest("join defaults window: rows, picker labels, menu entries and strings")]
public static void Window()
{
T.NotNull(new Dialog_JoinDefaults(), "new Dialog_JoinDefaults()");
List rows = Dialog_JoinDefaults.VisibleRows();
T.Equal(ModsConfig.IdeologyActive ? 5 : 3, rows.Count, "rows shown");
Caste c = FoodCaste("Window join test", Simple());
Caste other = FoodCaste("Window join test default", Fine());
CasteManager.SetDefault(null);
const string reason = JoinReason.NewColonist;
List menu = Dialog_JoinDefaults.RowMenu(reason);
T.Equal(2 + Fixtures.Comp.Castes.Count, menu.Count, "menu entries (No caste, Default caste, one per caste)");
List casteLabels = menu.Skip(2).Select(o => o.Label).ToList();
T.Check(casteLabels.SequenceEqual(casteLabels.OrderBy(l => l, StringComparer.CurrentCultureIgnoreCase)),
"castes not sorted by label like the Caste column: " + string.Join(", ", casteLabels));
menu.First(o => o.Label == c.label).action();
T.Check(Fixtures.Comp.ResolveRow(reason) == c, "picking a caste did not set the row");
T.Equal(c.label, Dialog_JoinDefaults.RowButtonLabel(reason), "picker label for a caste");
menu[1].action();
T.Equal(JoinRowMode.DefaultCaste, Fixtures.Comp.GetRow(reason).mode, "row mode after picking Default caste");
T.Equal((string)"BlaxCastes_DefaultCasteNone".Translate(), Dialog_JoinDefaults.RowButtonLabel(reason), "picker label with no default set");
CasteManager.SetDefault(other);
T.Check(Dialog_JoinDefaults.RowButtonLabel(reason).Contains(other.label), "picker label does not name the default caste");
menu[0].action();
T.Equal(JoinRowMode.NoCaste, Fixtures.Comp.GetRow(reason).mode, "row mode after picking No caste");
T.Equal((string)"BlaxCastes_NoCaste".Translate(), Dialog_JoinDefaults.RowButtonLabel(reason), "picker label for No caste");
Pawn a = Fixtures.Colonist(), b = Fixtures.Colonist();
string one = JoinDefaults.MessageText(c, new List { a });
string two = JoinDefaults.MessageText(c, new List { a, b });
T.Check(one.Contains(a.LabelShort) && one.Contains(c.label), "single join message: " + one);
T.Check(two.Contains(a.LabelShort) && two.Contains(b.LabelShort) && two.Contains("2") && two.Contains(c.label), "grouped join message: " + two);
var keys = new List
{
"BlaxCastes_JoinDefaultsDesc", "BlaxCastes_JoinDefaultsOff", "BlaxCastes_JoinDefaultsNoCastes",
"BlaxCastes_DefaultCasteNamed", "BlaxCastes_DefaultCasteNone", "BlaxCastes_JoinedCaste", "BlaxCastes_JoinedCasteMany",
};
keys.AddRange(JoinReason.Rows.Select(r => "BlaxCastes_RowTip_" + r));
List missing = keys.Where(k => !k.CanTranslate()).ToList();
T.Check(missing.Count == 0, "strings missing from Keyed: " + string.Join(", ", missing));
}
// ---- other mods ----------------------------------------------------------------------
[BlaxTest("join compat: a buy-mode slave or colonist choice (Blax Slaves or Trade as Slave or Colonist) lands in the right bought row")]
public static void BuyModeChoice()
{
if (!ModsConfig.IdeologyActive)
T.Skip("needs Ideology (slaves)");
bool tasoc = Compat.IsActive(TaSoC);
bool slaves = Compat.IsActive(Compat.BlaxSlaves);
if (!tasoc && !slaves)
T.Skip("neither Blax Slaves nor Trade as Slave or Colonist is active (run with -Compat)");
Caste slaveCaste = RowCaste("Bought slaves (buy mode test)", SlaveOrSoldier(), Simple());
Caste colonistCaste = RowCaste("Bought colonists (buy mode test)", Worker(), Fine());
Row(JoinReason.BoughtSlave, slaveCaste);
Row(JoinReason.BoughtColonist, colonistCaste);
Row(JoinReason.NewSlave, colonistCaste);
Row(JoinReason.NewColonist, slaveCaste);
// Stock that starts the other way, so the choice has to flip it.
Pawn toSlave = StockPawn(JoinStatus.JoinAsColonist);
Pawn toColonist = StockPawn(JoinStatus.JoinAsSlave);
Pawn negotiator = Fixtures.Colonist();
var trader = new TestTrader();
T.NotNull(trader.TraderKind, "a trader kind");
ITrader oldTrader = TradeSession.trader;
Pawn oldNegotiator = TradeSession.playerNegotiator;
TradeDeal oldDeal = TradeSession.deal;
bool oldGift = TradeSession.giftMode;
try
{
TradeSession.trader = trader;
TradeSession.playerNegotiator = negotiator;
TradeSession.deal = null;
TradeSession.giftMode = false;
foreach ((Pawn pawn, bool wantSlave) in new[] { (toSlave, true), (toColonist, false) })
{
var tradeable = new Tradeable_Pawn();
tradeable.AddThing(pawn, Transactor.Trader);
if (tasoc)
ChooseWithTaSoC(tradeable, pawn, wantSlave);
else
ChooseWithBlaxSlaves(tradeable, pawn, wantSlave);
tradeable.ForceToSource(1);
T.Equal(TradeAction.PlayerBuys, tradeable.ActionToDo, "trade action for " + Who(pawn));
tradeable.ResolveTrade();
T.Check(pawn.IsSlaveOfColony == wantSlave, Who(pawn) + (wantSlave ? " did not join as slave" : " did not join as colonist"));
T.Equal(JoinScopes.Bought, JoinDefaults.QueuedFor(pawn)?.reason, Who(pawn) + "'s queued reason");
Fixtures.Spawn(pawn);
}
}
finally
{
TradeSession.trader = oldTrader;
TradeSession.playerNegotiator = oldNegotiator;
TradeSession.deal = oldDeal;
TradeSession.giftMode = oldGift;
}
T.Info("buy mode driven through " + (tasoc ? "Trade as Slave or Colonist" : "Blax Slaves"));
Fixtures.Tick(1);
CheckMember(toSlave, slaveCaste, JoinReason.BoughtSlave);
CheckMember(toColonist, colonistCaste, JoinReason.BoughtColonist);
}
/// Trade as Slave or Colonist keeps the choice per trade row and sets joinStatus only during ResolveTrade.
private static void ChooseWithTaSoC(Tradeable tradeable, Pawn pawn, bool wantSlave)
{
MethodInfo getOrCreate = AccessTools.Method("TradeAsSlaveOrColonist.Choices:GetOrCreate");
T.NotNull(getOrCreate, "TradeAsSlaveOrColonist.Choices.GetOrCreate (mod updated?)");
object selection = getOrCreate.Invoke(null, new object[] { tradeable, pawn });
T.NotNull(selection, "Trade as Slave or Colonist selection");
FieldInfo mode = AccessTools.Field(selection.GetType(), "Mode");
T.NotNull(mode, "Selection.Mode (mod updated?)");
mode.SetValue(selection, wantSlave ? JoinStatus.JoinAsSlave : JoinStatus.JoinAsColonist);
}
/// Blax Slaves' buy mode flips joinStatus on the pawn, as its trade-row button does.
private static void ChooseWithBlaxSlaves(Tradeable tradeable, Pawn pawn, bool wantSlave)
{
MethodInfo toggle = AccessTools.Method("BlaxSlaves.BuyMode:Toggle");
T.NotNull(toggle, "BlaxSlaves.BuyMode.Toggle");
bool isSlave = pawn.guest.joinStatus == JoinStatus.JoinAsSlave;
if (isSlave != wantSlave)
T.Check((bool)toggle.Invoke(null, new object[] { tradeable }), "Blax Slaves refused to switch " + Who(pawn) + " (buy mode off in its settings?)");
T.Equal(wantSlave ? JoinStatus.JoinAsSlave : JoinStatus.JoinAsColonist, pawn.guest.joinStatus, Who(pawn) + "'s joinStatus after the switch");
}
// ---- save and reload -----------------------------------------------------------------
// Runs last in this class (source order): the queued join is checked after the reload.
[BlaxTest("join: set up a queued join for the reload")]
public static void ReloadSetup()
{
Fixtures.KeepCasteState();
Caste c = Fixtures.KeepCaste(RowCaste("Reload join test", Worker(), Fine()));
Row(JoinReason.BoughtColonist, c);
Pawn p = Fixtures.Keep(StockPawn(JoinStatus.JoinAsColonist));
Buy(p, Fixtures.Colonist(), new TestTrader());
QueuedJoin q = JoinDefaults.QueuedFor(p);
T.NotNull(q, "setup: the bought pawn was not queued");
T.Check(Fixtures.Comp.MembershipOf(p) == null, "setup: the join was applied before the save");
// Queued "on an earlier tick", so phase 2 can apply it without ticking the kept fixture prisoners.
q.tick--;
T.Carry["joinPawn"] = p.ThingID;
T.Carry["joinCaste"] = c.id.ToString();
}
[BlaxTest("join: a join queued before saving survives the reload and is applied", phase: 2)]
public static void QueuedJoinSurvives()
{
string casteId = null;
T.Check(T.Carry.TryGetValue("joinPawn", out string pawnId) && T.Carry.TryGetValue("joinCaste", out casteId), "phase 1 setup did not run");
Pawn p = Fixtures.FindPawnById(pawnId);
T.NotNull(p, "the bought pawn after reload");
Caste c = Fixtures.Comp.Castes.FirstOrDefault(x => x.id.ToString() == casteId);
T.NotNull(c, "the join test caste after reload");
QueuedJoin q = JoinDefaults.QueuedFor(p);
if (q != null)
{
T.Equal(JoinScopes.Bought, q.reason, "queued reason after reload");
JoinDefaults.ApplyQueue();
}
else
{
T.Info("the game ticked after the reload; the join was already applied");
}
T.Check(!JoinDefaults.IsQueued(p), Who(p) + " is still queued");
CheckMember(p, c, JoinReason.BoughtColonist);
T.Check(p.foodRestriction.CurrentFoodPolicy == c.FoodPolicy && p.outfits.CurrentApparelPolicy == c.ApparelPolicy,
Who(p) + " does not have the caste's policies after the reload: " + Policies(p));
}
}
}