using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using RimWorld; using UnityEngine; using Verse; namespace BlaxCastesTests { /// /// 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. /// [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) { } } /// Assertions and notes for test bodies. public static class T { /// Values carried from phase 1 into phase 2. Store ThingIDs or def names, never objects. public static readonly Dictionary Carry = new Dictionary(); /// Carry values read right before the save, after every phase-1 test ran. internal static readonly Dictionary> CarryAtSaveTime = new Dictionary>(); /// /// Carries a value read right before the save instead of now, for state that later phase-1 /// tests may still change (the next caste id, for example). /// public static void CarryAtSave(string key, Func read) => CarryAtSaveTime[key] = read; public static void Check(bool condition, string message) { if (!condition) throw new TestFailure(message); } public static void Equal(TV expected, TV actual, string what) { if (!EqualityComparer.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); /// /// The current test must log a "[Blax Castes]" warning that contains the fragment. Any other Blax Castes /// warning fails the test, the way an error does. /// public static void ExpectWarning(string fragment) => TestRunner.ExpectWarning(fragment, required: true); /// The current test may log "[Blax Castes]" warnings that contain the fragment (for paths this machine cannot always reach). public static void AllowWarning(string fragment) => TestRunner.ExpectWarning(fragment, required: false); /// Adds an INFO line under the current test in the results file. public static void Info(string message) => TestRunner.Note(message); private static string Show(object o) => o == null ? "null" : o.ToString(); } /// /// Drives the suite when the game runs with -quicktest -blaxcastestests: phase 1, save, load, /// phase 2, then writes BlaxCastesTestResults.txt into the save data folder and quits. /// public class TestRunner : GameComponent { public const string SaveName = "BlaxCastesTest"; public const string ResultFile = "BlaxCastesTestResults.txt"; private static int stage; // 0 waiting, 1 phase 1 done + reload queued, 2 finished private static bool reloaded; private static int pass, fail, skip; private static string currentTest; private static readonly List modErrors = new List(); private static readonly List otherErrors = new List(); // "[Blax Castes]" warnings: (where, text). Where is the test name or "(between tests)". private static readonly List<(string where, string text)> modWarnings = new List<(string, string)>(); private static readonly List<(string fragment, bool required)> expectedWarnings = new List<(string, bool)>(); private static bool hooked; public const string BetweenTests = "(between tests)"; /// The "[Blax Castes]" warnings in the game log before the first test ran: startup, defs, patches, the new game. public static List StartupWarnings { get; private set; } = new List(); /// The errors in the game log before the first test ran that name Blax Castes or come from its code. public static List StartupErrors { get; private set; } = new List(); /// The "[Blax Castes]" warnings logged outside a test so far (a load, a save), as text. public static List StrayWarnings() { lock (modErrors) return modWarnings.Where(w => w.where == BetweenTests).Select(w => w.text).ToList(); } internal static void ExpectWarning(string fragment, bool required) { if (!string.IsNullOrEmpty(fragment)) expectedWarnings.Add((fragment, required)); } private int settleFrames; public static bool Enabled => GenCommandLine.CommandLineArgPassed("blaxcastestests"); public static string ResultPath => Path.Combine(GenFilePaths.SaveDataFolderPath, ResultFile); public TestRunner(Game game) { } public override void LoadedGame() { if (Enabled && stage == 1) reloaded = true; } public override void GameComponentUpdate() { if (!Enabled || stage == 2) 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); } } // The save warns about each of these; name them here, so the test that left one is easy to find. foreach (string left in Fixtures.RitualObligationsOnDiscarded()) Note("ritual obligation on a discarded pawn before the save: " + left); GameDataSaveLoader.SaveGame(SaveName); GameDataSaveLoader.LoadGame(SaveName); } catch (Exception e) { Record("FAIL", "save and reload", e.ToString()); Finish(); } } else if (stage == 1 && reloaded) { stage = 2; Line("STAGE phase 2 (after reload)"); RunPhase(2); Finish(); } } private static void Begin() { try { File.Delete(ResultPath); } catch { } StartupWarnings = Log.Messages.Where(m => m.type == LogMessageType.Warning && m.text != null && m.text.Contains("[Blax Castes]")) .Select(m => m.text).ToList(); StartupErrors = Log.Messages.Where(m => m.type == LogMessageType.Error && m.text != null && (m.text.Contains("Blax Castes") || m.text.Contains("BlaxCastes") || (m.StackTrace != null && m.StackTrace.Contains("at BlaxCastes.")))) .Select(m => OneLine(m.text)).ToList(); HookLog(); Line("BEGIN Blax Castes in-game tests, RimWorld " + VersionControl.CurrentVersionStringWithRev); 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) { // Only the mod's own warnings: they all start with "[Blax Castes]". if (text != null && text.Contains("[Blax Castes]")) lock (modErrors) modWarnings.Add((currentTest ?? BetweenTests, OneLine(text))); return; } if (type != LogType.Error && type != LogType.Exception) return; string where = currentTest ?? BetweenTests; string entry = where + ": " + OneLine(text); bool ours = !IsKnownForeignError(text, stack) && ((text != null && (text.Contains("BlaxCastes") || text.Contains("Blax Castes"))) || (stack != null && stack.Contains("BlaxCastes"))); lock (modErrors) (ours ? modErrors : otherErrors).Add(entry); }; } /// /// 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 Castes; these show as LOGERR lines instead. Each entry is a /// text fragment and the frame that logs it: /// - Weapons Tab Reborn (-Compat): its JobGiver_EquipLoadout sits in the Humanlike_PreMain think tree /// hook, which every humanlike runs, and logs "Non-colonist X tried to equip loadout." once for the /// first pawn of another faction that thinks (a fixture that left the colony, a visitor, a raider). /// private static readonly (string text, string frame)[] KnownForeignErrors = { ("tried to equip loadout", "WeaponsTabReborn.JobGiver_EquipLoadout.TryGiveJob"), }; 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; } 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())) .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); } private static void RunOne(string name, MethodInfo method) { currentTest = name; expectedWarnings.Clear(); int modErrorsBefore, otherErrorsBefore, warningsBefore; lock (modErrors) { modErrorsBefore = modErrors.Count; otherErrorsBefore = otherErrors.Count; warningsBefore = modWarnings.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)); } } List newModErrors, newOtherErrors, newWarnings; lock (modErrors) { newModErrors = modErrors.Skip(modErrorsBefore).ToList(); newOtherErrors = otherErrors.Skip(otherErrorsBefore).ToList(); newWarnings = modWarnings.Skip(warningsBefore).Select(w => w.text).ToList(); } if (status == "PASS" && newModErrors.Count > 0) { status = "FAIL"; detail = "Blax Castes logged errors: " + string.Join(" | ", newModErrors.Take(3)); } if (status == "PASS") { // Zero warnings from the mod, except the ones the test declared. var unexpected = newWarnings.Where(w => !expectedWarnings.Any(e => w.Contains(e.fragment))).ToList(); var missing = expectedWarnings.Where(e => e.required && !newWarnings.Any(w => w.Contains(e.fragment))).Select(e => e.fragment).ToList(); if (unexpected.Count > 0) { status = "FAIL"; detail = "Blax Castes logged warnings: " + string.Join(" | ", unexpected.Take(3)); } else if (missing.Count > 0) { status = "FAIL"; detail = "expected Blax Castes warnings were not logged: " + string.Join(" | ", missing); } } Record(status, name, detail); foreach (string w in newWarnings.Take(5)) Line(" WARN " + w); foreach (string e in newOtherErrors.Take(5)) Line(" LOGERR " + e); expectedWarnings.Clear(); currentTest = null; } private static void Finish() { stage = 2; List stray; lock (modErrors) stray = modErrors.Where(e => e.StartsWith(BetweenTests)).ToList(); List strayWarnings = StrayWarnings(); foreach (string e in stray.Take(10)) Line(" MODERR " + e); foreach (string w in strayWarnings.Take(10)) Line(" MODWARN " + w); 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; } } }