using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using BlaxDefaults;
using HarmonyLib;
using RimWorld;
using Verse;
namespace BlaxDefaultsTests
{
/// The harness and the shared types (integrator). Feature tests live in each package's own file.
public static class SmokeTests
{
private static readonly string[] SharedKeys =
{
"BlaxDefaults_NeedsDlc", "BlaxDefaults_KindStockpile", "BlaxDefaults_KindStockpilePlural", "BlaxDefaults_KindDumping",
"BlaxDefaults_KindDumpingPlural", "BlaxDefaults_UnlistedGame", "BlaxDefaults_UnlistedRefuse", "BlaxDefaults_UnlistedAllow",
};
[BlaxTest("startup: every patch class applied and logged, no errors mentioning Blax Defaults")]
public static void StartupLogged()
{
int classes = typeof(BlaxDefaultsStartup).Assembly.GetTypes().Count(t => t.IsDefined(typeof(HarmonyPatch), false));
int ours = Harmony.GetAllPatchedMethods()
.Select(Harmony.GetPatchInfo)
.Where(info => info != null)
.SelectMany(info => info.Prefixes.Concat(info.Postfixes).Concat(info.Finalizers).Concat(info.Transpilers))
.Count(p => p.owner == BlaxDefaultsStartup.HarmonyId);
T.Info("patch classes: " + classes + ", Harmony patches owned by " + BlaxDefaultsStartup.HarmonyId + ": " + ours);
T.Equal(0, BlaxDefaultsStartup.PatchesFailed, "patch classes that failed");
T.Equal(classes, BlaxDefaultsStartup.PatchesApplied, "patch classes applied");
bool logged = Log.Messages.Any(m => m.text != null && m.text.Contains("[Blax Defaults] " + classes + " patches applied"));
T.Check(logged, "startup line '[Blax Defaults] " + classes + " patches applied' not in the log");
// Only what was logged before the first test: tests that expect errors (a failed write) log them later.
var errors = TestRunner.StartupErrors.Where(t => t.Contains("Blax Defaults") || t.Contains("BlaxDefaults")).ToList();
T.Check(errors.Count == 0, "errors mentioning Blax Defaults at startup: " + string.Join(" | ", errors.Take(3)));
}
[BlaxTest("startup: settings, the library and the shared strings are loaded")]
public static void Loaded()
{
T.NotNull(BlaxDefaultsMod.Settings, "BlaxDefaultsMod.Settings");
T.Check(DefaultsLibrary.LoadedAtStartup, "DefaultsLibrary.LoadAtStartup did not run");
T.Info("library entries at the first test: " + DefaultsLibrary.Count + ", Royalty: " + ModsConfig.RoyaltyActive
+ ", Ideology: " + ModsConfig.IdeologyActive + ", Biotech: " + ModsConfig.BiotechActive);
var missing = SharedKeys.Where(k => !k.CanTranslate()).ToList();
T.Check(missing.Count == 0, "strings missing from Keyed: " + string.Join(", ", missing));
}
[BlaxTest("compat: IsActive finds Blax Defaults and the base game, not a made-up id")]
public static void IsActiveWorks()
{
T.Check(Compat.IsActive("blax.defaults"), "Compat.IsActive(\"blax.defaults\") is false while Blax Defaults runs");
T.Check(Compat.IsActive("ludeon.rimworld"), "Compat.IsActive(\"ludeon.rimworld\") is false");
T.Check(!Compat.IsActive("blax.defaults.does.not.exist"), "Compat.IsActive is true for a made-up id");
}
[BlaxTest("dlc: DefOf MayRequire attributes name the DLC of a def")]
public static void DlcOfDefs()
{
T.Equal(DlcSupport.Biotech, DlcSupport.RequiredDlcOfThing("GrowthVat"), "DLC of GrowthVat");
T.Equal(DlcSupport.Ideology, DlcSupport.RequiredDlcOfThing("BiosculpterPod"), "DLC of BiosculpterPod");
T.Equal(null, DlcSupport.RequiredDlcOfThing("Shelf"), "DLC of Shelf");
T.Equal(null, DlcSupport.RequiredDlcOfThing("BlaxTest_Missing"), "DLC of a made-up name");
T.Equal(ModsConfig.BiotechActive ? null : DlcSupport.Biotech, DlcSupport.MissingDlcOfThing("GrowthVat"), "missing DLC of GrowthVat");
T.Equal("Needs Biotech", DlcSupport.NeedsLabel(DlcSupport.Biotech), "NeedsLabel");
}
[BlaxTest("kinds: stockpile types, covered buildings, parent filters and the game's defaults")]
public static void Kinds()
{
T.Check(StorageKinds.StockpileTypes.Count >= 2, "fewer than two stockpile types");
T.Equal(DefaultsKeys.Stockpile, StorageKinds.StockpileTypes[0].Key, "first stockpile type");
T.Equal(DefaultsKeys.Dumping, StorageKinds.StockpileTypes[1].Key, "second stockpile type");
T.Equal("stockpile", StorageKinds.VanillaStockpile.Label, "stockpile label");
foreach (string name in new[] { "Shelf", "ShelfSmall", "Bookcase", "BookcaseSmall", "Hopper" })
T.Check(StorageKinds.IsCovered(Fixtures.Thing(name)), name + " is not covered");
T.Check(!StorageKinds.IsCovered(Fixtures.Thing("Grave")), "Grave is covered in 1.0");
T.Check(!StorageKinds.ParentFilterFor(Fixtures.Thing("Shelf")).Allows(ThingDefOf.ChunkSlagSteel), "the shelf's parent filter allows slag chunks");
StorageSettings shelf = Fixtures.Kind("Shelf").GameDefault();
T.Equal(StoragePriority.Preferred, shelf.Priority, "shelf game default priority");
T.Check(shelf.filter.Allows(ThingDefOf.Steel), "shelf game default refuses Steel");
StorageSettings pile = Fixtures.StockpileKind.GameDefault();
T.Equal(StoragePriority.Normal, pile.Priority, "stockpile game default priority");
T.Check(pile.filter.Allows(ThingDefOf.Steel) && pile.filter.Allows(ThingDefOf.MealSimple), "stockpile game default refuses Steel or MealSimple");
StorageSettings dump = Fixtures.DumpingKind.GameDefault();
T.Check(!dump.filter.Allows(ThingDefOf.Steel), "dumping game default allows Steel");
T.Check(dump.filter.Allows(ThingDefOf.ChunkSlagSteel), "dumping game default refuses slag chunks");
ThingDef wastepack = DefDatabase.GetNamedSilentFail("Wastepack");
T.Equal(ModsConfig.BiotechActive, wastepack != null && dump.filter.Allows(wastepack), "dumping game default allows Wastepack");
T.Equal(Fixtures.Kind("Shelf").Key, StorageKinds.ForKey("storage:Shelf")?.Key, "ForKey(storage:Shelf)");
T.Equal(null, StorageKinds.ForKey("storage:BlaxTest_Missing"), "ForKey of a missing def");
}
[BlaxTest("template: capture and apply round-trip, missing names are kept and skipped silently")]
public static void TemplateRoundTrip()
{
StorageKind kind = Fixtures.Kind("Shelf");
StorageTemplate t = Fixtures.Template(kind, StoragePriority.Important, ThingDefOf.Steel);
T.Check(t.allowed.SequenceEqual(new[] { "Steel" }), "allowed is " + string.Join(",", t.allowed));
T.Check(!t.refused.Contains("ChunkSlagSteel"), "the template names a def the shelf's parent refuses");
t.allowed.Add("BlaxTest_Missing");
T.Check(t.UnresolvedNames().SequenceEqual(new[] { "BlaxTest_Missing" }), "unresolved names: " + string.Join(",", t.UnresolvedNames()));
var target = new StorageSettings();
kind.LoadDefault(target, t);
T.Equal(StoragePriority.Important, target.Priority, "priority after LoadDefault");
T.Check(target.filter.Allows(ThingDefOf.Steel), "Steel refused after LoadDefault");
T.Check(!target.filter.Allows(ThingDefOf.WoodLog), "WoodLog allowed after LoadDefault");
T.Check(kind.Capture(target).SameSettingsAs(Fixtures.Template(kind, StoragePriority.Important, ThingDefOf.Steel)), "captured settings differ from the template");
T.Check(t.Clone().Fingerprint() == t.Fingerprint(), "a clone has another fingerprint");
T.Check(T.ErrorsSoFar().Count == 0, "applying the template logged errors");
}
[BlaxTest("template: the unlisted rule decides items the template lists in neither list")]
public static void UnlistedRule_()
{
StorageKind kind = Fixtures.Kind("Shelf");
ThingDef widget = Fixtures.Thing("BlaxTest_Widget");
T.Check(kind.GameDefault().filter.Allows(widget), "the shelf's def default refuses BlaxTest_Widget");
StorageTemplate empty = Fixtures.Template(kind, StoragePriority.Normal);
empty.refused.Remove(widget.defName);
var s = new StorageSettings();
foreach (var (rule, allows) in new[] { (UnlistedRule.Refuse, false), (UnlistedRule.Game, true), (UnlistedRule.Allow, true) })
{
empty.unlisted = rule;
kind.LoadDefault(s, empty);
T.Equal(allows, s.filter.Allows(widget), "widget allowed with unlisted = " + rule);
T.Check(!s.filter.Allows(ThingDefOf.Steel), "Steel allowed with unlisted = " + rule);
}
}
[BlaxTest("library: set, get, forget and the test restore, in memory")]
public static void Library()
{
int before = DefaultsLibrary.Count;
var bill = new BillValues(DefaultsKeys.EveryBill) { storeMode = "DropOnFloor", setIngredientSearchRadius = true, ingredientSearchRadius = 30f };
Fixtures.Save(bill);
T.Check(DefaultsLibrary.Get(DefaultsKeys.EveryBill) == bill, "Get does not return the saved entry");
T.Check(bill.AnySet, "AnySet is false");
T.Check(bill.CloneValues().Fingerprint() == bill.Fingerprint(), "a clone has another fingerprint");
T.Check(DefaultsLibrary.Forget(DefaultsKeys.EveryBill), "Forget returned false");
T.Check(!DefaultsLibrary.Has(DefaultsKeys.EveryBill), "entry still there after Forget");
T.Equal(before, DefaultsLibrary.Count, "count after Forget");
}
[BlaxTest("harness: empty area and worker fixtures")]
public static void Fixtures_()
{
CellRect r = Fixtures.EmptyArea(3, 3);
T.Check(r.Cells.All(c => c.GetZone(Fixtures.Map) == null), "empty area has a zone");
T.Check(Fixtures.Worker().Spawned, "worker is not spawned");
}
[BlaxTest("save: the save holds nothing of Blax Defaults outside the mod list", phase: 2)]
public static void NothingInSave()
{
string path = GenFilePaths.FilePathForSavedGame(TestRunner.SaveName);
T.Check(File.Exists(path), "no save at " + path);
string text = File.ReadAllText(path);
int metaEnd = text.IndexOf("", StringComparison.Ordinal);
string body = metaEnd < 0 ? text : text.Substring(metaEnd);
// The test runner is a GameComponent of the test mod, BlaxDefaultsTests.TestRunner; it is allowed.
var hits = Regex.Matches(body, @"BlaxDefaults(?!Tests)|blax\.defaults(?!\.tests)").Cast().Select(m => m.Value).ToList();
T.Check(hits.Count == 0, "the save names Blax Defaults outside the meta block: " + string.Join(", ", hits.Distinct()));
}
}
}