rimworld-blax-zones/Tests/BlaxZonesTests/Source/Harness.cs

571 lines
26 KiB
C#
Raw Permalink Normal View History

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using BlaxZones;
using RimWorld;
using RimWorld.Planet;
using UnityEngine;
using Verse;
namespace BlaxZonesTests
{
/// <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 MapComponent_BlaxZones 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;
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, zone 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 that 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 &lt;DLC&gt;" 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 Zones 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 Zones saved.
/// </summary>
public static bool NamesVanillaTalePawn(string warning) => TestRunner.NamesVanillaTalePawn(warning);
private static string Show(object o) => o == null ? "null" : o.ToString();
}
/// <summary>
/// Drives the suite when the game runs with -quicktest -blaxzonestests: phase 1, save, load,
/// phase 2, save, strip the component class, load, phase 3, then writes BlaxZonesTestResults.txt
/// into the save data folder and quits.
/// </summary>
public class TestRunner : GameComponent
{
public const string SaveName = "BlaxZonesTest";
public const string Phase3SaveName = "BlaxZonesTest3";
public const string ResultFile = "BlaxZonesTestResults.txt";
/// <summary>The class attribute phase 3 replaces in the save.</summary>
public const string ComponentClassAttr = "Class=\"BlaxZones.MapComponent_BlaxZones\"";
/// <summary>A class that doesn't exist; the phase-3 save names it instead of MapComponent_BlaxZones.</summary>
public const string RemovedComponentClass = "BlaxZonesRemoved.MapComponent_BlaxZones";
/// <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;
}
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("blaxzonestests");
public static string ResultPath => Path.Combine(GenFilePaths.SaveDataFolderPath, ResultFile);
/// <summary>Maps whose component class 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); }
}
NoteDanglingRelations();
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 BlaxZonesTest3 (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. Zones' assembly stays loaded, so
/// Map.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>();
private static void Begin()
{
try { File.Delete(ResultPath); } catch { }
StartupLog = Log.Messages.ToList();
HookLog();
HookPawnWatchers();
Line("BEGIN Blax Zones 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();
Find.TickManager.CurTimeSpeed = TimeSpeed.Paused;
}
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));
}
return;
}
if (type != LogType.Error && type != LogType.Exception) return;
bool ours = !IsKnownForeignError(text, stack)
&& ((text != null && (text.Contains("BlaxZones") || text.Contains("Blax Zones"))) || (stack != null && stack.Contains("BlaxZones")));
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 Zones; 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 Castes 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).
/// </summary>
private static readonly (string text, string frame)[] KnownForeignErrors =
{
("non-exclusive interaction type: PrisonLabor_", "Patch_DefaultInteractionMode"),
};
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).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, so the note sits right above the
/// result line of the test that left it, 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
{
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;
if (!danglingSeen.Add(p.ThingID + ">" + (o?.ThingID ?? "null")))
continue;
// Vanilla's own leak; the phase-2 reload test counts these.
if (o != null && IsVanillaTalePawn(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));
}
}
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, also for every book in a trader's stock), a unique
/// weapon's name or a tale, keeps only its TaleData and never saves or discards the pawn
/// (TaleData_Pawn.cs:110-115). PawnGenerator may hand it a world pawn (it leaves WorldPawns) or a new
/// one with relations to existing pawns, colonists included. Either way those relations point at a
/// pawn no save holds, and every trader caravan in the suite can make some.
/// </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.zones.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))));
}
catch (Exception e)
{
Note("could not watch WorldPawns.RemovePawn or TaleData_Pawn.GenerateRandom: " + 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.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();
string status = "PASS", detail = "";
try
{
Find.TickManager.CurTimeSpeed = TimeSpeed.Paused;
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.Cleanup(); } catch (Exception e) { Note("cleanup threw: " + OneLine(e.Message)); }
ZonesTestHooks.Reset();
Compat.SimulatedActive.Clear();
NoteDanglingRelations();
}
List<LogEntry> newErrors;
lock (errors)
{
newErrors = errors.Skip(before).ToList();
var window = phase == 3 ? newErrors.Concat(errors.Take(before).Where(e => e.where == Phase3LoadTag)).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 Zones 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;
lock (errors) stray = errors.Where(e => e.where.StartsWith("(") && e.ours && !e.excused).ToList();
foreach (LogEntry e in stray.Take(10)) Line(" MODERR " + e.where + ": " + e.text);
Line($"SUMMARY pass={pass} fail={fail} skip={skip} strayModErrors={stray.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;
}
}
}