using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using BlaxZones;
using RimWorld;
using UnityEngine;
using Verse;
namespace BlaxZonesTests
{
///
/// 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.
///
[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 phases 2 and 3. Store ThingIDs, zone IDs or def names, never objects.
public static readonly Dictionary Carry = new Dictionary();
/// Carry values read right before the first 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.
///
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);
/// Skips the test unless the DLC is active, with "needs <DLC>" as the reason.
public static void NeedsDlc(string dlc, bool active)
{
if (!active) throw new TestSkipped("needs " + dlc);
}
/// Adds an INFO line under the current test in the results file.
public static void Info(string message) => TestRunner.Note(message);
///
/// Expects exactly errors whose text contains ,
/// 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.
///
public static void ExpectErrors(string fragment, int count) => TestRunner.Expect(fragment, count);
/// Error texts (one line each) logged while the phase-3 save loaded. Empty before phase 3.
public static List Phase3LoadErrors => TestRunner.LoadErrors();
/// "Could not resolve reference" warnings logged while the phase-3 save loaded.
public static int Phase3ResolveWarnings => TestRunner.ResolveWarnings;
private static string Show(object o) => o == null ? "null" : o.ToString();
}
///
/// 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.
///
public class TestRunner : GameComponent
{
public const string SaveName = "BlaxZonesTest";
public const string Phase3SaveName = "BlaxZonesTest3";
public const string ResultFile = "BlaxZonesTestResults.txt";
/// The class attribute phase 3 replaces in the save.
public const string ComponentClassAttr = "Class=\"BlaxZones.MapComponent_BlaxZones\"";
/// A class that doesn't exist; the phase-3 save names it instead of MapComponent_BlaxZones.
public const string RemovedComponentClass = "BlaxZonesRemoved.MapComponent_BlaxZones";
/// Where errors logged during the phase-3 load are filed.
public const string Phase3LoadTag = "(phase 3 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 errors = new List();
private static readonly List<(string fragment, int count)> expectations = new List<(string, int)>();
private static int resolveWarnings;
private static bool hooked;
private int settleFrames;
public static bool Enabled => GenCommandLine.CommandLineArgPassed("blaxzonestests");
public static string ResultPath => Path.Combine(GenFilePaths.SaveDataFolderPath, ResultFile);
/// Maps whose component class phase 3 replaced in the save. Set before the phase-3 load.
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); }
}
GameDataSaveLoader.SaveGame(SaveName);
GameDataSaveLoader.LoadGame(SaveName);
}
catch (Exception e)
{
Record("FAIL", "save and reload", e.ToString());
Finish();
}
}
else if (stage == 1 && loadsSeen >= 1)
{
stage = 2;
Line("STAGE phase 2 (after reload)");
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();
}
}
///
/// 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.
///
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);
}
/// The game log as it stood when the suite began, before any test ran (the startup test reads it).
public static List StartupLog { get; private set; } = new List();
private static void Begin()
{
try { File.Delete(ResultPath); } catch { }
StartupLog = Log.Messages.ToList();
HookLog();
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 (currentTest == Phase3LoadTag && text != null && text.Contains("Could not resolve reference"))
lock (errors) resolveWarnings++;
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);
};
}
///
/// 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).
///
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 LoadErrors()
{
lock (errors) return errors.Where(e => e.where == Phase3LoadTag).Select(e => e.text).ToList();
}
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, 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();
}
List 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 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;
}
}
}