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.Collections;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using Statecraft.Game;
using Statecraft.Game.UI;
using Statecraft.Sim;
using UnityEditor;
using UnityEngine;
using UnityEngine.TestTools;
using UnityEngine.UIElements;
using Object = UnityEngine.Object;
/// <summary>Each top-bar number explains itself (#1037, MeterTip): on hover, or after a tap, a tip under the bar gives the
/// meter in words (its tooltip) and the turn's main causes from the sim (HudModel.Causes), inside the window.</summary>
public class MeterTipTests
{
static readonly Content C = ContentLoader.Load(Paths.Content);
static UiText En => UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.Strings).text);
static UiText He => UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.StringsHebrew).text, "strings.he.yaml");
static void Enter(VisualElement e) { using var ev = PointerEnterEvent.GetPooled(new Event { type = EventType.MouseMove, mousePosition = e.worldBound.center }); ev.target = e; e.SendEvent(ev); }
static void Leave(VisualElement e) { using var ev = PointerLeaveEvent.GetPooled(new Event { type = EventType.MouseMove, mousePosition = Vector2.zero }); ev.target = e; e.SendEvent(ev); }
internal static void Tap(VisualElement e) { using var ev = ClickEvent.GetPooled(); ev.target = e; e.SendEvent(ev); }
static void MouseClick(VisualElement e) { using var ev = ClickEvent.GetPooled(new Event { type = EventType.MouseUp, mousePosition = e.worldBound.center }); ev.target = e; e.SendEvent(ev); }
/// <summary>A finger going down on <paramref name="e"/>; on the map, with nothing under it, the panel sends it to its root.</summary>
static void Press(VisualElement e) { using var ev = PointerDownEvent.GetPooled(new Touch { fingerId = 0, phase = TouchPhase.Began }); ev.target = e; e.SendEvent(ev); }
/// <summary>Shown only when MeterTip set it so (an unset inline display reads as Flex, the default).</summary>
internal static bool Shown(VisualElement tip) => tip.style.display.keyword == StyleKeyword.Undefined && tip.style.display.value == DisplayStyle.Flex;
static string Words(VisualElement root) => root.Q<Label>("meter-tip-words").text;
/// <summary>The tip's causes, one label each (B1), joined a line each.</summary>
static string CausesLine(VisualElement root) => string.Join("\n", root.Q("meter-tip-causes").Query<Label>().ToList().Select(l => l.text));
/// <summary>After the fixed opening turn, at 1280x720 and 390x844 in English and Hebrew: hovering the bar's first and
/// last numbers shows each one's words and the sim's causes under the bar and inside the window; leaving hides it.</summary>
[UnityTest]
public IEnumerator HoverExplainsANumberUnderTheBarInsideTheWindow()
{
var problems = new List<string>();
foreach (var hebrew in new[] { false, true })
foreach (var (w, h) in new[] { (1280, 720), (390, 844) })
{
string at = $"{(hebrew ? "he" : "en")} {w}x{h}";
yield return Rendered(w, h, hebrew, Check);
IEnumerator Check(VisualElement root, SimBridge bridge, UiText text)
{
var tip = root.Q(MeterTip.TipName);
foreach (var id in new[] { "treasury", "fx", "security" })
{
var meter = root.Q("meter-" + id);
Enter(meter);
for (int i = 0; i < 3; i++) yield return null; // the tip is placed once its width is laid out
var causes = HudModel.Causes(bridge.Session.Last, id, bridge.Content, w => CauseText.Line(w, bridge.Content, System.Array.Empty<Statecraft.Game.Map.Units.UnitEntry>(), text));
if (!Shown(tip)) { problems.Add($"{at} {id}: hovering shows no tip"); continue; }
if (Words(root) != meter.tooltip + "\n" + text["hud.tip." + id] + "\n" + text["hud.causes"]) problems.Add($"{at} {id}: the tip's words are '{Words(root)}', not its tooltip, its explanation and the causes' heading");
if (CausesLine(root) != string.Join("\n", causes)) problems.Add($"{at} {id}: the tip's causes are '{CausesLine(root)}', not the sim's '{string.Join(" | ", causes)}'");
if (UiDirection.RightToLeft(Words(root)) != hebrew) problems.Add($"{at} {id}: the words are not in the UI's language");
// B1: a keyed line is in the UI's language (#55: lines with no key stay English). Since #1565 Security's
// opening causes are One Army and Degania, two event lines with no key, so its causes stay English.
var keyed = HudModel.Causes(bridge.Session.Last, id, bridge.Content, w => w.Key).Any(k => k != "");
if (UiDirection.HasRightToLeft(CausesLine(root)) != (hebrew && keyed)) problems.Add($"{at} {id}: the causes '{CausesLine(root)}' are not in the UI's language");
if (causes.Count == 0) problems.Add($"{at} {id}: precondition: the opening turn has causes for it");
// #2212: the opening turn has more Money causes than MaxCauses, so Money's tip ends with one Other line.
if (id == "treasury" && causes.Count != HudModel.MaxCauses + 1) problems.Add($"{at} {id}: {causes.Count} causes, not the two largest and one Other line");
Rect t = tip.worldBound, m = meter.worldBound, win = root.worldBound;
if (t.xMin < win.xMin - 0.5f || t.xMax > win.xMax + 0.5f || t.yMax > win.yMax + 0.5f) problems.Add($"{at} {id}: the tip {t} leaves the window {win}");
if (t.yMin < m.yMax) problems.Add($"{at} {id}: the tip {t} is not under its number {m}");
Leave(meter);
if (Shown(tip)) problems.Add($"{at} {id}: the tip stays after the pointer leaves");
}
}
}
Assert.IsEmpty(problems, string.Join("\n", problems));
}
/// <summary>#2200: every top-bar meter's tip says what the meter is and what moves it (hud.tip.<id>, one key per
/// HudModel.MeterIds id, in English and Hebrew) after its number in words (the tooltip), and the longer tip still fits
/// in the window under the bar at each UI scale (100, 125 and 150%, SettingsPresenter.UiScales) and on a phone.</summary>
[UnityTest]
public IEnumerator EveryMeterTipExplainsItsMeterAndFits()
{
var problems = new List<string>();
foreach (var id in HudModel.MeterIds)
foreach (var (lang, t) in new[] { ("en", En), ("he", He) })
if (!t.Has("hud.tip." + id) || t["hud.tip." + id].Trim().Length == 0) problems.Add($"{lang}: no hud.tip.{id}");
if (problems.Count > 0) { Assert.Fail(string.Join("\n", problems)); yield break; }
foreach (var hebrew in new[] { false, true })
foreach (var (w, h, scale) in new[] { (1280, 720, 100), (1280, 720, 125), (1280, 720, 150), (390, 844, 100) })
{
string at = $"{(hebrew ? "he" : "en")} {w}x{h} {scale}%";
yield return Rendered(w, h, hebrew, Check, scale);
IEnumerator Check(VisualElement root, SimBridge bridge, UiText text)
{
var tip = root.Q(MeterTip.TipName);
foreach (var id in HudModel.MeterIds)
{
var meter = root.Q("meter-" + id);
Enter(meter);
for (int i = 0; i < 3; i++) yield return null; // the tip is placed once its width is laid out
if (!Shown(tip)) { problems.Add($"{at} {id}: hovering shows no tip"); Leave(meter); continue; }
var expected = meter.tooltip + "\n" + text["hud.tip." + id];
if (!Words(root).StartsWith(expected)) problems.Add($"{at} {id}: the tip's words are '{Words(root)}', not its number in words and then '{text["hud.tip." + id]}'");
if (UiDirection.RightToLeft(Words(root)) != hebrew) problems.Add($"{at} {id}: the words are not in the UI's language");
Rect r = tip.worldBound, m = meter.worldBound, win = root.worldBound;
if (r.xMin < win.xMin - 0.5f || r.xMax > win.xMax + 0.5f || r.yMax > win.yMax + 0.5f) problems.Add($"{at} {id}: the tip {r} leaves the window {win}");
if (r.yMin < m.yMax) problems.Add($"{at} {id}: the tip {r} is not under its number {m}");
Leave(meter);
}
}
}
Assert.IsEmpty(problems, string.Join("\n", problems));
}
/// <summary>A touchscreen has no hover: a tap pins the tip, a tap on another number moves it, a second tap closes it, and
/// End Turn closes it; the meter's tooltip stays its words alone (the accessibility text, HudModel.Spoken).</summary>
[UnityTest]
public IEnumerator ATapPinsTheTipAndASecondTapOrEndTurnClosesIt()
{
var problems = new List<string>();
yield return Rendered(390, 844, false, Check);
IEnumerator Check(VisualElement root, SimBridge bridge, UiText text)
{
var tip = root.Q(MeterTip.TipName);
VisualElement money = root.Q("meter-treasury"), security = root.Q("meter-security");
if (money.tooltip.Contains(text["hud.causes"])) problems.Add("the tooltip itself carries the causes");
Enter(money); Tap(money); Leave(money);
yield return null;
if (!Shown(tip)) problems.Add("a tap does not keep the tip");
Tap(security);
yield return null;
if (!Shown(tip) || !Words(root).StartsWith(security.tooltip)) problems.Add($"a tap on another number does not move the tip: '{Words(root)}'");
Tap(security);
if (Shown(tip)) problems.Add("a second tap does not close the tip");
Tap(money);
if (!Shown(tip)) problems.Add("a tap after closing does not open it again");
bridge.EndTurn();
if (Shown(tip)) problems.Add("End Turn does not close the tip");
}
Assert.IsEmpty(problems, string.Join("\n", problems));
}
/// <summary>#1108: a mouse has hover, so a click on a number does not pin its tip and leaving hides it; a tapped tip closes
/// on the next tap anywhere (the map, another control), while a tap on a number still moves or closes it.</summary>
[UnityTest]
public IEnumerator AClickedTipHidesOnLeaveAndATappedTipOnTheNextTapAnywhere()
{
var problems = new List<string>();
yield return Rendered(1280, 720, false, Check);
IEnumerator Check(VisualElement root, SimBridge bridge, UiText text)
{
var tip = root.Q(MeterTip.TipName);
VisualElement money = root.Q("meter-treasury"), security = root.Q("meter-security");
Enter(money); MouseClick(money); Leave(money);
if (Shown(tip)) problems.Add("a mouse click keeps the tip after the pointer leaves");
foreach (var (where, e) in new[] { ("the map", root.panel.visualTree), ("another control", root.Q("end-turn")) })
{
Tap(money);
if (!Shown(tip)) { problems.Add($"precondition: a tap shows the tip (before {where})"); continue; }
Press(e);
if (Shown(tip)) problems.Add($"a tap on {where} does not close a tapped tip");
}
Tap(money);
Press(security); Tap(security);
if (!Shown(tip) || !Words(root).StartsWith(security.tooltip)) problems.Add($"a tap on another number does not move the tip: '{Words(root)}'");
Press(security); Tap(security);
if (Shown(tip)) problems.Add("a second tap on the number does not close the tip");
Tap(money); Press(security); MouseClick(security);
if (Shown(tip)) problems.Add("a mouse click on a number does not drop a tap's pin (a touchscreen laptop)");
yield break;
}
Assert.IsEmpty(problems, string.Join("\n", problems));
}
/// <summary>Renders Game.uxml at w x h with the HUD after one turn, then runs <paramref name="check"/>, which may wait frames.
/// A <paramref name="uiScale"/> other than 100 sets the panel as the Settings scale choice does (#40).</summary>
internal static IEnumerator Rendered(int w, int h, bool hebrew, System.Func<VisualElement, SimBridge, UiText, IEnumerator> check, int uiScale = 100)
{
var rt = new RenderTexture(w, h, 0);
var ps = Object.Instantiate(AssetDatabase.LoadAssetAtPath<PanelSettings>(UiPaths.Panel));
ps.targetTexture = rt;
if (uiScale != 100) ps.referenceResolution = new Vector2Int(Mathf.RoundToInt(ps.referenceResolution.x * 100f / uiScale), Mathf.RoundToInt(ps.referenceResolution.y * 100f / uiScale));
var go = new GameObject("MeterTipLayout"); go.SetActive(false);
var doc = go.AddComponent<UIDocument>(); doc.panelSettings = ps;
doc.visualTreeAsset = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(UiPaths.GameUxml);
go.SetActive(true);
var root = doc.rootVisualElement;
root.Q("root").RemoveFromClassList("loading");
if (hebrew) root.Q("root").AddToClassList(UiLanguage.HebrewClass);
var text = hebrew ? He : En;
var bridge = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), text);
var hud = new HudPresenter(root, bridge, text);
try
{
bridge.EndTurn();
for (int i = 0; i < 30 && !(root.Q("meter-fx").layout.width > 0); i++) yield return null;
for (int i = 0; i < 3; i++) yield return null;
var inner = check(root, bridge, text);
while (inner.MoveNext()) yield return inner.Current;
}
finally
{
hud.Dispose();
Object.DestroyImmediate(go); Object.DestroyImmediate(ps); rt.Release(); Object.DestroyImmediate(rt);
}
}
/// <summary>#803 Task 5 (R-CTRL-019): while the player's Deports have emptied any place, International support's tip
/// always counts them, whatever the turn's causes; no other meter, and none at 0 places.</summary>
[Test]
public void PersistentCausesCountThePlacesDepopulatedByDeport()
{
var text = En;
var s = GameSession.New(C, GoldenRun.Seed, Mode.Historical).State;
s.DisplacedByPlayer = 2;
CollectionAssert.AreEqual(new[] { text.Format("hud.standing_displaced_places", 2) }, HudModel.PersistentCauses(text, s, "standing"));
StringAssert.Contains("2", HudModel.PersistentCauses(text, s, "standing")[0]);
CollectionAssert.IsEmpty(HudModel.PersistentCauses(text, s, "cohesion"), "only International support");
s.DisplacedByPlayer = 0;
CollectionAssert.IsEmpty(HudModel.PersistentCauses(text, s, "standing"), "none at 0 places");
}
/// <summary>#803 Task 5: rendered in English and Hebrew, International support's tip shows the places line after its
/// words and before the causes' heading on a turn with no Deport cause, so HudModel.MaxCauses never drops it.</summary>
[UnityTest]
public IEnumerator TheSupportTipCountsDepopulatedPlacesOnATurnWithNoDeport()
{
var problems = new List<string>();
foreach (var hebrew in new[] { false, true })
{
string at = hebrew ? "he" : "en";
yield return Rendered(1280, 720, hebrew, Check);
IEnumerator Check(VisualElement root, SimBridge bridge, UiText text)
{
bridge.State.DisplacedByPlayer = 2;
var meter = root.Q("meter-standing");
Enter(meter);
for (int i = 0; i < 3; i++) yield return null;
var line = text.Format("hud.standing_displaced_places", 2);
var causes = HudModel.Causes(bridge.Session.Last, "standing", bridge.Content, w => w.Key);
if (causes.Any(k => k.Contains("deport") || k.Contains("depopulation"))) problems.Add($"{at}: precondition: the turn has a Deport cause");
var words = Words(root);
var head = meter.tooltip + "\n" + text["hud.tip.standing"] + "\n" + line;
if (!words.StartsWith(head, System.StringComparison.Ordinal)) problems.Add($"{at}: the tip's words '{words}' do not show '{line}' after the meter's words");
if (causes.Count > 0 && words != head + "\n" + text["hud.causes"]) problems.Add($"{at}: the line is not before the causes' heading: '{words}'");
if (UiDirection.RightToLeft(line) != hebrew) problems.Add($"{at}: the line '{line}' is not in the UI's language");
Leave(meter);
}
}
Assert.IsEmpty(problems, string.Join("\n", problems));
}
}
/// <summary>#1184: a tap on the bare map never reaches the panel (the event system sends a pointer event only to a panel
/// that has an element under it), so MeterTip's press on the panel root does not hear it. A tapped tip still closes on it,
/// through the touchscreen itself; a tap on the UI is left to the panel (a second tap on the meter must not reopen it).
/// InputTestFixture runs the devices in edit mode; the edit-mode panel gets no pointer events at all, as the map's press.</summary>
public class MeterTipBareMapTests : UnityEngine.InputSystem.InputTestFixture
{
[UnityTest]
public IEnumerator ATappedTipClosesOnATapOnTheBareMap()
{
var touch = UnityEngine.InputSystem.InputSystem.AddDevice<UnityEngine.InputSystem.Touchscreen>();
var problems = new List<string>();
yield return MeterTipTests.Rendered(390, 844, false, Check);
IEnumerator Check(VisualElement root, SimBridge bridge, UiText text)
{
var tip = root.Q(MeterTip.TipName);
var money = root.Q("meter-treasury");
// screen points (y up) with and without an element under them, by the same test as the map's clicks (UiPointer)
Vector2? bare = null, onUi = null;
for (int y = 0; y < Screen.height; y += 10)
for (int x = 0; x < Screen.width; x += 10)
{
var p = new Vector2(x, y);
if (UiPointer.IsOverUi(root.panel, p, Screen.height)) onUi ??= p; else bare ??= p;
}
if (bare == null || onUi == null) { problems.Add($"precondition: the {Screen.width}x{Screen.height} screen has bare map ({bare}) and UI ({onUi})"); yield break; }
int id = 1;
void TapAt(Vector2 at) { BeginTouch(id, at); EndTouch(id, at); id++; }
MeterTipTests.Tap(money);
if (!MeterTipTests.Shown(tip)) problems.Add("precondition: a tap pins the tip");
TapAt(onUi.Value);
if (!MeterTipTests.Shown(tip)) problems.Add("a touch on the UI closed the tip itself: the panel's press (or the meter's click) decides that");
TapAt(bare.Value);
if (MeterTipTests.Shown(tip)) problems.Add("a tap on the bare map does not close a tapped tip");
}
Assert.IsEmpty(problems, string.Join("\n", problems));
}
}