rimworld-blax-defaults/Tests/BlaxDefaultsTests/Source/Harness.cs

317 lines
13 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using RimWorld;
using UnityEngine;
using Verse;
namespace BlaxDefaultsTests
{
/// <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.
/// </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 phase 2. Store ThingIDs or def names, never objects.</summary>
public static readonly Dictionary<string, string> Carry = new Dictionary<string, string>();
/// <summary>Carry values read right before the 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 (a library entry, for example).
/// </summary>
public static void CarryAtSave(string key, Func<string> read) => CarryAtSaveTime[key] = read;
/// <summary>
/// The test expects Blax Defaults to log errors (a broken file, a failed write): they no longer fail it.
/// Check them with ErrorsSoFar().
/// </summary>
public static void AllowErrors() => TestRunner.errorsAllowed = true;
/// <summary>Every error and exception logged since the current test started, ours and other mods', one line each.</summary>
public static List<string> ErrorsSoFar() => TestRunner.ErrorsSinceTestStart();
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>Adds an INFO line under the current test in the results file.</summary>
public static void Info(string message) => TestRunner.Note(message);
private static string Show(object o) => o == null ? "null" : o.ToString();
}
/// <summary>
/// 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.
/// </summary>
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<string> modErrors = new List<string>();
private static readonly List<string> otherErrors = new List<string>();
private static bool hooked;
private int settleFrames;
private static int testModErrorsStart, testOtherErrorsStart;
internal static bool errorsAllowed;
/// <summary>The error texts in the game's log when the suite began, so before any test: what startup logged.</summary>
internal static List<string> StartupErrors = new List<string>();
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);
};
}
/// <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 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.
/// </summary>
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<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);
}
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<string> 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;
}
/// <summary>Every error logged since the current test started, ours first, then other mods'.</summary>
internal static List<string> ErrorsSinceTestStart()
{
lock (modErrors)
return modErrors.Skip(testModErrorsStart).Concat(otherErrors.Skip(testOtherErrorsStart)).ToList();
}
private static void Finish()
{
stage = 2;
List<string> 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;
}
}
}