A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
#nullable enable
using System;
using System.IO;
using System.Linq;
using NUnit.Framework;
using Statecraft.Game;
using Statecraft.Game.Map;
using Statecraft.Sim;
using UnityEditor;
using UnityEngine;
/// <summary>#1009 step 2: the Unity map editor round-trips the one override file through the sim's parser/serializer, does not
/// touch an unchanged file, rejects invalid moves before save, and records edits with Unity Undo.</summary>
public sealed class MapOverrideEditorTests
{
string temporary = "";
[SetUp]
public void SetUp()
{
temporary = Path.Combine(Path.GetTempPath(), "statecraft-map-editor-" + Guid.NewGuid().ToString("N"));
CopyDirectory(Paths.Content, temporary);
}
[TearDown]
public void TearDown()
{
if (Directory.Exists(temporary)) Directory.Delete(temporary, true);
}
[Test]
public void LoadEditSaveAndReloadHaveTheSameData()
{
var document = MapOverrideEditorDocument.Load(temporary);
MapOverrideEditorDocument? reloaded = null;
try
{
var hex = document.Hexes.First(x => x.Land);
var terrain = document.LandBiomes.First(x => x != hex.Biome);
var location = document.Locations.OrderBy(x => x.Id, StringComparer.Ordinal).First();
var content = LoadSavedContent();
var target = document.Hexes.First(x => x.Land && (x.Q != location.BaseQ || x.R != location.BaseR) && InItsRegion(content, location.Id, x.Q, x.R));
var controlHex = Control1948.Parse(File.ReadAllText(Path.Combine(temporary, "map", Control1948.FileName))).EditorHexes.First();
var period = document.Periods[0].Id;
var control = document.ControlValues.First(x => x != document.ControlAt(controlHex.q, controlHex.r, period));
document.SetTerrain(hex.Q, hex.R, terrain);
document.SetControl(controlHex.q, controlHex.r, period, control);
document.SetLocation(location.Id, target.Q, target.R);
Assert.IsTrue(document.Save(out var error), error);
reloaded = MapOverrideEditorDocument.Load(temporary);
Assert.AreEqual(terrain, reloaded.TerrainAt(hex.Q, hex.R));
Assert.AreEqual(control, reloaded.ControlAt(controlHex.q, controlHex.r, period));
Assert.AreEqual((target.Q, target.R), reloaded.LocationAt(location.Id));
Assert.AreEqual(MapOverrides.Serialize(document.ToOverrides()), MapOverrides.Serialize(reloaded.ToOverrides()));
}
finally
{
if (reloaded != null) UnityEngine.Object.DestroyImmediate(reloaded);
UnityEngine.Object.DestroyImmediate(document);
}
}
[Test]
public void SavingUnchangedDataDoesNotRewriteTheFile()
{
var path = Path.Combine(temporary, MapOverrides.FileName);
var before = File.ReadAllBytes(path);
var beforeWrite = File.GetLastWriteTimeUtc(path);
var document = MapOverrideEditorDocument.Load(temporary);
try
{
Assert.IsFalse(document.HasUnsavedChanges);
Assert.IsTrue(document.Save(out var error), error);
CollectionAssert.AreEqual(before, File.ReadAllBytes(path));
Assert.AreEqual(beforeWrite, File.GetLastWriteTimeUtc(path), "an unchanged save does not touch the file");
}
finally { UnityEngine.Object.DestroyImmediate(document); }
}
[Test]
public void UnityUndoAndRedoRestoreEveryEditKind()
{
var document = MapOverrideEditorDocument.Load(temporary);
try
{
var hex = document.Hexes.First(x => x.Land);
var terrainBefore = document.TerrainAt(hex.Q, hex.R);
var terrainAfter = document.LandBiomes.First(x => x != terrainBefore);
var location = document.Locations.OrderBy(x => x.Id, StringComparer.Ordinal).First();
var before = document.LocationAt(location.Id);
var target = document.Hexes.First(x => x.Land && (x.Q != before.q || x.R != before.r));
var controlHex = Control1948.Parse(File.ReadAllText(Path.Combine(temporary, "map", Control1948.FileName))).EditorHexes.First();
var period = document.Periods[0].Id;
var controlBefore = document.ControlAt(controlHex.q, controlHex.r, period);
var controlAfter = document.ControlValues.First(x => x != controlBefore);
Undo.IncrementCurrentGroup();
Undo.RecordObject(document, "Edit map overrides");
document.SetTerrain(hex.Q, hex.R, terrainAfter);
document.SetControl(controlHex.q, controlHex.r, period, controlAfter);
document.SetLocation(location.Id, target.Q, target.R);
Undo.FlushUndoRecordObjects();
Assert.AreEqual(terrainAfter, document.TerrainAt(hex.Q, hex.R));
Assert.AreEqual(controlAfter, document.ControlAt(controlHex.q, controlHex.r, period));
Assert.AreEqual((target.Q, target.R), document.LocationAt(location.Id));
Undo.PerformUndo();
Assert.AreEqual(terrainBefore, document.TerrainAt(hex.Q, hex.R));
Assert.AreEqual(controlBefore, document.ControlAt(controlHex.q, controlHex.r, period));
Assert.AreEqual(before, document.LocationAt(location.Id));
Undo.PerformRedo();
Assert.AreEqual(terrainAfter, document.TerrainAt(hex.Q, hex.R));
Assert.AreEqual(controlAfter, document.ControlAt(controlHex.q, controlHex.r, period));
Assert.AreEqual((target.Q, target.R), document.LocationAt(location.Id));
}
finally
{
Undo.ClearUndo(document);
UnityEngine.Object.DestroyImmediate(document);
}
}
[Test]
public void InvalidInputIsClearAndLeavesTheSavedFileIntact()
{
var path = Path.Combine(temporary, MapOverrides.FileName);
var before = File.ReadAllBytes(path);
var document = MapOverrideEditorDocument.Load(temporary);
try
{
var location = document.Locations.First();
var water = document.Hexes.First(x => !x.Land);
var error = Assert.Throws<ArgumentException>(() => document.SetLocation(location.Id, water.Q, water.R));
StringAssert.Contains("not a land hex", error!.Message);
error = Assert.Throws<ArgumentException>(() => document.SetLocation("unknown_location", water.Q, water.R));
StringAssert.Contains("unknown location id", error!.Message);
Assert.IsFalse(document.HasUnsavedChanges);
CollectionAssert.AreEqual(before, File.ReadAllBytes(path));
}
finally { UnityEngine.Object.DestroyImmediate(document); }
}
[Test]
public void ALocationMoveThatBreaksASiteCannotReplaceTheSavedMap()
{
var path = Path.Combine(temporary, MapOverrides.FileName);
var before = File.ReadAllBytes(path);
var content = LoadSavedContent();
var site = content.Sites.First();
var location = content.SettlementHexes.First();
var document = MapOverrideEditorDocument.Load(temporary);
try
{
document.SetLocation(location.Id, site.Q, site.R);
Assert.IsFalse(document.Save(out var error), "a settlement cannot occupy a designated site's hex");
StringAssert.Contains(site.Id, error, "the failure identifies the affected dependent record");
CollectionAssert.AreEqual(before, File.ReadAllBytes(path), "the last valid saved map stays intact");
Assert.DoesNotThrow(() => { LoadSavedContent(); }, "the saved map still loads in the game");
}
finally { UnityEngine.Object.DestroyImmediate(document); }
}
[Test]
public void MovingACorridorEndpointReportsTheCorridorAndKeepsItsTracedHexes()
{
// A corridor is bound to hexes, not to a location id (corridors.yaml; ContentLoader.ValidateCorridors), so moving the
// location at its end cannot break loading: the move saves, the dependency is reported and no hex is rewritten.
var path = Path.Combine(temporary, MapOverrides.FileName);
var content = LoadSavedContent();
var corridor = content.Corridors.Single(x => x.Id == "tlv_netanya_road");
var tracedBefore = corridor.Segments.SelectMany(x => x.Hexes).Select(h => (h[0], h[1])).ToList();
var end = corridor.Segments.Last().Hexes.Last();
var occupied = content.SettlementHexes.Select(x => (x.Q, x.R)).Concat(content.MapLocations.Select(x => (x.Q, x.R)))
.Concat(content.Sites.Select(x => (x.Q, x.R))).ToHashSet();
var document = MapOverrideEditorDocument.Load(temporary);
try
{
var location = document.Locations.OrderBy(x => x.Id, StringComparer.Ordinal).First(x => x.BaseQ == end[0] && x.BaseR == end[1]);
var target = document.Hexes.First(x => x.Land && !occupied.Contains((x.Q, x.R)) && InItsRegion(content, location.Id, x.Q, x.R));
StringAssert.Contains("tlv_netanya_road", string.Join("\n", document.Dependencies(location.Id).Corridors),
"the corridor that ends on the location is reported before saving");
document.SetLocation(location.Id, target.Q, target.R);
Assert.IsTrue(document.Save(out var error), error);
var saved = LoadSavedContent();
CollectionAssert.AreEqual(tracedBefore, saved.Corridors.Single(x => x.Id == corridor.Id).Segments
.SelectMany(x => x.Hexes).Select(h => (h[0], h[1])).ToList(), "the corridor keeps its traced hexes");
var moved = saved.SettlementHexes.Select(x => (x.Id, x.Q, x.R)).Concat(saved.MapLocations.Select(x => (x.Id, x.Q, x.R)))
.Single(x => x.Id == location.Id);
Assert.AreEqual((target.Q, target.R), (moved.Q, moved.R), "the game reads the moved location");
StringAssert.Contains(location.Id, File.ReadAllText(path));
}
finally { UnityEngine.Object.DestroyImmediate(document); }
}
[Test]
public void UnsavedEditsSurviveADomainReload()
{
// A domain reload keeps a document's serialized fields and drops the rest; EditorJsonUtility does the same round trip.
var document = MapOverrideEditorDocument.Load(temporary);
var restored = ScriptableObject.CreateInstance<MapOverrideEditorDocument>();
try
{
var hex = document.Hexes.First(x => x.Land);
var terrain = document.LandBiomes.First(x => x != hex.Biome);
document.SetTerrain(hex.Q, hex.R, terrain);
EditorJsonUtility.FromJsonOverwrite(EditorJsonUtility.ToJson(document), restored);
Assert.IsFalse(restored.IsLoaded, "the map read from disk is not serialized");
restored.Restore();
Assert.IsTrue(restored.IsLoaded);
Assert.AreEqual(terrain, restored.TerrainAt(hex.Q, hex.R), "the unsaved edit survives");
Assert.IsTrue(restored.HasUnsavedChanges, "and still counts as unsaved");
}
finally
{
UnityEngine.Object.DestroyImmediate(restored);
UnityEngine.Object.DestroyImmediate(document);
}
}
// #1721 slice C: search finds a location by any part of its id, in any letter case, and only by its id.
[Test]
public void SearchFindsALocationByPartOfItsIdInAnyCase()
{
var document = MapOverrideEditorDocument.Load(temporary);
try
{
var location = document.Locations.OrderBy(x => x.Id, StringComparer.Ordinal).First(x => x.Id.Length >= 4);
var query = location.Id.Substring(1, location.Id.Length - 2).ToUpperInvariant();
var found = document.SearchLocations(query);
CollectionAssert.Contains(found.Select(x => x.Id).ToList(), location.Id);
Assert.IsTrue(found.All(x => x.Id.IndexOf(query, StringComparison.OrdinalIgnoreCase) >= 0), "every hit contains the query");
CollectionAssert.AreEqual(found.Select(x => x.Id).OrderBy(x => x, StringComparer.Ordinal).ToList(), found.Select(x => x.Id).ToList(),
"hits are ordered by id");
Assert.IsEmpty(document.SearchLocations("no_such_location_id_zz"));
Assert.AreEqual(document.Locations.Count, document.SearchLocations(" ").Count, "a blank query lists every location");
}
finally { UnityEngine.Object.DestroyImmediate(document); }
}
// #1721 slice C: the diff preview lists each edited row against the saved override file, with both values.
[Test]
public void TheDiffListsEachEditedRowAgainstTheSavedFile()
{
var document = MapOverrideEditorDocument.Load(temporary);
try
{
Assert.IsEmpty(document.Changes(), "a freshly loaded map has no unsaved rows");
var hex = document.Hexes.First(x => x.Land);
var terrain = document.LandBiomes.First(x => x != hex.Biome);
var location = document.Locations.OrderBy(x => x.Id, StringComparer.Ordinal).First();
var before = document.LocationAt(location.Id);
var content = LoadSavedContent();
var target = document.Hexes.First(x => x.Land && (x.Q != before.q || x.R != before.r) && InItsRegion(content, location.Id, x.Q, x.R));
var controlHex = Control1948.Parse(File.ReadAllText(Path.Combine(temporary, "map", Control1948.FileName))).EditorHexes.First();
var period = document.Periods[0].Id;
var controlBefore = document.ControlAt(controlHex.q, controlHex.r, period);
var control = document.ControlValues.First(x => x != controlBefore);
document.SetTerrain(hex.Q, hex.R, terrain);
document.SetControl(controlHex.q, controlHex.r, period, control);
document.SetLocation(location.Id, target.Q, target.R);
var changes = document.Changes();
Assert.AreEqual(3, changes.Count, string.Join("\n", changes));
var t = changes.Single(x => x.Kind == MapEditorChange.Terrain);
Assert.AreEqual((hex.Q, hex.R, hex.Biome, terrain), (t.Q, t.R, t.Saved, t.Current));
var c = changes.Single(x => x.Kind == MapEditorChange.Control);
Assert.AreEqual((controlHex.q, controlHex.r, period, controlBefore, control), (c.Q, c.R, c.Period, c.Saved, c.Current));
var l = changes.Single(x => x.Kind == MapEditorChange.Location);
Assert.AreEqual(location.Id, l.Id);
StringAssert.Contains(location.Id, l.ToString());
Assert.AreNotEqual(l.Saved, l.Current);
document.SetTerrain(hex.Q, hex.R, hex.Biome);
Assert.AreEqual(2, document.Changes().Count, "an edit set back to its saved value leaves the diff");
Assert.IsTrue(document.Save(out var error), error);
Assert.IsEmpty(document.Changes(), "after save nothing differs from the file");
document.SetLocation(location.Id, before.q, before.r);
var back = document.Changes().Single();
Assert.AreEqual(FormattableString.Invariant($"q={target.Q} r={target.R}"), back.Saved, "the saved side is the file, not the generated map");
}
finally { UnityEngine.Object.DestroyImmediate(document); }
}
// #1721 slice C review: a saved override equal to the generated map disappears when the user picks that same value, so the
// diff must still list the row, or it says nothing changed while the document has unsaved changes.
[Test]
public void TheDiffListsARemovedRedundantOverride()
{
var path = Path.Combine(temporary, MapOverrides.FileName);
var file = MapOverrides.Parse(File.Exists(path) ? File.ReadAllText(path) : "");
var probe = MapOverrideEditorDocument.Load(temporary);
var land = probe.Hexes.First(x => x.Land && probe.TerrainAt(x.Q, x.R) == x.Biome && file.Terrain.All(t => t.Hex.Q != x.Q || t.Hex.R != x.R));
var controlHex = Control1948.Parse(File.ReadAllText(Path.Combine(temporary, "map", Control1948.FileName))).EditorHexes
.First(x => file.Control.All(c => c.Hex.Q != x.q || c.Hex.R != x.r));
var period = probe.Periods[0].Id;
var generatedControl = probe.ControlAt(controlHex.q, controlHex.r, period);
UnityEngine.Object.DestroyImmediate(probe);
file.Terrain.Add(new TerrainOverride { Hex = new MapHexRef { Q = land.Q, R = land.R }, Value = land.Biome });
file.Control.Add(new ControlOverride { Hex = new MapHexRef { Q = controlHex.q, R = controlHex.r }, Period = period, Value = generatedControl });
File.WriteAllText(path, MapOverrides.Serialize(file));
var document = MapOverrideEditorDocument.Load(temporary);
try
{
Assert.IsFalse(document.HasUnsavedChanges);
Assert.IsEmpty(document.Changes());
document.SetTerrain(land.Q, land.R, land.Biome);
document.SetControl(controlHex.q, controlHex.r, period, generatedControl);
Assert.IsTrue(document.HasUnsavedChanges, "the redundant overrides are gone from the document");
var changes = document.Changes();
Assert.AreEqual(2, changes.Count, "each removed redundant override is a row: " + string.Join("\n", changes));
var t = changes.Single(x => x.Kind == MapEditorChange.Terrain);
Assert.AreEqual((land.Q, land.R, land.Biome, land.Biome), (t.Q, t.R, t.Saved, t.Current));
document.Revert(t);
document.Revert(changes.Single(x => x.Kind == MapEditorChange.Control));
Assert.IsFalse(document.HasUnsavedChanges, "reverting the rows brings the saved overrides back");
Assert.IsEmpty(document.Changes());
}
finally { UnityEngine.Object.DestroyImmediate(document); }
}
// #1721 slice C: reverting one diff row restores only that row to the saved file, is undoable and writes nothing.
[Test]
public void RevertingOneRowRestoresOnlyThatRowAndUndoBringsItBack()
{
var path = Path.Combine(temporary, MapOverrides.FileName);
var document = MapOverrideEditorDocument.Load(temporary);
try
{
var hex = document.Hexes.First(x => x.Land);
var savedTerrain = document.LandBiomes.First(x => x != hex.Biome);
var controlHex = Control1948.Parse(File.ReadAllText(Path.Combine(temporary, "map", Control1948.FileName))).EditorHexes.First();
var period = document.Periods[0].Id;
var savedControl = document.ControlValues.First(x => x != document.ControlAt(controlHex.q, controlHex.r, period));
document.SetTerrain(hex.Q, hex.R, savedTerrain);
document.SetControl(controlHex.q, controlHex.r, period, savedControl);
Assert.IsTrue(document.Save(out var error), error);
var bytes = File.ReadAllBytes(path);
var editedTerrain = document.LandBiomes.First(x => x != hex.Biome && x != savedTerrain);
var location = document.Locations.OrderBy(x => x.Id, StringComparer.Ordinal).First();
var before = document.LocationAt(location.Id);
var target = document.Hexes.First(x => x.Land && (x.Q != before.q || x.R != before.r));
document.SetTerrain(hex.Q, hex.R, editedTerrain);
document.SetLocation(location.Id, target.Q, target.R);
Undo.IncrementCurrentGroup();
Undo.RecordObject(document, "Revert one map override edit");
document.Revert(document.Changes().Single(x => x.Kind == MapEditorChange.Terrain));
Undo.FlushUndoRecordObjects();
Assert.AreEqual(savedTerrain, document.TerrainAt(hex.Q, hex.R), "revert goes back to the saved file, not the generated map");
Assert.AreEqual((target.Q, target.R), document.LocationAt(location.Id), "the other edit stays");
Assert.AreEqual(MapEditorChange.Location, document.Changes().Single().Kind);
CollectionAssert.AreEqual(bytes, File.ReadAllBytes(path), "revert does not write the file");
Undo.PerformUndo();
Assert.AreEqual(editedTerrain, document.TerrainAt(hex.Q, hex.R), "Undo brings the reverted edit back");
Assert.AreEqual(2, document.Changes().Count);
document.Revert(document.Changes().Single(x => x.Kind == MapEditorChange.Location));
Assert.AreEqual(before, document.LocationAt(location.Id));
document.SetControl(controlHex.q, controlHex.r, period, document.ControlValues.First(x => x != savedControl));
document.Revert(document.Changes().Single(x => x.Kind == MapEditorChange.Control));
Assert.AreEqual(savedControl, document.ControlAt(controlHex.q, controlHex.r, period), "a control row reverts to the saved file too");
Assert.Throws<ArgumentNullException>(() => document.Revert(null!));
}
finally
{
Undo.ClearUndo(document);
UnityEngine.Object.DestroyImmediate(document);
}
}
/// <summary>R-ENEMY-007 (#2543) reads regions.yaml under both GDD identities, so a place that is a region's member must
/// stay on one of that region's member hexes (PlayerRegions: "effective location lies outside member_hexes"). A move
/// within the region is a plain edit; a place in no region can go anywhere.</summary>
static bool InItsRegion(Content c, string id, int q, int r)
{
var region = c.PlayerRegions.AtLocation(id);
return region == null || region.MemberHexes.Contains((q, r));
}
// R-ENEMY-007 (#2543): the editor validates through the game's loader, which reads the regions under both GDD
// identities, so moving a region's member place off the region's hexes is refused, and the saved map stays intact.
[Test]
public void MovingARegionsPlaceOutsideTheRegionIsRefused()
{
var content = LoadSavedContent();
var path = Path.Combine(temporary, MapOverrides.FileName);
var before = File.ReadAllBytes(path);
var document = MapOverrideEditorDocument.Load(temporary);
try
{
var location = document.Locations.OrderBy(x => x.Id, StringComparer.Ordinal).First(x => content.PlayerRegions.AtLocation(x.Id) != null);
var target = document.Hexes.First(x => x.Land && !InItsRegion(content, location.Id, x.Q, x.R));
document.SetLocation(location.Id, target.Q, target.R);
Assert.IsFalse(document.Save(out var error), "a region's place cannot leave the region's hexes");
StringAssert.Contains("effective location lies outside member_hexes", error);
StringAssert.Contains("regions.yaml", error, "the failure names the file to edit as well");
CollectionAssert.AreEqual(before, File.ReadAllBytes(path), "the last valid saved map stays intact");
Assert.DoesNotThrow(() => { LoadSavedContent(); }, "the saved map still loads in the game");
}
finally { UnityEngine.Object.DestroyImmediate(document); }
}
Content LoadSavedContent() => ContentLoader.Load(relative =>
{
var file = Path.Combine(temporary, relative);
return File.Exists(file) ? File.ReadAllText(file) : null;
}, Directory.GetFiles(Path.Combine(temporary, "events"), "*.yaml").Select(x => "events/" + Path.GetFileName(x)).ToList());
static void CopyDirectory(string source, string destination)
{
Directory.CreateDirectory(destination);
foreach (var file in Directory.GetFiles(source)) File.Copy(file, Path.Combine(destination, Path.GetFileName(file)));
foreach (var directory in Directory.GetDirectories(source))
CopyDirectory(directory, Path.Combine(destination, Path.GetFileName(directory)));
}
// R-MEDIT-002, R-MEDIT-003: SYNTHETIC fixture-only authoring state; no files are written.
[Test]
public void InfrastructureDocumentKeepsEditsAndRawFailedInputAcrossReloadAndUndo()
{
const string source = "version: map-editor-0.3\nruleset: gdd-0.3\ndraft: true\n"
+ "base_revision: fixture-only\nbase_digest: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ "overlay: { terrain: [], control: [], locations: [] }\nworkable: []\nregions: []\ninfrastructure: []\noffsets: []\n";
var document = ScriptableObject.CreateInstance<MapOverrideEditorDocument>();
try
{
Assert.IsTrue(document.TryReplaceInfrastructure(source, SaveGame.Gdd03Ruleset, out var error), error);
var saved = document.InfrastructureSource;
Undo.RegisterCompleteObjectUndo(document, "fixture-only edit");
Assert.IsTrue(document.TryReplaceInfrastructure(source.Replace("workable: []",
"workable: [{ hex: { q: 1, r: -2 }, value: false }]"), SaveGame.Gdd03Ruleset, out error), error);
Undo.FlushUndoRecordObjects();
var edited = document.InfrastructureSource;
Assert.IsFalse(document.TryReplaceInfrastructure("unreadable: [", SaveGame.Gdd03Ruleset, out error));
Assert.AreEqual(edited, document.InfrastructureSource);
Assert.AreEqual("unreadable: [", document.RejectedInfrastructureSource);
var clone = ScriptableObject.CreateInstance<MapOverrideEditorDocument>();
try
{
EditorJsonUtility.FromJsonOverwrite(EditorJsonUtility.ToJson(document), clone);
Assert.AreEqual(edited, clone.InfrastructureSource);
Assert.AreEqual(document.RejectedInfrastructureSource, clone.RejectedInfrastructureSource);
Assert.IsFalse(clone.InfrastructureCandidate().CanExport);
Assert.IsNotEmpty(clone.InfrastructureCandidate().Diagnostics("fixture-only", new string('a', 64)));
}
finally { UnityEngine.Object.DestroyImmediate(clone); }
Undo.PerformUndo();
Assert.AreEqual(saved, document.InfrastructureSource);
Undo.PerformRedo();
Assert.AreEqual(edited, document.InfrastructureSource);
}
finally { UnityEngine.Object.DestroyImmediate(document); }
}
}