using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
using BlaxZones;
using HarmonyLib;
using RimWorld;
using UnityEngine;
using Verse;
namespace BlaxZonesTests
{
///
/// Package Store. Design: 1.0 "Save-safe zone storage" > Tests.
/// Tests: [BlaxTest("store: what", phase: N)], phase 1 fresh colony, 2 after save and reload, 3 after the component class was stripped.
///
/// Phase 1 keeps three delivery zones (A and B with different filters and priorities, E with one
/// saved cell under a wall) and a stockpile S; zone C is deleted and zone D walled over before the
/// save. Every kept delivery zone has its orbital checkbox off, so other packages' routing tests
/// never pick them.
///
public static class StoreTests
{
private const string ExtraSaveName = "BlaxZonesStoreExtra";
private const string DeliveryClass = "BlaxZones.Zone_Delivery";
// ---- phase 1 -----------------------------------------------------------------------------
// Runs first in this class (source order): the later phase-1 tests and phases 2 and 3 read what it keeps.
[BlaxTest("store: set up two delivery zones, a deleted zone, a walled-over zone and a stockpile for the reload")]
public static void Setup()
{
Map map = Fixtures.Map;
CellRect area = Fixtures.TestArea(15, 2);
int x0 = area.minX, z0 = area.minZ;
// A: steel and industrial medicine, Important. A kept wall on its corner leaves that cell out.
Zone_Delivery a = Fixtures.KeepZone(Fixtures.DeliveryZone(new CellRect(x0, z0, 3, 2),
Fixtures.FilterOf(ThingDefOf.Steel, ThingDefOf.MedicineIndustrial), StoragePriority.Important, orbital: false));
var aWall = new IntVec3(x0 + 2, 0, z0 + 1);
Fixtures.Keep(Fixtures.Wall(aWall));
T.Equal(5, a.CellCount, "zone A cells after a wall on its corner");
T.Check(map.zoneManager.ZoneAt(aWall) == null, "the walled cell still belongs to a zone");
// B: silver only, Low.
Zone_Delivery b = Fixtures.KeepZone(Fixtures.DeliveryZone(new CellRect(x0 + 4, z0, 2, 2),
Fixtures.FilterOf(ThingDefOf.Silver), StoragePriority.Low, orbital: false));
T.Check(a.filter.Allows(ThingDefOf.Steel) && !a.filter.Allows(ThingDefOf.Silver), "zone A filter setup");
T.Check(b.filter.Allows(ThingDefOf.Silver) && !b.filter.Allows(ThingDefOf.Steel), "zone B filter setup");
// C: deleted before the save.
var cRect = new CellRect(x0 + 7, z0, 1, 2);
Zone_Delivery c = Fixtures.DeliveryZone(cRect, orbital: false);
c.Delete(playSound: false);
T.Check(!map.zoneManager.AllZones.Contains(c), "deleted zone C is still registered");
// D: a wall on its only cell deregisters it (Zone.cs:248-251).
var dCell = new IntVec3(x0 + 9, 0, z0);
Zone_Delivery d = Fixtures.DeliveryZone(new CellRect(dCell.x, dCell.z, 1, 1), orbital: false);
Fixtures.Wall(dCell);
T.Check(!map.zoneManager.AllZones.Contains(d), "walled-over zone D is still registered");
// E: one normal cell plus a saved cell under a wall. Vanilla never makes this state; written
// straight into the cell list it shows that the load prefix registers our zones before
// vanilla's spawn loop, which then trims the walled cell as it trims stockpiles.
var eKeep = new IntVec3(x0 + 11, 0, z0);
var eWalled = new IntVec3(x0 + 11, 0, z0 + 1);
Zone_Delivery e = Fixtures.KeepZone(Fixtures.DeliveryZone(new CellRect(eKeep.x, eKeep.z, 1, 1), orbital: false));
Fixtures.Keep(Fixtures.Wall(eWalled));
e.cells.Add(eWalled);
T.Equal(2, e.CellCount, "zone E cells with the walled cell written in");
// S: a vanilla stockpile for phase 3.
Zone_Stockpile s = Fixtures.KeepZone(Fixtures.Stockpile(new CellRect(x0 + 13, z0, 2, 2)));
T.Carry["store.A.id"] = a.ID.ToString();
T.Carry["store.B.id"] = b.ID.ToString();
T.Carry["store.C.id"] = c.ID.ToString();
T.Carry["store.C.cells"] = Cells(cRect.Cells);
T.Carry["store.D.id"] = d.ID.ToString();
T.Carry["store.D.cells"] = Cells(new[] { dCell });
T.Carry["store.E.id"] = e.ID.ToString();
T.Carry["store.E.keep"] = Cells(new[] { eKeep });
T.Carry["store.E.walled"] = Cells(new[] { eWalled });
T.Carry["store.A.wallCell"] = Cells(new[] { aWall });
T.Carry["store.S.id"] = s.ID.ToString();
// Read at save time: the comparison in phase 2 is against what was saved.
foreach (string key in new[] { "A", "B", "E" })
{
string k = key;
T.CarryAtSave("store." + k + ".label", () => DeliveryByKey(k)?.label ?? "missing");
T.CarryAtSave("store." + k + ".cells", () => DeliveryByKey(k) is Zone_Delivery z ? Cells(z.cells) : "missing");
T.CarryAtSave("store." + k + ".filter", () => DeliveryByKey(k) is Zone_Delivery z ? FilterText(z) : "missing");
T.CarryAtSave("store." + k + ".priority", () => DeliveryByKey(k)?.priority.ToString() ?? "missing");
T.CarryAtSave("store." + k + ".sources", () => DeliveryByKey(k) is Zone_Delivery z ? SourcesText(z) : "missing");
}
T.CarryAtSave("store.S.label", () => Fixtures.FindZoneById(IdOf("S"))?.label ?? "missing");
T.CarryAtSave("store.S.cells", () => Fixtures.FindZoneById(IdOf("S")) is Zone z ? Cells(z.cells) : "missing");
T.Equal(0, Fixtures.Comp.LoadedZones.Count, "loaded zones held by the component while the game runs");
T.Check(!ZoneStore.Loading, "ZoneStore.Loading is set while the game runs");
T.Check(ZoneStore.IsBlaxZone(a), "IsBlaxZone(delivery zone)");
T.Check(!ZoneStore.IsBlaxZone(s), "IsBlaxZone(stockpile)");
T.Check(!ZoneStore.IsBlaxZone(null), "IsBlaxZone(null)");
}
[BlaxTest("store: an extra save without a reload keeps the zones registered, the same list object and the zone grid")]
public static void ExtraSave()
{
Zone_Delivery a = NeedDelivery("A"), b = NeedDelivery("B"), e = NeedDelivery("E");
Map map = a.Map;
List before = map.zoneManager.AllZones;
List snapshot = before.ToList();
string path = GenFilePaths.FilePathForSavedGame(ExtraSaveName);
Fixtures.OnCleanup(() => DeleteSave(path));
GameDataSaveLoader.SaveGame(ExtraSaveName);
StopScribe();
T.Check(ReferenceEquals(before, map.zoneManager.AllZones), "AllZones is a different list object after the save");
T.Check(before.SequenceEqual(snapshot), "AllZones changed during the save");
foreach (Zone_Delivery z in new[] { a, b })
{
T.Check(map.zoneManager.AllZones.Contains(z), z.label + " left AllZones during the save");
foreach (IntVec3 c in z.cells)
T.Check(map.zoneManager.ZoneAt(c) == z, "ZoneAt(" + c + ") is not " + z.label + " after the save");
}
T.Check(map.zoneManager.ZoneAt(ParseCells(T.Carry["store.E.keep"])[0]) == e, "ZoneAt(E's cell) is not E after the save");
CheckSaveLayout(path, "extra save");
}
[BlaxTest("store: a zone that throws while saving logs one error and the list object is restored")]
public static void ThrowWhileSaving()
{
Map map = Fixtures.Map;
StoreTestZone tz = NewTestZone(map);
List before = map.zoneManager.AllZones;
List snapshot = before.ToList();
T.Check(snapshot.Any(ZoneStore.IsBlaxZone), "setup: no Blax zone on the map (did the store setup run?)");
T.ExpectErrors(StoreTestZone.SaveMessage, 1);
string xml;
List after;
List afterContents;
tz.fault = StoreTestZone.Fault.ThrowOnSave;
try
{
xml = Scribe.saver.DebugOutputFor(map.zoneManager);
}
finally
{
tz.fault = StoreTestZone.Fault.None;
after = ZoneStore.AllZonesRef(map.zoneManager);
afterContents = after.ToList();
Repair(map, before, tz);
}
StopScribe();
T.Check(ReferenceEquals(before, after), "AllZones is a different list object after the save threw");
T.Check(afterContents.SequenceEqual(snapshot), "AllZones changed during the save");
T.Check(!xml.NullOrEmpty() && xml.Contains("allZones"), "setup: the debug save wrote no zone list");
T.Check(!xml.Contains("BlaxZones."), "the saved zoneManager holds a Blax zone");
}
[BlaxTest("store: an exception escaping ZoneManager.ExposeData still gets the list object restored by the finalizer")]
public static void EscapingSaveException()
{
Map map = Fixtures.Map;
StoreTestZone tz = NewTestZone(map);
List before = map.zoneManager.AllZones;
List snapshot = before.ToList();
// The test zone adds itself to the list being written, so the list's enumerator throws in
// Scribe_Collections, outside the per-item catch in Scribe_Deep, and the exception leaves
// ZoneManager.ExposeData. DebugOutputFor's own Scribe_Deep then logs it.
T.ExpectErrors("Exception while saving Verse.ZoneManager", 1);
List after;
List afterContents;
tz.fault = StoreTestZone.Fault.BreakListOnSave;
try
{
Scribe.saver.DebugOutputFor(map.zoneManager);
}
finally
{
tz.fault = StoreTestZone.Fault.None;
after = ZoneStore.AllZonesRef(map.zoneManager);
afterContents = after.ToList();
Repair(map, before, tz);
}
StopScribe();
T.Check(tz.brokeList, "setup: the test zone never wrote into the list being saved");
T.Check(ReferenceEquals(before, after), "AllZones is a different list object after the exception");
T.Check(afterContents.SequenceEqual(snapshot), "the original list changed: the save wrote the unfiltered list");
}
[BlaxTest("store: ZoneStore has no type initializer, so a failed reflection bind can't make ZoneStore.Loading throw")]
public static void NoTypeInitializer()
{
T.Check(typeof(ZoneStore).TypeInitializer == null,
"ZoneStore has a static initializer: if a bind in it throws, every read of ZoneStore.Loading throws TypeInitializationException in the load hook");
}
[BlaxTest("store: with allZones unbound the save still leaves Blax zones out and restores the list, and the load hooks don't throw")]
public static void UnboundAllZones()
{
Map map = Fixtures.Map;
List before = map.zoneManager.AllZones;
List snapshot = before.ToList();
T.Check(snapshot.Any(ZoneStore.IsBlaxZone), "setup: no Blax zone on the map (did the store setup run?)");
ZonesTestHooks.AllZonesUnbound = true;
T.Check(ZoneStore.AllZonesRef == null, "setup: the hook left allZones bound");
string xml;
try
{
xml = Scribe.saver.DebugOutputFor(map.zoneManager);
}
finally
{
ZonesTestHooks.AllZonesUnbound = false;
}
StopScribe();
List after = map.zoneManager.AllZones;
List afterContents = after.ToList();
if (!afterContents.SequenceEqual(snapshot))
{
after.Clear();
after.AddRange(snapshot);
}
T.Check(ReferenceEquals(before, after), "AllZones is a different list object after the unbound save");
T.Check(afterContents.SequenceEqual(snapshot), "AllZones lost or reordered zones in the unbound save");
T.Check(!xml.NullOrEmpty() && xml.Contains("allZones"), "setup: the debug save wrote no zone list");
T.Check(!xml.Contains("BlaxZones."), "the unbound save wrote a Blax zone into the zoneManager");
ZonesTestHooks.AllZonesUnbound = true;
bool wasLoading = ZoneStore.Loading;
Patch_Map_FinalizeLoading.Prefix(map, out bool state);
T.Check(ZoneStore.Loading, "the FinalizeLoading prefix didn't set ZoneStore.Loading");
T.Equal(wasLoading, state, "the prefix's saved load flag");
var vanillaError = new InvalidOperationException("vanilla's own exception");
T.Check(ReferenceEquals(Patch_Map_FinalizeLoading.Finalizer(state, vanillaError), vanillaError), "the finalizer swallowed or replaced vanilla's exception");
T.Equal(wasLoading, ZoneStore.Loading, "ZoneStore.Loading after the finalizer");
}
[BlaxTest("store: RegisterLoadedZones registers loaded zones with their cells, skips nulls and taken cells, and leaves the rest out after an exception")]
public static void RegisterLoadedZones()
{
Map map = Fixtures.Map;
FieldInfo field = AccessTools.Field(typeof(MapComponent_BlaxZones), "loadedZones");
T.NotNull(field, "MapComponent_BlaxZones.loadedZones");
CellRect area = Fixtures.TestArea(5, 1);
IntVec3 Cell(int i) => new IntVec3(area.minX + i, 0, area.minZ);
Zone_Delivery g = LoadedDelivery(map, Cell(0));
Zone_Delivery k = LoadedDelivery(map, Cell(0), Cell(1)); // Cell(0) is g's by then
var tz = new StoreTestZone(map.zoneManager);
tz.cells.Add(Cell(2));
tz.zoneManager = null;
tz.fault = StoreTestZone.Fault.ThrowOnRegister;
Zone_Delivery left = LoadedDelivery(map, Cell(4));
foreach (Zone z in new Zone[] { g, k, tz, left })
Fixtures.TrackZone(z);
var fresh = new MapComponent_BlaxZones(map);
field.SetValue(fresh, new List { g, null, k, tz, left });
T.Equal(5, fresh.LoadedZones.Count, "loaded zones before registering");
T.ExpectErrors("Registering loaded zones failed", 1);
try
{
fresh.RegisterLoadedZones();
}
finally
{
tz.fault = StoreTestZone.Fault.None;
}
ZoneManager zm = map.zoneManager;
T.Equal(0, fresh.LoadedZones.Count, "loaded zones after registering");
T.Check(zm.AllZones.Contains(g) && g.zoneManager == zm, "zone g is not registered with its manager");
T.Check(zm.ZoneAt(Cell(0)) == g, "ZoneAt(cell 0) is not zone g");
T.Check(zm.AllZones.Contains(k), "zone k is not registered");
T.Equal(Cells(new[] { Cell(1) }), Cells(k.cells), "zone k cells (cell 0 was taken)");
T.Check(zm.ZoneAt(Cell(1)) == k, "ZoneAt(cell 1) is not zone k");
T.Check(!zm.AllZones.Contains(tz), "the zone that threw while registering stayed registered");
T.Check(zm.ZoneAt(Cell(2)) == null, "the zone that threw left a grid cell");
T.Check(!zm.AllZones.Contains(left) && left.zoneManager == null, "a zone after the exception was registered");
T.Check(zm.ZoneAt(Cell(4)) == null, "a zone after the exception got a grid cell");
T.Check(!ZoneStore.IsBlaxZone(tz), "IsBlaxZone(test zone from another assembly)");
}
[BlaxTest("store: a fresh component (mod added mid-save) starts with no loaded zones and registers nothing")]
public static void FreshComponent()
{
Map map = Fixtures.Map;
var fresh = new MapComponent_BlaxZones(map);
T.Equal(0, fresh.LoadedZones.Count, "loaded zones of a fresh component");
int before = map.zoneManager.AllZones.Count;
fresh.RegisterLoadedZones();
T.Equal(before, map.zoneManager.AllZones.Count, "zones after a fresh component registered its loaded zones");
T.Equal(1, map.components.Count(x => x is MapComponent_BlaxZones), "MapComponent_BlaxZones on the map");
T.Check(MapComponent_BlaxZones.Of(map) != fresh, "the stray component became the map's");
}
// ---- phase 2 -----------------------------------------------------------------------------
[BlaxTest("store: the phase-1 save holds Blax zones only under MapComponent_BlaxZones", phase: 2)]
public static void SaveFileLayout()
{
CheckSaveLayout(GenFilePaths.FilePathForSavedGame(TestRunner.SaveName), TestRunner.SaveName + ".rws");
}
[BlaxTest("store: both delivery zones come back with ID, label, cells, filter, priority and sources", phase: 2)]
public static void ZonesAfterReload()
{
foreach (string key in new[] { "A", "B" })
{
Zone_Delivery z = NeedDelivery(key);
string what = "zone " + key + " (ID " + z.ID + ")";
ZoneManager zm = z.Map.zoneManager;
T.Check(zm.AllZones.Contains(z), what + " is not in AllZones");
T.Check(z.zoneManager == zm, what + " has no zoneManager link");
T.Equal(T.Carry["store." + key + ".label"], z.label, what + " label");
T.Equal(T.Carry["store." + key + ".cells"], Cells(z.cells), what + " cells");
T.Equal(T.Carry["store." + key + ".filter"], FilterText(z), what + " filter");
T.Equal(T.Carry["store." + key + ".priority"], z.priority.ToString(), what + " priority");
T.Equal(T.Carry["store." + key + ".sources"], SourcesText(z), what + " sources");
foreach (IntVec3 c in z.cells)
T.Check(zm.ZoneAt(c) == z, "ZoneAt(" + c + ") is not " + what);
}
Zone_Delivery a = NeedDelivery("A"), b = NeedDelivery("B");
T.Check(FilterText(a) != FilterText(b) && a.priority != b.priority, "setup: zones A and B saved the same filter or priority");
IntVec3 wallCell = ParseCells(T.Carry["store.A.wallCell"])[0];
T.Check(a.Map.zoneManager.ZoneAt(wallCell) == null, "the cell walled before the save is in a zone");
T.Check(wallCell.GetEdifice(a.Map) != null, "the wall on zone A's corner is gone");
foreach (Map m in Find.Maps)
T.Equal(0, MapComponent_BlaxZones.Of(m)?.LoadedZones.Count ?? -1, "loaded zones still held on map " + m.Index);
T.Check(!ZoneStore.Loading, "ZoneStore.Loading is still set after the load");
}
[BlaxTest("store: the deleted and walled-over zones stay gone", phase: 2)]
public static void RemovedZonesStayGone()
{
Map map = Fixtures.Map;
foreach (string key in new[] { "C", "D" })
{
T.Check(Fixtures.FindZoneById(IdOf(key)) == null, "zone " + key + " (ID " + IdOf(key) + ") came back");
foreach (IntVec3 c in ParseCells(T.Carry["store." + key + ".cells"]))
T.Check(map.zoneManager.ZoneAt(c) == null, "ZoneAt(" + c + ") of removed zone " + key + " is " + map.zoneManager.ZoneAt(c));
}
int max = new[] { "A", "B", "C", "D", "E", "S" }.Select(IdOf).Max();
int next = Find.UniqueIDsManager.GetNextZoneID();
T.Check(next > max, "next zone ID " + next + " reuses a saved or removed zone ID (max " + max + ")");
}
[BlaxTest("store: a saved zone cell under a wall is trimmed by vanilla's spawn loop on load", phase: 2)]
public static void WalledCellTrimmedOnLoad()
{
IntVec3 keep = ParseCells(T.Carry["store.E.keep"])[0];
IntVec3 walled = ParseCells(T.Carry["store.E.walled"])[0];
T.Equal(Cells(new[] { keep, walled }), T.Carry["store.E.cells"], "setup: zone E's cells at save time");
Zone_Delivery e = NeedDelivery("E");
ZoneManager zm = e.Map.zoneManager;
T.Equal(Cells(new[] { keep }), Cells(e.cells), "zone E cells after the load");
T.Check(zm.ZoneAt(keep) == e, "ZoneAt(E's open cell) is not E");
T.Check(zm.ZoneAt(walled) == null, "the walled cell is still in a zone");
T.Check(walled.GetEdifice(e.Map) != null, "the wall on zone E's saved cell did not spawn");
}
// ---- phase 3 -----------------------------------------------------------------------------
[BlaxTest("store: after removal the save loads, the stockpile is intact and no Blax zones exist", phase: 3)]
public static void RemovedModLoad()
{
int maps = TestRunner.Phase3ReplacedCount;
T.Check(maps >= 1, "phase 3 replaced no component node");
T.ExpectErrors("Could not find class " + TestRunner.RemovedComponentClass, maps);
T.ExpectErrors("Can't load abstract class Verse.MapComponent", maps);
List loadErrors = T.Phase3LoadErrors;
List nre = loadErrors.Where(x => x.Contains("NullReferenceException")).ToList();
T.Check(nre.Count == 0, "NullReferenceException while loading: " + string.Join(" | ", nre.Take(2)));
List mapLoad = loadErrors.Where(x => x.Contains("Error in Map.FinalizeLoading")).ToList();
T.Check(mapLoad.Count == 0, "Map.FinalizeLoading failed: " + string.Join(" | ", mapLoad.Take(2)));
T.Check(Current.ProgramState == ProgramState.Playing && Find.CurrentMap != null, "the game is not running a map after the load");
foreach (Map m in Find.Maps)
{
T.NotNull(m.zoneManager, "zoneManager of map " + m.Index);
List blax = m.zoneManager.AllZones.Where(ZoneStore.IsBlaxZone).ToList();
T.Check(blax.Count == 0, "Blax zones on map " + m.Index + ": " + string.Join(", ", blax.Select(z => z.label)));
MapComponent_BlaxZones comp = MapComponent_BlaxZones.Of(m);
T.NotNull(comp, "fresh MapComponent_BlaxZones on map " + m.Index);
T.Equal(0, comp.LoadedZones.Count, "loaded zones of the fresh component on map " + m.Index);
}
Map map = Fixtures.Map;
foreach (string key in new[] { "A", "B", "E" })
{
T.Check(Fixtures.FindZoneById(IdOf(key)) == null, "zone " + key + " exists after removal");
}
foreach (string key in new[] { "A", "B" })
{
foreach (IntVec3 c in ParseCells(T.Carry["store." + key + ".cells"]))
T.Check(map.zoneManager.ZoneAt(c) == null, "ZoneAt(" + c + ") of removed zone " + key + " is " + map.zoneManager.ZoneAt(c));
}
Zone s = Fixtures.FindZoneById(IdOf("S"));
T.Check(s is Zone_Stockpile, "the kept stockpile (ID " + IdOf("S") + ") is gone or not a stockpile: " + s);
T.Equal(T.Carry["store.S.label"], s.label, "stockpile label");
T.Equal(T.Carry["store.S.cells"], Cells(s.cells), "stockpile cells");
foreach (IntVec3 c in s.cells)
T.Check(s.Map.zoneManager.ZoneAt(c) == s, "ZoneAt(" + c + ") is not the kept stockpile");
}
// ---- helpers -----------------------------------------------------------------------------
private static int IdOf(string key)
{
T.Check(T.Carry.TryGetValue("store." + key + ".id", out string id), "phase 1 value store." + key + ".id missing (did the store setup run?)");
return int.Parse(id);
}
private static Zone_Delivery DeliveryByKey(string key) =>
T.Carry.TryGetValue("store." + key + ".id", out string id) ? Fixtures.FindZoneById(int.Parse(id)) as Zone_Delivery : null;
private static Zone_Delivery NeedDelivery(string key)
{
int id = IdOf(key);
Zone_Delivery z = Fixtures.FindZoneById(id) as Zone_Delivery;
T.NotNull(z, "delivery zone " + key + " (ID " + id + ")");
return z;
}
/// A delivery zone in the state the loader leaves it: cells set, no manager, not registered.
private static Zone_Delivery LoadedDelivery(Map map, params IntVec3[] cells)
{
var z = new Zone_Delivery(map.zoneManager);
z.cells.AddRange(cells);
z.zoneManager = null;
return z;
}
/// A registered test zone with no cells, deleted after the test.
private static StoreTestZone NewTestZone(Map map)
{
var tz = new StoreTestZone(map.zoneManager);
map.zoneManager.RegisterZone(tz);
return Fixtures.TrackZone(tz);
}
///
/// Keeps the rest of the run sane if the finalizer failed: puts the original list back and drops
/// extra copies of the test zone. Callers read the list state before calling this.
///
private static void Repair(Map map, List original, StoreTestZone tz)
{
if (!ReferenceEquals(ZoneStore.AllZonesRef(map.zoneManager), original))
{
T.Info("AllZones was not restored; put the original list back so later tests run");
ZoneStore.AllZonesRef(map.zoneManager) = original;
}
while (original.Count(z => z == tz) > 1)
original.Remove(tz);
}
/// A Scribe left mid-save would break the runner's save and reload after phase 1.
private static void StopScribe()
{
if (Scribe.mode == LoadSaveMode.Inactive)
return;
T.Info("Scribe was left in mode " + Scribe.mode + "; forced stop");
Scribe.ForceStop();
T.Fail("Scribe was left active after saving");
}
private static void DeleteSave(string path)
{
foreach (string p in new[] { path, path + ".old", path + ".new" })
{
try
{
if (File.Exists(p))
File.Delete(p);
}
catch (Exception e)
{
TestRunner.Note("could not delete " + p + ": " + e.Message);
}
}
}
///
/// Parses a save: no "BlaxZones." inside any map's zoneManager or things, zones A, B and E sit under
/// the MapComponent_BlaxZones node (E with its walled cell), and neither zone C nor D is anywhere.
///
private static void CheckSaveLayout(string path, string what)
{
T.Check(File.Exists(path), what + ": no file at " + path);
var doc = new XmlDocument();
doc.Load(path);
XmlNodeList maps = doc.SelectNodes("/savegame/game/maps/li");
T.Check(maps != null && maps.Count > 0, what + ": no map nodes under savegame/game/maps");
var inComponent = new Dictionary();
var inManager = new HashSet();
foreach (XmlNode m in maps)
{
XmlNode zm = m["zoneManager"];
T.NotNull(zm, what + ": of a map");
T.Check(!zm.OuterXml.Contains("BlaxZones."), what + ": \"BlaxZones.\" inside ");
XmlNode things = m["things"];
T.Check(things == null || !things.OuterXml.Contains("BlaxZones."), what + ": \"BlaxZones.\" inside ");
foreach (XmlNode id in zm.SelectNodes("allZones/li/ID"))
{
if (int.TryParse(id.InnerText, out int n))
inManager.Add(n);
}
XmlNode comp = m.SelectSingleNode("components/li[@Class='BlaxZones.MapComponent_BlaxZones']");
T.NotNull(comp, what + ": MapComponent_BlaxZones node of a map");
foreach (XmlNode z in comp.SelectNodes("zones/li"))
{
XmlNode id = z["ID"];
if (id != null && int.TryParse(id.InnerText, out int n))
inComponent[n] = (z.Attributes?["Class"]?.Value, z.SelectNodes("cells/li").Count);
}
}
foreach (string key in new[] { "A", "B", "E" })
{
int id = IdOf(key);
T.Check(inComponent.TryGetValue(id, out var saved), what + ": zone " + key + " (ID " + id + ") is not under MapComponent_BlaxZones");
T.Equal(DeliveryClass, saved.cls, what + ": class of zone " + key);
T.Check(!inManager.Contains(id), what + ": zone " + key + " is under ");
}
T.Equal(2, inComponent[IdOf("E")].cells, what + ": saved cells of zone E (one under a wall)");
foreach (string key in new[] { "C", "D" })
{
int id = IdOf(key);
T.Check(!inComponent.ContainsKey(id) && !inManager.Contains(id), what + ": removed zone " + key + " (ID " + id + ") was saved");
}
T.Check(inManager.Contains(IdOf("S")), what + ": the kept stockpile is not under ");
}
private static string Cells(IEnumerable cells) =>
string.Join(";", cells.OrderBy(c => c.x).ThenBy(c => c.z).Select(c => c.x + "," + c.z));
private static List ParseCells(string text)
{
var list = new List();
if (text.NullOrEmpty())
return list;
foreach (string part in text.Split(';'))
{
string[] xz = part.Split(',');
list.Add(new IntVec3(int.Parse(xz[0]), 0, int.Parse(xz[1])));
}
return list;
}
private static string FilterText(Zone_Delivery z) =>
z.filter == null ? "null" : string.Join(",", z.filter.AllowedThingDefs.Select(d => d.defName).OrderBy(n => n, StringComparer.Ordinal));
private static string SourcesText(Zone_Delivery z) => "orbital=" + z.acceptOrbital + ",camp=" + z.campHere;
}
///
/// A test-only zone from this assembly, so ZoneStore treats it as vanilla and it stays in the list
/// ZoneManager writes. Each instance can fail on purpose in one place.
///
public class StoreTestZone : Zone
{
public enum Fault
{
None,
/// ExposeData throws while saving; Scribe_Deep catches it per zone.
ThrowOnSave,
/// ExposeData adds this zone to the list being saved once, so the save's enumerator throws.
BreakListOnSave,
/// PostRegister throws, as a zone whose registration fails halfway.
ThrowOnRegister,
}
public const string SaveMessage = "store test zone threw while saving on purpose";
public const string RegisterMessage = "store test zone threw while registering on purpose";
public Fault fault;
public bool brokeList;
public StoreTestZone()
{
}
public StoreTestZone(ZoneManager zoneManager) : base("Store test zone", zoneManager)
{
}
protected override Color NextZoneColor => new Color(0.5f, 0.5f, 0.5f, 0.09f);
public override void ExposeData()
{
if (Scribe.mode == LoadSaveMode.Saving)
{
if (fault == Fault.ThrowOnSave)
throw new InvalidOperationException(SaveMessage);
if (fault == Fault.BreakListOnSave && zoneManager != null)
{
fault = Fault.None;
brokeList = true;
ZoneStore.AllZonesRef(zoneManager).Add(this);
}
}
base.ExposeData();
}
public override void PostRegister()
{
if (fault == Fault.ThrowOnRegister)
throw new InvalidOperationException(RegisterMessage);
base.PostRegister();
}
}
}