using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using RimWorld; using UnityEngine; using Verse; namespace BlaxDefaultsTests { /// /// 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 (a library entry, for example). /// public static void CarryAtSave(string key, Func read) => CarryAtSaveTime[key] = read; /// /// The test expects Blax Defaults to log errors (a broken file, a failed write): they no longer fail it. /// Check them with ErrorsSoFar(). /// public static void AllowErrors() => TestRunner.errorsAllowed = true; /// Every error and exception logged since the current test started, ours and other mods', one line each. public static List ErrorsSoFar() => TestRunner.ErrorsSinceTestStart(); 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); /// 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 -blaxdefaultstests: phase 1, save, load, /// phase 2, then writes BlaxDefaultsTestResults.txt into the save data folder and quits. /// public class TestRunner : GameComponent { public const string SaveName = "BlaxDefaultsTest"; public const string ResultFile = "BlaxDefaultsTestResults.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(); private static bool hooked; private int settleFrames; private static int testModErrorsStart, testOtherErrorsStart; internal static bool errorsAllowed; /// The error texts in the game's log when the suite began, so before any test: what startup logged. internal static List StartupErrors = new List(); public static bool Enabled => GenCommandLine.CommandLineArgPassed("blaxdefaultstests"); 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); } } 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 { } StartupErrors = Log.Messages.Where(m => m.type == LogMessageType.Error && m.text != null).Select(m => m.text).ToList(); HookLog(); Line("BEGIN Blax Defaults 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.Error && type != LogType.Exception) return; string where = currentTest ?? "(between tests)"; string entry = where + ": " + OneLine(text); bool ours = !IsKnownForeignError(text, stack) && ((text != null && (text.Contains("BlaxDefaults") || text.Contains("Blax Defaults"))) || (stack != null && stack.Contains("BlaxDefaults"))); 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 Defaults; these show as LOGERR lines instead. Each entry is a /// text fragment and the frame that logs it, with a line saying which mod and why. None known yet. /// private static readonly (string text, string frame)[] KnownForeignErrors = { }; 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; errorsAllowed = false; int modErrorsBefore, otherErrorsBefore; lock (modErrors) { modErrorsBefore = modErrors.Count; otherErrorsBefore = otherErrors.Count; } testModErrorsStart = modErrorsBefore; testOtherErrorsStart = otherErrorsBefore; 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; lock (modErrors) { newModErrors = modErrors.Skip(modErrorsBefore).ToList(); newOtherErrors = otherErrors.Skip(otherErrorsBefore).ToList(); } if (status == "PASS" && newModErrors.Count > 0 && !errorsAllowed) { status = "FAIL"; detail = "Blax Defaults logged errors: " + string.Join(" | ", newModErrors.Take(3)); } Record(status, name, detail); if (errorsAllowed) foreach (string e in newModErrors.Take(5)) Line(" EXPECTEDERR " + e); foreach (string e in newOtherErrors.Take(5)) Line(" LOGERR " + e); currentTest = null; errorsAllowed = false; } /// Every error logged since the current test started, ours first, then other mods'. internal static List ErrorsSinceTestStart() { lock (modErrors) return modErrors.Skip(testModErrorsStart).Concat(otherErrors.Skip(testOtherErrorsStart)).ToList(); } private static void Finish() { stage = 2; List stray; lock (modErrors) stray = modErrors.Where(e => e.StartsWith("(between tests)")).ToList(); foreach (string e in stray.Take(10)) Line(" MODERR " + e); 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; } } }