754 lines
36 KiB
C#
754 lines
36 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using System.Reflection;
|
|
using System.Text.RegularExpressions;
|
|
using BlaxLaws;
|
|
using RimWorld;
|
|
using RimWorld.Planet;
|
|
using UnityEngine;
|
|
using Verse;
|
|
|
|
namespace BlaxLawsTests
|
|
{
|
|
/// <summary>
|
|
/// Marks a public static void method without parameters as a test. Phase 1 runs in a fresh quick-test
|
|
/// colony. Phase 2 runs after the runner saved that game and loaded it again. Phase 3 runs after the
|
|
/// runner saved again, replaced the GameComponent_BlaxLaws class in the save with one that doesn't exist
|
|
/// and loaded that: the vanilla side of a save whose mod was removed.
|
|
/// </summary>
|
|
[AttributeUsage(AttributeTargets.Method)]
|
|
public sealed class BlaxTestAttribute : Attribute
|
|
{
|
|
public readonly string Name;
|
|
public readonly int Phase;
|
|
|
|
/// <summary>
|
|
/// Where the test runs in its phase: below 0 before the others, above 0 after them; 0 by default. Tests
|
|
/// with the same order run in class name order. A phase-2 test that needs the game as the save left it,
|
|
/// before another phase-2 test ticks it, runs first.
|
|
/// </summary>
|
|
public int Order { get; set; }
|
|
|
|
public BlaxTestAttribute(string name, int phase = 1)
|
|
{
|
|
Name = name;
|
|
Phase = phase;
|
|
}
|
|
}
|
|
|
|
public class TestFailure : Exception
|
|
{
|
|
public TestFailure(string message) : base(message) { }
|
|
}
|
|
|
|
public class TestSkipped : Exception
|
|
{
|
|
public TestSkipped(string message) : base(message) { }
|
|
}
|
|
|
|
/// <summary>Assertions and notes for test bodies.</summary>
|
|
public static class T
|
|
{
|
|
/// <summary>Values carried from phase 1 into phases 2 and 3. Store ThingIDs, ids or def names, never objects.</summary>
|
|
public static readonly Dictionary<string, string> Carry = new Dictionary<string, string>();
|
|
|
|
/// <summary>Carry values read right before the first save, after every phase-1 test ran.</summary>
|
|
internal static readonly Dictionary<string, Func<string>> CarryAtSaveTime = new Dictionary<string, Func<string>>();
|
|
|
|
/// <summary>Carries a value read right before the save instead of now, for state later phase-1 tests may still change.</summary>
|
|
public static void CarryAtSave(string key, Func<string> read) => CarryAtSaveTime[key] = read;
|
|
|
|
public static void Check(bool condition, string message)
|
|
{
|
|
if (!condition) throw new TestFailure(message);
|
|
}
|
|
|
|
public static void Equal<TV>(TV expected, TV actual, string what)
|
|
{
|
|
if (!EqualityComparer<TV>.Default.Equals(expected, actual))
|
|
throw new TestFailure($"{what}: expected {Show(expected)}, got {Show(actual)}");
|
|
}
|
|
|
|
public static void NotNull(object value, string what)
|
|
{
|
|
if (value == null) throw new TestFailure(what + " is null");
|
|
}
|
|
|
|
public static void Fail(string message) => throw new TestFailure(message);
|
|
|
|
public static void Skip(string reason) => throw new TestSkipped(reason);
|
|
|
|
/// <summary>Skips the test unless the DLC is active, with "needs <DLC>" as the reason.</summary>
|
|
public static void NeedsDlc(string dlc, bool active)
|
|
{
|
|
if (!active) throw new TestSkipped("needs " + dlc);
|
|
}
|
|
|
|
/// <summary>Adds an INFO line under the current test in the results file.</summary>
|
|
public static void Info(string message) => TestRunner.Note(message);
|
|
|
|
/// <summary>
|
|
/// Expects exactly <paramref name="count"/> errors whose text contains <paramref name="fragment"/>,
|
|
/// logged during this test or, in phase 3, during the phase-3 load. Checked when the test ends, so call
|
|
/// it before or after the action. Matching errors are excused: they never count as Blax Laws errors,
|
|
/// here or as stray errors. Several tests may expect the same errors.
|
|
/// </summary>
|
|
public static void ExpectErrors(string fragment, int count) => TestRunner.Expect(fragment, count);
|
|
|
|
/// <summary>Error texts (one line each) logged while the phase-3 save loaded. Empty before phase 3.</summary>
|
|
public static List<string> Phase3LoadErrors => TestRunner.LoadErrors();
|
|
|
|
/// <summary>"Could not resolve reference" warnings logged while the phase-3 save loaded.</summary>
|
|
public static int Phase3ResolveWarnings => TestRunner.ResolveWarnings;
|
|
|
|
/// <summary>"Could not resolve reference" warnings (one line each) logged while the phase-1 save loaded for phase 2.</summary>
|
|
public static List<string> Phase2ResolveWarnings => TestRunner.Phase2Warnings();
|
|
|
|
/// <summary>
|
|
/// The warning names a pawn vanilla's TaleData_Pawn.GenerateRandom made for a book or tale and never
|
|
/// saved (a vanilla leak, see TestRunner.vanillaTalePawns), not anything Blax Laws saved.
|
|
/// </summary>
|
|
public static bool NamesVanillaTalePawn(string warning) => TestRunner.NamesVanillaTalePawn(warning);
|
|
|
|
/// <summary>
|
|
/// The warning names a pawn a relation already pointed at, with no save holding it, when the suite
|
|
/// began (left by the world's generation, see TestRunner.unsavedAtStart), not anything Blax Laws saved.
|
|
/// </summary>
|
|
public static bool NamesPawnUnsavedAtStart(string warning) => TestRunner.NamesPawnUnsavedAtStart(warning);
|
|
|
|
/// <summary>
|
|
/// The warning is about a vanilla RelationshipRecord's reference to a pawn no save held right before the
|
|
/// phase-1 save (see TestRunner.unsavedRecordPawns), never a pawn a Blax Laws case names.
|
|
/// </summary>
|
|
public static bool NamesVanillaRelationshipRecordPawn(string warning) => TestRunner.NamesVanillaRelationshipRecordPawn(warning);
|
|
|
|
private static string Show(object o) => o == null ? "null" : o.ToString();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Drives the suite when the game runs with -quicktest -blaxlawstests: phase 1, save, load, phase 2, save,
|
|
/// strip the component class, load, phase 3, then writes BlaxLawsTestResults.txt into the save data
|
|
/// folder and quits.
|
|
/// </summary>
|
|
public class TestRunner : GameComponent
|
|
{
|
|
public const string SaveName = "BlaxLawsTest";
|
|
public const string Phase3SaveName = "BlaxLawsTest3";
|
|
public const string ResultFile = "BlaxLawsTestResults.txt";
|
|
|
|
/// <summary>The class attribute phase 3 replaces in the save.</summary>
|
|
public const string ComponentClassAttr = "Class=\"BlaxLaws.GameComponent_BlaxLaws\"";
|
|
|
|
/// <summary>A class that doesn't exist; the phase-3 save names it instead of GameComponent_BlaxLaws.</summary>
|
|
public const string RemovedComponentClass = "BlaxLawsRemoved.GameComponent_BlaxLaws";
|
|
|
|
/// <summary>Where errors logged during the phase-3 load are filed.</summary>
|
|
public const string Phase3LoadTag = "(phase 3 load)";
|
|
|
|
/// <summary>Where errors logged while the phase-1 save loads for phase 2 are filed.</summary>
|
|
public const string Phase2LoadTag = "(phase 2 load)";
|
|
|
|
private class LogEntry
|
|
{
|
|
public string where;
|
|
public string text;
|
|
public bool ours;
|
|
public bool excused;
|
|
public bool warning;
|
|
}
|
|
|
|
private static int stage; // 0 waiting, 1 phase 1 done + reload queued, 2 phase 2 done + phase-3 load queued, 3 finished
|
|
private static int loadsSeen;
|
|
private static int pass, fail, skip;
|
|
private static string currentTest;
|
|
private static readonly List<LogEntry> errors = new List<LogEntry>();
|
|
private static readonly List<(string fragment, int count)> expectations = new List<(string, int)>();
|
|
private static int resolveWarnings;
|
|
private static readonly List<string> phase2Warnings = new List<string>();
|
|
private static readonly HashSet<string> danglingSeen = new HashSet<string>();
|
|
private static bool hooked;
|
|
private int settleFrames;
|
|
|
|
public static bool Enabled => GenCommandLine.CommandLineArgPassed("blaxlawstests");
|
|
|
|
public static string ResultPath => Path.Combine(GenFilePaths.SaveDataFolderPath, ResultFile);
|
|
|
|
/// <summary>Component nodes phase 3 replaced in the save. Set before the phase-3 load.</summary>
|
|
public static int Phase3ReplacedCount { get; private set; }
|
|
|
|
public static int ResolveWarnings => resolveWarnings;
|
|
|
|
public TestRunner(Game game) { }
|
|
|
|
public override void LoadedGame()
|
|
{
|
|
if (Enabled && (stage == 1 || stage == 2)) loadsSeen++;
|
|
}
|
|
|
|
public override void GameComponentUpdate()
|
|
{
|
|
if (!Enabled || stage == 3) return;
|
|
if (LongEventHandler.AnyEventNowOrWaiting || Find.CurrentMap == null) return;
|
|
if (++settleFrames < 30) return;
|
|
|
|
if (stage == 0)
|
|
{
|
|
stage = 1;
|
|
Begin();
|
|
RunPhase(1);
|
|
Line("STAGE save+reload");
|
|
try
|
|
{
|
|
foreach (var kv in T.CarryAtSaveTime)
|
|
{
|
|
try { T.Carry[kv.Key] = kv.Value(); }
|
|
catch (Exception e) { Note("carry " + kv.Key + " failed: " + e.Message); }
|
|
}
|
|
Fixtures.RestoreBystanderBonds();
|
|
NoteDanglingRelations();
|
|
NoteRelationshipRecords();
|
|
GameDataSaveLoader.SaveGame(SaveName);
|
|
lock (errors) phase2Warnings.Clear();
|
|
currentTest = Phase2LoadTag;
|
|
GameDataSaveLoader.LoadGame(SaveName);
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
currentTest = null;
|
|
Record("FAIL", "save and reload", e.ToString());
|
|
Finish();
|
|
}
|
|
}
|
|
else if (stage == 1 && loadsSeen >= 1)
|
|
{
|
|
stage = 2;
|
|
currentTest = null;
|
|
Line("STAGE phase 2 (after reload)");
|
|
Note("phase 2 load: " + Phase2Warnings().Count + " 'Could not resolve reference' warning(s)");
|
|
RunPhase(2);
|
|
Line("STAGE phase 3 (component class removed from the save)");
|
|
try
|
|
{
|
|
StartPhase3Load();
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
currentTest = null;
|
|
Record("FAIL", "phase 3 save and load", e.ToString());
|
|
Finish();
|
|
}
|
|
}
|
|
else if (stage == 2 && loadsSeen >= 2)
|
|
{
|
|
currentTest = null;
|
|
Note("phase 3 load: " + Phase3ReplacedCount + " component node(s) replaced, " + LoadErrors().Count + " error(s), " +
|
|
resolveWarnings + " 'Could not resolve reference' warning(s)");
|
|
RunPhase(3);
|
|
Finish();
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Saves as BlaxLawsTest3 (saves are plain XML in 1.7, ScribeSaver.cs:45-49), replaces the component's
|
|
/// class with one that doesn't exist and loads it. Laws' assembly stays loaded, so Game.FillComponents
|
|
/// adds a fresh, empty component after the load.
|
|
/// </summary>
|
|
private static void StartPhase3Load()
|
|
{
|
|
GameDataSaveLoader.SaveGame(Phase3SaveName);
|
|
string path = GenFilePaths.FilePathForSavedGame(Phase3SaveName);
|
|
string xml = File.ReadAllText(path);
|
|
int count = 0;
|
|
for (int i = xml.IndexOf(ComponentClassAttr, StringComparison.Ordinal); i >= 0; i = xml.IndexOf(ComponentClassAttr, i + 1, StringComparison.Ordinal))
|
|
count++;
|
|
if (count == 0)
|
|
throw new Exception("the phase-3 save holds no " + ComponentClassAttr);
|
|
Phase3ReplacedCount = count;
|
|
File.WriteAllText(path, xml.Replace(ComponentClassAttr, "Class=\"" + RemovedComponentClass + "\""));
|
|
lock (errors) resolveWarnings = 0;
|
|
currentTest = Phase3LoadTag;
|
|
GameDataSaveLoader.LoadGame(Phase3SaveName);
|
|
}
|
|
|
|
/// <summary>The game log as it stood when the suite began, before any test ran (the startup test reads it).</summary>
|
|
public static List<LogMessage> StartupLog { get; private set; } = new List<LogMessage>();
|
|
|
|
/// <summary>
|
|
/// The new game as it stood when the suite began, before any test ran: rows, cases, the watch flags and
|
|
/// the enforcement queue. Test classes run in name order, so the empty-book test reads this instead of
|
|
/// the state other tests left behind.
|
|
/// </summary>
|
|
public static NewGameState AtStart { get; private set; }
|
|
|
|
public sealed class NewGameState
|
|
{
|
|
public int laws, cases, pending;
|
|
public bool watchAny, categoryFlag, specialFlag;
|
|
}
|
|
|
|
private static void Begin()
|
|
{
|
|
try { File.Delete(ResultPath); } catch { }
|
|
StartupLog = Log.Messages.ToList();
|
|
GameComponent_BlaxLaws comp = GameComponent_BlaxLaws.Instance;
|
|
AtStart = new NewGameState
|
|
{
|
|
laws = comp?.Laws.Count ?? -1,
|
|
cases = comp?.Cases.Count ?? -1,
|
|
pending = Enforcement.Pending,
|
|
watchAny = Watch.Any,
|
|
categoryFlag = Watch.Break || Watch.Ate || Watch.Used || Watch.Interaction || Watch.RecordedAct || Watch.Record || Watch.Bill || Watch.Special,
|
|
specialFlag = Watch.SetFire || Watch.DisplayedCorpse || Watch.StartedSocialFight,
|
|
};
|
|
HookLog();
|
|
HookPawnWatchers();
|
|
Line("BEGIN Blax Laws in-game tests, RimWorld " + VersionControl.CurrentVersionStringWithRev);
|
|
Line("DLCs: Royalty " + ModsConfig.RoyaltyActive + ", Ideology " + ModsConfig.IdeologyActive + ", Biotech " + ModsConfig.BiotechActive +
|
|
", Anomaly " + ModsConfig.AnomalyActive + ", Odyssey " + ModsConfig.OdysseyActive);
|
|
Fixtures.QuietStoryteller();
|
|
Fixtures.StripBystanderBonds();
|
|
Find.TickManager.CurTimeSpeed = TimeSpeed.Paused;
|
|
NoteUnsavedAtStart();
|
|
}
|
|
|
|
private static void HookLog()
|
|
{
|
|
if (hooked) return;
|
|
hooked = true;
|
|
Application.logMessageReceivedThreaded += (text, stack, type) =>
|
|
{
|
|
if (type == LogType.Warning)
|
|
{
|
|
if (text != null && text.Contains("Could not resolve reference"))
|
|
{
|
|
if (currentTest == Phase3LoadTag)
|
|
lock (errors) resolveWarnings++;
|
|
else if (currentTest == Phase2LoadTag)
|
|
lock (errors) phase2Warnings.Add(OneLine(text));
|
|
}
|
|
// Blax Laws' own warnings ("[Blax Laws] ...") between tests count as stray mod warnings.
|
|
if (text != null && text.Contains("[Blax Laws]"))
|
|
lock (errors) errors.Add(new LogEntry { where = currentTest ?? "(between tests)", text = OneLine(text), ours = true, warning = true });
|
|
return;
|
|
}
|
|
if (type != LogType.Error && type != LogType.Exception) return;
|
|
bool ours = !IsKnownForeignError(text, stack)
|
|
&& ((text != null && (text.Contains("BlaxLaws") || text.Contains("Blax Laws"))) || (stack != null && stack.Contains("BlaxLaws")));
|
|
var entry = new LogEntry { where = currentTest ?? "(between tests)", text = OneLine(text), ours = ours };
|
|
lock (errors) errors.Add(entry);
|
|
};
|
|
}
|
|
|
|
/// <summary>
|
|
/// Errors another mod logs from its own code while a test ticks the game. The test's frames are in the
|
|
/// stack, so the check above would blame Blax Laws; these show as LOGERR lines instead. Each entry is a
|
|
/// text fragment and the frame that logs it. Add one per mod, with the reason, as Zones does:
|
|
/// - Prison Labor (-Compat): its postfix on Pawn_GuestTracker.SetGuestStatus passes its own
|
|
/// PrisonLabor_workOption, a non-exclusive mode in 1.7, to SetExclusiveInteraction, so the game logs
|
|
/// "Attempted to set guest exclusive interaction to a non-exclusive interaction type" once for the
|
|
/// first pawn made a prisoner (the prisoner fixture).
|
|
/// - Prisoner Realism (-Compat): HediffComp_Solitary ticks on a prisoner the release job carries
|
|
/// (JobDriver_ReleasePrisoner.cs:27), and SolitaryUtility.IsInSolitary passes pawn.Map, null while it is
|
|
/// carried, to GetDoor (its Source/Features/Solitary/SolitaryUtility.cs:56-59): an NRE the game logs as
|
|
/// "Exception ticking hediff (PR_Solitary ...)" whenever a warden releases a prisoner from a cell.
|
|
/// </summary>
|
|
private static readonly (string text, string frame)[] KnownForeignErrors =
|
|
{
|
|
("non-exclusive interaction type: PrisonLabor_", "Patch_DefaultInteractionMode"),
|
|
("PrisonerRealism.SolitaryUtility.IsInSolitary", "Pawn_HealthTracker.HealthTick"),
|
|
};
|
|
|
|
private static bool IsKnownForeignError(string text, string stack)
|
|
{
|
|
if (text == null || stack == null)
|
|
return false;
|
|
foreach (var (fragment, frame) in KnownForeignErrors)
|
|
{
|
|
if (text.Contains(fragment) && stack.Contains(frame))
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
internal static void Expect(string fragment, int count)
|
|
{
|
|
if (fragment.NullOrEmpty()) throw new TestFailure("ExpectErrors needs a text fragment");
|
|
expectations.Add((fragment, count));
|
|
}
|
|
|
|
internal static List<string> LoadErrors()
|
|
{
|
|
lock (errors) return errors.Where(e => e.where == Phase3LoadTag && !e.warning).Select(e => e.text).ToList();
|
|
}
|
|
|
|
internal static List<string> Phase2Warnings()
|
|
{
|
|
lock (errors) return phase2Warnings.ToList();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Notes every pawn relation, new since the last check, whose other pawn no save holds (discarded, or
|
|
/// on no map, in no container and not a world pawn). Each one becomes a "Could not resolve reference"
|
|
/// warning when the save loads. Runs after every test and once more right before the phase-1 save.
|
|
/// Pawns vanilla made for books and tales are left out here (see vanillaTalePawns); the reload test
|
|
/// counts them.
|
|
/// </summary>
|
|
private static void NoteDanglingRelations()
|
|
{
|
|
try
|
|
{
|
|
foreach (var (p, r, o) in DanglingRelations())
|
|
{
|
|
if (!danglingSeen.Add(p.ThingID + ">" + (o?.ThingID ?? "null")))
|
|
continue;
|
|
if (o != null && (IsVanillaTalePawn(o.ThingID) || IsUnsavedAtStart(o.ThingID)))
|
|
continue;
|
|
Note("dangling relation: " + p.ThingID + " (" + p.LabelShort + ", " + (p.Faction?.GetUniqueLoadID() ?? "no faction") + ") " +
|
|
r.def.defName + " -> " + Describe(o));
|
|
}
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
Note("relation check threw: " + OneLine(e.Message));
|
|
}
|
|
}
|
|
|
|
/// <summary>Every pawn relation whose other pawn no save holds (discarded, or on no map, in no container and not a world pawn).</summary>
|
|
private static List<(Pawn p, DirectPawnRelation r, Pawn o)> DanglingRelations()
|
|
{
|
|
var found = new List<(Pawn, DirectPawnRelation, Pawn)>();
|
|
var all = new HashSet<Pawn>(PawnsFinder.All_AliveOrDead);
|
|
foreach (Pawn p in all.ToList())
|
|
{
|
|
if (p?.relations == null)
|
|
continue;
|
|
foreach (DirectPawnRelation r in p.relations.DirectRelations)
|
|
{
|
|
Pawn o = r.otherPawn;
|
|
if (o != null && !o.Discarded && all.Contains(o))
|
|
continue;
|
|
found.Add((p, r, o));
|
|
}
|
|
}
|
|
return found;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Pawns that relations already pointed at, with no save holding them, when the suite began: the new
|
|
/// world's generation left them so (seen with an AncientSoldier ex-lover of a faction pawn), before any
|
|
/// test ran and with an empty lawbook. The reload test excuses them like the tale pawns.
|
|
/// </summary>
|
|
private static readonly HashSet<string> unsavedAtStart = new HashSet<string>();
|
|
|
|
private static bool IsUnsavedAtStart(string thingId) => thingId != null && unsavedAtStart.Contains(thingId);
|
|
|
|
/// <summary>The "Could not resolve reference" warning names a pawn no save held when the suite began.</summary>
|
|
internal static bool NamesPawnUnsavedAtStart(string warning)
|
|
{
|
|
Match m = warning == null ? null : ResolveWarningId.Match(warning);
|
|
return m != null && m.Success && IsUnsavedAtStart(m.Groups[1].Value);
|
|
}
|
|
|
|
private static void NoteUnsavedAtStart()
|
|
{
|
|
try
|
|
{
|
|
foreach (var (p, r, o) in DanglingRelations())
|
|
{
|
|
if (o == null || !unsavedAtStart.Add(o.ThingID))
|
|
continue;
|
|
Note("unsaved at the start (world generation): " + p.ThingID + " (" + p.LabelShort + ") " + r.def.defName + " -> " + Describe(o));
|
|
}
|
|
// The other direction: an unsaved pawn that holds a relation to a saved one. Only the saved pawn's
|
|
// pawnsWithDirectRelationsWithMe names it, and vanilla's Pawn.Discard turns such a child of a
|
|
// discarded parent into a RelationshipRecord reference (Pawn.cs:2452-2460).
|
|
var all = new HashSet<Pawn>(PawnsFinder.All_AliveOrDead);
|
|
foreach (Pawn p in all.ToList())
|
|
{
|
|
if (p?.relations == null || !(PawnsWithRelationsWithMe.GetValue(p.relations) is HashSet<Pawn> others))
|
|
continue;
|
|
foreach (Pawn q in others)
|
|
{
|
|
if (q == null || q.Discarded || all.Contains(q) || !unsavedAtStart.Add(q.ThingID))
|
|
continue;
|
|
Note("unsaved at the start (world generation), relation to a saved pawn: " + Describe(q) + " -> " + p.ThingID + " (" + p.LabelShort + ")");
|
|
}
|
|
}
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
Note("start relation check threw: " + OneLine(e.Message));
|
|
}
|
|
}
|
|
|
|
private static readonly FieldInfo PawnsWithRelationsWithMe = HarmonyLib.AccessTools.Field(typeof(Pawn_RelationsTracker), "pawnsWithDirectRelationsWithMe");
|
|
|
|
/// <summary>
|
|
/// Pawns vanilla's RelationshipRecords name with no save holding them, found right before the phase-1
|
|
/// save (ThingIDs). RelationshipRecord saves its references by reference (RelationshipRecord.cs:70), and
|
|
/// Pawn.Discard adds the children of a discarded parent to one (Pawn.cs:2452-2460; Pawn_RelationsTracker.cs:
|
|
/// 475-480), saved or not. Each becomes a "Could not resolve reference" warning on the reload whose parent
|
|
/// is a RelationshipRecord, never Blax Laws' data.
|
|
/// </summary>
|
|
private static readonly HashSet<string> unsavedRecordPawns = new HashSet<string>();
|
|
|
|
private static void NoteRelationshipRecords()
|
|
{
|
|
try
|
|
{
|
|
var all = new HashSet<Pawn>(PawnsFinder.All_AliveOrDead);
|
|
var laws = new HashSet<Pawn>();
|
|
foreach (LawCase c in GameComponent_BlaxLaws.Instance?.Cases ?? new List<LawCase>())
|
|
{
|
|
if (c.offender != null) laws.Add(c.offender);
|
|
if (c.victim != null) laws.Add(c.victim);
|
|
if (c.enforcer != null) laws.Add(c.enforcer);
|
|
}
|
|
foreach (var kv in Find.RelationshipRecords.Records)
|
|
{
|
|
foreach (Pawn o in kv.Value.References)
|
|
{
|
|
if (o == null || (!o.Discarded && all.Contains(o)) || laws.Contains(o))
|
|
continue;
|
|
if (unsavedRecordPawns.Add(o.ThingID))
|
|
Note("vanilla relationship record " + kv.Key + " names a pawn no save holds: " + Describe(o));
|
|
}
|
|
}
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
Note("relationship record check threw: " + OneLine(e.Message));
|
|
}
|
|
}
|
|
|
|
/// <summary>The warning is about a RelationshipRecord's reference to a pawn the pre-save scan found unsaved.</summary>
|
|
internal static bool NamesVanillaRelationshipRecordPawn(string warning)
|
|
{
|
|
if (warning == null || !warning.Contains("curParent=RimWorld.RelationshipRecord") || !warning.Contains("curPathRelToParent=/references"))
|
|
return false;
|
|
Match m = ResolveWarningId.Match(warning);
|
|
return m.Success && unsavedRecordPawns.Contains(m.Groups[1].Value);
|
|
}
|
|
|
|
private static string Describe(Pawn o)
|
|
{
|
|
if (o == null)
|
|
return "null";
|
|
string removed;
|
|
lock (worldRemovals) worldRemovals.TryGetValue(o.ThingID, out removed);
|
|
return o.ThingID + " (" + o.LabelShort + ", kind " + o.kindDef?.defName + ", " + (o.Faction?.GetUniqueLoadID() ?? "no faction") +
|
|
", destroyed " + o.Destroyed + ", discarded " + o.Discarded + ", dead " + o.Dead + ", spawned " + o.Spawned +
|
|
", world pawn " + o.IsWorldPawn() + ", held by " + (o.ParentHolder?.ToString() ?? "nothing") + ")" +
|
|
(IsVanillaTalePawn(o.ThingID) ? "; vanilla: made by TaleData_Pawn.GenerateRandom and never saved" : "") +
|
|
(removed != null ? "; left the world pawns from: " + removed : "");
|
|
}
|
|
|
|
/// <summary>Who took each pawn out of WorldPawns this run (ThingID to the calling frames), for the dangling-relation notes.</summary>
|
|
private static readonly Dictionary<string, string> worldRemovals = new Dictionary<string, string>();
|
|
|
|
private static bool pawnWatchersHooked;
|
|
|
|
/// <summary>
|
|
/// Pawns vanilla's TaleData_Pawn.GenerateRandom made this run (ThingIDs). It generates a pawn for a
|
|
/// book's text (Book.GenerateBook, Book.cs:235), a unique weapon's name or a tale, keeps only its
|
|
/// TaleData and never saves or discards the pawn (TaleData_Pawn.cs:110-115). Relations to such a pawn
|
|
/// point at a pawn no save holds.
|
|
/// </summary>
|
|
private static readonly HashSet<string> vanillaTalePawns = new HashSet<string>();
|
|
|
|
private static readonly Regex ResolveWarningId = new Regex(@"loadID Thing_(\S+) of type Verse\.Pawn");
|
|
|
|
private static bool IsVanillaTalePawn(string thingId)
|
|
{
|
|
lock (vanillaTalePawns) return thingId != null && vanillaTalePawns.Contains(thingId);
|
|
}
|
|
|
|
/// <summary>The "Could not resolve reference" warning names a pawn vanilla's TaleData_Pawn.GenerateRandom made and never saved.</summary>
|
|
internal static bool NamesVanillaTalePawn(string warning)
|
|
{
|
|
Match m = warning == null ? null : ResolveWarningId.Match(warning);
|
|
return m != null && m.Success && IsVanillaTalePawn(m.Groups[1].Value);
|
|
}
|
|
|
|
/// <summary>Installs the WorldPawns.RemovePawn and TaleData_Pawn.GenerateRandom watchers once, at startup (QuickTestMap), before the world exists.</summary>
|
|
internal static void HookPawnWatchers()
|
|
{
|
|
if (pawnWatchersHooked)
|
|
return;
|
|
pawnWatchersHooked = true;
|
|
try
|
|
{
|
|
var harmony = new HarmonyLib.Harmony("blax.laws.tests.harness");
|
|
harmony.Patch(HarmonyLib.AccessTools.Method(typeof(WorldPawns), nameof(WorldPawns.RemovePawn)),
|
|
postfix: new HarmonyLib.HarmonyMethod(HarmonyLib.AccessTools.Method(typeof(TestRunner), nameof(OnWorldPawnRemoved))));
|
|
harmony.Patch(HarmonyLib.AccessTools.Method(typeof(TaleData_Pawn), nameof(TaleData_Pawn.GenerateRandom)),
|
|
postfix: new HarmonyLib.HarmonyMethod(HarmonyLib.AccessTools.Method(typeof(TestRunner), nameof(OnTalePawnGenerated))));
|
|
harmony.Patch(HarmonyLib.AccessTools.Method(typeof(Pawn), nameof(Pawn.Kill)),
|
|
prefix: new HarmonyLib.HarmonyMethod(HarmonyLib.AccessTools.Method(typeof(TestRunner), nameof(OnPawnKill))));
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
Note("could not watch WorldPawns.RemovePawn or TaleData_Pawn.GenerateRandom: " + OneLine(e.Message));
|
|
}
|
|
}
|
|
|
|
private static void OnPawnKill(Pawn __instance, DamageInfo? dinfo, Hediff exactCulprit)
|
|
{
|
|
try { Fixtures.NoteKill(__instance, dinfo, exactCulprit); }
|
|
catch (Exception e) { Note("kill note threw: " + OneLine(e.Message)); }
|
|
}
|
|
|
|
private static void OnTalePawnGenerated(TaleData_Pawn __result)
|
|
{
|
|
string id = __result?.pawn?.ThingID;
|
|
if (id != null)
|
|
lock (vanillaTalePawns) vanillaTalePawns.Add(id);
|
|
}
|
|
|
|
private static void OnWorldPawnRemoved(Pawn p)
|
|
{
|
|
if (p == null)
|
|
return;
|
|
var frames = new System.Diagnostics.StackTrace(2, false).GetFrames() ?? new System.Diagnostics.StackFrame[0];
|
|
string where = string.Join(" < ", frames.Take(8).Select(f => f.GetMethod()).Where(m => m != null)
|
|
.Select(m => m.DeclaringType?.Name + "." + m.Name));
|
|
lock (worldRemovals) worldRemovals[p.ThingID] = where;
|
|
}
|
|
|
|
private static void RunPhase(int phase)
|
|
{
|
|
var tests = typeof(TestRunner).Assembly.GetTypes()
|
|
.SelectMany(t => t.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static))
|
|
.Select(m => (method: m, attr: m.GetCustomAttribute<BlaxTestAttribute>()))
|
|
.Where(x => x.attr != null && x.attr.Phase == phase)
|
|
.OrderBy(x => x.attr.Order)
|
|
.ThenBy(x => x.method.DeclaringType.FullName)
|
|
.ThenBy(x => x.method.MetadataToken)
|
|
.ToList();
|
|
foreach (var (method, attr) in tests) RunOne(attr.Name, method, phase);
|
|
}
|
|
|
|
private static void RunOne(string name, MethodInfo method, int phase)
|
|
{
|
|
currentTest = name;
|
|
expectations.Clear();
|
|
int before;
|
|
lock (errors) before = errors.Count;
|
|
var settings = Fixtures.SnapshotSettings();
|
|
var lawbook = Fixtures.SnapshotLawbook();
|
|
Dictionary<Pawn, HashSet<Hediff>> bystanders = null;
|
|
string status = "PASS", detail = "";
|
|
try
|
|
{
|
|
Find.TickManager.CurTimeSpeed = TimeSpeed.Paused;
|
|
if (phase == 1)
|
|
Fixtures.CalmBystanders();
|
|
bystanders = Fixtures.BystanderInjuries();
|
|
method.Invoke(null, null);
|
|
}
|
|
catch (TargetInvocationException tie) when (tie.InnerException is TestSkipped s)
|
|
{
|
|
status = "SKIP"; detail = s.Message;
|
|
}
|
|
catch (TargetInvocationException tie) when (tie.InnerException is TestFailure f)
|
|
{
|
|
status = "FAIL"; detail = f.Message;
|
|
}
|
|
catch (TargetInvocationException tie)
|
|
{
|
|
status = "FAIL"; detail = "exception: " + tie.InnerException;
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
status = "FAIL"; detail = "runner exception: " + e;
|
|
}
|
|
finally
|
|
{
|
|
Fixtures.RestoreSettings(settings);
|
|
try { Fixtures.RestoreLawbook(lawbook); } catch (Exception e) { Note("lawbook restore threw: " + OneLine(e.Message)); }
|
|
try { Fixtures.Cleanup(); } catch (Exception e) { Note("cleanup threw: " + OneLine(e.Message)); }
|
|
LawsTestHooks.Reset();
|
|
Compat.SimulatedActive.Clear();
|
|
NoteDanglingRelations();
|
|
try
|
|
{
|
|
string harm = bystanders == null ? "" : Fixtures.BystanderHarm(bystanders);
|
|
if (harm.Length > 0) Note("the test left colonists it didn't make harmed: " + harm);
|
|
}
|
|
catch (Exception e) { Note("bystander check threw: " + OneLine(e.Message)); }
|
|
}
|
|
|
|
List<LogEntry> newErrors;
|
|
lock (errors)
|
|
{
|
|
newErrors = errors.Skip(before).Where(e => !e.warning).ToList();
|
|
var window = phase == 3 ? newErrors.Concat(errors.Take(before).Where(e => e.where == Phase3LoadTag && !e.warning)).ToList() : newErrors;
|
|
foreach (var (fragment, count) in expectations)
|
|
{
|
|
var matches = window.Where(e => e.text.Contains(fragment)).ToList();
|
|
foreach (LogEntry m in matches) m.excused = true;
|
|
if (matches.Count != count && status == "PASS")
|
|
{
|
|
status = "FAIL";
|
|
detail = $"expected {count} error(s) containing '{fragment}', got {matches.Count}";
|
|
}
|
|
}
|
|
}
|
|
expectations.Clear();
|
|
var newModErrors = newErrors.Where(e => e.ours && !e.excused).ToList();
|
|
var newOtherErrors = newErrors.Where(e => !e.ours && !e.excused).ToList();
|
|
if (status == "PASS" && newModErrors.Count > 0)
|
|
{
|
|
status = "FAIL";
|
|
detail = "Blax Laws logged errors: " + string.Join(" | ", newModErrors.Take(3).Select(e => e.text));
|
|
}
|
|
Record(status, name, detail);
|
|
foreach (LogEntry e in newOtherErrors.Take(5)) Line(" LOGERR " + e.where + ": " + e.text);
|
|
currentTest = null;
|
|
}
|
|
|
|
private static void Finish()
|
|
{
|
|
stage = 3;
|
|
currentTest = null;
|
|
List<LogEntry> stray, strayWarnings;
|
|
lock (errors)
|
|
{
|
|
stray = errors.Where(e => e.where.StartsWith("(") && e.ours && !e.excused && !e.warning).ToList();
|
|
strayWarnings = errors.Where(e => e.where.StartsWith("(") && e.warning).ToList();
|
|
}
|
|
foreach (LogEntry e in stray.Take(10)) Line(" MODERR " + e.where + ": " + e.text);
|
|
foreach (LogEntry e in strayWarnings.Take(10)) Line(" MODWARN " + e.where + ": " + e.text);
|
|
Line($"SUMMARY pass={pass} fail={fail} skip={skip} strayModErrors={stray.Count} strayModWarnings={strayWarnings.Count}");
|
|
Line("END");
|
|
Log.Message($"[BlaxTest] finished: pass={pass} fail={fail} skip={skip}");
|
|
Root.Shutdown();
|
|
}
|
|
|
|
internal static void Note(string message) => Line(" INFO " + OneLine(message));
|
|
|
|
private static void Record(string status, string name, string detail)
|
|
{
|
|
if (status == "PASS") pass++;
|
|
else if (status == "FAIL") fail++;
|
|
else skip++;
|
|
Line(string.IsNullOrEmpty(detail) ? $"{status} {name}" : $"{status} {name}: {OneLine(detail)}");
|
|
}
|
|
|
|
private static void Line(string text)
|
|
{
|
|
Log.Message("[BlaxTest] " + text);
|
|
try { File.AppendAllText(ResultPath, text + Environment.NewLine); } catch { }
|
|
}
|
|
|
|
private static string OneLine(string s)
|
|
{
|
|
if (s == null) return "";
|
|
s = s.Replace("\r", " ").Replace("\n", " | ");
|
|
return s.Length > 1500 ? s.Substring(0, 1500) + "..." : s;
|
|
}
|
|
}
|
|
}
|