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

348 lines
22 KiB
C#

using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using BlaxDefaults;
using RimWorld;
using Verse;
namespace BlaxDefaultsTests
{
/// <summary>
/// Work package "page". The tests of design.md: Defaults library and settings page (the page and edit window).
/// Methods: [BlaxTest("<area>: <what>", phase: N)] public static void X(). Skip DLC-only checks with
/// Fixtures.NeedDlc(DlcSupport.Biotech) ("skipped: needs Biotech"). Drawing is checked by hand, since
/// headless runs have no GUI; these tests cover the strings and the templates the page and window build.
/// </summary>
public static class PageTests
{
private static readonly string[] PageKeys =
{
"BlaxDefaults_PageEnabled", "BlaxDefaults_PageEnabledTip", "BlaxDefaults_PageStatusNone", "BlaxDefaults_PageStatusOne",
"BlaxDefaults_PageStatusMany", "BlaxDefaults_PageInactiveOne", "BlaxDefaults_PageInactiveMany", "BlaxDefaults_PageStatusTip",
"BlaxDefaults_PageBrokenBoth", "BlaxDefaults_PageBrokenRecovered", "BlaxDefaults_PageBrokenEmpty",
"BlaxDefaults_PageUnread", "BlaxDefaults_PageUnreadKept", "BlaxDefaults_PageNewerFile",
"BlaxDefaults_PageSectionStockpiles", "BlaxDefaults_PageStockpilesToggle", "BlaxDefaults_PageStockpilesToggleTip",
"BlaxDefaults_PageStockpilesNone", "BlaxDefaults_PageSectionStorage", "BlaxDefaults_PageStorageToggle",
"BlaxDefaults_PageStorageToggleTip", "BlaxDefaults_PageStorageNone", "BlaxDefaults_PageSectionBills",
"BlaxDefaults_PageBillsToggle", "BlaxDefaults_PageBillsToggleTip", "BlaxDefaults_PageRowSummary",
"BlaxDefaults_PageRowRefusesUnlisted", "BlaxDefaults_PageRowAllowsUnlisted", "BlaxDefaults_PageRowUnlistedTip",
"BlaxDefaults_PageInactiveNamesTip", "BlaxDefaults_PageEdit", "BlaxDefaults_PageForget", "BlaxDefaults_PageEditNeedsDlc",
"BlaxDefaults_PageEditKindMissing", "BlaxDefaults_PageForgetConfirm", "BlaxDefaults_PageEditTitle", "BlaxDefaults_PagePriority",
"BlaxDefaults_PageUnlisted", "BlaxDefaults_PageUnlistedTip", "BlaxDefaults_PageFilterNeedsGame", "BlaxDefaults_PageSave",
"BlaxDefaults_PageCancel",
};
// ---- helpers ---------------------------------------------------------------------
private static StorageKind Shelf => Fixtures.Kind("Shelf");
/// <summary>A shelf template allowing Steel only, unlisted Game, not saved.</summary>
private static StorageTemplate ShelfSteel(StoragePriority priority = StoragePriority.Normal) =>
Fixtures.Template(Shelf, priority, ThingDefOf.Steel);
private static string Count(int n) => n.ToString("N0", CultureInfo.InvariantCulture);
private static string Normal => StoragePriority.Normal.Label().CapitalizeFirst();
/// <summary>Puts exactly these entries in memory without writing the file; the runner restores the library after the test.</summary>
private static void LibraryOf(params DefaultsEntry[] entries) => DefaultsLibrary.ReplaceInMemory(entries.ToList());
/// <summary>What differs between two templates, for failure messages (fingerprints are thousands of names long).</summary>
private static string Diff(StorageTemplate expected, StorageTemplate actual)
{
var parts = new List<string>();
void Lists(string what, List<string> e, List<string> a)
{
List<string> missing = e.Except(a).Take(5).ToList();
List<string> extra = a.Except(e).Take(5).ToList();
if (missing.Count + extra.Count > 0)
parts.Add(what + " missing [" + string.Join(",", missing) + "] extra [" + string.Join(",", extra) + "]");
}
if (expected.priority != actual.priority) parts.Add("priority " + expected.priority + " vs " + actual.priority);
if (expected.unlisted != actual.unlisted) parts.Add("unlisted " + expected.unlisted + " vs " + actual.unlisted);
Lists("allowed", expected.allowed, actual.allowed);
Lists("refused", expected.refused, actual.refused);
Lists("allowedSpecial", expected.allowedSpecial, actual.allowedSpecial);
Lists("refusedSpecial", expected.refusedSpecial, actual.refusedSpecial);
if (expected.hitPoints != actual.hitPoints) parts.Add("hitPoints " + expected.hitPoints + " vs " + actual.hitPoints);
if (expected.quality != actual.quality) parts.Add("quality " + expected.quality + " vs " + actual.quality);
return parts.Count == 0 ? "(same)" : string.Join("; ", parts);
}
// ---- settings page ---------------------------------------------------------------
[BlaxTest("page: every string of the settings page and the edit window is in Keyed")]
public static void Strings()
{
var missing = PageKeys.Where(k => !k.CanTranslate()).ToList();
T.Check(missing.Count == 0, "strings missing from Keyed: " + string.Join(", ", missing));
}
[BlaxTest("page: a row names the kind, the priority, how many items it allows and the unlisted rule")]
public static void RowSummary_()
{
StorageTemplate t = ShelfSteel();
int total = StorageKinds.StorableDefs(Shelf.ParentFilter).Count();
T.Equal(total, t.allowed.Count + t.refused.Count, "names in a captured shelf template");
string expected = "Shelf: " + Normal + ", allows 1 of " + Count(total) + " items";
T.Info("row: " + expected);
T.Equal("Shelf", SettingsPage.KindLabel(t), "KindLabel of a shelf default");
T.Equal(expected, SettingsPage.RowSummary(t), "row with unlisted = Game");
t.unlisted = UnlistedRule.Refuse;
T.Equal(expected + ", refuses unlisted items", SettingsPage.RowSummary(t), "row with unlisted = Refuse");
t.unlisted = UnlistedRule.Allow;
T.Equal(expected + ", allows unlisted items", SettingsPage.RowSummary(t), "row with unlisted = Allow");
T.Equal("Stockpile", SettingsPage.KindLabel(new StorageTemplate(DefaultsKeys.Stockpile)), "KindLabel of the stockpile default");
T.Equal("Dumping stockpile", SettingsPage.KindLabel(new StorageTemplate(DefaultsKeys.Dumping)), "KindLabel of the dumping default");
T.Equal("BlaxTest_MissingShelf", SettingsPage.KindLabel(new StorageTemplate("storage:BlaxTest_MissingShelf")), "KindLabel of a kind that is not loaded");
}
[BlaxTest("page: the status line counts defaults and names from inactive mods")]
public static void StatusLine_()
{
LibraryOf();
T.Equal("No defaults saved yet.", SettingsPage.StatusLine(), "status line of an empty library");
StorageTemplate clean = ShelfSteel();
LibraryOf(clean);
T.Equal("1 default.", SettingsPage.StatusLine(), "status line with one clean default");
StorageTemplate withMissing = ShelfSteel();
withMissing.allowed.Add("BlaxTest_Missing");
LibraryOf(withMissing);
T.Equal(1, SettingsPage.InactiveNameCount(withMissing), "inactive names of a template naming BlaxTest_Missing");
T.Equal("1 default. 1 name from a mod that is not active.", SettingsPage.StatusLine(), "status line");
T.Check(SettingsPage.RowSummary(withMissing).Contains("allows 1 of "), "the row counts the unresolved name: " + SettingsPage.RowSummary(withMissing));
// A kind from a removed mod is one more inactive name; its row still shows and can't be edited.
var gone = new StorageTemplate("storage:BlaxTest_MissingShelf");
gone.allowed.Add("Steel");
T.Equal(null, SettingsPage.DisabledReason(gone), "DisabledReason of a kind from a removed mod");
T.Equal(1, SettingsPage.InactiveNameCount(gone), "inactive names of a kind from a removed mod");
T.Equal(null, StorageKinds.ForKey(gone.key), "kind of storage:BlaxTest_MissingShelf");
var bill = new BillValues(DefaultsKeys.EveryBill) { storeMode = "DropOnFloor" };
LibraryOf(withMissing, gone, bill);
T.Equal("3 defaults. 2 names from mods that are not active.", SettingsPage.StatusLine(), "status line with three defaults");
T.Equal("Every new bill", SettingsPage.RowSummary(bill), "row of the every-bill values");
T.Check(!SettingsPage.StorageEntries().Contains(bill), "the every-bill values are listed as a storage row");
}
[BlaxTest("dlc: without Biotech a Wastepack name in a stockpile default counts as an inactive name")]
public static void WastepackInactive()
{
if (ModsConfig.BiotechActive)
T.Skip("runs without Biotech only");
T.Equal(null, DefDatabase<ThingDef>.GetNamedSilentFail("Wastepack"), "Wastepack def without Biotech");
StorageTemplate t = Fixtures.Template(Fixtures.StockpileKind, StoragePriority.Normal, ThingDefOf.Steel);
t.refused.Add("Wastepack");
T.Equal(null, SettingsPage.DisabledReason(t), "DisabledReason of a stockpile default");
T.Equal(1, SettingsPage.InactiveNameCount(t), "inactive names");
LibraryOf(t);
T.Equal("1 default. 1 name from a mod that is not active.", SettingsPage.StatusLine(), "status line");
}
[BlaxTest("dlc: a saved growth vat default shows disabled with Needs Biotech while Biotech is off")]
public static void GrowthVatDisabled()
{
var t = new StorageTemplate(DefaultsKeys.ForStorage("GrowthVat"));
t.allowed.Add("Steel");
t.allowed.Add("BlaxTest_Missing");
Fixtures.Save(t);
T.Check(SettingsPage.StorageEntries().Contains(t), "the growth vat default is not listed");
if (ModsConfig.BiotechActive)
{
T.Equal(null, SettingsPage.DisabledReason(t), "DisabledReason with Biotech");
T.Equal(1, SettingsPage.InactiveNameCount(t), "inactive names with Biotech (BlaxTest_Missing)");
T.Info("Biotech active: the growth vat row is enabled; the -NoDlc run checks the disabled row");
return;
}
T.Equal("Needs Biotech", SettingsPage.DisabledReason(t), "DisabledReason without Biotech");
T.Equal(0, SettingsPage.InactiveNameCount(t), "inactive names of a disabled row");
T.Equal("GrowthVat", SettingsPage.KindLabel(t), "KindLabel without Biotech");
}
[BlaxTest("page: Forget removes the entry from the library and the page")]
public static void Forget()
{
StorageTemplate t = Fixtures.Save(ShelfSteel());
T.Check(SettingsPage.StorageEntries().Contains(t), "the saved shelf default is not listed");
T.Check(DefaultsLibrary.Forget(t.key), "Forget returned false");
T.Check(!SettingsPage.StorageEntries().Any(e => e.key == t.key), "the shelf default is still listed after Forget");
T.Check(!DefaultsLibrary.Has(t.key), "the shelf default is still in the library after Forget");
}
[BlaxTest("page: storage rows list stockpile types first, then buildings by name, without the bill values")]
public static void StorageEntriesOrder()
{
LibraryOf(
new StorageTemplate("storage:Shelf"),
new BillValues(DefaultsKeys.EveryBill),
new StorageTemplate(DefaultsKeys.Dumping),
new StorageTemplate("stockpile:BlaxTest_Designator"),
new StorageTemplate(DefaultsKeys.Stockpile),
new StorageTemplate("storage:Bookcase"));
string order = string.Join(" ", SettingsPage.StorageEntries().Select(e => e.key));
T.Equal("stockpile:Stockpile stockpile:Dumping stockpile:BlaxTest_Designator storage:Bookcase storage:Shelf", order, "row order");
}
[BlaxTest("page: the red line names the broken copies, and is empty for a clean load")]
public static void BrokenFilesLine_()
{
T.Equal(null, SettingsPage.BrokenFilesLine(new LoadResult()), "line for a clean load");
T.Equal(null, SettingsPage.BrokenFilesLine(null), "line for no load");
if (DefaultsLibrary.LastLoad.BrokenCopies.Count == 0)
T.Equal(null, SettingsPage.BrokenFilesLine(), "line for this run's startup load");
string folder = DefaultsFile.FolderPath;
const string main = "Defaults.broken-20261129-120000.xml";
const string bak = "Defaults.bak.broken-20261129-120000.xml";
var both = new LoadResult { BothFailed = true };
both.BrokenCopies.Add(Path.Combine(folder, main));
both.BrokenCopies.Add(Path.Combine(folder, bak));
string line = SettingsPage.BrokenFilesLine(both);
T.NotNull(line, "line when both files failed");
T.Info("both failed: " + line);
string shownFolder = Path.GetDirectoryName(Path.Combine(folder, main));
T.Check(line.Contains(main) && line.Contains(bak) && line.Contains(shownFolder), "the line doesn't name both copies and their folder: " + line);
var recovered = new LoadResult { LoadedFrom = DefaultsFile.BackupPath };
recovered.BrokenCopies.Add(Path.Combine(folder, main));
line = SettingsPage.BrokenFilesLine(recovered);
T.NotNull(line, "line when the backup loaded");
T.Check(line.Contains(main) && line.Contains(Path.GetFileName(DefaultsFile.BackupPath)), "the line doesn't name the copy and the backup: " + line);
}
[BlaxTest("page: a lone broken file gets the one-file line; unread and newer files get their own lines")]
public static void BrokenFilesLineCases()
{
string folder = DefaultsFile.FolderPath;
const string main = "Defaults.broken-20261129-120000.xml";
string shownFolder = Path.GetDirectoryName(Path.Combine(folder, main));
// Main file broken, no .bak ever written: Load sets BothFailed with one copy.
var lone = new LoadResult { BothFailed = true };
lone.BrokenCopies.Add(Path.Combine(folder, main));
string line = SettingsPage.BrokenFilesLine(lone);
T.Equal("BlaxDefaults_PageBrokenEmpty".Translate(shownFolder, main).Resolve(), line, "line for a lone broken file");
T.Check(!line.Contains("backup"), "the line for a lone broken file mentions a backup: " + line);
var unread = new LoadResult();
unread.Unread.Add(DefaultsFile.FilePath);
line = SettingsPage.BrokenFilesLine(unread);
T.Equal("BlaxDefaults_PageUnread".Translate(Path.GetDirectoryName(DefaultsFile.FilePath)).Resolve(), line, "line for an unread file");
const string kept = "Defaults.unread-20261129-120000.xml";
var moved = new LoadResult();
moved.UnreadCopies.Add(Path.Combine(folder, kept));
line = SettingsPage.BrokenFilesLine(moved);
T.Check(line != null && line.Contains(kept) && line.Contains(shownFolder), "the line doesn't name the moved file and its folder: " + line);
var newer = new LoadResult { LoadedFrom = DefaultsFile.FilePath, FormatVersion = DefaultsLibrary.FormatVersion + 1 };
T.Equal("BlaxDefaults_PageNewerFile".Translate().Resolve(), SettingsPage.BrokenFilesLine(newer), "line for a newer version's file");
var current = new LoadResult { LoadedFrom = DefaultsFile.FilePath, FormatVersion = DefaultsLibrary.FormatVersion };
T.Equal(null, SettingsPage.BrokenFilesLine(current), "line for a clean load of this version's file");
}
// ---- edit window -----------------------------------------------------------------
[BlaxTest("edit window: unchanged, it builds the template it was opened with")]
public static void EditUnchanged()
{
StorageTemplate t = ShelfSteel(StoragePriority.Important);
t.unlisted = UnlistedRule.Refuse;
var w = new Dialog_EditStorageTemplate(Shelf, t);
T.NotNull(w.Scratch, "Scratch");
T.Equal(StoragePriority.Important, w.Scratch.Priority, "Scratch priority");
T.Check(w.Scratch.filter.Allows(ThingDefOf.Steel) && !w.Scratch.filter.Allows(ThingDefOf.WoodLog), "Scratch filter is not Steel only");
T.Equal(UnlistedRule.Refuse, w.Unlisted, "Unlisted");
StorageTemplate built = w.BuildTemplate();
T.Equal(Shelf.Key, built.key, "key of the built template");
T.Check(built.SameSettingsAs(t), "the built template differs from the one opened: " + Diff(t, built));
// Without a template (1.1 "Add a default") the window starts at the game's default.
var fresh = new Dialog_EditStorageTemplate(Shelf, null);
StorageTemplate gameDefault = Shelf.Capture(Shelf.GameDefault());
T.Equal(UnlistedRule.Game, fresh.Unlisted, "Unlisted without a template");
T.Check(fresh.BuildTemplate().SameSettingsAs(gameDefault), "without a template the window is not the game's default: " + Diff(gameDefault, fresh.BuildTemplate()));
}
[BlaxTest("edit window: changes to the filter, the priority and the unlisted rule reach the built template")]
public static void EditChanges()
{
StorageTemplate t = ShelfSteel();
var w = new Dialog_EditStorageTemplate(Shelf, t);
w.Scratch.filter.SetAllow(ThingDefOf.WoodLog, true);
w.Scratch.Priority = StoragePriority.Low;
w.Unlisted = UnlistedRule.Allow;
StorageTemplate built = w.BuildTemplate();
T.Check(built.allowed.Contains("WoodLog") && !built.refused.Contains("WoodLog"), "WoodLog is not allowed in the built template");
T.Check(built.allowed.Contains("Steel"), "Steel is no longer allowed");
T.Equal(StoragePriority.Low, built.Priority, "priority of the built template");
T.Equal(UnlistedRule.Allow, built.unlisted, "unlisted rule of the built template");
T.Check(!t.allowed.Contains("WoodLog"), "the window changed the template it was opened with");
}
[BlaxTest("edit window: names from inactive mods survive in the list they were in")]
public static void EditKeepsUnresolved()
{
StorageTemplate t = ShelfSteel();
t.allowed.Add("BlaxTest_Missing");
t.refused.Add("BlaxTest_MissingRefused");
t.allowedSpecial.Add("BlaxTest_MissingFilter");
var w = new Dialog_EditStorageTemplate(Shelf, t);
w.Scratch.filter.SetAllow(ThingDefOf.WoodLog, true);
StorageTemplate built = w.BuildTemplate();
T.Check(built.allowed.Contains("BlaxTest_Missing"), "BlaxTest_Missing left the allowed list");
T.Check(built.refused.Contains("BlaxTest_MissingRefused"), "BlaxTest_MissingRefused left the refused list");
T.Check(built.allowedSpecial.Contains("BlaxTest_MissingFilter"), "BlaxTest_MissingFilter left the allowed special filters");
T.Check(!built.refused.Contains("BlaxTest_Missing") && !built.allowed.Contains("BlaxTest_MissingRefused"), "an unresolved name moved to the other list");
StorageTemplate again = w.BuildTemplate();
T.Equal(1, again.allowed.Count(n => n == "BlaxTest_Missing"), "copies of BlaxTest_Missing after a second build");
T.Equal(3, again.UnresolvedNames().Count(), "unresolved names after a second build");
}
[BlaxTest("edit window: Save stores the template under the kind's key")]
public static void EditSave()
{
var w = new Dialog_EditStorageTemplate(Shelf, ShelfSteel());
w.Scratch.filter.SetAllow(ThingDefOf.WoodLog, true);
w.Save();
StorageTemplate saved = DefaultsLibrary.Get<StorageTemplate>(Shelf.Key);
T.NotNull(saved, "the saved shelf default");
T.Check(saved.allowed.Contains("WoodLog") && saved.allowed.Contains("Steel"), "the saved default doesn't allow Steel and WoodLog");
T.Check(saved.SameSettingsAs(w.BuildTemplate()), "the saved default differs from BuildTemplate: " + Diff(w.BuildTemplate(), saved));
var settings = new StorageSettings();
Shelf.LoadDefault(settings, saved);
T.Check(settings.filter.Allows(ThingDefOf.WoodLog) && settings.filter.Allows(ThingDefOf.Steel), "the saved default doesn't load as Steel and WoodLog");
StorageKind pile = Fixtures.StockpileKind;
var wp = new Dialog_EditStorageTemplate(pile, Fixtures.Template(pile, StoragePriority.Normal, ThingDefOf.Steel));
wp.Save();
T.NotNull(DefaultsLibrary.Get<StorageTemplate>(DefaultsKeys.Stockpile), "the stockpile default saved under " + DefaultsKeys.Stockpile);
}
[BlaxTest("edit window: the item filter's read of the game is bridged, so it draws from the main menu")]
public static void FilterGuard()
{
T.Info("patched: " + string.Join(", ", MainMenuFilterGuard.Replaced.Select(kv => kv.Key + " (getter " + kv.Value.getter + ", Matches " + kv.Value.matches + ")")));
T.Check(MainMenuFilterGuard.Ready, "the filter tree's reads of the game were not all replaced");
T.Check(MainMenuFilterGuard.Replaced.TryGetValue("DoCategoryChildren", out var children) && children.getter == 1,
"Find.HiddenItemsManager in Listing_TreeThingFilter.DoCategoryChildren was not replaced");
T.Check(MainMenuFilterGuard.Replaced.TryGetValue("DoThingDef", out var row) && row.matches == 1,
"QuickSearchFilter.Matches(ThingDef) in Listing_TreeThingFilter.DoThingDef was not replaced");
T.Check(ReferenceEquals(MainMenuFilterGuard.HiddenItems(), Find.HiddenItemsManager), "in a game the guard returns another manager than the game's");
var search = new QuickSearchFilter();
search.Text = "steel";
T.Equal(search.Matches(ThingDefOf.Steel), MainMenuFilterGuard.Matches(search, ThingDefOf.Steel), "Matches(Steel) in a game");
T.Equal(search.Matches(ThingDefOf.WoodLog), MainMenuFilterGuard.Matches(search, ThingDefOf.WoodLog), "Matches(WoodLog) in a game");
ThingDef hidden = DefDatabase<ThingDef>.AllDefsListForReading.FirstOrDefault(d => d.hiddenWhileUndiscovered);
if (hidden != null)
T.Check(!MainMenuFilterGuard.NothingHidden.Hidden(hidden), "the main menu manager hides " + hidden.defName);
}
}
}