Skip to content

A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.

fix(sim): empty YAML lists and maps are content errors, not crashes (I1)

eyalgolan80173d125b92
diff --git a/sim/Statecraft.Sim.Tests/ValidationTests.cs b/sim/Statecraft.Sim.Tests/ValidationTests.cs
new file mode 100644
index 000000000..c7644f59a
--- /dev/null
+++ b/sim/Statecraft.Sim.Tests/ValidationTests.cs
@@ -0,0 +1,65 @@
+using System;
+using System.Collections.Generic;
+using Statecraft.Sim;
+
+/// <summary>Load-time validation of malformed content: empty keys, enum-like fields, number ranges and ids.</summary>
+public class ValidationTests
+{
+ internal const string Event = @"
+id: drought
+title: Drought
+text: '{finance_minister} reports a drought.'
+anchor: soft
+tags: [economy]
+office: finance_minister
+from: 1948-06-01
+to: 1948-09-01
+conditions:
+ - indicator: food_supply
+ max: 0.9
+options:
+ - id: ration
+ text: Ration water
+ historical: true
+ effects:
+ - target: food_supply
+ delta: 0.1
+ - id: wait
+ text: Wait for rain
+status: draft
+";
+
+ /// <summary>Loads the fixture with one text replacement in <paramref name="file"/> (an events/ file when it
+ /// starts with "events/") and returns the ContentException it must raise.</summary>
+ internal static ContentException Bad(string file, string from, string to)
+ {
+ var overrides = new Dictionary<string, string>();
+ var events = new Dictionary<string, string> { ["drought.yaml"] = Event };
+ string original = file.StartsWith("events/") ? Event : Fixture.Files[file];
+ Assert.Contains(from, original);
+ var bad = original.Replace(from, to);
+ if (file.StartsWith("events/")) events["drought.yaml"] = bad; else overrides[file] = bad;
+ return Assert.Throws<ContentException>(() => ContentLoader.Load(Fixture.Write(overrides, events)));
+ }
+
+ [Fact]
+ public void FixtureWithTheTestEventLoads() =>
+ ContentLoader.Load(Fixture.Write(events: new Dictionary<string, string> { ["drought.yaml"] = Event }));
+
+ // I1: a key written with no value deserialises to null.
+ [Theory]
+ [InlineData("events/drought.yaml", "tags: [economy]", "tags:", "events[drought].tags", "must be a list")]
+ [InlineData("events/drought.yaml", "options:\n - id: ration\n text: Ration water\n historical: true\n effects:\n - target: food_supply\n delta: 0.1\n - id: wait\n text: Wait for rain\n", "options:\n", "events[drought].options", "must be a list")]
+ [InlineData("events/drought.yaml", " effects:\n - target: food_supply\n delta: 0.1\n", " effects:\n", "events[drought].options[ration].effects", "must be a list")]
+ [InlineData("people.yaml", " offices:\n - office: defense_minister\n from: 1949-01-01\n - office: finance_minister\n from: 1948-05-14\n", " offices:\n", "people[def_two].offices", "must be a list")]
+ [InlineData("legislatures.yaml", "seats: { alpha: 4, beta: 6 }", "seats:", "legislatures[house].seats", "must be a map")]
+ [InlineData("rules.yaml", "budget_start: { finance_minister: 1.0 }", "budget_start:", "budget_start", "must be a map")]
+ [InlineData("parties.yaml", "parties:\n - id: alpha\n name: Alpha\n - id: beta\n name: Beta\n", "parties:\n", "parties", "must be a list")]
+ public void EmptyListOrMapIsAContentError(string file, string from, string to, string field, string message)
+ {
+ var ex = Bad(file, from, to);
+ Assert.Equal(file, ex.File);
+ Assert.Equal(field, ex.Field);
+ Assert.EndsWith(message, ex.Message);
+ }
+}
diff --git a/sim/Statecraft.Sim/ContentLoader.cs b/sim/Statecraft.Sim/ContentLoader.cs
index 21c292011..5eeb3471f 100644
--- a/sim/Statecraft.Sim/ContentLoader.cs
+++ b/sim/Statecraft.Sim/ContentLoader.cs
@@ -1,7 +1,9 @@
using System;
+using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
+using System.Reflection;
using YamlDotNet.Core;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;
@@ -35,12 +37,50 @@ namespace Statecraft.Sim
{
var path = Path.Combine(root, relPath);
if (!File.Exists(path)) throw new ContentException(relPath, "(file)", "missing file");
- try { return Yaml.Deserialize<T>(File.ReadAllText(path)) ?? throw new ContentException(relPath, "(file)", "empty file"); }
+ T result;
+ try { result = Yaml.Deserialize<T>(File.ReadAllText(path)) ?? throw new ContentException(relPath, "(file)", "empty file"); }
catch (YamlException e) { throw new ContentException(relPath, $"line {e.Start.Line}", e.InnerException?.Message ?? e.Message); }
catch (IOException e) { throw new ContentException(relPath, "(file)", e.Message); }
catch (UnauthorizedAccessException e) { throw new ContentException(relPath, "(file)", e.Message); }
+ CheckNulls(relPath, result is GameEvent ev ? $"events[{ev.Id}]" : "", result!);
+ return result;
}
+ /// <summary>A key written with no value (`tags:`) deserialises to null. Null lists and maps become load errors
+ /// naming the field; null strings become "" (the default every check already handles). Walks nested content
+ /// objects, naming list entries by id when they have one, else by index.</summary>
+ static void CheckNulls(string file, string path, object o)
+ {
+ foreach (var p in o.GetType().GetProperties())
+ {
+ if (p.GetCustomAttribute<YamlIgnoreAttribute>() != null) continue;
+ var key = (path == "" ? "" : path + ".") + UnderscoredNamingConvention.Instance.Apply(p.Name);
+ var t = p.PropertyType;
+ var v = p.GetValue(o);
+ if (t == typeof(string)) { if (v == null) p.SetValue(o, ""); }
+ else if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(List<>))
+ {
+ if (v == null) throw new ContentException(file, key, "must be a list");
+ var list = (IList)v;
+ for (int i = 0; i < list.Count; i++)
+ {
+ var item = list[i];
+ if (item == null) throw new ContentException(file, FormattableString.Invariant($"{key}[{i}]"), "empty entry");
+ if (!IsContentType(item.GetType())) continue;
+ var id = item.GetType().GetProperty("Id")?.GetValue(item) as string;
+ CheckNulls(file, string.IsNullOrEmpty(id) ? FormattableString.Invariant($"{key}[{i}]") : $"{key}[{id}]", item);
+ }
+ }
+ else if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Dictionary<,>))
+ {
+ if (v == null) throw new ContentException(file, key, "must be a map");
+ }
+ else if (v != null && IsContentType(t)) CheckNulls(file, key, v);
+ }
+ }
+
+ static bool IsContentType(Type t) => t.IsClass && t != typeof(string) && t.Namespace == typeof(Content).Namespace;
+
public static Content Load(string contentRoot)
{
var c = new Content();